Win8-Examples: Media engine native C++ video playback/C++/meplayer.cpp Source File

  • Main Page
  • Namespaces
  • Classes
  • Files
  • Directories
  • File List
  • File Members
  • Media engine native C++ video playback
  • C++

meplayer.cpp

Go to the documentation of this file.
00001 //
00002 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00003 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00004 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00005 // PARTICULAR PURPOSE.
00006 //
00007 // Copyright (c) Microsoft Corporation. All rights reserved.
00008 //
00009
00010 #include "pch.h"
00011 #include "MEPlayer.h"
00012 #include <d3dmanagerlock.hxx>
00013
00014 using namespace std;
00015 using namespace Microsoft::WRL;
00016 using namespace Windows::System::Threading;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::ApplicationModel::Core;
00019 using namespace Windows::UI::Core;
00020 using namespace Windows::Storage;
00021 using namespace Windows::Storage::Pickers;
00022 using namespace Windows::Storage::Streams;
00023 using namespace concurrency;
00024
00025 // MediaEngineNotify: Implements the callback for Media Engine event notification.
00026 class MediaEngineNotify : public IMFMediaEngineNotify
00027 {
00028     long m_cRef;
00029     Platform::Agile<Windows::UI::Core::CoreWindow> m_cWindow;
00030     MediaEngineNotifyCallback^ m_pCB;
00031
00032 public:
00033     MediaEngineNotify(Platform::Agile<Windows::UI::Core::CoreWindow> cWindow) : m_cWindow(cWindow), m_cRef(1), m_pCB(nullptr)
00034     {
00035     }
00036
00037     STDMETHODIMP QueryInterface(REFIID riid, void** ppv)
00038     {
00039         if(__uuidof(IMFMediaEngineNotify) == riid)
00040         {
00041             *ppv = static_cast<IMFMediaEngineNotify*>(this);
00042         }
00043         else
00044         {
00045             *ppv = nullptr;
00046             return E_NOINTERFACE;
00047         }
00048
00049         AddRef();
00050
00051         return S_OK;
00052     }
00053
00054     STDMETHODIMP_(ULONG) AddRef()
00055     {
00056         return InterlockedIncrement(&m_cRef);
00057     }
00058
00059     STDMETHODIMP_(ULONG) Release()
00060     {
00061         LONG cRef = InterlockedDecrement(&m_cRef);
00062         if (cRef == 0)
00063         {
00064             delete this;
00065         }
00066         return cRef;
00067     }
00068
00069     // EventNotify is called when the Media Engine sends an event.
00070     STDMETHODIMP EventNotify(DWORD meEvent, DWORD_PTR param1, DWORD param2)
00071     {
00072         if (meEvent == MF_MEDIA_ENGINE_EVENT_NOTIFYSTABLESTATE)
00073         {
00074             SetEvent(reinterpret_cast<HANDLE>(param1));
00075         }
00076         else
00077         {
00078             m_pCB->OnMediaEngineEvent(meEvent);
00079         }
00080
00081         return S_OK;
00082     }
00083
00084     void MediaEngineNotifyCallback(MediaEngineNotifyCallback^ pCB)
00085     {
00086         m_pCB = pCB;
00087     }
00088 };
00089
00090 MEPlayer::MEPlayer() :
00091 m_spDX11Device(nullptr),
00092 m_spDX11DeviceContext(nullptr),
00093 m_spDXGIOutput(nullptr),
00094 m_spDX11SwapChain(nullptr),
00095 m_spDXGIManager(nullptr),
00096 m_spMediaEngine(nullptr),
00097 m_spEngineEx(nullptr),
00098 m_bstrURL(nullptr),
00099 m_TimerThreadHandle(nullptr),
00100 m_fPlaying(FALSE),
00101 m_fLoop(FALSE),
00102 m_fEOS(FALSE),
00103 m_fStopTimer(TRUE),
00104 m_d3dFormat(DXGI_FORMAT_B8G8R8A8_UNORM),
00105 m_fInitSuccess(FALSE),
00106 m_fExitApp(FALSE),
00107 m_fUseDX(TRUE)
00108 {
00109     memset(&m_bkgColor, 0, sizeof(MFARGB));
00110
00111     InitializeCriticalSectionEx(&m_critSec, 0, 0);
00112 }
00113
00114 MEPlayer::~MEPlayer()
00115 {
00116     Shutdown();
00117
00118     MFShutdown();
00119
00120     DeleteCriticalSection(&m_critSec);
00121 }
00122
00123 //+-------------------------------------------------------------------------
00124 //
00125 //  Function:   CreateDX11Device()
00126 //
00127 //  Synopsis:   creates a default device
00128 //
00129 //--------------------------------------------------------------------------
00130 void MEPlayer::CreateDX11Device()
00131 {
00132     static const D3D_FEATURE_LEVEL levels[] = {
00133         D3D_FEATURE_LEVEL_11_1,
00134         D3D_FEATURE_LEVEL_11_0,
00135         D3D_FEATURE_LEVEL_10_1,
00136         D3D_FEATURE_LEVEL_10_0,
00137         D3D_FEATURE_LEVEL_9_3,
00138         D3D_FEATURE_LEVEL_9_2,
00139         D3D_FEATURE_LEVEL_9_1
00140     };
00141
00142     D3D_FEATURE_LEVEL FeatureLevel;
00143     HRESULT hr = S_OK;
00144
00145     if(m_fUseDX)
00146     {
00147         hr = D3D11CreateDevice(
00148             nullptr,
00149             D3D_DRIVER_TYPE_HARDWARE,
00150             nullptr,
00151             D3D11_CREATE_DEVICE_VIDEO_SUPPORT | D3D11_CREATE_DEVICE_BGRA_SUPPORT,
00152             levels,
00153             ARRAYSIZE(levels),
00154             D3D11_SDK_VERSION,
00155             &m_spDX11Device,
00156             &FeatureLevel,
00157             &m_spDX11DeviceContext
00158             );
00159     }
00160
00161     //Failed to create DX11 Device (using VM?), create device using WARP
00162     if(FAILED(hr))
00163     {
00164         m_fUseDX = FALSE;
00165     }
00166
00167     if(!m_fUseDX)
00168     {
00169         MEDIA::ThrowIfFailed(D3D11CreateDevice(
00170             nullptr,
00171             D3D_DRIVER_TYPE_WARP,
00172             nullptr,
00173             D3D11_CREATE_DEVICE_BGRA_SUPPORT,
00174             levels,
00175             ARRAYSIZE(levels),
00176             D3D11_SDK_VERSION,
00177             &m_spDX11Device,
00178             &FeatureLevel,
00179             &m_spDX11DeviceContext
00180             ));
00181     }
00182
00183     if(m_fUseDX)
00184     {
00185         ComPtr<ID3D10Multithread> spMultithread;
00186         MEDIA::ThrowIfFailed(
00187             m_spDX11Device.Get()->QueryInterface(IID_PPV_ARGS(&spMultithread))
00188             );
00189         spMultithread->SetMultithreadProtected(TRUE);
00190     }
00191
00192     return;
00193 }
00194
00195 //+-----------------------------------------------------------------------------
00196 //
00197 //  Function:   CreateBackBuffers
00198 //
00199 //  Synopsis:   Creates the D3D back buffers
00200 //
00201 //------------------------------------------------------------------------------
00202 void MEPlayer::CreateBackBuffers()
00203 {
00204     EnterCriticalSection(&m_critSec);
00205
00206     // make sure everything is released first;
00207     if(m_spDX11Device)
00208     {
00209         // Acquire the DXGIdevice lock
00210         CAutoDXGILock DXGILock(m_spDXGIManager);
00211
00212         ComPtr<ID3D11Device> spDevice;
00213         MEDIA::ThrowIfFailed(
00214             DXGILock.LockDevice(/*out*/spDevice)
00215             );
00216
00217         // swap chain does not exist - so create it
00218         if (m_spDX11SwapChain == nullptr)
00219         {
00220             DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00221
00222             // Don't use Multi-sampling
00223             swapChainDesc.SampleDesc.Count = 1;
00224             swapChainDesc.SampleDesc.Quality = 0;
00225
00226             swapChainDesc.BufferUsage = DXGI_USAGE_BACK_BUFFER | DXGI_USAGE_RENDER_TARGET_OUTPUT;
00227             swapChainDesc.Scaling = DXGI_SCALING_NONE;
00228             swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
00229
00230             // Use more than 1 buffer to enable Flip effect.
00231             swapChainDesc.BufferCount = 4;
00232
00233             // Most common swapchain format is DXGI_FORMAT_R8G8B8A8-UNORM
00234             swapChainDesc.Format = m_d3dFormat;
00235             swapChainDesc.Width = m_rcTarget.right;
00236             swapChainDesc.Height = m_rcTarget.bottom;
00237
00238             // long QI chain to get DXGIFactory from the device
00239             ComPtr<IDXGIDevice2> spDXGIDevice;
00240             MEDIA::ThrowIfFailed(
00241                 spDevice.Get()->QueryInterface(IID_PPV_ARGS(&spDXGIDevice))
00242                 );
00243
00244             // Ensure that DXGI does not queue more than one frame at a time. This both reduces
00245             // latency and ensures that the application will only render after each VSync, minimizing
00246             // power consumption.
00247             MEDIA::ThrowIfFailed(
00248                 spDXGIDevice->SetMaximumFrameLatency(1)
00249                 );
00250
00251             ComPtr<IDXGIAdapter> spDXGIAdapter;
00252             MEDIA::ThrowIfFailed(
00253                 spDXGIDevice->GetParent(IID_PPV_ARGS(&spDXGIAdapter))
00254                 );
00255
00256             ComPtr<IDXGIFactory2> spDXGIFactory;
00257             MEDIA::ThrowIfFailed(
00258                 spDXGIAdapter->GetParent(IID_PPV_ARGS(&spDXGIFactory))
00259                 );
00260
00261             // and then we pass the device to the factory...
00262             MEDIA::ThrowIfFailed(
00263                 spDXGIFactory.Get()->CreateSwapChainForCoreWindow(spDevice.Get(), reinterpret_cast<IUnknown*>((Windows::UI::Core::CoreWindow^)m_window.Get()), &swapChainDesc, nullptr, &m_spDX11SwapChain)
00264                 );
00265         }
00266         else
00267         {
00268             // otherwise just resize it
00269             MEDIA::ThrowIfFailed(m_spDX11SwapChain->ResizeBuffers(
00270                 4,
00271                 m_rcTarget.right,
00272                 m_rcTarget.bottom,
00273                 m_d3dFormat,
00274                 0
00275                 ));
00276         }
00277     }
00278
00279     LeaveCriticalSection(&m_critSec);
00280
00281     return;
00282 }
00283
00284 // Create a new instance of the Media Engine.
00285 void MEPlayer::Initialize(Windows::UI::Core::CoreWindow^ window)
00286 {
00287     ComPtr<IMFMediaEngineClassFactory> spFactory;
00288     ComPtr<IMFAttributes> spAttributes;
00289     ComPtr<MediaEngineNotify> spNotify;
00290
00291     HRESULT hr = S_OK;
00292
00293     m_window = window;
00294
00295     // Get the bounding rectangle of the window.
00296     m_rcTarget.left = 0;
00297     m_rcTarget.top = 0;
00298     m_rcTarget.right = (LONG)m_window->Bounds.Width;
00299     m_rcTarget.bottom = (LONG)m_window->Bounds.Height;
00300
00301     MEDIA::ThrowIfFailed(MFStartup(MF_VERSION));
00302
00303     EnterCriticalSection(&m_critSec);
00304
00305     try
00306     {
00307
00308         // Create DX11 device.
00309         CreateDX11Device();
00310
00311         UINT resetToken;
00312         MEDIA::ThrowIfFailed(
00313             MFCreateDXGIDeviceManager(&resetToken, &m_spDXGIManager)
00314             );
00315
00316         MEDIA::ThrowIfFailed(
00317             m_spDXGIManager->ResetDevice(m_spDX11Device.Get(), resetToken)
00318             );
00319
00320         // Create our event callback object.
00321         spNotify = new MediaEngineNotify(m_window);
00322         if (spNotify == nullptr)
00323         {
00324             MEDIA::ThrowIfFailed(E_OUTOFMEMORY);
00325         }
00326
00327         spNotify->MediaEngineNotifyCallback(this);
00328
00329         // Create the class factory for the Media Engine.
00330         MEDIA::ThrowIfFailed(
00331             CoCreateInstance(CLSID_MFMediaEngineClassFactory, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&spFactory))
00332             );
00333
00334         // Set configuration attribiutes.
00335         MEDIA::ThrowIfFailed(
00336             MFCreateAttributes(&spAttributes, 1)
00337             );
00338
00339         MEDIA::ThrowIfFailed(
00340             spAttributes->SetUnknown(MF_MEDIA_ENGINE_DXGI_MANAGER, (IUnknown*) m_spDXGIManager.Get())
00341             );
00342
00343         MEDIA::ThrowIfFailed(
00344             spAttributes->SetUnknown(MF_MEDIA_ENGINE_CALLBACK, (IUnknown*) spNotify.Get())
00345             );
00346
00347         MEDIA::ThrowIfFailed(
00348             spAttributes->SetUINT32(MF_MEDIA_ENGINE_VIDEO_OUTPUT_FORMAT, m_d3dFormat)
00349             );
00350
00351         // Create the Media Engine.
00352         const DWORD flags = MF_MEDIA_ENGINE_WAITFORSTABLE_STATE;
00353         MEDIA::ThrowIfFailed(
00354             spFactory->CreateInstance(flags, spAttributes.Get(), &m_spMediaEngine)
00355             );
00356
00357         MEDIA::ThrowIfFailed(
00358             m_spMediaEngine.Get()->QueryInterface(__uuidof(IMFMediaEngine), (void**) &m_spEngineEx)
00359             );
00360
00361         // Create/Update swap chain
00362         UpdateForWindowSizeChange();
00363
00364         m_fInitSuccess = TRUE;
00365
00366     }
00367     catch (Platform::Exception^)
00368     {
00369         CoreWindowDialog^ coreWindowDialog = ref new CoreWindowDialog( \
00370             "Failed to initialize DirectX device.");
00371         task<Windows::UI::Popups::IUICommand^> coreWindowDialogTask(coreWindowDialog->ShowAsync());
00372
00373         coreWindowDialogTask.then([this](Windows::UI::Popups::IUICommand^ uiCommand){
00374             m_fExitApp = TRUE;
00375             });
00376     }
00377
00378     LeaveCriticalSection(&m_critSec);
00379
00380     return;
00381 }
00382
00383 // Shut down the player and release all interface pointers.
00384 void MEPlayer::Shutdown()
00385 {
00386     EnterCriticalSection(&m_critSec);
00387
00388     StopTimer();
00389
00390     if (m_spMediaEngine)
00391     {
00392         m_spMediaEngine->Shutdown();
00393     }
00394
00395     if(nullptr != m_bstrURL)
00396     {
00397         ::CoTaskMemFree(m_bstrURL);
00398     }
00399
00400     LeaveCriticalSection(&m_critSec);
00401
00402     return;
00403 }
00404
00405 // Open File
00406 void MEPlayer::OpenFile()
00407 {
00408     if(m_fInitSuccess == FALSE)
00409     {
00410         return;
00411     }
00412     if(IsPlaying())
00413     {
00414         Pause();
00415     }
00416     if(m_fEOS)
00417     {
00418         StopTimer();
00419     }
00420
00421     FileOpenPicker^ getVidFile = ref new FileOpenPicker();
00422
00423     getVidFile->SuggestedStartLocation = PickerLocationId::VideosLibrary;
00424     getVidFile->ViewMode = PickerViewMode::Thumbnail;
00425
00426     getVidFile->FileTypeFilter->Clear();
00427     getVidFile->FileTypeFilter->Append(".mp4");
00428     getVidFile->FileTypeFilter->Append(".m4v");
00429     getVidFile->FileTypeFilter->Append(".mts");
00430     getVidFile->FileTypeFilter->Append(".mov");
00431     getVidFile->FileTypeFilter->Append(".wmv");
00432     getVidFile->FileTypeFilter->Append(".avi");
00433     getVidFile->FileTypeFilter->Append(".asf");
00434
00435
00436     m_pickFileTask = task<StorageFile^>(getVidFile->PickSingleFileAsync(), m_tcs.get_token());
00437
00438     m_pickFileTask.then([this](StorageFile^ fileHandle)
00439     {
00440         try
00441         {
00442             if(!fileHandle)
00443             {
00444                 if(!m_spMediaEngine->HasVideo())
00445                 {
00446                     m_fExitApp = TRUE;
00447                 }
00448                 return;
00449             }
00450
00451             task<IRandomAccessStream^> fOpenStreamTask(fileHandle->OpenAsync(Windows::Storage::FileAccessMode::Read));
00452
00453             SetURL(fileHandle->Path);
00454
00455             auto vidPlayer = this;
00456             fOpenStreamTask.then([vidPlayer](IRandomAccessStream^ streamHandle)
00457             {
00458                 try
00459                 {
00460                     vidPlayer->SetBytestream(streamHandle);
00461                 } catch(Platform::Exception^)
00462                 {
00463                     MEDIA::ThrowIfFailed(E_UNEXPECTED);
00464                 }
00465             });
00466
00467         } catch(Platform::Exception^)
00468         {
00469             if(!m_spMediaEngine->HasVideo())
00470             {
00471                 m_fExitApp = TRUE;
00472             }
00473
00474         }
00475     });
00476
00477     return;
00478 }
00479
00480 // Set a URL
00481 void MEPlayer::SetURL(Platform::String^ szURL)
00482 {
00483     if(nullptr != m_bstrURL)
00484     {
00485         ::CoTaskMemFree(m_bstrURL);
00486         m_bstrURL = nullptr;
00487     }
00488
00489     size_t cchAllocationSize = 1 + ::wcslen(szURL->Data());
00490     m_bstrURL = (LPWSTR)::CoTaskMemAlloc(sizeof(WCHAR)*(cchAllocationSize));
00491
00492     if (m_bstrURL == 0)
00493     {
00494         MEDIA::ThrowIfFailed(E_OUTOFMEMORY);
00495     }
00496
00497     StringCchCopyW(m_bstrURL, cchAllocationSize, szURL->Data());
00498
00499     return;
00500 }
00501
00502 // Set Bytestream
00503 void MEPlayer::SetBytestream(IRandomAccessStream^ streamHandle)
00504 {
00505     HRESULT hr = S_OK;
00506     ComPtr<IMFByteStream> spMFByteStream = nullptr;
00507
00508     MEDIA::ThrowIfFailed(
00509         MFCreateMFByteStreamOnStreamEx((IUnknown*)streamHandle, &spMFByteStream)
00510         );
00511
00512     MEDIA::ThrowIfFailed(
00513         m_spEngineEx->SetSourceFromByteStream(spMFByteStream.Get(), m_bstrURL)
00514         );
00515
00516     return;
00517 }
00518
00519 void MEPlayer::OnMediaEngineEvent(DWORD meEvent)
00520 {
00521     switch (meEvent)
00522     {
00523     case MF_MEDIA_ENGINE_EVENT_LOADEDMETADATA:
00524         {
00525             m_fEOS = FALSE;
00526         }
00527         break;
00528     case MF_MEDIA_ENGINE_EVENT_CANPLAY:
00529         {
00530             // Start the Playback
00531             Play();
00532         }
00533         break;
00534     case MF_MEDIA_ENGINE_EVENT_PLAY:
00535         m_fPlaying = TRUE;
00536         break;
00537     case MF_MEDIA_ENGINE_EVENT_PAUSE:
00538         m_fPlaying = FALSE;
00539         break;
00540     case MF_MEDIA_ENGINE_EVENT_ENDED:
00541
00542         if(m_spMediaEngine->HasVideo())
00543         {
00544             StopTimer();
00545         }
00546         m_fEOS = TRUE;
00547         break;
00548     case MF_MEDIA_ENGINE_EVENT_TIMEUPDATE:
00549         break;
00550     case MF_MEDIA_ENGINE_EVENT_ERROR:
00551         break;
00552     }
00553
00554     return;
00555 }
00556
00557 // Start playback.
00558 void MEPlayer::Play()
00559 {
00560     if (m_spMediaEngine)
00561     {
00562         if(m_spMediaEngine->HasVideo() && m_fStopTimer)
00563         {
00564             // Start the Timer thread
00565             StartTimer();
00566         }
00567
00568         if(m_fEOS)
00569         {
00570             SetPlaybackPosition(0);
00571             m_fPlaying = TRUE;
00572         }
00573         else
00574         {
00575             MEDIA::ThrowIfFailed(
00576                 m_spMediaEngine->Play()
00577                 );
00578         }
00579
00580         m_fEOS = FALSE;
00581     }
00582     return;
00583 }
00584
00585 // Pause playback.
00586 void MEPlayer::Pause()
00587 {
00588     if (m_spMediaEngine)
00589     {
00590         MEDIA::ThrowIfFailed(
00591             m_spMediaEngine->Pause()
00592             );
00593     }
00594     return;
00595 }
00596
00597 // Set the audio volume.
00598 void MEPlayer::SetVolume(float fVol)
00599 {
00600     if (m_spMediaEngine)
00601     {
00602         MEDIA::ThrowIfFailed(
00603             m_spMediaEngine->SetVolume(fVol)
00604             );
00605     }
00606     return;
00607 }
00608
00609 // Set the audio balance.
00610 void MEPlayer::SetBalance(float fBal)
00611 {
00612     if (m_spEngineEx)
00613     {
00614         MEDIA::ThrowIfFailed(
00615             m_spEngineEx->SetBalance(fBal)
00616             );
00617     }
00618     return;
00619 }
00620
00621 // Mute the audio.
00622 void MEPlayer::Mute(BOOL mute)
00623 {
00624     if (m_spMediaEngine)
00625     {
00626         MEDIA::ThrowIfFailed(
00627             m_spMediaEngine->SetMuted(mute)
00628             );
00629     }
00630     return;
00631 }
00632
00633 // Step forward one frame.
00634 void MEPlayer::FrameStep()
00635 {
00636     if (m_spEngineEx)
00637     {
00638         MEDIA::ThrowIfFailed(
00639             m_spEngineEx->FrameStep(TRUE)
00640             );
00641     }
00642     return;
00643 }
00644
00645 // Get the duration of the content.
00646 void MEPlayer::GetDuration(double *pDuration, BOOL *pbCanSeek)
00647 {
00648     if (m_spMediaEngine)
00649     {
00650         double duration = m_spMediaEngine->GetDuration();
00651
00652         // NOTE:
00653         // "duration != duration"
00654         // This tests if duration is NaN, because NaN != NaN
00655
00656         if (duration != duration || duration == std::numeric_limits<float>::infinity())
00657         {
00658             *pDuration = 0;
00659             *pbCanSeek = FALSE;
00660         }
00661         else
00662         {
00663             *pDuration = duration;
00664
00665             DWORD caps = 0;
00666             m_spEngineEx->GetResourceCharacteristics(&caps);
00667             *pbCanSeek = (caps & ME_CAN_SEEK) == ME_CAN_SEEK;
00668         }
00669     }
00670     else
00671     {
00672         MEDIA::ThrowIfFailed(E_FAIL);
00673     }
00674
00675     return;
00676 }
00677
00678 // Get the current playback position.
00679 double MEPlayer::GetPlaybackPosition()
00680 {
00681     if (m_spMediaEngine)
00682     {
00683         return m_spMediaEngine->GetCurrentTime();
00684     }
00685     else
00686     {
00687         return 0;
00688     }
00689 }
00690
00691 // Seek to a new playback position.
00692 void MEPlayer::SetPlaybackPosition(float pos)
00693 {
00694     if (m_spMediaEngine)
00695     {
00696         MEDIA::ThrowIfFailed(
00697             m_spMediaEngine->SetCurrentTime(pos)
00698             );
00699     }
00700 }
00701
00702 // Is the player in the middle of a seek operation?
00703 BOOL MEPlayer::IsSeeking()
00704 {
00705     if (m_spMediaEngine)
00706     {
00707         return m_spMediaEngine->IsSeeking();
00708     }
00709     else
00710     {
00711         return FALSE;
00712     }
00713 }
00714
00715 void MEPlayer::EnableVideoEffect(BOOL enable)
00716 {
00717     HRESULT hr = S_OK;
00718
00719     if(m_spEngineEx)
00720     {
00721         MEDIA::ThrowIfFailed(m_spEngineEx->RemoveAllEffects());
00722         if(enable)
00723         {
00724             ComPtr<IMFActivate> spActivate;
00725             LPCWSTR szActivatableClassId = WindowsGetStringRawBuffer((HSTRING)Windows::Media::VideoEffects::VideoStabilization->Data(), nullptr);
00726
00727             MEDIA::ThrowIfFailed(MFCreateMediaExtensionActivate(szActivatableClassId, nullptr, IID_PPV_ARGS(&spActivate)));
00728
00729             MEDIA::ThrowIfFailed(m_spEngineEx->InsertVideoEffect(spActivate.Get(), FALSE));
00730         }
00731     }
00732
00733     return;
00734 }
00735
00736 // Window Event Handlers
00737 void MEPlayer::UpdateForWindowSizeChange()
00738 {
00739     if ((m_window->Bounds.Width  != m_rcTarget.right ||
00740         m_window->Bounds.Height != m_rcTarget.bottom) ||
00741         m_spDX11SwapChain == nullptr)
00742     {
00743         // Get the bounding rectangle of the window.
00744         m_rcTarget.left = 0;
00745         m_rcTarget.top = 0;
00746         m_rcTarget.right = (LONG)m_window->Bounds.Width;
00747         m_rcTarget.bottom = (LONG)m_window->Bounds.Height;
00748
00749         if(m_spEngineEx)
00750         {
00751             CreateBackBuffers();
00752         }
00753     }
00754
00755     return;
00756 }
00757
00758 //Timer related
00759
00760 //+-----------------------------------------------------------------------------
00761 //
00762 //  Function:   StartTimer
00763 //
00764 //  Synopsis:   Our timer is based on the displays VBlank interval
00765 //
00766 //------------------------------------------------------------------------------
00767 void MEPlayer::StartTimer()
00768 {
00769     ComPtr<IDXGIFactory1> spFactory;
00770     MEDIA::ThrowIfFailed(
00771         CreateDXGIFactory1(IID_PPV_ARGS(&spFactory))
00772         );
00773
00774     ComPtr<IDXGIAdapter> spAdapter;
00775     MEDIA::ThrowIfFailed(
00776         spFactory->EnumAdapters(0, &spAdapter)
00777         );
00778
00779     ComPtr<IDXGIOutput> spOutput;
00780     MEDIA::ThrowIfFailed(
00781         spAdapter->EnumOutputs(0, &m_spDXGIOutput)
00782         );
00783
00784     m_fStopTimer = FALSE;
00785
00786     auto vidPlayer = this;
00787     task<void> workItem(ThreadPool::RunAsync(ref new WorkItemHandler([=](IAsyncAction^ /*sender*/){
00788         vidPlayer->RealVSyncTimer();
00789         }
00790         ),
00791         WorkItemPriority::High
00792         ));
00793
00794     return;
00795 }
00796
00797 //+-----------------------------------------------------------------------------
00798 //
00799 //  Function:   StopTimer
00800 //
00801 //  Synopsis:   Stops the Timer and releases all its resources
00802 //
00803 //------------------------------------------------------------------------------
00804 void MEPlayer::StopTimer()
00805 {
00806     m_fStopTimer = TRUE;
00807     m_fPlaying = FALSE;
00808
00809     return;
00810 }
00811
00812 //+-----------------------------------------------------------------------------
00813 //
00814 //  Function:   realVSyncTimer
00815 //
00816 //  Synopsis:   A real VSyncTimer - a timer that fires at approx 60 Hz
00817 //              synchronized with the display's real VBlank interrupt.
00818 //
00819 //------------------------------------------------------------------------------
00820 DWORD MEPlayer::RealVSyncTimer()
00821 {
00822     for ( ;; )
00823     {
00824         if (m_fStopTimer)
00825         {
00826             break;
00827         }
00828
00829         if (SUCCEEDED(m_spDXGIOutput->WaitForVBlank()))
00830         {
00831             OnTimer();
00832         }
00833         else break;
00834     }
00835
00836     return 0;
00837 }
00838
00839 //+-----------------------------------------------------------------------------
00840 //
00841 //  Function:   OnTimer
00842 //
00843 //  Synopsis:   Called at 60Hz - we simply call the media engine and draw
00844 //              a new frame to the screen if told to do so.
00845 //
00846 //------------------------------------------------------------------------------
00847 void MEPlayer::OnTimer()
00848 {
00849     EnterCriticalSection(&m_critSec);
00850
00851     if (m_spMediaEngine != nullptr)
00852     {
00853         LONGLONG pts;
00854         if (m_spMediaEngine->OnVideoStreamTick(&pts) == S_OK)
00855         {
00856             // new frame available at the media engine so get it
00857             ComPtr<ID3D11Texture2D> spTextureDst;
00858             MEDIA::ThrowIfFailed(
00859                 m_spDX11SwapChain->GetBuffer(0, IID_PPV_ARGS(&spTextureDst))
00860                 );
00861
00862             MEDIA::ThrowIfFailed(
00863                 m_spMediaEngine->TransferVideoFrame(spTextureDst.Get(), nullptr, &m_rcTarget, &m_bkgColor)
00864                 );
00865
00866             // and the present it to the screen
00867             MEDIA::ThrowIfFailed(
00868                 m_spDX11SwapChain->Present(1, 0)
00869                 );
00870         }
00871     }
00872
00873     LeaveCriticalSection(&m_critSec);
00874
00875     return;
00876 }
00877
00878 //+-----------------------------------------------------------------------------
00879 //
00880 //  Function:   ExitApp
00881 //
00882 //  Synopsis:   Checks if there has been an error and indicates if the app
00883 //        should exit.
00884 //
00885 //------------------------------------------------------------------------------
00886 BOOL MEPlayer::ExitApp()
00887 {
00888     return m_fExitApp;
00889 }
Generated on Sat Nov 23 2024 16:08:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Background task/C++/Tasks/pch.cpp Source File

  • Files
  • Directories
  • File List
  • File Members
  • Background task
  • C++
  • Tasks

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 Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D command list/C++/pch.cpp Source File

  • File Members
  • Direct2D command list
  • C++

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Buffer Member List

This is the complete list of members for Buffer, including all inherited members.
Allocate(DWORD alloc) | Buffer | [private]
Allocate(DWORD alloc) | Buffer | [private]
Buffer() | Buffer |
Buffer() | Buffer |
CurrentFreeSize() const | Buffer | [private]
CurrentFreeSize() const | Buffer | [private]
DataPtr() | Buffer |
DataPtr() | Buffer |
DataSize() const | Buffer |
DataSize() const | Buffer |
Initalize(DWORD cbSize) | Buffer |
Initalize(DWORD cbSize) | Buffer |
m_allocated | Buffer | [private]
m_begin | Buffer | [private]
m_count | Buffer | [private]
m_end | Buffer | [private]
m_pArray | Buffer | [private]
MoveEnd(DWORD cb) | Buffer |
MoveEnd(DWORD cb) | Buffer |
MoveStart(DWORD cb) | Buffer |
MoveStart(DWORD cb) | Buffer |
Ptr() | Buffer | [inline, private]
Ptr() | Buffer | [inline, private]
Reserve(DWORD cb) | Buffer |
Reserve(DWORD cb) | Buffer |
SetSize(DWORD count) | Buffer | [private]
SetSize(DWORD count) | Buffer | [private]
~Buffer() | Buffer | [inline]
~Buffer() | Buffer | [inline]
Generated on Sat Nov 23 2024 16:09:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Web authentication broker/C++/App.xaml.h Source File

  • Web authentication broker

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: HttpClient/C++/Scenario5.xaml.h Source File

  • HttpClient

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 #include "HttpRequest.h"
00022
00023 namespace SDKSample
00024 {
00025     namespace HttpClientSample
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 Scenario5 sealed
00032         {
00033         public:
00034             Scenario5();
00035
00036         protected:
00037             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00038
00039         private:
00040             MainPage^ rootPage;
00041             Web::HttpRequest httpRequest;
00042             concurrency::cancellation_token_source cancellationTokenSource;
00043             void Start_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00044             void Cancel_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00045             IStream* GenerateSampleStream(unsigned int size);
00046             void DisplayTextResult(const std::wstring& response, Windows::UI::Xaml::Controls::TextBox^ output);
00047         };
00048     }
00049 }
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/GameTimer.h Source File

  • DirectX 3D shooting game

GameTimer.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 ref class GameTimer
00011 {
00012 internal:
00013     GameTimer();
00014
00015     float PlayingTime();            // Return the Elapsed time the Game has been active in seconds since Reset
00016     void PlayingTime(float time);   // Set the Elapsed playing time -- used for restarting in the middle of a game
00017     float DeltaTime();              // Return the Delta time between the last two updates
00018
00019     void Reset();
00020     void Start();
00021     void Stop();
00022     void Update();
00023     bool Active() { return m_active; };
00024
00025 private:
00026     float m_secondsPerCount;  // 1.0 / Frequency
00027     float m_deltaTime;
00028
00029     LARGE_INTEGER m_baseTime;
00030     LARGE_INTEGER m_pausedTime;
00031     LARGE_INTEGER m_stopTime;
00032     LARGE_INTEGER m_previousTime;
00033     LARGE_INTEGER m_currentTime;
00034
00035     bool m_active;
00036 };
00037
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML user and custom controls/C++/BasicCustomControl.h Source File

  • XAML user and custom controls

BasicCustomControl.h

Go to the documentation of this file.
00001 ﻿//
00002 // BasicCustomControl.h
00003 // Declaration of the BasicCustomControl class.
00004 //
00005
00006 #pragma once
00007
00008 #include "pch.h"
00009
00010 namespace SDKSample
00011 {
00012     namespace UserAndCustomControls
00013     {
00014       public ref class BasicCustomControl sealed : public Windows::UI::Xaml::Controls::Control
00015       {
00016       public:
00017         BasicCustomControl();
00018       };
00019     }
00020 }
Generated on Sat Nov 23 2024 16:08:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite vertical text/C++/pch.h Source File

  • DirectWrite vertical text

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 <d3d11_1.h>
00012 #include <d2d1_1.h>
00013 #include <d2d1_1helper.h>
00014 #include <d2d1effects.h>
00015 #include <wincodec.h>
00016 #include <math.h>
00017 #include <agile.h>
00018
00019 // C headers:
00020 #include <stdlib.h>
00021 #include <malloc.h>
00022 #include <memory.h>
00023 #include <math.h>
00024
00025 // C++ headers:
00026 #include <algorithm>
00027 #include <numeric>
00028 #include <string>
00029 #include <vector>
00030 #include <utility>
00031 #include <limits>
00032
00033 // Windows headers:
00034 #include <windows.h>
00035 #include <unknwn.h>
00036 #include <dwrite_1.h>
00037 #include <intsafe.h>
00038 #include <strsafe.h>
00039
00040 // Ignore unreferenced parameters, since they are very common
00041 // when implementing callbacks.
00042 #pragma warning(disable : 4100)
00043
00044 ////////////////////////////////////////
00045 // Application specific headers/functions:
00046
00047 enum {
00048     UnicodeMax = 0x10FFFF
00049 };
00050
00051 // Needed text editor backspace deletion.
00052 inline bool IsSurrogate(UINT32 ch)
00053 {
00054     // 0xD800 <= ch <= 0xDFFF
00055     return (ch & 0xF800) == 0xD800;
00056 }
00057
00058 inline bool IsLeadingSurrogate(UINT32 ch)
00059 {
00060     // 0xD800 <= ch <= 0xDBFF
00061     return (ch & 0xFC00) == 0xD800;
00062 }
00063
00064 inline bool IsTrailingSurrogate(UINT32 ch)
00065 {
00066     // 0xDC00 <= ch <= 0xDFFF
00067     return (ch & 0xFC00) == 0xDC00;
00068 }
00069
00070 inline UINT32 MakeUnicodeCodepoint(UINT32 leading, UINT32 trailing)
00071 {
00072     return ((leading & 0x03FF) << 10 | (trailing & 0x03FF)) + 0x10000;
00073 }
00074
00075 // Acquires an additional reference, if non-null.
00076 template <typename InterfaceType>
00077 inline InterfaceType* SafeAcquire(InterfaceType* newObject)
00078 {
00079     if (newObject != nullptr)
00080     {
00081         newObject->AddRef();
00082     }
00083     return newObject;
00084 }
00085
00086 // Generic COM base implementation for classes, since DirectWrite uses
00087 // callbacks for several different kinds of objects, particularly the
00088 // script analysis source/sink.
00089 //
00090 // Example:
00091 //
00092 //  class TextAnalysis : public ComBase<QiList<IDWriteTextAnalysisSink>>
00093 //
00094 template <typename InterfaceChain>
00095 class ComBase : public InterfaceChain
00096 {
00097 public:
00098     explicit ComBase()
00099     :   refValue_(0)
00100     { }
00101
00102     // IUnknown interface
00103     IFACEMETHOD(QueryInterface)(IID const& iid, OUT void** ppObject)
00104     {
00105         *ppObject = nullptr;
00106         InterfaceChain::QueryInterfaceInternal(iid, ppObject);
00107         if (*ppObject == nullptr)
00108             return E_NOINTERFACE;
00109
00110         AddRef();
00111         return S_OK;
00112     }
00113
00114     IFACEMETHOD_(ULONG, AddRef)()
00115     {
00116         return InterlockedIncrement(&refValue_);
00117     }
00118
00119     IFACEMETHOD_(ULONG, Release)()
00120     {
00121         ULONG newCount = InterlockedDecrement(&refValue_);
00122         if (newCount == 0)
00123             delete this;
00124
00125         return newCount;
00126     }
00127
00128     virtual ~ComBase()
00129     { }
00130
00131 protected:
00132     ULONG refValue_;
00133
00134 private:
00135     // No copy construction allowed.
00136     ComBase(const ComBase& b);
00137     ComBase& operator =(ComBase const&);
00138 };
00139
00140
00141 struct QiListNil
00142 {
00143 };
00144
00145
00146 // When the QueryInterface list refers to itself as class,
00147 // which hasn't fully been defined yet.
00148 template <typename InterfaceName, typename InterfaceChain>
00149 class QiListSelf : public InterfaceChain
00150 {
00151 public:
00152     inline void QueryInterfaceInternal(IID const& iid, OUT void** ppObject)
00153     {
00154         if (iid != __uuidof(InterfaceName))
00155             return InterfaceChain::QueryInterfaceInternal(iid, ppObject);
00156
00157         *ppObject = static_cast<InterfaceName*>(this);
00158     }
00159 };
00160
00161 // When this interface is implemented and more follow.
00162 template <typename InterfaceName, typename InterfaceChain = QiListNil>
00163 class QiList : public InterfaceName, public InterfaceChain
00164 {
00165 public:
00166     inline void QueryInterfaceInternal(IID const& iid, OUT void** ppObject)
00167     {
00168         if (iid != __uuidof(InterfaceName))
00169             return InterfaceChain::QueryInterfaceInternal(iid, ppObject);
00170
00171         *ppObject = static_cast<InterfaceName*>(this);
00172     }
00173 };
00174
00175 // When the this is the last implemented interface in the list.
00176 template <typename InterfaceName>
00177 class QiList<InterfaceName, QiListNil> : public InterfaceName
00178 {
00179 public:
00180     inline void QueryInterfaceInternal(IID const& iid, OUT void** ppObject)
00181     {
00182         if (iid != __uuidof(InterfaceName))
00183             return;
00184
00185         *ppObject = static_cast<InterfaceName*>(this);
00186     }
00187 };
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Search contract/C++/Scenario7.xaml.h Source File

  • Search contract

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 // Scenario1.xaml.h
00013 // Declaration of the Scenario1 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario7.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace SearchContract
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 Scenario7 sealed
00031         {
00032         public:
00033             Scenario7();
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     }
00040 }
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Date and time formatting/C++/StringTemplate.xaml.h Source File

  • Date and time formatting

StringTemplate.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 // StringTemplate.xaml.h
00013 // Declaration of the StringTemplate class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "StringTemplate.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace DateTimeFormatting
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 StringTemplate sealed
00031         {
00032         public:
00033             StringTemplate();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void Display_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:08:02 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D tutorial/C++/Lesson5.Components/BasicReaderWriter.cpp Source File

  • Direct3D tutorial
  • Lesson5.Components

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     m_locationPath = Platform::String::Concat(m_location->Path, "\\");
00023 }
00024
00025 BasicReaderWriter::BasicReaderWriter(
00026     _In_ Windows::Storage::StorageFolder^ folder
00027     )
00028 {
00029     m_location = folder;
00030     Platform::String^ path = m_location->Path;
00031     if (path->Length() == 0)
00032     {
00033         // Applications are not permitted to access certain
00034         // folders, such as the Documents folder, using this
00035         // code path.  In such cases, the Path property for
00036         // the folder will be an empty string.
00037         throw ref new Platform::FailureException();
00038     }
00039     m_locationPath = Platform::String::Concat(path, "\\");
00040 }
00041
00042 Platform::Array<byte>^ BasicReaderWriter::ReadData(
00043     _In_ Platform::String^ filename
00044     )
00045 {
00046     CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {0};
00047     extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
00048     extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
00049     extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN;
00050     extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
00051     extendedParams.lpSecurityAttributes = nullptr;
00052     extendedParams.hTemplateFile = nullptr;
00053
00054     Wrappers::FileHandle file(
00055         CreateFile2(
00056             Platform::String::Concat(m_locationPath, filename)->Data(),
00057             GENERIC_READ,
00058             FILE_SHARE_READ,
00059             OPEN_EXISTING,
00060             &extendedParams
00061             )
00062         );
00063     if (file.Get() == INVALID_HANDLE_VALUE)
00064     {
00065         throw ref new Platform::FailureException();
00066     }
00067
00068     FILE_STANDARD_INFO fileInfo = {0};
00069     if (!GetFileInformationByHandleEx(
00070         file.Get(),
00071         FileStandardInfo,
00072         &fileInfo,
00073         sizeof(fileInfo)
00074         ))
00075     {
00076         throw ref new Platform::FailureException();
00077     }
00078
00079     if (fileInfo.EndOfFile.HighPart != 0)
00080     {
00081         throw ref new Platform::OutOfMemoryException();
00082     }
00083
00084     Platform::Array<byte>^ fileData = ref new Platform::Array<byte>(fileInfo.EndOfFile.LowPart);
00085
00086     if (!ReadFile(
00087         file.Get(),
00088         fileData->Data,
00089         fileData->Length,
00090         nullptr,
00091         nullptr
00092         ))
00093     {
00094         throw ref new Platform::FailureException();
00095     }
00096
00097     return fileData;
00098 }
00099
00100 task<Platform::Array<byte>^> BasicReaderWriter::ReadDataAsync(
00101     _In_ Platform::String^ filename
00102     )
00103 {
00104     return task<StorageFile^>(m_location->GetFileAsync(filename)).then([=](StorageFile^ file)
00105     {
00106         return FileIO::ReadBufferAsync(file);
00107     }).then([=](IBuffer^ buffer)
00108     {
00109         auto fileData = ref new Platform::Array<byte>(buffer->Length);
00110         DataReader::FromBuffer(buffer)->ReadBytes(fileData);
00111         return fileData;
00112     });
00113 }
00114
00115 uint32 BasicReaderWriter::WriteData(
00116     _In_ Platform::String^ filename,
00117     _In_ const Platform::Array<byte>^ fileData
00118     )
00119 {
00120     CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {0};
00121     extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
00122     extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
00123     extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN;
00124     extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
00125     extendedParams.lpSecurityAttributes = nullptr;
00126     extendedParams.hTemplateFile = nullptr;
00127
00128     Wrappers::FileHandle file(
00129         CreateFile2(
00130             Platform::String::Concat(m_locationPath, filename)->Data(),
00131             GENERIC_WRITE,
00132             0,
00133             CREATE_ALWAYS,
00134             &extendedParams
00135             )
00136         );
00137     if (file.Get() == INVALID_HANDLE_VALUE)
00138     {
00139         throw ref new Platform::FailureException();
00140     }
00141
00142     DWORD numBytesWritten;
00143     if (
00144         !WriteFile(
00145             file.Get(),
00146             fileData->Data,
00147             fileData->Length,
00148             &numBytesWritten,
00149             nullptr
00150             ) ||
00151         numBytesWritten != fileData->Length
00152         )
00153     {
00154         throw ref new Platform::FailureException();
00155     }
00156
00157     return numBytesWritten;
00158 }
00159
00160 task<void> BasicReaderWriter::WriteDataAsync(
00161     _In_ Platform::String^ filename,
00162     _In_ const Platform::Array<byte>^ fileData
00163     )
00164 {
00165     return task<StorageFile^>(m_location->CreateFileAsync(filename, CreationCollisionOption::ReplaceExisting)).then([=](StorageFile^ file)
00166     {
00167         FileIO::WriteBytesAsync(file, fileData);
00168     });
00169 }
Generated on Sat Nov 23 2024 16:08:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Toast notifications/C#,C++/ScenarioInput2.xaml.cpp Source File

  • Toast notifications
  • C#,C++

ScenarioInput2.xaml.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 //
00009 // Scenario2Input.xaml.cpp
00010 // Implementation of the Scenario2Input class.
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioInput2.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace ToastsSampleCPP;
00018
00019 using namespace NotificationsExtensions::ToastContent;
00020 using namespace Platform;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Foundation::Collections;
00023 using namespace Windows::Graphics::Display;
00024 using namespace Windows::UI::Notifications;
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::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
00034 ScenarioInput2::ScenarioInput2()
00035 {
00036   InitializeComponent();
00037
00038   Scenario2DisplayToastImage01->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00039     Scenario2DisplayToast(ToastTemplateType::ToastImageAndText01);
00040   });
00041
00042   Scenario2DisplayToastImage02->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00043     Scenario2DisplayToast(ToastTemplateType::ToastImageAndText02);
00044   });
00045
00046   Scenario2DisplayToastImage03->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00047     Scenario2DisplayToast(ToastTemplateType::ToastImageAndText03);
00048   });
00049
00050   Scenario2DisplayToastImage04->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00051     Scenario2DisplayToast(ToastTemplateType::ToastImageAndText04);
00052   });
00053
00054
00055   Scenario2DisplayToastImage01String->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00056     Scenario2DisplayToastWithStringManipulation(ToastTemplateType::ToastImageAndText01);
00057   });
00058
00059   Scenario2DisplayToastImage02String->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00060     Scenario2DisplayToastWithStringManipulation(ToastTemplateType::ToastImageAndText02);
00061   });
00062
00063   Scenario2DisplayToastImage03String->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00064     Scenario2DisplayToastWithStringManipulation(ToastTemplateType::ToastImageAndText03);
00065   });
00066
00067   Scenario2DisplayToastImage04String->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00068     Scenario2DisplayToastWithStringManipulation(ToastTemplateType::ToastImageAndText04);
00069   });
00070 }
00071
00072 ScenarioInput2::~ScenarioInput2()
00073 {
00074 }
00075
00076 #pragma region Template-Related Code - Do not remove
00077 void ScenarioInput2::OnNavigatedTo(NavigationEventArgs^ e)
00078 {
00079   // Get a pointer to our main page.
00080   rootPage = dynamic_cast<MainPage^>(e->Parameter);
00081 }
00082
00083 void ScenarioInput2::OnNavigatedFrom(NavigationEventArgs^ e)
00084 {
00085 }
00086
00087 #pragma endregion
00088
00089 void ScenarioInput2::OutputText(String^ text) {
00090   if (outputText == nullptr)
00091   {
00092     // Get a pointer to the content within the OutputFrame.
00093     Page^ outputFrame = dynamic_cast<Page^>(rootPage->OutputFrame->Content);
00094
00095     // Go find the elements that we need for this scenario
00096     outputText = dynamic_cast<TextBlock^>(outputFrame->FindName("Scenario2OutputText"));
00097   }
00098
00099   outputText->Text = text;
00100 }
00101
00102 void ScenarioInput2::Scenario2DisplayToast(ToastTemplateType templateType)
00103 {
00104   IToastNotificationContent^ toastContent = nullptr;
00105
00106   if (templateType == ToastTemplateType::ToastImageAndText01)
00107   {
00108     IToastImageAndText01^ specializedContent = ToastContentFactory::CreateToastImageAndText01();
00109     specializedContent->TextBodyWrap->Text = "Body text that wraps";
00110     specializedContent->Image->Src = "images/toastImageAndText.png";
00111     specializedContent->Image->Alt = "Placeholder image";
00112     toastContent = specializedContent;
00113   }
00114   else if (templateType == ToastTemplateType::ToastImageAndText02)
00115   {
00116     IToastImageAndText02^ specializedContent = ToastContentFactory::CreateToastImageAndText02();
00117     specializedContent->TextHeading->Text = "Heading text";
00118     specializedContent->TextBodyWrap->Text = "Body text that wraps";
00119     specializedContent->Image->Src = "images/toastImageAndText.png";
00120     specializedContent->Image->Alt = "Placeholder image";
00121     toastContent = specializedContent;
00122   }
00123   else if (templateType == ToastTemplateType::ToastImageAndText03)
00124   {
00125     IToastImageAndText03^ specializedContent = ToastContentFactory::CreateToastImageAndText03();
00126     specializedContent->TextHeadingWrap->Text = "Heading text that wraps";
00127     specializedContent->TextBody->Text = "Body text";
00128     specializedContent->Image->Src = "images/toastImageAndText.png";
00129     specializedContent->Image->Alt = "Placeholder image";
00130     toastContent = specializedContent;
00131   }
00132   else if (templateType == ToastTemplateType::ToastImageAndText04)
00133   {
00134     IToastImageAndText04^ specializedContent = ToastContentFactory::CreateToastImageAndText04();
00135     specializedContent->TextHeading->Text = "Heading text that wraps";
00136     specializedContent->TextBody1->Text = "First body text";
00137     specializedContent->TextBody2->Text = "Second body text";
00138     specializedContent->Image->Src = "images/toastImageAndText.png";
00139     specializedContent->Image->Alt = "Placeholder image";
00140     toastContent = specializedContent;
00141   }
00142
00143     if (toastContent != nullptr)
00144     {
00145         OutputText(toastContent->GetContent());
00146         // Create a toast, then create a ToastNotifier object to show
00147         // the toast
00148         auto toast = toastContent->CreateNotification();
00149
00150         // If you have other applications in your package, you can specify the AppId of
00151         // the app to create a ToastNotifier for that application
00152       ToastNotificationManager::CreateToastNotifier()->Show(toast);
00153     }
00154 }
00155
00156 void ScenarioInput2::Scenario2DisplayToastWithStringManipulation(ToastTemplateType templateType)
00157 {
00158   String^ toastXmlString = nullptr;
00159
00160   if (templateType == ToastTemplateType::ToastImageAndText01)
00161   {
00162     toastXmlString = "<toast>"
00163       + "<visual version='1'>"
00164       + "<binding template='toastImageAndText01'>"
00165       + "<text id='1'>Body text that wraps over three lines</text>"
00166       + "<image id='1' src='images/toastImageAndText.png' alt='Placeholder image'/>"
00167       + "</binding>"
00168       + "</visual>"
00169       + "</toast>";
00170   }
00171   else if (templateType == ToastTemplateType::ToastImageAndText02)
00172   {
00173     toastXmlString = "<toast>"
00174       + "<visual version='1'>"
00175       + "<binding template='toastImageAndText02'>"
00176       + "<text id='1'>Heading text</text>"
00177       + "<text id='2'>Body text that wraps over two lines</text>"
00178       + "<image id='1' src='images/toastImageAndText.png' alt='Placeholder image'/>"
00179       + "</binding>"
00180       + "</visual>"
00181       + "</toast>";
00182   }
00183   else if (templateType == ToastTemplateType::ToastImageAndText03)
00184   {
00185     toastXmlString = "<toast>"
00186       + "<visual version='1'>"
00187       + "<binding template='toastImageAndText03'>"
00188       + "<text id='1'>Heading text that wraps over two lines</text>"
00189       + "<text id='2'>Body text</text>"
00190       + "<image id='1' src='images/toastImageAndText.png' alt='Placeholder image'/>"
00191       + "</binding>"
00192       + "</visual>"
00193       + "</toast>";
00194   }
00195   else if (templateType == ToastTemplateType::ToastImageAndText04)
00196   {
00197     toastXmlString = "<toast>"
00198       + "<visual version='1'>"
00199       + "<binding template='toastImageAndText04'>"
00200       + "<text id='1'>Heading text</text>"
00201       + "<text id='2'>First body text</text>"
00202       + "<text id='3'>Second body text</text>"
00203       + "<image id='1' src='images/toastImageAndText.png' alt='Placeholder image'/>"
00204       + "</binding>"
00205       + "</visual>"
00206       + "</toast>";
00207   }
00208
00209   auto toastDOM = ref new Windows::Data::Xml::Dom::XmlDocument();
00210   toastDOM->LoadXml(toastXmlString);
00211
00212   OutputText(toastDOM->GetXml());
00213
00214   // Create a toast, then create a ToastNotifier object to show
00215   // the toast
00216   auto toast = ref new ToastNotification(toastDOM);
00217
00218   // If you have other applications in your package, you can specify the AppId of
00219   // the app to create a ToastNotifier for that application
00220   ToastNotificationManager::CreateToastNotifier()->Show(toast);
00221 }
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML two-dimensional transforms/C++/App.xaml.h Source File

  • XAML two-dimensional transforms

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Scaling according to DPI/C++/pch.h Source File

  • Scaling according to DPI

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File picker/C++/Scenario3.xaml.h Source File

  • File picker

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 SDKSample
00023 {
00024     namespace FilePicker
00025     {
00026         /// <summary>
00027         /// An empty page that can be used on its own or navigated to within a Frame.
00028         /// </summary>
00029         public ref class Scenario3 sealed
00030         {
00031         public:
00032             Scenario3();
00033
00034         private:
00035             MainPage^ rootPage;
00036
00037             void PickFolderButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038         };
00039     }
00040 }
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Account picture name/C++/GetAccountPicture.xaml.h Source File

  • Account picture name

GetAccountPicture.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 // GetAccountPicture.xaml.h
00013 // Declaration of the GetAccountPicture class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "GetAccountPicture.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace AccountPictureName
00023 {
00024     [Windows::Foundation::Metadata::WebHostHidden]
00025     public ref class GetAccountPicture sealed
00026     {
00027     public:
00028         GetAccountPicture();
00029
00030     protected:
00031         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00032
00033     private:
00034         MainPage^ rootPage;
00035         void GetSmallImageButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00036         void GetLargeImageButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00037         void GetVideoButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038         void HideImageAndVideoControls();
00039     };
00040 }
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DXGI offer and reclaim resources/C++/BasicTimer.h Source File

  • DXGI offer and reclaim resources

BasicTimer.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 timer class used to drive the render loop of the actively-animated
00011 // DirectX SDK samples. Uses the QueryPerformanceCounter function to retrieve
00012 // high-resolution timing information.
00013 ref class BasicTimer
00014 {
00015 private:
00016     LARGE_INTEGER m_frequency;
00017     LARGE_INTEGER m_currentTime;
00018     LARGE_INTEGER m_startTime;
00019     LARGE_INTEGER m_lastTime;
00020     float m_total;
00021     float m_delta;
00022
00023 internal:
00024     BasicTimer();
00025     void Reset();
00026     void Update();
00027     property float Total
00028     {
00029         float get();
00030     }
00031     property float Delta
00032     {
00033         float get();
00034     }
00035 };
Generated on Sat Nov 23 2024 16:08:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D interpolation modes/C++/pch.cpp Source File

  • Direct2D interpolation modes

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML accessibility/C++/Scenario3.xaml.cpp Source File

  • XAML accessibility

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 #include "pch.h"
00016 #include "Scenario3.xaml.h"
00017
00018 using namespace SDKSample::Accessibility;
00019
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Controls;
00022 using namespace Windows::UI::Xaml::Navigation;
00023
00024
00025 MediaContainerAP::MediaContainerAP(MediaElementContainer^ owner, MediaElement^ mediaElement)
00026     :  FrameworkElementAutomationPeer(owner)
00027 {
00028     _mediaElement = mediaElement;
00029 }
00030
00031
00032 Scenario3::Scenario3()
00033 {
00034     InitializeComponent();
00035     MediaElementContainer^ me = ref new MediaElementContainer(Scenario3Output);
00036     Windows::UI::Xaml::Automation::AutomationProperties::SetName(me, "CustomMediaElement");
00037
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 void Scenario3::OnNavigatedTo(NavigationEventArgs^ e)
00046 {
00047     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00048     // as NotifyUser()
00049     rootPage = MainPage::Current;
00050 }
00051
00052
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SimpleCommunication::App Member List

This is the complete list of members for SimpleCommunication::App, including all inherited members.
__pad0__ | SimpleCommunication::App |
OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^pArgs) override | SimpleCommunication::App | [virtual]
OnSuspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^pArgs) | SimpleCommunication::App | [virtual]
SetupWindowing(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^pArgs) | SimpleCommunication::App | [private]
Generated on Sat Nov 23 2024 16:09:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: LightSensor/C++/App.xaml.h Source File

  • LightSensor

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows account authorization/C++/Constants.cpp Source File

  • Windows account authorization

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully qualified name for the class that implements the scenario" }
00021     { "DELEGATION tickets", "SDKSample.MicrosoftAccount.DelegationTickets" },
00022 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Toast notifications/C#,C++/ScenarioInput1.xaml.cpp Source File

  • Toast notifications
  • C#,C++

ScenarioInput1.xaml.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 //
00009 // Scenario1Input.xaml.cpp
00010 // Implementation of the Scenario1Input class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioInput1.xaml.h"
00015
00016 using namespace ToastsSampleCPP;
00017
00018 using namespace NotificationsExtensions::ToastContent;
00019 using namespace Platform;
00020 using namespace Windows::Data::Xml::Dom;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Foundation::Collections;
00023 using namespace Windows::Graphics::Display;
00024 using namespace Windows::UI::Notifications;
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::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
00034 ScenarioInput1::ScenarioInput1()
00035 {
00036   InitializeComponent();
00037
00038   Scenario1DisplayToastText01->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00039     Scenario1DisplayToast(ToastTemplateType::ToastText01);
00040   });
00041   Scenario1DisplayToastText02->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00042     Scenario1DisplayToast(ToastTemplateType::ToastText02);
00043   });
00044
00045   Scenario1DisplayToastText03->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00046     Scenario1DisplayToast(ToastTemplateType::ToastText03);
00047   });
00048
00049   Scenario1DisplayToastText04->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00050     Scenario1DisplayToast(ToastTemplateType::ToastText04);
00051   });
00052
00053   Scenario1DisplayToastText01String->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00054     Scenario1DisplayToastWithStringManipulation(ToastTemplateType::ToastText01);
00055   });
00056   Scenario1DisplayToastText02String->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00057     Scenario1DisplayToastWithStringManipulation(ToastTemplateType::ToastText02);
00058   });
00059
00060   Scenario1DisplayToastText03String->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00061     Scenario1DisplayToastWithStringManipulation(ToastTemplateType::ToastText03);
00062   });
00063
00064   Scenario1DisplayToastText04String->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00065     Scenario1DisplayToastWithStringManipulation(ToastTemplateType::ToastText04);
00066   });
00067 }
00068
00069 ScenarioInput1::~ScenarioInput1()
00070 {
00071 }
00072
00073 #pragma region Template-Related Code - Do not remove
00074 void ScenarioInput1::OnNavigatedTo(NavigationEventArgs^ e)
00075 {
00076   // Get a pointer to our main page.
00077   rootPage = dynamic_cast<MainPage^>(e->Parameter);
00078 }
00079
00080 void ScenarioInput1::OnNavigatedFrom(NavigationEventArgs^ e)
00081 {
00082 }
00083
00084 #pragma endregion
00085
00086 void ScenarioInput1::OutputText(String^ text) {
00087   if (outputText == nullptr)
00088   {
00089     // Get a pointer to the content within the OutputFrame.
00090     Page^ outputFrame = dynamic_cast<Page^>(rootPage->OutputFrame->Content);
00091
00092     // Go find the elements that we need for this scenario
00093     outputText = dynamic_cast<TextBlock^>(outputFrame->FindName("Scenario1OutputText"));
00094   }
00095
00096   outputText->Text = text;
00097 }
00098
00099 void ScenarioInput1::Scenario1DisplayToast(ToastTemplateType templateType)
00100 {
00101   // Creates a toast using the notification object model, which is another project
00102   // in this solution.  For an example using Xml manipulation, see the function
00103   // DisplayToastUsingXmlManipulation below.
00104   IToastNotificationContent^ toastContent = nullptr;
00105
00106   if (templateType == ToastTemplateType::ToastText01)
00107   {
00108     IToastText01^ specializedContent = ToastContentFactory::CreateToastText01();
00109     specializedContent->TextBodyWrap->Text = "Body text that wraps over three lines";
00110     toastContent = specializedContent;
00111   }
00112   else if (templateType == ToastTemplateType::ToastText02)
00113   {
00114     IToastText02^ specializedContent = ToastContentFactory::CreateToastText02();
00115     specializedContent->TextHeading->Text = "Heading text";
00116     specializedContent->TextBodyWrap->Text = "Body text that wraps over two lines";
00117     toastContent = specializedContent;
00118   }
00119   else if (templateType == ToastTemplateType::ToastText03)
00120   {
00121     IToastText03^ specializedContent = ToastContentFactory::CreateToastText03();
00122     specializedContent->TextHeadingWrap->Text = "Heading text that is very long and wraps over two lines";
00123     specializedContent->TextBody->Text = "Body text";
00124     toastContent = specializedContent;
00125   }
00126   else if (templateType == ToastTemplateType::ToastText04)
00127   {
00128     IToastText04^ specializedContent = ToastContentFactory::CreateToastText04();
00129     specializedContent->TextHeading->Text = "Heading text";
00130     specializedContent->TextBody1->Text = "First body text";
00131     specializedContent->TextBody2->Text = "Second body text";
00132     toastContent = specializedContent;
00133   }
00134
00135     if (toastContent != nullptr)
00136     {
00137         OutputText(toastContent->GetContent());
00138         // Create a toast, then create a ToastNotifier object to show
00139         // the toast
00140         ToastNotification^ toast = toastContent->CreateNotification();
00141
00142         // If you have other applications in your package, you can specify the AppId of
00143         // the app to create a ToastNotifier for that application
00144         ToastNotificationManager::CreateToastNotifier()->Show(toast);
00145     }
00146 }
00147
00148 void ScenarioInput1::Scenario1DisplayToastWithStringManipulation(ToastTemplateType templateType)
00149 {
00150   String^ toastXmlString = nullptr;
00151   if (templateType == ToastTemplateType::ToastText01)
00152   {
00153     toastXmlString = "<toast>"
00154       + "<visual version='1'>"
00155       + "<binding template='ToastText01'>"
00156       + "<text id='1'>Body text that wraps over three lines</text>"
00157       + "</binding>"
00158       + "</visual>"
00159       + "</toast>";
00160   }
00161   else if (templateType == ToastTemplateType::ToastText02)
00162   {
00163     toastXmlString = "<toast>"
00164       + "<visual version='1'>"
00165       + "<binding template='ToastText02'>"
00166       + "<text id='1'>Heading text</text>"
00167       + "<text id='2'>Body text that wraps over two lines</text>"
00168       + "</binding>"
00169       + "</visual>"
00170       + "</toast>";
00171   }
00172   else if (templateType == ToastTemplateType::ToastText03)
00173   {
00174     toastXmlString = "<toast>"
00175       + "<visual version='1'>"
00176       + "<binding template='ToastText03'>"
00177       + "<text id='1'>Heading text that is very long and wraps over two lines</text>"
00178       + "<text id='2'>Body text</text>"
00179       + "</binding>"
00180       + "</visual>"
00181       + "</toast>";
00182   }
00183   else if (templateType == ToastTemplateType::ToastText04)
00184   {
00185     toastXmlString = "<toast>"
00186       + "<visual version='1'>"
00187       + "<binding template='ToastText04'>"
00188       + "<text id='1'>Heading text</text>"
00189       + "<text id='2'>First body text</text>"
00190       + "<text id='3'>Second body text</text>"
00191       + "</binding>"
00192       + "</visual>"
00193       + "</toast>";
00194   }
00195
00196   auto toastDOM = ref new Windows::Data::Xml::Dom::XmlDocument();
00197   toastDOM->LoadXml(toastXmlString);
00198
00199   OutputText(toastDOM->GetXml());
00200
00201   // Create a toast, then create a ToastNotifier object to show
00202   // the toast
00203   auto toast = ref new ToastNotification(toastDOM);
00204
00205   // If you have other applications in your package, you can specify the AppId of
00206   // the app to create a ToastNotifier for that application
00207   ToastNotificationManager::CreateToastNotifier()->Show(toast);
00208 }
Generated on Sat Nov 23 2024 16:07:59 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Custom driver access/C#,C++/DLL/fx2device.cpp Source File

  • Custom driver access
  • C#,C++
  • DLL

fx2device.cpp

Go to the documentation of this file.
00001 ﻿#include "fx2device.h"
00002
00003 Fx2Device::Fx2Device(_In_ IDeviceIoControl* DeviceControl, _In_ String^ Id) : m_DeviceIoControl(DeviceControl),
00004                                                                               m_Id(Id) {
00005     OutputDebugString(L"Fx2 constructor invoked\n");
00006     return;
00007 }
00008
00009 Fx2Device::~Fx2Device ()
00010 {
00011     OutputDebugString(L"Fx2Device destructor invoked\n");
00012     return;
00013 }
00014
00015 String^
00016 Fx2Device::GetDeviceSelector()
00017 {
00018     return L"System.Devices.InterfaceClassGuid:=\"{573E8C73-0CB4-4471-A1BF-FAB26C31D384}\" AND "
00019            L"System.Devices.InterfaceEnabled:=System.StructuredQueryType.Boolean#True";
00020 }
00021
00022 Fx2Device^
00023 Fx2Device::FromId(
00024     _In_ String^ InstancePath
00025     )
00026 {
00027     ComPtr<ICreateDeviceAccessAsync> access;
00028     ComPtr<IDeviceIoControl> deviceControl;
00029     HRESULT hr;
00030
00031     hr = CreateDeviceAccessInstance(InstancePath->Data(),
00032                                     GENERIC_READ | GENERIC_WRITE,
00033                                     &access);
00034     THROW_HR(hr);
00035
00036     //
00037     // Wait on the open
00038     //
00039
00040     hr = access->Wait(INFINITE);
00041     THROW_HR(hr);
00042
00043     hr = access->GetResult(IID_PPV_ARGS(&deviceControl));
00044     THROW_HR(hr);
00045
00046     OutputDebugStringW(L"Creating device\n");
00047
00048     //
00049     // Create an instance of the class and initialize it.
00050     //
00051     return ref new Fx2Device(deviceControl.Get(), InstancePath);
00052 }
00053
00054 String^
00055 Fx2Device::Id::get(void) {
00056     return m_Id;
00057 }
00058
00059 BYTE
00060 Fx2Device::SevenSegmentDisplay::get(VOID) {
00061
00062     BYTE ssValue = 0;
00063     ULONG numBytesReturned;
00064     HRESULT hr;
00065
00066     hr = m_DeviceIoControl->DeviceIoControlSync(
00067             IOCTL_OSRUSBFX2_GET_7_SEGMENT_DISPLAY,
00068             NULL,
00069             0,
00070             &ssValue,
00071             sizeof(ssValue),
00072             &numBytesReturned
00073             );
00074     THROW_HR(hr);
00075
00076     for(int i = 0; i < c_SegmentMaskCe; i += 1) {
00077         if (ssValue == c_SegmentMask[i]) {
00078             return (BYTE) i;
00079         }
00080     }
00081
00082     throw ref new InvalidArgumentException(L"Seven segment display value is not between 0 and 9");
00083 }
00084
00085 void
00086 Fx2Device::SevenSegmentDisplay::set(
00087     _In_ BYTE Value
00088     )
00089 {
00090     BYTE ssValue;
00091     HRESULT hr;
00092     DWORD bytesRead;
00093
00094     if (Value >= c_SegmentMaskCe) {
00095         throw ref new InvalidArgumentException(L"Value must be between 0 and 9");
00096     }
00097
00098     ssValue = c_SegmentMask[Value];
00099
00100     hr = m_DeviceIoControl->DeviceIoControlSync(
00101         IOCTL_OSRUSBFX2_SET_7_SEGMENT_DISPLAY,
00102         &ssValue,
00103         sizeof(ssValue),
00104         NULL,
00105         0,
00106         &bytesRead
00107         );
00108     THROW_HR(hr);
00109 }
00110
00111 Array<bool>^
00112 Fx2Device::SwitchState::get(VOID) {
00113
00114     BYTE ssValue = 0;
00115     ULONG numBytesReturned;
00116     HRESULT hr;
00117
00118     hr = m_DeviceIoControl->DeviceIoControlSync(
00119             IOCTL_OSRUSBFX2_READ_SWITCHES,
00120             NULL,
00121             0,
00122             &ssValue,
00123             sizeof(ssValue),
00124             &numBytesReturned
00125             );
00126     THROW_HR(hr);
00127
00128     Array<bool>^ result = ref new Array<bool>(c_NumSwitches);
00129
00130     for(int i = 0; i < c_NumSwitches; i += 1) {
00131         result[i] = ((ssValue & (1 << i)) != 0);
00132     }
00133
00134     return result;
00135 }
00136
00137 void
00138 Fx2Device::SetBarGraphDisplay(
00139     _In_ const Array<bool>^ Values
00140     )
00141 {
00142     BAR_GRAPH_STATE state;
00143     int valuesCe = Values->Length;
00144     DWORD bytesRead;
00145
00146
00147     state.BarsAsUChar = 0;
00148     for(int i = 0; i < min(c_NumBarsInGraph, valuesCe); i += 1) {
00149         state.BarsAsUChar |= (Values[i] ? 1 : 0) << i;
00150     }
00151
00152     HRESULT hr = m_DeviceIoControl->DeviceIoControlSync(
00153         IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY,
00154         (PBYTE) &state,
00155         sizeof(state),
00156         NULL,
00157         0,
00158         &bytesRead
00159         );
00160
00161     THROW_HR(hr);
00162 }
00163
00164 EventRegistrationToken
00165 Fx2Device::SwitchStateChanged::add(
00166     __in SwitchStateChangedHandler^ h
00167     )
00168 {
00169     EventRegistrationToken t = m_SwitchStateChangedEvent::add(h);
00170
00171     if (InterlockedIncrement(&m_SwitchState.ListenerCount) == 1) {
00172         m_SwitchState.Repeater.Start(
00173             [this](cancellation_token cancelToken, task_continuation_context& context) {
00174
00175                 // register for cancellation and abort the IOCTL if it happens
00176                 auto cancelTokenRegistration = cancelToken.register_callback([=]() {
00177                     m_DeviceIoControl->CancelOperation(m_SwitchState.CancelContext);
00178                 });
00179
00180                 // Create a task chain.  Send an ioctl to get the next switch
00181                 // state change.  Chain a task to convert that into the switch
00182                 // change event.
00183                 auto op =
00184                 StartIoctl(m_DeviceIoControl.Get(),
00185                             IOCTL_OSRUSBFX2_GET_INTERRUPT_MESSAGE,
00186                             NULL,
00187                             0,
00188                             (PBYTE) &m_SwitchState.Buffer,
00189                             sizeof(m_SwitchState.Buffer),
00190                             &m_SwitchState.CancelContext).
00191                 then([=](DeviceControlResult dcr) {
00192
00193                     bool abort = false;
00194                     SwitchStateChangedEventArgs^ e = nullptr;
00195
00196                     // unregister for cancellation
00197                     cancelToken.deregister_callback(cancelTokenRegistration);
00198
00199                     if (dcr.Result == HRESULT_FROM_WIN32(ERROR_OPERATION_ABORTED)) {
00200                         // fall through for cancellation
00201                         abort = true;
00202                     } else if (dcr.Result != S_OK) {
00203                         // Update the error count.  If it exceeds our limit then abort
00204                         // the reader.
00205                         m_SwitchState.FailureCount += 1;
00206                         if (m_SwitchState.FailureCount > 10) {
00207                             e = ref new SwitchStateChangedEventArgs(dcr.Result);
00208                             abort = true;
00209                         }
00210                     } else {
00211                         // Success.  Reset the failure count.
00212                         e = ref new SwitchStateChangedEventArgs(m_SwitchState.Buffer);
00213                         m_SwitchState.FailureCount = 0;
00214                     }
00215
00216                     // Raise the event if appropriate.
00217                     if (e != nullptr) {
00218                         m_SwitchStateChangedEvent(this, e);
00219                     }
00220
00221                     return !abort;
00222                 }, context);    // Since this task raises an event back to javascript
00223                                 // it must run in the context of the original call to
00224                                 // start the Repeater (which was from the UI thread)
00225
00226                 // Return the task chain.  The repeater will run this each
00227                 // time it starts an I/O operation, and takes care of starting
00228                 // the next task
00229                 return op;
00230             }
00231         );
00232     }
00233     return t;
00234 }
00235
00236 void
00237 Fx2Device::SwitchStateChanged::remove(
00238     __in EventRegistrationToken cookie
00239     )
00240 {
00241     m_SwitchStateChangedEvent::remove(cookie);
00242
00243     if (InterlockedDecrement(&m_SwitchState.ListenerCount) == 0) {
00244         m_SwitchState.Repeater.Stop();
00245     }
00246 }
00247
00248 IAsyncOperation<BarGraphDisplayResult^>^ Fx2Device::GetBarGraphDisplayAsync(void) {
00249
00250     // create an async operation object and return it to the caller.  The lambda
00251     // provided is the Start function for the operation, and returns a chain of tasks
00252     // that eventually provides the BarGraphDisplayResult^ object to the caller.
00253
00254     return create_async([this](cancellation_token cancelToken) {
00255
00256         // create the final result object, which we use to store the response
00257         // from the driver.
00258         BarGraphDisplayResult^ bgr = ref new BarGraphDisplayResult();
00259
00260         // Hook up cancellation using the cancel_token.
00261         auto registrationToken = cancelToken.register_callback([this, bgr]() {
00262             ULONG_PTR t = *(bgr->GetCancelToken());
00263             if (t != 0) {
00264                 m_DeviceIoControl->CancelOperation(t);
00265             }
00266         });
00267
00268         // StartIoctl returns a task that completes when the IOCTL completes.
00269         // Attach a follow-on task to convert the IOCTL results into bar graph
00270         // results.
00271         auto taskChain =
00272             StartIoctl(this->m_DeviceIoControl.Get(),
00273                        IOCTL_OSRUSBFX2_GET_BAR_GRAPH_DISPLAY,
00274                        nullptr,
00275                        0,
00276                        (PUCHAR) &(bgr->m_State),
00277                        sizeof(bgr->m_State),
00278                        bgr->GetCancelToken()).
00279             then([bgr,cancelToken,registrationToken](DeviceControlResult result) {
00280                 cancelToken.deregister_callback(registrationToken);
00281                 if ((result.Result == S_OK) &&
00282                     (result.BytesTransferred != sizeof(BAR_GRAPH_STATE))) {
00283                     result.Result = E_FAIL;
00284                 }
00285
00286                 if (result.Result != S_OK) {
00287                     throw Platform::Exception::CreateException(result.Result, L"Error getting bar graph display");
00288                 }
00289
00290                 bgr->UpdateBars();
00291                 return bgr;
00292             });
00293
00294         return taskChain;
00295     });
00296 }
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

D2DFactoryLock Member List

This is the complete list of members for D2DFactoryLock, including all inherited members.
D2DFactoryLock(_In_ ID2D1Factory *d2dFactory) | D2DFactoryLock | [inline]
m_d2dMultithread | D2DFactoryLock | [private]
~D2DFactoryLock() | D2DFactoryLock | [inline]
Generated on Sat Nov 23 2024 16:09:10 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::MediaCapture::sealed Member List

This is the complete list of members for SDKSample::MediaCapture::sealed, including all inherited members.
AddEffectToImageStream() | SDKSample::MediaCapture::sealed | [private]
AdvancedCapture() | SDKSample::MediaCapture::sealed |
AudioCapture() | SDKSample::MediaCapture::sealed |
BasicCapture() | SDKSample::MediaCapture::sealed |
btnStartDevice_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::MediaCapture::sealed | [private]
btnStartDevice_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::MediaCapture::sealed | [private]
btnStartDevice_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::MediaCapture::sealed | [private]
btnStartPreview_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::MediaCapture::sealed | [private]
btnStartPreview_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::MediaCapture::sealed | [private]
btnStartPreview_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::MediaCapture::sealed | [private]
btnStartStopRecord_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::MediaCapture::sealed | [private]
btnStartStopRecord_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::MediaCapture::sealed | [private]
btnStartStopRecord_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::MediaCapture::sealed | [private]
btnTakePhoto_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::MediaCapture::sealed | [private]
btnTakePhoto_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::MediaCapture::sealed | [private]
chkAddRemoveEffect_Checked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::MediaCapture::sealed | [private]
chkAddRemoveEffect_Unchecked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::MediaCapture::sealed | [private]
DisplayProperties_OrientationChanged(Platform::Object^sender) | SDKSample::MediaCapture::sealed | [private]
EnableButton(bool enabled, Platform::String^name) | SDKSample::MediaCapture::sealed | [private]
EnableButton(bool enabled, Platform::String^name) | SDKSample::MediaCapture::sealed | [private]
EnableButton(bool enabled, Platform::String^name) | SDKSample::MediaCapture::sealed | [private]
EnumerateWebcamsAsync() | SDKSample::MediaCapture::sealed | [private]
Failed(Windows::Media::Capture::MediaCapture^mediaCapture, Windows::Media::Capture::MediaCaptureFailedEventArgs^args) | SDKSample::MediaCapture::sealed | [private]
Failed(Windows::Media::Capture::MediaCapture^mediaCapture, Windows::Media::Capture::MediaCaptureFailedEventArgs^args) | SDKSample::MediaCapture::sealed | [private]
Failed(Windows::Media::Capture::MediaCapture^mediaCapture, Windows::Media::Capture::MediaCaptureFailedEventArgs^args) | SDKSample::MediaCapture::sealed | [private]
GetCurrentPhotoRotation() | SDKSample::MediaCapture::sealed | [private]
lstEnumedDevices_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | SDKSample::MediaCapture::sealed | [private]
m_bEffectAdded | SDKSample::MediaCapture::sealed | [private]
m_bEffectAddedToPhoto | SDKSample::MediaCapture::sealed | [private]
m_bEffectAddedToRecord | SDKSample::MediaCapture::sealed | [private]
m_bPreviewing | SDKSample::MediaCapture::sealed | [private]
m_bRecording | SDKSample::MediaCapture::sealed | [private]
m_bReversePreviewRotation | SDKSample::MediaCapture::sealed | [private]
m_bRotateVideoOnOrientationChange | SDKSample::MediaCapture::sealed | [private]
m_bSuspended | SDKSample::MediaCapture::sealed | [private]
m_currentScenarioLoaded | SDKSample::MediaCapture::sealed | [private]
m_devInfoCollection | SDKSample::MediaCapture::sealed | [private]
m_eventRegistrationToken | SDKSample::MediaCapture::sealed | [private]
m_mediaCaptureMgr | SDKSample::MediaCapture::sealed | [private]
m_orientationChangedEventToken | SDKSample::MediaCapture::sealed | [private]
m_photoStorageFile | SDKSample::MediaCapture::sealed | [private]
m_recordStorageFile | SDKSample::MediaCapture::sealed | [private]
m_visbilityHandler | SDKSample::MediaCapture::sealed | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::MediaCapture::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::MediaCapture::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::MediaCapture::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::MediaCapture::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::MediaCapture::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::MediaCapture::sealed | [protected, virtual]
PhotoRotationLookup(Windows::Graphics::Display::DisplayOrientations displayOrientation, bool counterclockwise) | SDKSample::MediaCapture::sealed | [private]
PrepareForVideoRecording() | SDKSample::MediaCapture::sealed | [private]
RecordLimitationExceeded(Windows::Media::Capture::MediaCapture^mediaCapture) | SDKSample::MediaCapture::sealed | [private]
RecordLimitationExceeded(Windows::Media::Capture::MediaCapture^mediaCapture) | SDKSample::MediaCapture::sealed | [private]
RecordLimitationExceeded(Windows::Media::Capture::MediaCapture^mediaCapture) | SDKSample::MediaCapture::sealed | [private]
ReencodePhotoAsync(Windows::Storage::StorageFile^tempStorageFile, Windows::Storage::FileProperties::PhotoOrientation photoRotation) | SDKSample::MediaCapture::sealed | [private]
Resuming(Object^sender, Object^e) | SDKSample::MediaCapture::sealed | [private]
rootPage | SDKSample::MediaCapture::sealed | [private]
ScenarioInit() | SDKSample::MediaCapture::sealed | [private]
ScenarioInit() | SDKSample::MediaCapture::sealed | [private]
ScenarioInit() | SDKSample::MediaCapture::sealed | [private]
ScenarioReset() | SDKSample::MediaCapture::sealed | [private]
ScenarioReset() | SDKSample::MediaCapture::sealed | [private]
ScenarioReset() | SDKSample::MediaCapture::sealed | [private]
SetupVideoDeviceControl(Windows::Media::Devices::MediaDeviceControl^videoDeviceControl, Slider^slider) | SDKSample::MediaCapture::sealed | [private]
ShowExceptionMessage(Platform::Exception^ex) | SDKSample::MediaCapture::sealed | [private]
ShowExceptionMessage(Platform::Exception^ex) | SDKSample::MediaCapture::sealed | [private]
ShowExceptionMessage(Platform::Exception^ex) | SDKSample::MediaCapture::sealed | [private]
ShowStatusMessage(Platform::String^text) | SDKSample::MediaCapture::sealed | [private]
ShowStatusMessage(Platform::String^text) | SDKSample::MediaCapture::sealed | [private]
ShowStatusMessage(Platform::String^text) | SDKSample::MediaCapture::sealed | [private]
sldBrightness_ValueChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^e) | SDKSample::MediaCapture::sealed | [private]
sldContrast_ValueChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^e) | SDKSample::MediaCapture::sealed | [private]
SoundLevelChanged(Object^sender, Object^e) | SDKSample::MediaCapture::sealed | [private]
SoundLevelChanged(Object^sender, Object^e) | SDKSample::MediaCapture::sealed | [private]
SoundLevelChanged(Object^sender, Object^e) | SDKSample::MediaCapture::sealed | [private]
Suspending(Object^sender, Windows::ApplicationModel::SuspendingEventArgs^e) | SDKSample::MediaCapture::sealed | [private]
SwitchRecordButtonContent() | SDKSample::MediaCapture::sealed | [private]
SwitchRecordButtonContent() | SDKSample::MediaCapture::sealed | [private]
SwitchRecordButtonContent() | SDKSample::MediaCapture::sealed | [private]
VideoRotationLookup(Windows::Graphics::Display::DisplayOrientations displayOrientation, bool counterclockwise) | SDKSample::MediaCapture::sealed | [private]
Generated on Sat Nov 23 2024 16:09:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Network status background/C++/NetworkStatusApp/Constants.h Source File

  • Network status background
  • NetworkStatusApp

Constants.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 "NetworkStatusTask.BackgroundTask"
00020 #define SampleBackgroundTaskWithConditionName "SampleBackgroundTaskWithCondition"
00021
00022 namespace SDKSample
00023 {
00024     public value struct Scenario
00025     {
00026         Platform::String^ Title;
00027         Platform::String^ ClassName;
00028     };
00029
00030     partial ref class MainPage
00031     {
00032     public:
00033         static property Platform::String^ FEATURE_NAME
00034         {
00035             Platform::String^ get()
00036             {
00037                 return ref new Platform::String(L"Network Status");
00038             }
00039         }
00040
00041         static property Platform::Array<Scenario>^ scenarios
00042         {
00043             Platform::Array<Scenario>^ get()
00044             {
00045                 return scenariosInner;
00046             }
00047         }
00048     private:
00049         static Platform::Array<Scenario>^ scenariosInner;
00050     };
00051
00052     class BackgroundTaskSample
00053     {
00054     public:
00055         static BackgroundTaskRegistration^ RegisterBackgroundTask(String^ taskEntryPoint, String^ name, IBackgroundTrigger^ trigger, IBackgroundCondition^ condition);
00056         static void UnregisterBackgroundTasks(String^ name);
00057         static void UpdateBackgroundTaskStatus(Platform::String^ name, bool registered);
00058
00059         static bool SampleBackgroundTaskWithConditionRegistered;
00060     };
00061
00062 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Credential picker/C++/MainPage.xaml.cpp Source File

  • Credential picker

MainPage.xaml.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 //
00009 // MainPage.xaml.cpp
00010 // Implementation of the MainPage.xaml class.
00011 //
00012
00013 #include "pch.h"
00014 #include "MainPage.xaml.h"
00015 #include "App.xaml.h"
00016
00017 using namespace Windows::UI::Xaml;
00018 using namespace Windows::UI::Xaml::Controls;
00019 using namespace Windows::UI::Xaml::Data;
00020 using namespace Windows::UI::Core;
00021 using namespace Windows::System;
00022 using namespace Windows::Foundation;
00023 using namespace Platform;
00024 using namespace CredentialPickerCPP;
00025 using namespace CppSamplesUtils;
00026 using namespace Windows::UI::Xaml::Navigation;
00027 using namespace Windows::UI::Xaml::Interop;
00028 using namespace Windows::Graphics::Display;
00029 using namespace Windows::UI::ViewManagement;
00030 using namespace Windows::ApplicationModel::Core;
00031
00032 MainPage::MainPage()
00033 {
00034     InitializeComponent();
00035
00036     SetFeatureName("CredentialPicker C++ Sample");
00037
00038     _scenariosFrame = ScenarioList;
00039     _inputFrame = ScenarioInput;
00040     _outputFrame = ScenarioOutput;
00041
00042     _layoutHandlerToken = Window::Current->SizeChanged += ref new Windows::UI::Xaml::WindowSizeChangedEventHandler(this, &MainPage::Page_SizeChanged);
00043
00044     _pageLoadedHandlerToken = Loaded += ref new RoutedEventHandler(this, &MainPage::Page_Loaded);
00045     _logicalDpiChangedToken = DisplayProperties::LogicalDpiChanged += ref new DisplayPropertiesEventHandler(this, &MainPage::DisplayProperties_LogicalDpiChanged);
00046 }
00047
00048 MainPage::~MainPage()
00049 {
00050 }
00051
00052 void MainPage::Page_Loaded(Object^ sender, RoutedEventArgs^ e)
00053 {
00054     // Load the ScenarioList page into the proper frame
00055     TypeName pageType = { "CredentialPickerCPP.ScenarioList", TypeKind::Custom };
00056     ScenarioList->Navigate(pageType, this);
00057
00058     // Figure out what resolution and orientation we are in and respond appropriately.
00059     CheckResolutionAndViewState();
00060 }
00061
00062 void MainPage::SetFeatureName(String^ strFeature)
00063 {
00064     FeatureName->Text = strFeature;
00065 }
00066
00067 void MainPage::Page_SizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00068 {
00069     CheckResolutionAndViewState();
00070 }
00071
00072 void MainPage::DisplayProperties_LogicalDpiChanged(Object^ sender)
00073 {
00074     CheckResolutionAndViewState();
00075 }
00076
00077 void MainPage::CheckResolutionAndViewState()
00078 {
00079     ApplicationViewState state = ApplicationView::Value;
00080     String^ stateString = ConvertViewState(state);
00081
00082     ResolutionScale scale = DisplayProperties::ResolutionScale;
00083     String^ scaleString = ConvertResolution(scale);
00084
00085     VisualStateManager::GoToState(this, stateString + scaleString, false);
00086 }
00087
00088 String^ MainPage::ConvertViewState(ApplicationViewState state)
00089 {
00090     switch(state)
00091     {
00092     case ApplicationViewState::Filled:
00093         return "Filled";
00094     case ApplicationViewState::FullScreenLandscape:
00095         return "FullScreenLandscape";
00096     case ApplicationViewState::FullScreenPortrait:
00097         return "FullScreenPortrait";
00098     case ApplicationViewState::Snapped:
00099         return "Snapped";
00100     }
00101     return "";
00102 }
00103
00104 String^ MainPage::ConvertResolution(ResolutionScale scale)
00105 {
00106     switch(scale)
00107     {
00108     case ResolutionScale::Scale100Percent:
00109         return "Scale100Percent";
00110     case ResolutionScale::Scale140Percent:
00111         return "Scale140Percent";
00112     case ResolutionScale::Scale180Percent:
00113         return "Scale180Percent";
00114     }
00115     return "";
00116 }
00117
00118 void MainPage::DoNavigation(TypeName inPageType, Windows::UI::Xaml::Controls::Frame^ inFrame, TypeName outPageType, Windows::UI::Xaml::Controls::Frame^ outFrame)
00119 {
00120     inFrame->Navigate(inPageType, this);
00121     outFrame->Navigate(outPageType, this);
00122
00123     // Raise OutputFrameLoaded so downstream pages know that the output frame content has been loaded
00124     OutputFrameLoaded(this, nullptr);
00125     // Raise InputFrameLoaded so downstream pages know that the input frame content has been loaded
00126     InputFrameLoaded(this, nullptr);
00127 }
00128
00129 void MainPage::NotifyUserFromAsyncThread(String^ strMessage, NotifyType type)
00130 {
00131     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, strMessage, type] ()
00132     {
00133         NotifyUser(strMessage, type);
00134     }, CallbackContext::Any));
00135 }
00136
00137 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00138 {
00139     switch (type)
00140     {
00141     case NotifyType::StatusMessage:
00142         StatusBlock->Style = dynamic_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00143         break;
00144     case NotifyType::ErrorMessage:
00145         StatusBlock->Style = dynamic_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00146         break;
00147     default:
00148         break;
00149     }
00150     StatusBlock->Text = strMessage;
00151 }
00152
00153 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00154 {
00155     auto _hyperlinkButton = (HyperlinkButton^)sender;
00156     auto uri = ref new Windows::Foundation::Uri((String^)_hyperlinkButton->Tag);
00157
00158     Windows::System::Launcher::LaunchUriAsync(uri);
00159 }
Generated on Sat Nov 23 2024 16:07:41 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C#,C++/ScenarioOutput3.xaml.cs Source File

  • Media extensions
  • C#,C++

ScenarioOutput3.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 System;
00009 using System.Linq;
00010 using System.Collections.Generic;
00011 using Windows.Foundation;
00012 using Windows.Foundation.Collections;
00013 using Windows.Graphics.Display;
00014 using Windows.UI.ViewManagement;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Controls.Primitives;
00018 using Windows.UI.Xaml.Data;
00019 using Windows.UI.Xaml.Input;
00020 using Windows.UI.Xaml.Media;
00021 using Windows.UI.Xaml.Navigation;
00022 using SDKTemplateCS;
00023
00024 namespace MediaExtensionsCS
00025 {
00026     public sealed partial class ScenarioOutput3 : Page
00027     {
00028         // A pointer back to the main page which is used to gain access to the input and output frames and their content
00029         MainPage rootPage = null;
00030
00031         public ScenarioOutput3()
00032         {
00033             InitializeComponent();
00034         }
00035
00036         #region Template-Related Code - Do not remove
00037         protected override void OnNavigatedTo(NavigationEventArgs e)
00038         {
00039             // Get a pointer to our main page.
00040             rootPage = e.Parameter as MainPage;
00041
00042             Video.MediaFailed += new ExceptionRoutedEventHandler(rootPage.VideoOnError);
00043             VideoStabilized.MediaFailed += new ExceptionRoutedEventHandler(rootPage.VideoOnError);
00044         }
00045
00046         protected override void OnNavigatedFrom(NavigationEventArgs e)
00047         {
00048             Video.MediaFailed -= new ExceptionRoutedEventHandler(rootPage.VideoOnError);
00049             VideoStabilized.MediaFailed -= new ExceptionRoutedEventHandler(rootPage.VideoOnError);
00050             Video.Source = null;
00051             VideoStabilized.Source = null;
00052         }
00053         #endregion
00054     }
00055 }
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML data binding/C++/Constants.h Source File

  • XAML data binding

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"XAML data binding sample");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044
00045
00046 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D-Direct2D interop/C++/BasicReaderWriter.h Source File

  • Direct3D-Direct2D interop

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     Platform::String^ m_locationPath;
00019
00020 internal:
00021     BasicReaderWriter();
00022     BasicReaderWriter(
00023         _In_ Windows::Storage::StorageFolder^ folder
00024         );
00025
00026     Platform::Array<byte>^ ReadData(
00027         _In_ Platform::String^ filename
00028         );
00029
00030     concurrency::task<Platform::Array<byte>^> ReadDataAsync(
00031         _In_ Platform::String^ filename
00032         );
00033
00034     uint32 WriteData(
00035         _In_ Platform::String^ filename,
00036         _In_ const Platform::Array<byte>^ fileData
00037         );
00038
00039     concurrency::task<void> WriteDataAsync(
00040         _In_ Platform::String^ filename,
00041         _In_ const Platform::Array<byte>^ fileData
00042         );
00043 };
Generated on Sat Nov 23 2024 16:08:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text editing/C++/Scenario1.xaml.h Source File

  • XAML text editing

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 SDKSample
00023 {
00024     namespace TextEditing
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 Scenario1 sealed
00031         {
00032         public:
00033             Scenario1();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040             void Other_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         };
00042     }
00043 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DirectX::Image Member List

This is the complete list of members for DirectX::Image, including all inherited members.
format | DirectX::Image
height | DirectX::Image
pixels | DirectX::Image
rowPitch | DirectX::Image
slicePitch | DirectX::Image
width | DirectX::Image
Generated on Sat Nov 23 2024 16:09:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Animation metrics/C++/Scenario1.xaml.cpp Source File

  • Animation metrics

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::AnimationMetrics;
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::UI::Core::AnimationMetrics;
00025
00026 Scenario1::Scenario1()
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 Scenario1::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 double TimeSpanToMilliseconds(Windows::Foundation::TimeSpan timeSpan)
00044 {
00045     return timeSpan.Duration / 10000.0f;
00046 }
00047
00048 void Scenario1::DisplayMetrics(AnimationEffect effect, AnimationEffectTarget target)
00049 {
00050     std::wostringstream ss;
00051     AnimationDescription^ animationDescription = ref new AnimationDescription(effect, target);
00052     ss << "Stagger delay = " << TimeSpanToMilliseconds(animationDescription->StaggerDelay) << "ms" << std::endl;
00053     ss << "Stagger delay factor = " << animationDescription->StaggerDelayFactor << std::endl;
00054     ss << "Delay limit = " << TimeSpanToMilliseconds(animationDescription->DelayLimit) << "ms" << std::endl;
00055     ss << "ZOrder = " << animationDescription->ZOrder << std::endl;
00056     ss << std::endl;
00057     auto animations = animationDescription->Animations;
00058     for (unsigned int i = 0; i < animations->Size; i++)
00059     {
00060         ss << "Animation #" << (i + 1) << ":" << std::endl;
00061         IPropertyAnimation^ animation = animations->GetAt(i);
00062         switch (animation->Type)
00063         {
00064         case PropertyAnimationType::Scale:
00065             {
00066                 ScaleAnimation^ scale = dynamic_cast<ScaleAnimation^>(animation);
00067                 ss << "Type = Scale" << std::endl;
00068                 if (scale->InitialScaleX != nullptr)
00069                 {
00070                     ss << "InitialScaleX = " << scale->InitialScaleX->Value << std::endl;
00071                 }
00072                 if (scale->InitialScaleY != nullptr)
00073                 {
00074                     ss << "InitialScaleY = " << scale->InitialScaleY->Value << std::endl;
00075                 }
00076                 ss << "FinalScaleX = " << scale->FinalScaleX << std::endl;
00077                 ss << "FinalScaleY = " << scale->FinalScaleY << std::endl;
00078                 ss << "Origin = " << scale->NormalizedOrigin.X << ", " << scale->NormalizedOrigin.Y << std::endl;
00079             }
00080             break;
00081         case PropertyAnimationType::Translation:
00082                 ss << "Type = Translation" << std::endl;
00083             break;
00084         case PropertyAnimationType::Opacity:
00085             {
00086                 OpacityAnimation^ opacity = dynamic_cast<OpacityAnimation^>(animation);
00087                 ss << "Type = Opacity" << std::endl;
00088                 if (opacity->InitialOpacity != nullptr)
00089                 {
00090                     ss << "InitialOpacity = " << opacity->InitialOpacity->Value << std::endl;
00091                 }
00092                 ss << "FinalOpacity = " << opacity->FinalOpacity << std::endl;
00093             }
00094             break;
00095         }
00096         ss << "Delay = " << TimeSpanToMilliseconds(animation->Delay) << "ms" << std::endl;
00097         ss << "Duration = " << TimeSpanToMilliseconds(animation->Duration) << "ms" << std::endl;
00098         ss << "Cubic Bezier control points" << std::endl;
00099         ss << "    X1 = " << animation->Control1.X << ", Y1 = " << animation->Control1.Y << std::endl;
00100         ss << "    X2 = " << animation->Control2.X << ", Y2 = " << animation->Control2.Y << std::endl;
00101         ss << std::endl;
00102     }
00103     std::wstring s = ss.str();
00104     auto str = ref new Platform::String(s.c_str());
00105     Metrics->Text = str;
00106 }
00107
00108 void Scenario1::Animations_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00109 {
00110     ListBoxItem^ selectedListBoxItem = dynamic_cast<ListBoxItem^>(Animations->SelectedItem);
00111     if (selectedListBoxItem == AddToListAdded)
00112     {
00113         DisplayMetrics(AnimationEffect::AddToList, AnimationEffectTarget::Added);
00114     }
00115     else if (selectedListBoxItem == AddToListAffected)
00116     {
00117         DisplayMetrics(AnimationEffect::AddToList, AnimationEffectTarget::Affected);
00118     }
00119     else if (selectedListBoxItem == EnterPage)
00120     {
00121         DisplayMetrics(AnimationEffect::EnterPage, AnimationEffectTarget::Primary);
00122     }
00123 }
00124
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media Server client/C++/MainPage.xaml.cpp Source File

  • Media Server client

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:42 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/BasicLoader.h Source File

  • XAML DirectX 3D shooting game

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 Sat Nov 23 2024 16:08:08 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML high contrast style/C++/pch.h Source File

  • XAML high contrast style

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D animation/C++/animation.h Source File

  • Direct2D animation

animation.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 <math.h>
00011
00012 /******************************************************************
00013 *                                                                 *
00014 * Base Animation Class                                            *
00015 *                                                                 *
00016 ******************************************************************/
00017
00018 template <class T>
00019 class Animation
00020 {
00021 public:
00022     Animation(T start, T end, T duration) :
00023         m_Start(start),
00024         m_End(end),
00025         m_Duration(duration)
00026     {
00027     }
00028
00029     void SetStart(T start)
00030     {
00031         m_Start = start;
00032     }
00033
00034     T GetStart()
00035     {
00036         return m_Start;
00037     }
00038
00039     void SetEnd(T end)
00040     {
00041         m_End = end;
00042     }
00043
00044     T GetEnd()
00045     {
00046         return m_End;
00047     }
00048
00049     void SetDuration(T duration)
00050     {
00051         m_Duration = max(0, duration);
00052     }
00053
00054     T GetDuration()
00055     {
00056         return m_Duration;
00057     }
00058
00059     T GetValue(T time)
00060     {
00061         time = min(max(time, 0), m_Duration);
00062         return ComputeValue(time);
00063     }
00064
00065 protected:
00066     virtual T ComputeValue(T time) = 0;
00067
00068     T m_Duration;
00069     T m_Start;
00070     T m_End;
00071 };
00072
00073 /******************************************************************
00074 *                                                                 *
00075 * Linearly Interpolate Between Start and End                      *
00076 *                                                                 *
00077 ******************************************************************/
00078
00079 template <class T>
00080 class LinearAnimation : public Animation<T>
00081 {
00082 public:
00083     LinearAnimation(T start = 0, T end = 0, T duration = 0) :
00084         Animation(start, end, duration)
00085     {
00086     }
00087 protected:
00088     virtual T ComputeValue(T time)
00089     {
00090         return m_Start + ((m_End - m_Start) * (time / m_Duration));
00091     }
00092 };
00093
00094 /******************************************************************
00095 *                                                                 *
00096 *                                                                 *
00097 *                                                                 *
00098 ******************************************************************/
00099
00100 template <class T>
00101 class EaseInExponentialAnimation : public Animation<T>
00102 {
00103 public:
00104     EaseInExponentialAnimation(T start = 0, T end = 0, T duration = 0) :
00105         Animation(start, end, duration)
00106     {
00107     }
00108 protected:
00109     T ComputeValue(T time)
00110     {
00111         return m_Start + (m_End - m_Start) * pow(2, 10 * (time/m_Duration - 1));
00112     }
00113 };
00114
00115 /******************************************************************
00116 *                                                                 *
00117 *                                                                 *
00118 *                                                                 *
00119 ******************************************************************/
00120
00121 template <class T>
00122 class EaseOutExponentialAnimation : public Animation<T>
00123 {
00124 public:
00125     EaseOutExponentialAnimation(T start = 0, T end = 0, T duration = 0) :
00126         Animation(start, end, duration)
00127     {
00128     }
00129 protected:
00130     T ComputeValue(T time)
00131     {
00132         return m_Start + (m_End - m_Start) * (-pow(2, -10 * time/m_Duration) + 1);
00133     }
00134 };
00135
00136 /******************************************************************
00137 *                                                                 *
00138 *                                                                 *
00139 *                                                                 *
00140 ******************************************************************/
00141
00142 template <class T>
00143 class EaseInOutExponentialAnimation : public Animation<T>
00144 {
00145 public:
00146     EaseInOutExponentialAnimation(T start = 0, T end = 0, T duration = 0) :
00147         Animation(start, end, duration)
00148     {
00149     }
00150 protected:
00151     T ComputeValue(T time)
00152     {
00153         // compute the current time relative to the midpoint
00154         time = time / (m_Duration / 2);
00155         // if we haven't reached the midpoint, we want to do the ease-in portion
00156         if (time < 1)
00157         {
00158             return m_Start + (m_End - m_Start)/2 * pow(2, 10 * (time - 1));
00159         }
00160         // otherwise, do the ease-out portion
00161         return m_Start + (m_End - m_Start)/2 * (-pow(2, -10 * --time) + 2);
00162     }
00163 };
00164
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D tutorial/C++/Lesson5.Components/BasicLoader.cpp Source File

  • Direct3D tutorial
  • Lesson5.Components

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 Sat Nov 23 2024 16:08:07 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/MediaExtensions/GeometricSource/pch.cpp Source File

  • Media extensions
  • MediaExtensions
  • GeometricSource

pch.cpp

Go to the documentation of this file.
00001 ﻿// pch.cpp : source file that includes just the standard includes
00002 //   pch.pch will be the pre-compiled header
00003 //   pch.obj will contain the pre-compiled type information
00004
00005 #include "StdAfx.h"
00006
00007 // TODO: reference any additional headers you need in PCH.H and not in this file
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C#,C++/ScenarioInput1.xaml.cs Source File

  • Media extensions
  • C#,C++

ScenarioInput1.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 System;
00009 using System.Linq;
00010 using System.Collections.Generic;
00011 using Windows.Foundation;
00012 using Windows.Foundation.Collections;
00013 using Windows.Graphics.Display;
00014 using Windows.UI.ViewManagement;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Controls.Primitives;
00018 using Windows.UI.Xaml.Data;
00019 using Windows.UI.Xaml.Input;
00020 using Windows.UI.Xaml.Media;
00021 using Windows.UI.Xaml.Navigation;
00022 using SDKTemplateCS;
00023
00024 namespace MediaExtensionsCS
00025 {
00026     public sealed partial class ScenarioInput1 : Page
00027     {
00028         private readonly Guid MFVideoFormat_MPG1 = Guid.Parse("3147504d-0000-0010-8000-00aa00389b71");
00029
00030         // A pointer back to the main page which is used to gain access to the input and output frames and their content.
00031         MainPage rootPage = null;
00032         MediaElement outputVideo;
00033
00034         public ScenarioInput1()
00035         {
00036             InitializeComponent();
00037         }
00038
00039         #region Template-Related Code - Do not remove
00040         protected override void OnNavigatedTo(NavigationEventArgs e)
00041         {
00042             // Get a pointer to our main page
00043             rootPage = e.Parameter as MainPage;
00044
00045             // We want to be notified with the OutputFrame is loaded so we can get to the content.
00046             rootPage.OutputFrameLoaded += new System.EventHandler(rootPage_OutputFrameLoaded);
00047
00048             rootPage.ExtensionManager.RegisterByteStreamHandler("MPEG1Source.MPEG1ByteStreamHandler", ".mpg", "video/mpeg");
00049             rootPage.ExtensionManager.RegisterVideoDecoder("MPEG1Decoder.MPEG1Decoder", MFVideoFormat_MPG1, Guid.Empty);
00050         }
00051
00052         protected override void OnNavigatedFrom(NavigationEventArgs e)
00053         {
00054             rootPage.OutputFrameLoaded -= new System.EventHandler(rootPage_OutputFrameLoaded);
00055         }
00056
00057         #endregion
00058
00059         #region Event handlers
00060         void rootPage_OutputFrameLoaded(object sender, object e)
00061         {
00062             // At this point, we know that the Output Frame has been loaded and we can go ahead
00063             // and reference elements in the page contained in the Output Frame.
00064
00065             // Get a pointer to the content within the OutputFrame.
00066             Page outputFrame = (Page)rootPage.OutputFrame.Content;
00067
00068             // Go find the elements that we need for this scenario.
00069             outputVideo = outputFrame.FindName("Video") as MediaElement;
00070         }
00071
00072         /// <summary>
00073         /// This is the click handler for the 'Open' button.
00074         /// </summary>
00075         /// <param name="sender"></param>
00076         /// <param name="e"></param>
00077         private void Open_Click(object sender, RoutedEventArgs e)
00078         {
00079             rootPage.PickSingleFileAndSet(new string[] { ".mpg" }, outputVideo);
00080         }
00081
00082
00083         /// <summary>
00084         /// This is the click handler for the 'Stop' button.
00085         /// </summary>
00086         /// <param name="sender"></param>
00087         /// <param name="e"></param>
00088         private void Stop_Click(object sender, RoutedEventArgs e)
00089         {
00090             outputVideo.Source = null;
00091         }
00092         #endregion
00093     }
00094 }
Generated on Sat Nov 23 2024 16:08:21 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DatagramSocket/C++/Constants.h Source File

  • DatagramSocket

Constants.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 namespace DatagramSocketSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"DatagramSocket");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

CppSamplesUtils::SuspensionManager Member List

This is the complete list of members for CppSamplesUtils::SuspensionManager, including all inherited members.
SessionState() | CppSamplesUtils::SuspensionManager | [inline, static]
SessionState() | CppSamplesUtils::SuspensionManager | [inline, static]
SessionState() | CppSamplesUtils::SuspensionManager | [inline, static]
SessionState() | CppSamplesUtils::SuspensionManager | [inline, static]
SessionState() | CppSamplesUtils::SuspensionManager | [inline, static]
SessionState() | CppSamplesUtils::SuspensionManager | [inline, static]
SessionState() | CppSamplesUtils::SuspensionManager | [inline, static]
SessionState() | CppSamplesUtils::SuspensionManager | [inline, static]
SessionState() | CppSamplesUtils::SuspensionManager | [inline, static]
SessionState() | CppSamplesUtils::SuspensionManager | [inline, static]
SessionState() | CppSamplesUtils::SuspensionManager | [inline, static]
SessionState() | CppSamplesUtils::SuspensionManager | [inline, static]
SessionState() | CppSamplesUtils::SuspensionManager | [inline, static]
SessionState() | CppSamplesUtils::SuspensionManager | [inline, static]
SessionState() | CppSamplesUtils::SuspensionManager | [inline, static]
SessionState() | CppSamplesUtils::SuspensionManager | [inline, static]
SessionState() | CppSamplesUtils::SuspensionManager | [inline, static]
SessionState() | CppSamplesUtils::SuspensionManager | [inline, static]
SessionState() | CppSamplesUtils::SuspensionManager | [inline, static]
SessionState() | CppSamplesUtils::SuspensionManager | [inline, static]
SessionState() | CppSamplesUtils::SuspensionManager | [inline, static]
SessionState() | CppSamplesUtils::SuspensionManager | [inline, static]
SessionState() | CppSamplesUtils::SuspensionManager | [inline, static]
SessionState() | CppSamplesUtils::SuspensionManager | [inline, static]
SessionState() | CppSamplesUtils::SuspensionManager | [inline, static]
SessionState() | CppSamplesUtils::SuspensionManager | [inline, static]
StartRestoreTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartRestoreTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartRestoreTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartRestoreTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartRestoreTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartRestoreTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartRestoreTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartRestoreTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartRestoreTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartRestoreTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartRestoreTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartRestoreTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartRestoreTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartRestoreTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartRestoreTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartRestoreTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartRestoreTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartRestoreTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartRestoreTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartRestoreTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartRestoreTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartRestoreTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartRestoreTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartRestoreTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartRestoreTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartRestoreTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartSaveTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartSaveTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartSaveTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartSaveTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartSaveTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartSaveTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartSaveTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartSaveTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartSaveTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartSaveTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartSaveTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartSaveTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartSaveTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartSaveTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartSaveTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartSaveTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartSaveTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartSaveTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartSaveTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartSaveTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartSaveTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartSaveTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartSaveTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartSaveTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartSaveTask() | CppSamplesUtils::SuspensionManager | [inline, static]
StartSaveTask() | CppSamplesUtils::SuspensionManager | [inline, static]
Generated on Sat Nov 23 2024 16:09:36 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::PlaybackManager2::sealed Member List

This is the complete list of members for SDKSample::PlaybackManager2::sealed, including all inherited members.
_playback | SDKSample::PlaybackManager2::sealed | [private]
AppMuted() | SDKSample::PlaybackManager2::sealed | [private]
AppUnmuted() | SDKSample::PlaybackManager2::sealed | [private]
Button_Pause_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::PlaybackManager2::sealed | [private]
Button_Play_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::PlaybackManager2::sealed | [private]
Button_Stop_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::PlaybackManager2::sealed | [private]
cw | SDKSample::PlaybackManager2::sealed | [private]
Default_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::PlaybackManager2::sealed | [private]
Default_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::PlaybackManager2::sealed | [private]
Default_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::PlaybackManager2::sealed | [private]
Default_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::PlaybackManager2::sealed | [private]
DisplayStatus(Platform::String^text) | SDKSample::PlaybackManager2::sealed | [private]
GetTimeStampedMessage(Platform::String^EventCalled) | SDKSample::PlaybackManager2::sealed | [private]
IsPlaying | SDKSample::PlaybackManager2::sealed | [private]
IsRegistered | SDKSample::PlaybackManager2::sealed | [private, static]
MediaControl_PausePressed(Platform::Object^sender, Platform::Object^e) | SDKSample::PlaybackManager2::sealed | [private]
MediaControl_PlayPauseTogglePressed(Platform::Object^sender, Platform::Object^e) | SDKSample::PlaybackManager2::sealed | [private]
MediaControl_PlayPressed(Platform::Object^sender, Platform::Object^e) | SDKSample::PlaybackManager2::sealed | [private]
MediaControl_SoundLevelChanged(Platform::Object^sender, Platform::Object^e) | SDKSample::PlaybackManager2::sealed | [private]
MediaControl_StopPressed(Platform::Object^sender, Platform::Object^e) | SDKSample::PlaybackManager2::sealed | [private]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::PlaybackManager2::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::PlaybackManager2::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::PlaybackManager2::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::PlaybackManager2::sealed | [protected, virtual]
Pause() | SDKSample::PlaybackManager2::sealed |
PausePressedToken | SDKSample::PlaybackManager2::sealed | [private, static]
Play() | SDKSample::PlaybackManager2::sealed |
PlaybackControl() | SDKSample::PlaybackManager2::sealed |
PlayPauseTogglePressedToken | SDKSample::PlaybackManager2::sealed | [private, static]
PlayPressedToken | SDKSample::PlaybackManager2::sealed | [private, static]
rootPage | SDKSample::PlaybackManager2::sealed | [private]
SelectFile() | SDKSample::PlaybackManager2::sealed |
SetAudioCategory(Windows::UI::Xaml::Media::AudioCategory category) | SDKSample::PlaybackManager2::sealed |
SetAudioDeviceType(Windows::UI::Xaml::Media::AudioDeviceType devicetype) | SDKSample::PlaybackManager2::sealed |
SoundLevelChangedToken | SDKSample::PlaybackManager2::sealed | [private, static]
SoundLevelToString(Windows::Media::SoundLevel level) | SDKSample::PlaybackManager2::sealed | [private]
Stop() | SDKSample::PlaybackManager2::sealed |
StopPressedToken | SDKSample::PlaybackManager2::sealed | [private, static]
StreamTypeAlert() | SDKSample::PlaybackManager2::sealed |
StreamTypeCommunications() | SDKSample::PlaybackManager2::sealed |
StreamTypeMedia() | SDKSample::PlaybackManager2::sealed |
StreamTypeOther() | SDKSample::PlaybackManager2::sealed |
Generated on Sat Nov 23 2024 16:09:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Web::Details::HttpRequestBuffersCallback Member List

This is the complete list of members for Web::Details::HttpRequestBuffersCallback, including all inherited members.
cancellationToken | Web::Details::HttpRequestBuffersCallback | [private]
CreateDataTask() | Web::Details::HttpRequestBuffersCallback |
CreateDataTask() | Web::Details::HttpRequestBuffersCallback |
CreateDataTask() | Web::Details::HttpRequestBuffersCallback |
CreateDataTask() | Web::Details::HttpRequestBuffersCallback |
CreateDataTask() | Web::Details::HttpRequestBuffersCallback |
dataEvent | Web::Details::HttpRequestBuffersCallback | [private]
dataEventLock | Web::Details::HttpRequestBuffersCallback | [private]
dataHResult | Web::Details::HttpRequestBuffersCallback | [private]
dataStream | Web::Details::HttpRequestBuffersCallback | [private]
GetError() const | Web::Details::HttpRequestBuffersCallback | [inline]
GetError() const | Web::Details::HttpRequestBuffersCallback | [inline]
GetError() const | Web::Details::HttpRequestBuffersCallback | [inline]
GetError() const | Web::Details::HttpRequestBuffersCallback | [inline]
GetError() const | Web::Details::HttpRequestBuffersCallback | [inline]
GetReasonPhrase() const | Web::Details::HttpRequestBuffersCallback | [inline]
GetReasonPhrase() const | Web::Details::HttpRequestBuffersCallback | [inline]
GetReasonPhrase() const | Web::Details::HttpRequestBuffersCallback | [inline]
GetReasonPhrase() const | Web::Details::HttpRequestBuffersCallback | [inline]
GetReasonPhrase() const | Web::Details::HttpRequestBuffersCallback | [inline]
GetStatusCode() const | Web::Details::HttpRequestBuffersCallback | [inline]
GetStatusCode() const | Web::Details::HttpRequestBuffersCallback | [inline]
GetStatusCode() const | Web::Details::HttpRequestBuffersCallback | [inline]
GetStatusCode() const | Web::Details::HttpRequestBuffersCallback | [inline]
GetStatusCode() const | Web::Details::HttpRequestBuffersCallback | [inline]
HttpRequestBuffersCallback(IXMLHTTPRequest2 *httpRequest, concurrency::cancellation_token ct=concurrency::cancellation_token::none()) | Web::Details::HttpRequestBuffersCallback | [inline]
HttpRequestBuffersCallback(IXMLHTTPRequest2 *httpRequest, concurrency::cancellation_token ct=concurrency::cancellation_token::none()) | Web::Details::HttpRequestBuffersCallback | [inline]
HttpRequestBuffersCallback(IXMLHTTPRequest2 *httpRequest, concurrency::cancellation_token ct=concurrency::cancellation_token::none()) | Web::Details::HttpRequestBuffersCallback | [inline]
HttpRequestBuffersCallback(IXMLHTTPRequest2 *httpRequest, concurrency::cancellation_token ct=concurrency::cancellation_token::none()) | Web::Details::HttpRequestBuffersCallback | [inline]
HttpRequestBuffersCallback(IXMLHTTPRequest2 *httpRequest, concurrency::cancellation_token ct=concurrency::cancellation_token::none()) | Web::Details::HttpRequestBuffersCallback | [inline]
IsResponseReceived() const | Web::Details::HttpRequestBuffersCallback | [inline]
IsResponseReceived() const | Web::Details::HttpRequestBuffersCallback | [inline]
IsResponseReceived() const | Web::Details::HttpRequestBuffersCallback | [inline]
IsResponseReceived() const | Web::Details::HttpRequestBuffersCallback | [inline]
IsResponseReceived() const | Web::Details::HttpRequestBuffersCallback | [inline]
OnDataAvailable(IXMLHTTPRequest2 *, ISequentialStream *stream) | Web::Details::HttpRequestBuffersCallback | [inline]
OnDataAvailable(IXMLHTTPRequest2 *, ISequentialStream *stream) | Web::Details::HttpRequestBuffersCallback | [inline]
OnDataAvailable(IXMLHTTPRequest2 *, ISequentialStream *stream) | Web::Details::HttpRequestBuffersCallback | [inline]
OnDataAvailable(IXMLHTTPRequest2 *, ISequentialStream *stream) | Web::Details::HttpRequestBuffersCallback | [inline]
OnDataAvailable(IXMLHTTPRequest2 *, ISequentialStream *stream) | Web::Details::HttpRequestBuffersCallback | [inline]
OnError(IXMLHTTPRequest2 *, HRESULT hrError) | Web::Details::HttpRequestBuffersCallback | [inline]
OnError(IXMLHTTPRequest2 *, HRESULT hrError) | Web::Details::HttpRequestBuffersCallback | [inline]
OnError(IXMLHTTPRequest2 *, HRESULT hrError) | Web::Details::HttpRequestBuffersCallback | [inline]
OnError(IXMLHTTPRequest2 *, HRESULT hrError) | Web::Details::HttpRequestBuffersCallback | [inline]
OnError(IXMLHTTPRequest2 *, HRESULT hrError) | Web::Details::HttpRequestBuffersCallback | [inline]
OnHeadersAvailable(IXMLHTTPRequest2 *, DWORD statusCode, PCWSTR reasonPhrase) | Web::Details::HttpRequestBuffersCallback | [inline]
OnHeadersAvailable(IXMLHTTPRequest2 *, DWORD statusCode, PCWSTR reasonPhrase) | Web::Details::HttpRequestBuffersCallback | [inline]
OnHeadersAvailable(IXMLHTTPRequest2 *, DWORD statusCode, PCWSTR reasonPhrase) | Web::Details::HttpRequestBuffersCallback | [inline]
OnHeadersAvailable(IXMLHTTPRequest2 *, DWORD statusCode, PCWSTR reasonPhrase) | Web::Details::HttpRequestBuffersCallback | [inline]
OnHeadersAvailable(IXMLHTTPRequest2 *, DWORD statusCode, PCWSTR reasonPhrase) | Web::Details::HttpRequestBuffersCallback | [inline]
OnRedirect(IXMLHTTPRequest2 *, PCWSTR) | Web::Details::HttpRequestBuffersCallback | [inline]
OnRedirect(IXMLHTTPRequest2 *, PCWSTR) | Web::Details::HttpRequestBuffersCallback | [inline]
OnRedirect(IXMLHTTPRequest2 *, PCWSTR) | Web::Details::HttpRequestBuffersCallback | [inline]
OnRedirect(IXMLHTTPRequest2 *, PCWSTR) | Web::Details::HttpRequestBuffersCallback | [inline]
OnRedirect(IXMLHTTPRequest2 *, PCWSTR) | Web::Details::HttpRequestBuffersCallback | [inline]
OnResponseReceived(IXMLHTTPRequest2 *xhr, ISequentialStream *responseStream) | Web::Details::HttpRequestBuffersCallback | [inline]
OnResponseReceived(IXMLHTTPRequest2 *xhr, ISequentialStream *responseStream) | Web::Details::HttpRequestBuffersCallback | [inline]
OnResponseReceived(IXMLHTTPRequest2 *xhr, ISequentialStream *responseStream) | Web::Details::HttpRequestBuffersCallback | [inline]
OnResponseReceived(IXMLHTTPRequest2 *xhr, ISequentialStream *responseStream) | Web::Details::HttpRequestBuffersCallback | [inline]
OnResponseReceived(IXMLHTTPRequest2 *xhr, ISequentialStream *responseStream) | Web::Details::HttpRequestBuffersCallback | [inline]
ReadData(_Out_writes_(outputBufferSize) byte *outputBuffer, unsigned int outputBufferSize) | Web::Details::HttpRequestBuffersCallback |
ReadData(_Out_writes_(outputBufferSize) byte *outputBuffer, unsigned int outputBufferSize) | Web::Details::HttpRequestBuffersCallback |
ReadData(_Out_writes_(outputBufferSize) byte *outputBuffer, unsigned int outputBufferSize) | Web::Details::HttpRequestBuffersCallback |
ReadData(_Out_writes_(outputBufferSize) byte *outputBuffer, unsigned int outputBufferSize) | Web::Details::HttpRequestBuffersCallback |
ReadData(_Out_writes_(outputBufferSize) byte *outputBuffer, unsigned int outputBufferSize) | Web::Details::HttpRequestBuffersCallback |
reasonPhrase | Web::Details::HttpRequestBuffersCallback | [private]
registrationToken | Web::Details::HttpRequestBuffersCallback | [private]
request | Web::Details::HttpRequestBuffersCallback | [private]
responseReceived | Web::Details::HttpRequestBuffersCallback | [private]
statusCode | Web::Details::HttpRequestBuffersCallback | [private]
~HttpRequestBuffersCallback() | Web::Details::HttpRequestBuffersCallback | [inline, private]
~HttpRequestBuffersCallback() | Web::Details::HttpRequestBuffersCallback | [inline, private]
~HttpRequestBuffersCallback() | Web::Details::HttpRequestBuffersCallback | [inline, private]
~HttpRequestBuffersCallback() | Web::Details::HttpRequestBuffersCallback | [inline, private]
~HttpRequestBuffersCallback() | Web::Details::HttpRequestBuffersCallback | [inline, private]
Generated on Sat Nov 23 2024 16:09:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Programmatic file search/C++/App.xaml.h Source File

  • Programmatic file search

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML ListView and GridView essentials/C++/pch.cpp Source File

  • XAML ListView and GridView essentials

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playback Manager msAudioCategory/C++/PlaybackControl.xaml.h Source File

  • Playback Manager msAudioCategory

PlaybackControl.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 // PlaybackControl.xaml.h
00013 // Declaration of the PlaybackControl class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "PlaybackControl.g.h"
00020 #include "MainPage.xaml.h"
00021 #include <agile.h>
00022
00023 namespace SDKSample
00024 {
00025     namespace  PlaybackManager
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 PlaybackControl sealed
00032         {
00033         public:
00034             PlaybackControl();
00035             void Play();
00036             void Pause();
00037             void Stop();
00038             void SetAudioCategory(Windows::UI::Xaml::Media::AudioCategory category);
00039             void SetAudioDeviceType(Windows::UI::Xaml::Media::AudioDeviceType devicetype);
00040             void SelectFile();
00041
00042         private:
00043             void DisplayStatus(Platform::String^ text);
00044             Platform::String^ GetTimeStampedMessage(Platform::String^ EventCalled);
00045             Platform::String^ SoundLevelToString(Windows::Media::SoundLevel level);
00046             void AppMuted();
00047             void AppUnmuted();
00048             void MediaControl_SoundLevelChanged(Platform::Object^ sender, Platform::Object^ e);
00049             void MediaControl_PlayPauseTogglePressed(Platform::Object^ sender, Platform::Object^ e);
00050             void MediaControl_PlayPressed(Platform::Object^ sender, Platform::Object^ e);
00051             void MediaControl_StopPressed(Platform::Object^ sender, Platform::Object^ e);
00052             void MediaControl_PausePressed(Platform::Object^ sender, Platform::Object^ e);
00053             void Button_Play_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00054             void Button_Pause_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00055             void Button_Stop_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00056
00057         private:
00058             bool IsPlaying;
00059             Platform::Agile<Windows::UI::Core::CoreWindow> cw;
00060
00061             static bool IsRegistered;
00062             static Windows::Foundation::EventRegistrationToken SoundLevelChangedToken;
00063             static Windows::Foundation::EventRegistrationToken PlayPauseTogglePressedToken;
00064             static Windows::Foundation::EventRegistrationToken PlayPressedToken;
00065             static Windows::Foundation::EventRegistrationToken PausePressedToken;
00066             static Windows::Foundation::EventRegistrationToken StopPressedToken;
00067
00068         };
00069     }
00070 }
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Device auto rotation preferences/C++/Portrait.xaml.cpp Source File

  • Device auto rotation preferences

Portrait.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 // Portrait.xaml.cpp
00013 // Implementation of the Portrait class
00014 //
00015
00016 #include "pch.h"
00017 #include "Portrait.xaml.h"
00018
00019 using namespace SDKSample::Rotation;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 Portrait::Portrait()
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 Portrait::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 SDKSample::Rotation::Portrait::SetPortrait_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00043 {
00044     Button^ b = safe_cast<Button^>(sender);
00045     if (b != nullptr)
00046     {
00047         Windows::Graphics::Display::DisplayProperties::AutoRotationPreferences = Windows::Graphics::Display::DisplayOrientations::Portrait;
00048
00049         if (Windows::Graphics::Display::DisplayProperties::AutoRotationPreferences == Windows::Graphics::Display::DisplayOrientations::Portrait)
00050         {
00051             rootPage->NotifyUser("Succeeded: Preference set to Portrait.", NotifyType::StatusMessage);
00052         }
00053         else
00054         {
00055             rootPage->NotifyUser("Error: Failed to set the preference.", NotifyType::StatusMessage);
00056         }
00057     }
00058 }
Generated on Sat Nov 23 2024 16:08:02 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D bump mapping/C++/BasicCamera.h Source File

  • Direct3D bump mapping

BasicCamera.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 camera class.
00011 ref class BasicCamera
00012 {
00013
00014 private:
00015     float3 m_position;      // the position of the camera
00016     float3 m_direction;     // the unit vector of the viewing direction
00017     float4x4 m_view;        // view matrix
00018     float4x4 m_projection;  // projection matrix
00019
00020 internal:
00021     void GetViewMatrix(_Out_ float4x4 *viewMatrix);
00022     void GetProjectionMatrix(_Out_ float4x4 *projectionMatrix);
00023
00024     // this method updates the view matrix based on new position and focus coordinates
00025     void SetViewParameters(
00026         _In_ float3 eyePosition,    // the position of the camera
00027         _In_ float3 lookPosition,   // the point the camera should look at
00028         _In_ float3 up              // the durection vector for up
00029         );
00030
00031     // this method updates the projection matrix based on new parameters
00032     void SetProjectionParameters(
00033         _In_ float minimumFieldOfView,  // the minimum horizontal or vertical field of view, in degrees
00034         _In_ float aspectRatio,         // the aspect ratio of the projection (width / height)
00035         _In_ float nearPlane,           // depth to map to 0
00036         _In_ float farPlane             // depth to map to 1
00037         );
00038 };
Generated on Sat Nov 23 2024 16:08:07 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D interpolation modes/C++/BasicTimer.cpp Source File

  • Direct2D interpolation modes

BasicTimer.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 "BasicTimer.h"
00010
00011 BasicTimer::BasicTimer()
00012 {
00013     if (!QueryPerformanceFrequency(&m_frequency))
00014     {
00015         throw ref new Platform::FailureException();
00016     }
00017     Reset();
00018 }
00019
00020 void BasicTimer::Reset()
00021 {
00022     Update();
00023     m_startTime = m_currentTime;
00024     m_total = 0.0f;
00025     m_delta = 1.0f / 60.0f;
00026 }
00027
00028 void BasicTimer::Update()
00029 {
00030     if (!QueryPerformanceCounter(&m_currentTime))
00031     {
00032         throw ref new Platform::FailureException();
00033     }
00034
00035     m_total = static_cast<float>(
00036         static_cast<double>(m_currentTime.QuadPart-m_startTime.QuadPart) /
00037         static_cast<double>(m_frequency.QuadPart)
00038         );
00039
00040     if (m_lastTime.QuadPart == m_startTime.QuadPart)
00041     {
00042         // If the timer was just reset, report a time delta equivalent to 60Hz frame time.
00043         m_delta = 1.0f / 60.0f;
00044     }
00045     else
00046     {
00047         m_delta = static_cast<float>(
00048             static_cast<double>(m_currentTime.QuadPart-m_lastTime.QuadPart) /
00049             static_cast<double>(m_frequency.QuadPart)
00050             );
00051     }
00052
00053     m_lastTime = m_currentTime;
00054 }
00055
00056 float BasicTimer::Total::get()
00057 {
00058     return m_total;
00059 }
00060
00061 float BasicTimer::Delta::get()
00062 {
00063     return m_delta;
00064 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Programmatic file search/C++/Constants.cpp Source File

  • Programmatic file search

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     { "Obtain all files that match a search query", "SDKSample.FileSearch.Scenario1" },
00020 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: EAS policies for mail clients/C++/pch.h Source File

  • EAS policies for mail clients

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/CartoonEffect/FrameProcessing.h Source File

  • Hilo C++
  • CartoonEffect

FrameProcessing.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
00009 class FrameProcessing
00010 {
00011 public:
00012     FrameProcessing();
00013     ~FrameProcessing();
00014
00015     void SetCancellationToken(concurrency::cancellation_token token);
00016     void SetNeighbourArea(unsigned int area);
00017     void SetCurrentFrame(byte* pFrame, int size, int width, int height, int pitch, int bpp, int clrPlanes);
00018     void ApplyFilters(int nPhases);
00019
00020 private:
00021     byte* m_pCurrentImage;
00022     byte* m_pBufferImage;
00023     unsigned int m_neighborWindow;
00024     unsigned int m_width;
00025     unsigned int m_height;
00026     unsigned int m_size;
00027     int m_pitch;
00028     unsigned int m_BPP;
00029     unsigned int m_colorPlanes;
00030     concurrency::cancellation_token m_token;
00031
00032     unsigned int GetNeighbourArea();
00033     void StopFilters();
00034     void ApplyColorSimplifier();
00035     void ApplyColorSimplifier(int nPhases);
00036     void ApplyColorSimplifier(unsigned int startHeight, unsigned int endHeight, unsigned int startWidth, unsigned int endWidth);
00037     void SimplifyIndexOptimized(byte* pFrame, int x, int y);
00038     void ApplyEdgeDetection();
00039     void ApplyEdgeDetectionParallel(unsigned int startHeight, unsigned int endHeight, unsigned int startWidth, unsigned int endWidth);
00040     void CalculateSobel(byte* pSource, int row, int column, float& dy, float& du, float& dv);
00041
00042     static inline COLORREF GetPixel(byte* pFrame, int x, int y, int pitch, int bpp)
00043     {
00044         int width = abs((int)pitch);
00045         int bytesPerPixel = bpp / 8;
00046         int byteIndex = y * width + x * bytesPerPixel;
00047         return RGB(pFrame[byteIndex + 2],
00048             pFrame[byteIndex + 1],
00049             pFrame[byteIndex]);
00050     }
00051
00052     static inline void SetPixel(byte* pFrame, int x, int y, int pitch, int bpp, COLORREF color)
00053     {
00054         int width = abs((int)pitch);
00055         int bytesPerPixel = bpp / 8;
00056         int byteIndex = y * width + x * bytesPerPixel;
00057         pFrame[byteIndex + 2] = GetRValue(color);
00058         pFrame[byteIndex + 1] = GetGValue(color);
00059         pFrame[byteIndex] = GetBValue(color);
00060     }
00061 };
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

CDocumentSource Member List

This is the complete list of members for CDocumentSource, including all inherited members.
GetPreviewPageCollection(_In_ IPrintDocumentPackageTarget *docPackageTarget, _Out_ IPrintPreviewPageCollection **docPageCollection) | CDocumentSource |
GetPreviewPageCollection(_In_ IPrintDocumentPackageTarget *docPackageTarget, _Out_ IPrintPreviewPageCollection **docPageCollection) | CDocumentSource |
InspectableClass(L"Windows.Graphics.Printing.IPrintDocumentSource", BaseTrust) | CDocumentSource | [private]
InspectableClass(L"Windows.Graphics.Printing.IPrintDocumentSource", BaseTrust) | CDocumentSource | [private]
m_dxgiPreviewTarget | CDocumentSource | [private]
m_height | CDocumentSource | [private]
m_imageableRect | CDocumentSource | [private]
m_paginateCalled | CDocumentSource | [private]
m_renderer | CDocumentSource | [private]
m_totalPages | CDocumentSource | [private]
m_width | CDocumentSource | [private]
MakeDocument(_In_ IInspectable *docOptions, _In_ IPrintDocumentPackageTarget *docPackageTarget) | CDocumentSource |
MakeDocument(_In_ IInspectable *docOptions, _In_ IPrintDocumentPackageTarget *docPackageTarget) | CDocumentSource |
MakePage(_In_ uint32 desiredJobPage, _In_ float width, _In_ float height) | CDocumentSource |
MakePage(_In_ uint32 desiredJobPage, _In_ float width, _In_ float height) | CDocumentSource |
Paginate(_In_ uint32 currentJobPage, _In_ IInspectable *docOptions) | CDocumentSource |
Paginate(_In_ uint32 currentJobPage, _In_ IInspectable *docOptions) | CDocumentSource |
RuntimeClassInitialize(_In_ IUnknown *pageRenderer) | CDocumentSource | [inline]
RuntimeClassInitialize(_In_ IUnknown *pageRenderer) | CDocumentSource | [inline]
TransformedPageSize(_In_ float desiredWidth, _In_ float desiredHeight, _Out_ Windows::Foundation::Size *previewSize) | CDocumentSource | [private]
TransformedPageSize(_In_ float desiredWidth, _In_ float desiredHeight, _Out_ Windows::Foundation::Size *previewSize) | CDocumentSource | [private]
Generated on Sat Nov 23 2024 16:09:07 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SimpleCommunication::Common::LayoutAwarePage Member List

This is the complete list of members for SimpleCommunication::Common::LayoutAwarePage, including all inherited members.
__pad0__ | SimpleCommunication::Common::LayoutAwarePage |
_defaultViewModel | SimpleCommunication::Common::LayoutAwarePage | [private]
_layoutAwareControls | SimpleCommunication::Common::LayoutAwarePage | [private]
_useFilledStateForNarrowWindow | SimpleCommunication::Common::LayoutAwarePage | [private]
_windowSizeEventToken | SimpleCommunication::Common::LayoutAwarePage | [private]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SimpleCommunication::Common::LayoutAwarePage | [virtual]
GoBack(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SimpleCommunication::Common::LayoutAwarePage | [virtual]
InvalidateVisualState() | SimpleCommunication::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SimpleCommunication::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SimpleCommunication::Common::LayoutAwarePage |
WindowSizeChanged(Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SimpleCommunication::Common::LayoutAwarePage | [private]
Generated on Sat Nov 23 2024 16:09:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

TextButton Member List

This is the complete list of members for TextButton, including all inherited members.
CalculateSize() | TextButton | [protected, virtual]
CreateTextLayout() | TextElement | [protected]
ElementBase() | ElementBase | [protected]
FadeOut(float fadeOutTime) | TextElement |
GetBounds() | ElementBase |
GetSelected() const | TextButton | [inline]
GetTextStyle() | TextElement | [inline]
Initialize() | TextButton | [virtual]
IsPressed() const | TextButton | [inline]
IsVisible() const | ElementBase | [inline]
m_alignment | ElementBase | [protected]
m_container | ElementBase | [protected]
m_fadeOutTime | TextElement | [protected]
m_fadeOutTimeElapsed | TextElement | [protected]
m_fadeStartingOpacity | TextElement | [protected]
m_isFadingOut | TextElement | [protected]
m_padding | TextButton | [protected]
m_pressed | TextButton | [protected]
m_selected | TextButton | [protected]
m_shadowColorBrush | TextElement | [protected]
m_size | ElementBase | [protected]
m_text | TextElement | [protected]
m_textColorBrush | TextElement | [protected]
m_textExtents | TextElement | [protected]
m_textLayout | TextElement | [protected]
m_textStyle | TextElement | [protected]
m_visible | ElementBase | [protected]
Render() | TextButton | [virtual]
SetAlignment(AlignType horizontal, AlignType vertical) | ElementBase |
SetContainer(const D2D1_RECT_F &container) | ElementBase | [virtual]
SetPadding(D2D1_SIZE_F padding) | TextButton |
SetPressed(bool pressed) | TextButton |
SetSelected(bool selected) | TextButton |
SetText(__nullterminated WCHAR *text) | TextElement |
SetText(Platform::String^text) | TextElement |
SetTextColor(const D2D1_COLOR_F &textColor) | TextElement |
SetTextOpacity(float textOpacity) | TextElement |
SetVisible(bool visible) | ElementBase |
TextButton() | TextButton |
TextElement() | TextElement |
Update(float timeTotal, float timeDelta) | TextButton | [virtual]
Generated on Sat Nov 23 2024 16:09:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SConversion Member List

This is the complete list of members for SConversion, including all inherited members.
pNext | SConversion
szDest | SConversion
szSrc | SConversion
Generated on Sat Nov 23 2024 16:09:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX postcard app/C++/ExtrudedTextRenderer.h Source File

  • DirectX postcard app

ExtrudedTextRenderer.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 "OutlineRenderer.h"
00011 #include "Extruder.h"
00012
00013 // describes the constant buffer that will be used to draw the cube for extruded text
00014 struct ConstantBuffer
00015 {
00016     float4x4 model;
00017     float4x4 view;
00018     float4x4 projection;
00019 };
00020
00021 inline static float Clamp(float value, float low, float high)
00022 {
00023     return (value < low) ? low : (value > high) ? high : value;
00024 }
00025
00026 ref class ExtrudedTextRenderer
00027 {
00028 internal:
00029     ExtrudedTextRenderer();
00030
00031     void CreateDeviceIndependentResources(
00032         Microsoft::WRL::ComPtr<ID2D1Factory1> d2dFactory,
00033         Microsoft::WRL::ComPtr<IDWriteFactory1> dwriteFactory
00034         );
00035
00036     void CreateDeviceResources(
00037         Microsoft::WRL::ComPtr<ID3D11Device1> d3dDevice,
00038         Microsoft::WRL::ComPtr<ID3D11DeviceContext1> d3dContext
00039         );
00040
00041     void CreateWindowSizeDependentResources(
00042         float dpi,
00043         Microsoft::WRL::ComPtr<ID3D11RenderTargetView> renderTargetView,
00044         Microsoft::WRL::ComPtr<ID3D11DepthStencilView> depthStencilView,
00045         Windows::Foundation::Size renderTargetSize
00046         );
00047
00048     void DrawExtrudedText();
00049
00050     void SetExtrudedText(Platform::String^ text);
00051     void Reset();
00052     void ReleaseBufferResources();
00053
00054     void OnManipulationDelta(
00055         Windows::Foundation::Point position,
00056         Windows::Foundation::Point positionDelta,
00057         float zoomDelta,
00058         float rotation
00059         );
00060
00061 private:
00062     void UpdateModelAndCamera();
00063     void UpdateTextGeometry();
00064     void GenerateTextOutline(ID2D1Geometry** ppGeometry);
00065
00066     void CreateBuffers(
00067         uint32 numVertices,
00068         uint32 numIndices,
00069         BasicVertex* vertexData,
00070         unsigned short* indexData,
00071         ID3D11Buffer** vertexBuffer,
00072         ID3D11Buffer** indexBuffer
00073         );
00074
00075     // Resources shared with PostcardRenderer.
00076     Microsoft::WRL::ComPtr<ID2D1Factory1>                   m_d2dFactory;
00077     Microsoft::WRL::ComPtr<IDWriteFactory1>                 m_dwriteFactory;
00078     Microsoft::WRL::ComPtr<ID3D11Device1>                   m_d3dDevice;
00079     Microsoft::WRL::ComPtr<ID3D11DeviceContext1>            m_d3dContext;
00080     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>          m_d3dRenderTargetView;
00081     Microsoft::WRL::ComPtr<ID3D11DepthStencilView>          m_d3dDepthStencilView;
00082     Windows::Foundation::Size                               m_renderTargetSize;
00083     float                                                   m_dpi;
00084
00085     // Resources specific to this renderer.
00086     Microsoft::WRL::ComPtr<ID3D11InputLayout>               m_inputLayout;          // cube vertex input layout
00087     Microsoft::WRL::ComPtr<ID3D11Buffer>                    m_vertexBuffer;         // cube vertex buffer
00088     Microsoft::WRL::ComPtr<ID3D11Buffer>                    m_indexBuffer;          // cube index buffer
00089     Microsoft::WRL::ComPtr<ID3D11VertexShader>              m_vertexShader;         // cube vertex shader
00090     Microsoft::WRL::ComPtr<ID3D11PixelShader>               m_pixelShader;          // cube pixel shader
00091     Microsoft::WRL::ComPtr<ID3D11Buffer>                    m_constantBuffer;       // constant buffer resource
00092
00093     unsigned int                                            m_indexCount;           // cube index count
00094     ConstantBuffer                                          m_constantBufferData;   // constant buffer resource data
00095     BasicCamera^                                            m_camera;               // scene camera
00096
00097     Platform::String^                                       m_characters;           // the text to be extruded
00098     Windows::Foundation::Point                              m_panPosition;          // position of the text
00099     float                                                   m_zoom;                 // zoom size of the text
00100
00101     Microsoft::WRL::ComPtr<ID2D1Geometry>                   m_textGeometry;
00102     Microsoft::WRL::ComPtr<IDWriteTextLayout>               m_textLayout;
00103 };
Generated on Sat Nov 23 2024 16:08:15 for Win8-Examples by doxygen 1.7.1


Win8-Examples: App settings/C++/Constants.cpp Source File

  • App settings

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
00021     { "Default behavior with no settings integration", "SDKSample.ApplicationSettings.DefaultScenario" },
00022     { "Add settings commands to the settings charm", "SDKSample.ApplicationSettings.AddSettingsScenario" }
00023 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::TileContent::TileWideBase Member List

This is the complete list of members for NotificationsExtensions::TileContent::TileWideBase, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
Branding | NotificationsExtensions::TileContent::TileNotificationBase |
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
m_RequireSquareContent | NotificationsExtensions::TileContent::TileWideBase | [private]
m_SquareContent | NotificationsExtensions::TileContent::TileWideBase | [private]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
RequireSquareContent | NotificationsExtensions::TileContent::TileWideBase |
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SquareContent | NotificationsExtensions::TileContent::TileWideBase |
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextFields | NotificationsExtensions::NotificationBase |
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:43 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Device capabilities/C++/Constants.h Source File

  • Input Device capabilities

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"Device Capabilities C++ sample");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044
00045
00046 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX touch input/C++/DirectXApp.cpp Source File

  • DirectX touch input

DirectXApp.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 "DirectXApp.h"
00010 #include "BasicTimer.h"
00011
00012 using namespace Windows::ApplicationModel;
00013 using namespace Windows::ApplicationModel::Core;
00014 using namespace Windows::ApplicationModel::Activation;
00015 using namespace Windows::UI::Core;
00016 using namespace Windows::System;
00017 using namespace Windows::Storage;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::Graphics::Display;
00021
00022 DirectXApp::DirectXApp() :
00023     m_windowClosed(false),
00024     m_windowVisible(true)
00025 {
00026 }
00027
00028 void DirectXApp::Initialize(
00029     _In_ CoreApplicationView^ applicationView
00030     )
00031 {
00032     applicationView->Activated +=
00033         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &DirectXApp::OnActivated);
00034
00035     CoreApplication::Suspending +=
00036         ref new EventHandler<SuspendingEventArgs^>(this, &DirectXApp::OnSuspending);
00037
00038     CoreApplication::Resuming +=
00039         ref new EventHandler<Platform::Object^>(this, &DirectXApp::OnResuming);
00040
00041     m_renderer = ref new Simple3DTouch();
00042 }
00043
00044 void DirectXApp::SetWindow(
00045     _In_ CoreWindow^ window
00046     )
00047 {
00048     window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
00049
00050     window->SizeChanged +=
00051         ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &DirectXApp::OnWindowSizeChanged);
00052
00053     window->VisibilityChanged +=
00054         ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &DirectXApp::OnVisibilityChanged);
00055
00056     window->Closed +=
00057         ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &DirectXApp::OnWindowClosed);
00058
00059     DisplayProperties::LogicalDpiChanged +=
00060         ref new DisplayPropertiesEventHandler(this, &DirectXApp::OnLogicalDpiChanged);
00061
00062     m_renderer->Initialize(window, DisplayProperties::LogicalDpi);
00063 }
00064
00065 void DirectXApp::Load(
00066     _In_ Platform::String^ entryPoint
00067     )
00068 {
00069     IPropertySet^ appState = ApplicationData::Current->LocalSettings->Values;
00070     m_renderer->LoadInternalState(appState);
00071 }
00072
00073 void DirectXApp::Run()
00074 {
00075     BasicTimer^ timer = ref new BasicTimer();
00076
00077     while (!m_windowClosed)
00078     {
00079         if (m_windowVisible)
00080         {
00081             timer->Update();
00082             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
00083             m_renderer->Update(timer->Total, timer->Delta);
00084             m_renderer->Render();
00085             m_renderer->Present(); // This call is synchronized to the display frame rate.
00086         }
00087         else
00088         {
00089             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
00090         }
00091     }
00092 }
00093
00094 void DirectXApp::Uninitialize()
00095 {
00096 }
00097
00098 void DirectXApp::OnWindowSizeChanged(
00099     _In_ CoreWindow^ sender,
00100     _In_ WindowSizeChangedEventArgs^ args
00101     )
00102 {
00103     m_renderer->UpdateForWindowSizeChange();
00104 }
00105
00106 void DirectXApp::OnVisibilityChanged(
00107     _In_ CoreWindow^ sender,
00108     _In_ VisibilityChangedEventArgs^ args
00109     )
00110 {
00111     m_windowVisible = args->Visible;
00112 }
00113
00114 void DirectXApp::OnWindowClosed(
00115     _In_ CoreWindow^ sender,
00116     _In_ CoreWindowEventArgs^ args
00117     )
00118 {
00119     m_windowClosed = true;
00120 }
00121
00122 void DirectXApp::OnLogicalDpiChanged(
00123     _In_ Platform::Object^ sender
00124     )
00125 {
00126     m_renderer->SetDpi(DisplayProperties::LogicalDpi);
00127 }
00128
00129 void DirectXApp::OnActivated(
00130     _In_ CoreApplicationView^ applicationView,
00131     _In_ IActivatedEventArgs^ args
00132     )
00133 {
00134     CoreWindow::GetForCurrentThread()->Activate();
00135 }
00136
00137 void DirectXApp::OnSuspending(
00138     _In_ Platform::Object^ sender,
00139     _In_ SuspendingEventArgs^ args
00140     )
00141 {
00142     IPropertySet^ appState = ApplicationData::Current->LocalSettings->Values;
00143     m_renderer->SaveInternalState(appState);
00144 }
00145
00146 void DirectXApp::OnResuming(
00147     _In_ Platform::Object^ sender,
00148     _In_ Platform::Object^ args
00149     )
00150 {
00151 }
00152
00153 IFrameworkView^ DirectXAppSource::CreateView()
00154 {
00155     return ref new DirectXApp();
00156 }
00157
00158 [Platform::MTAThread]
00159 int main(Platform::Array<Platform::String^>^)
00160 {
00161     auto directXAppSource = ref new DirectXAppSource();
00162     CoreApplication::Run(directXAppSource);
00163     return 0;
00164 }
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D composite effect modes/C++/CompositeModes.h Source File

  • Direct2D composite effect modes

CompositeModes.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 "DirectXBase.h"
00011 #include "SampleOverlay.h"
00012
00013 ref class CompositeModes : public DirectXBase, public Windows::ApplicationModel::Core::IFrameworkView
00014 {
00015 internal:
00016     CompositeModes();
00017
00018     // DirectXBase Methods
00019     virtual void CreateDeviceIndependentResources() override;
00020     virtual void CreateDeviceResources() override;
00021     virtual void CreateWindowSizeDependentResources() override;
00022     virtual void Render() override;
00023
00024 public:
00025     // IFrameworkView Methods
00026     virtual void Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00027     virtual void SetWindow(_In_ Windows::UI::Core::CoreWindow^ window);
00028     virtual void Load(_In_ Platform::String^ entryPoint);
00029     virtual void Run();
00030     virtual void Uninitialize();
00031
00032 private:
00033     // Event Handlers
00034     void OnWindowSizeChanged(
00035         _In_ Windows::UI::Core::CoreWindow^ sender,
00036         _In_ Windows::UI::Core::WindowSizeChangedEventArgs^ args
00037         );
00038
00039     void OnLogicalDpiChanged(
00040         _In_ Platform::Object^ sender
00041         );
00042
00043     void OnDisplayContentsInvalidated(
00044         _In_ Platform::Object^ sender
00045         );
00046
00047     void OnActivated(
00048         _In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView,
00049         _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^ args
00050         );
00051
00052     void OnSuspending(
00053         _In_ Platform::Object^ sender,
00054         _In_ Windows::ApplicationModel::SuspendingEventArgs^ args
00055         );
00056
00057     void OnResuming(
00058         _In_ Platform::Object^ sender,
00059         _In_ Platform::Object^ args
00060         );
00061
00062     void OnPointerPressed(
00063         _In_ Windows::UI::Core::CoreWindow^ sender,
00064         _In_ Windows::UI::Core::PointerEventArgs^ args
00065         );
00066
00067     void OnPointerReleased(
00068         _In_ Windows::UI::Core::CoreWindow^ sender,
00069         _In_ Windows::UI::Core::PointerEventArgs^ args
00070         );
00071
00072     void OnPointerMoved(
00073         _In_ Windows::UI::Core::CoreWindow^ sender,
00074         _In_ Windows::UI::Core::PointerEventArgs^ args
00075         );
00076
00077     void OnManipulationUpdated(
00078         _In_ Windows::UI::Input::GestureRecognizer^ recognizer,
00079         _In_ Windows::UI::Input::ManipulationUpdatedEventArgs^ args
00080         );
00081
00082     ~CompositeModes();
00083
00084     inline static float Clamp(float v, float low, float high)
00085     {
00086         return (v < low) ? low : (v > high) ? high : v;
00087     }
00088
00089     void UpdateAlpha(_In_ float verticalPositionDelta);
00090
00091     SampleOverlay^                                      m_sampleOverlay;
00092
00093     Platform::Agile<Windows::UI::Input::GestureRecognizer> m_gestureRecognizer;
00094
00095     Microsoft::WRL::ComPtr<IWICFormatConverter>         m_appleBitmap;
00096     Microsoft::WRL::ComPtr<IWICFormatConverter>         m_bananaBitmap;
00097     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>        m_whiteBrush;
00098     Microsoft::WRL::ComPtr<IDWriteTextFormat>           m_headingTextFormat;
00099     Microsoft::WRL::ComPtr<IDWriteTextFormat>           m_textFormat;
00100     Microsoft::WRL::ComPtr<IDWriteTextFormat>           m_snappedViewFormat;
00101     Microsoft::WRL::ComPtr<IDWriteTextLayout>           m_compositeModeTextLayout;
00102     Microsoft::WRL::ComPtr<IDWriteTextLayout>           m_blendModeTextLayout;
00103     Microsoft::WRL::ComPtr<ID2D1Effect>                 m_appleEffect;
00104     Microsoft::WRL::ComPtr<ID2D1Effect>                 m_bananaEffect;
00105     Microsoft::WRL::ComPtr<ID2D1Effect>                 m_compositeEffect;
00106     Microsoft::WRL::ComPtr<ID2D1Effect>                 m_blendEffect;
00107     Microsoft::WRL::ComPtr<ID2D1Effect>                 m_scaleEffect;
00108     Microsoft::WRL::ComPtr<ID2D1Effect>                 m_appleAlphaEffect;
00109     Microsoft::WRL::ComPtr<ID2D1Effect>                 m_bananaAlphaEffect;
00110
00111     Platform::Array<Platform::String^>^                 m_compositeModeNames;
00112     Platform::Array<Platform::String^>^                 m_blendModeNames;
00113     D2D1_SIZE_U                                         m_bitmapPixelSize;
00114     D2D1_SIZE_F                                         m_imageSize;
00115     D2D1_SIZE_F                                         m_contextSize;
00116     D2D1_SIZE_F                                         m_cellSize;
00117     float                                               m_alpha;
00118     float                                               m_horizontalOffset;
00119     bool                                                m_drawEnabled;
00120
00121     IDWriteTextLayout**                                 m_captionLayouts;
00122 };
00123
00124 ref class DirectXAppSource : Windows::ApplicationModel::Core::IFrameworkViewSource
00125 {
00126 public:
00127     virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00128 };
Generated on Sat Nov 23 2024 16:08:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Scaling according to DPI/C++/App.xaml.h Source File

  • Scaling according to DPI

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CameraOptionsUI/C++/common/LayoutAwarePage.h Source File

  • CameraOptionsUI
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX marble maze game/C++/DDSTextureLoader.cpp Source File

  • DirectX marble maze game

DDSTextureLoader.cpp

Go to the documentation of this file.
00001 //--------------------------------------------------------------------------------------
00002 // File: DDSTextureLoader.cpp
00003 //
00004 // Function for loading a DDS texture and creating a Direct3D 11 runtime resource for it
00005 //
00006 // Note this function is 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
00018 #include "pch.h"
00019 #include <dxgiformat.h>
00020 #include <assert.h>
00021 #include <memory>
00022 #include <algorithm>
00023 #include "DDSTextureLoader.h"
00024 #include "DirectXSample.h"
00025
00026 using namespace Microsoft::WRL;
00027
00028 //--------------------------------------------------------------------------------------
00029 // Macros
00030 //--------------------------------------------------------------------------------------
00031 #ifndef MAKEFOURCC
00032     #define MAKEFOURCC(ch0, ch1, ch2, ch3)                              \
00033                 ((uint32)(byte)(ch0) | ((uint32)(byte)(ch1) << 8) |       \
00034                 ((uint32)(byte)(ch2) << 16) | ((uint32)(byte)(ch3) << 24))
00035 #endif /* defined(MAKEFOURCC) */
00036
00037 //--------------------------------------------------------------------------------------
00038 // DDS file structure definitions
00039 //
00040 // See DDS.h in the 'Texconv' sample and the 'DirectXTex' library
00041 //--------------------------------------------------------------------------------------
00042 #pragma pack(push, 1)
00043
00044 #define DDS_MAGIC 0x20534444 // "DDS "
00045
00046 struct DDS_PIXELFORMAT
00047 {
00048     uint32  size;
00049     uint32  flags;
00050     uint32  fourCC;
00051     uint32  RGBBitCount;
00052     uint32  RBitMask;
00053     uint32  GBitMask;
00054     uint32  BBitMask;
00055     uint32  ABitMask;
00056 };
00057
00058 #define DDS_FOURCC      0x00000004  // DDPF_FOURCC
00059 #define DDS_RGB         0x00000040  // DDPF_RGB
00060 #define DDS_RGBA        0x00000041  // DDPF_RGB | DDPF_ALPHAPIXELS
00061 #define DDS_LUMINANCE   0x00020000  // DDPF_LUMINANCE
00062 #define DDS_LUMINANCEA  0x00020001  // DDPF_LUMINANCE | DDPF_ALPHAPIXELS
00063 #define DDS_ALPHA       0x00000002  // DDPF_ALPHA
00064 #define DDS_PAL8        0x00000020  // DDPF_PALETTEINDEXED8
00065
00066 #define DDS_HEADER_FLAGS_TEXTURE        0x00001007  // DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT
00067 #define DDS_HEADER_FLAGS_MIPMAP         0x00020000  // DDSD_MIPMAPCOUNT
00068 #define DDS_HEADER_FLAGS_VOLUME         0x00800000  // DDSD_DEPTH
00069 #define DDS_HEADER_FLAGS_PITCH          0x00000008  // DDSD_PITCH
00070 #define DDS_HEADER_FLAGS_LINEARSIZE     0x00080000  // DDSD_LINEARSIZE
00071
00072 #define DDS_HEIGHT 0x00000002 // DDSD_HEIGHT
00073 #define DDS_WIDTH  0x00000004 // DDSD_WIDTH
00074
00075 #define DDS_SURFACE_FLAGS_TEXTURE 0x00001000 // DDSCAPS_TEXTURE
00076 #define DDS_SURFACE_FLAGS_MIPMAP  0x00400008 // DDSCAPS_COMPLEX | DDSCAPS_MIPMAP
00077 #define DDS_SURFACE_FLAGS_CUBEMAP 0x00000008 // DDSCAPS_COMPLEX
00078
00079 #define DDS_CUBEMAP_POSITIVEX 0x00000600 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEX
00080 #define DDS_CUBEMAP_NEGATIVEX 0x00000a00 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEX
00081 #define DDS_CUBEMAP_POSITIVEY 0x00001200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEY
00082 #define DDS_CUBEMAP_NEGATIVEY 0x00002200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEY
00083 #define DDS_CUBEMAP_POSITIVEZ 0x00004200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEZ
00084 #define DDS_CUBEMAP_NEGATIVEZ 0x00008200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEZ
00085
00086 #define DDS_CUBEMAP_ALLFACES (DDS_CUBEMAP_POSITIVEX | DDS_CUBEMAP_NEGATIVEX |\
00087                               DDS_CUBEMAP_POSITIVEY | DDS_CUBEMAP_NEGATIVEY |\
00088                               DDS_CUBEMAP_POSITIVEZ | DDS_CUBEMAP_NEGATIVEZ)
00089
00090 #define DDS_CUBEMAP 0x00000200 // DDSCAPS2_CUBEMAP
00091
00092 #define DDS_FLAGS_VOLUME 0x00200000 // DDSCAPS2_VOLUME
00093
00094 typedef struct
00095 {
00096     uint32          size;
00097     uint32          flags;
00098     uint32          height;
00099     uint32          width;
00100     uint32          pitchOrLinearSize;
00101     uint32          depth; // only if DDS_HEADER_FLAGS_VOLUME is set in flags
00102     uint32          mipMapCount;
00103     uint32          reserved1[11];
00104     DDS_PIXELFORMAT ddspf;
00105     uint32          caps;
00106     uint32          caps2;
00107     uint32          caps3;
00108     uint32          caps4;
00109     uint32          reserved2;
00110 } DDS_HEADER;
00111
00112 typedef struct
00113 {
00114     DXGI_FORMAT dxgiFormat;
00115     uint32      resourceDimension;
00116     uint32      miscFlag; // see D3D11_RESOURCE_MISC_FLAG
00117     uint32      arraySize;
00118     uint32      reserved;
00119 } DDS_HEADER_DXT10;
00120
00121 #pragma pack(pop)
00122
00123 //--------------------------------------------------------------------------------------
00124 // Return the BPP for a particular format
00125 //--------------------------------------------------------------------------------------
00126 static size_t BitsPerPixel(_In_ DXGI_FORMAT fmt)
00127 {
00128     switch (fmt)
00129     {
00130     case DXGI_FORMAT_R32G32B32A32_TYPELESS:
00131     case DXGI_FORMAT_R32G32B32A32_FLOAT:
00132     case DXGI_FORMAT_R32G32B32A32_UINT:
00133     case DXGI_FORMAT_R32G32B32A32_SINT:
00134         return 128;
00135
00136     case DXGI_FORMAT_R32G32B32_TYPELESS:
00137     case DXGI_FORMAT_R32G32B32_FLOAT:
00138     case DXGI_FORMAT_R32G32B32_UINT:
00139     case DXGI_FORMAT_R32G32B32_SINT:
00140         return 96;
00141
00142     case DXGI_FORMAT_R16G16B16A16_TYPELESS:
00143     case DXGI_FORMAT_R16G16B16A16_FLOAT:
00144     case DXGI_FORMAT_R16G16B16A16_UNORM:
00145     case DXGI_FORMAT_R16G16B16A16_UINT:
00146     case DXGI_FORMAT_R16G16B16A16_SNORM:
00147     case DXGI_FORMAT_R16G16B16A16_SINT:
00148     case DXGI_FORMAT_R32G32_TYPELESS:
00149     case DXGI_FORMAT_R32G32_FLOAT:
00150     case DXGI_FORMAT_R32G32_UINT:
00151     case DXGI_FORMAT_R32G32_SINT:
00152     case DXGI_FORMAT_R32G8X24_TYPELESS:
00153     case DXGI_FORMAT_D32_FLOAT_S8X24_UINT:
00154     case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS:
00155     case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT:
00156         return 64;
00157
00158     case DXGI_FORMAT_R10G10B10A2_TYPELESS:
00159     case DXGI_FORMAT_R10G10B10A2_UNORM:
00160     case DXGI_FORMAT_R10G10B10A2_UINT:
00161     case DXGI_FORMAT_R11G11B10_FLOAT:
00162     case DXGI_FORMAT_R8G8B8A8_TYPELESS:
00163     case DXGI_FORMAT_R8G8B8A8_UNORM:
00164     case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
00165     case DXGI_FORMAT_R8G8B8A8_UINT:
00166     case DXGI_FORMAT_R8G8B8A8_SNORM:
00167     case DXGI_FORMAT_R8G8B8A8_SINT:
00168     case DXGI_FORMAT_R16G16_TYPELESS:
00169     case DXGI_FORMAT_R16G16_FLOAT:
00170     case DXGI_FORMAT_R16G16_UNORM:
00171     case DXGI_FORMAT_R16G16_UINT:
00172     case DXGI_FORMAT_R16G16_SNORM:
00173     case DXGI_FORMAT_R16G16_SINT:
00174     case DXGI_FORMAT_R32_TYPELESS:
00175     case DXGI_FORMAT_D32_FLOAT:
00176     case DXGI_FORMAT_R32_FLOAT:
00177     case DXGI_FORMAT_R32_UINT:
00178     case DXGI_FORMAT_R32_SINT:
00179     case DXGI_FORMAT_R24G8_TYPELESS:
00180     case DXGI_FORMAT_D24_UNORM_S8_UINT:
00181     case DXGI_FORMAT_R24_UNORM_X8_TYPELESS:
00182     case DXGI_FORMAT_X24_TYPELESS_G8_UINT:
00183     case DXGI_FORMAT_R9G9B9E5_SHAREDEXP:
00184     case DXGI_FORMAT_R8G8_B8G8_UNORM:
00185     case DXGI_FORMAT_G8R8_G8B8_UNORM:
00186     case DXGI_FORMAT_B8G8R8A8_UNORM:
00187     case DXGI_FORMAT_B8G8R8X8_UNORM:
00188     case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM:
00189     case DXGI_FORMAT_B8G8R8A8_TYPELESS:
00190     case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
00191     case DXGI_FORMAT_B8G8R8X8_TYPELESS:
00192     case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB:
00193         return 32;
00194
00195     case DXGI_FORMAT_R8G8_TYPELESS:
00196     case DXGI_FORMAT_R8G8_UNORM:
00197     case DXGI_FORMAT_R8G8_UINT:
00198     case DXGI_FORMAT_R8G8_SNORM:
00199     case DXGI_FORMAT_R8G8_SINT:
00200     case DXGI_FORMAT_R16_TYPELESS:
00201     case DXGI_FORMAT_R16_FLOAT:
00202     case DXGI_FORMAT_D16_UNORM:
00203     case DXGI_FORMAT_R16_UNORM:
00204     case DXGI_FORMAT_R16_UINT:
00205     case DXGI_FORMAT_R16_SNORM:
00206     case DXGI_FORMAT_R16_SINT:
00207     case DXGI_FORMAT_B5G6R5_UNORM:
00208     case DXGI_FORMAT_B5G5R5A1_UNORM:
00209     case DXGI_FORMAT_B4G4R4A4_UNORM:
00210         return 16;
00211
00212     case DXGI_FORMAT_R8_TYPELESS:
00213     case DXGI_FORMAT_R8_UNORM:
00214     case DXGI_FORMAT_R8_UINT:
00215     case DXGI_FORMAT_R8_SNORM:
00216     case DXGI_FORMAT_R8_SINT:
00217     case DXGI_FORMAT_A8_UNORM:
00218         return 8;
00219
00220     case DXGI_FORMAT_R1_UNORM:
00221         return 1;
00222
00223     case DXGI_FORMAT_BC1_TYPELESS:
00224     case DXGI_FORMAT_BC1_UNORM:
00225     case DXGI_FORMAT_BC1_UNORM_SRGB:
00226     case DXGI_FORMAT_BC4_TYPELESS:
00227     case DXGI_FORMAT_BC4_UNORM:
00228     case DXGI_FORMAT_BC4_SNORM:
00229         return 4;
00230
00231     case DXGI_FORMAT_BC2_TYPELESS:
00232     case DXGI_FORMAT_BC2_UNORM:
00233     case DXGI_FORMAT_BC2_UNORM_SRGB:
00234     case DXGI_FORMAT_BC3_TYPELESS:
00235     case DXGI_FORMAT_BC3_UNORM:
00236     case DXGI_FORMAT_BC3_UNORM_SRGB:
00237     case DXGI_FORMAT_BC5_TYPELESS:
00238     case DXGI_FORMAT_BC5_UNORM:
00239     case DXGI_FORMAT_BC5_SNORM:
00240     case DXGI_FORMAT_BC6H_TYPELESS:
00241     case DXGI_FORMAT_BC6H_UF16:
00242     case DXGI_FORMAT_BC6H_SF16:
00243     case DXGI_FORMAT_BC7_TYPELESS:
00244     case DXGI_FORMAT_BC7_UNORM:
00245     case DXGI_FORMAT_BC7_UNORM_SRGB:
00246         return 8;
00247
00248     default:
00249         return 0;
00250     }
00251 }
00252
00253
00254 //--------------------------------------------------------------------------------------
00255 // Get surface information for a particular format
00256 //--------------------------------------------------------------------------------------
00257 static void GetSurfaceInfo(
00258     _In_ size_t width,
00259     _In_ size_t height,
00260     _In_ DXGI_FORMAT fmt,
00261     _Out_opt_ size_t* outNumBytes,
00262     _Out_opt_ size_t* outRowBytes,
00263     _Out_opt_ size_t* outNumRows
00264     )
00265 {
00266     size_t numBytes = 0;
00267     size_t rowBytes = 0;
00268     size_t numRows = 0;
00269
00270     bool bc = false;
00271     bool packed  = false;
00272     size_t bcnumBytesPerBlock = 0;
00273     switch (fmt)
00274     {
00275     case DXGI_FORMAT_BC1_TYPELESS:
00276     case DXGI_FORMAT_BC1_UNORM:
00277     case DXGI_FORMAT_BC1_UNORM_SRGB:
00278     case DXGI_FORMAT_BC4_TYPELESS:
00279     case DXGI_FORMAT_BC4_UNORM:
00280     case DXGI_FORMAT_BC4_SNORM:
00281         bc = true;
00282         bcnumBytesPerBlock = 8;
00283         break;
00284
00285     case DXGI_FORMAT_BC2_TYPELESS:
00286     case DXGI_FORMAT_BC2_UNORM:
00287     case DXGI_FORMAT_BC2_UNORM_SRGB:
00288     case DXGI_FORMAT_BC3_TYPELESS:
00289     case DXGI_FORMAT_BC3_UNORM:
00290     case DXGI_FORMAT_BC3_UNORM_SRGB:
00291     case DXGI_FORMAT_BC5_TYPELESS:
00292     case DXGI_FORMAT_BC5_UNORM:
00293     case DXGI_FORMAT_BC5_SNORM:
00294     case DXGI_FORMAT_BC6H_TYPELESS:
00295     case DXGI_FORMAT_BC6H_UF16:
00296     case DXGI_FORMAT_BC6H_SF16:
00297     case DXGI_FORMAT_BC7_TYPELESS:
00298     case DXGI_FORMAT_BC7_UNORM:
00299     case DXGI_FORMAT_BC7_UNORM_SRGB:
00300         bc = true;
00301         bcnumBytesPerBlock = 16;
00302         break;
00303
00304     case DXGI_FORMAT_R8G8_B8G8_UNORM:
00305     case DXGI_FORMAT_G8R8_G8B8_UNORM:
00306         packed = true;
00307         break;
00308     }
00309
00310     if (bc)
00311     {
00312         size_t numBlocksWide = 0;
00313         if (width > 0)
00314         {
00315             numBlocksWide = std::max<size_t>(1, (width + 3) / 4);
00316         }
00317         size_t numBlocksHigh = 0;
00318         if (height > 0)
00319         {
00320             numBlocksHigh = std::max<size_t>(1, (height + 3) / 4);
00321         }
00322         rowBytes = numBlocksWide * bcnumBytesPerBlock;
00323         numRows = numBlocksHigh;
00324     }
00325     else if (packed)
00326     {
00327         rowBytes = ((width + 1) >> 1) * 4;
00328         numRows = height;
00329     }
00330     else
00331     {
00332         size_t bpp = BitsPerPixel(fmt);
00333         rowBytes = (width * bpp + 7) / 8; // round up to nearest byte
00334         numRows = height;
00335     }
00336
00337     numBytes = rowBytes * numRows;
00338     if (outNumBytes)
00339     {
00340         *outNumBytes = numBytes;
00341     }
00342     if (outRowBytes)
00343     {
00344         *outRowBytes = rowBytes;
00345     }
00346     if (outNumRows)
00347     {
00348         *outNumRows = numRows;
00349     }
00350 }
00351
00352
00353 //--------------------------------------------------------------------------------------
00354 #define ISBITMASK(r, g, b, a) (ddpf.RBitMask == r && ddpf.GBitMask == g && ddpf.BBitMask == b && ddpf.ABitMask == a)
00355
00356 static DXGI_FORMAT GetDXGIFormat(const DDS_PIXELFORMAT& ddpf)
00357 {
00358     if (ddpf.flags & DDS_RGB)
00359     {
00360         // Note that sRGB formats are written using the "DX10" extended header
00361
00362         switch (ddpf.RGBBitCount)
00363         {
00364         case 32:
00365             if (ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000))
00366             {
00367                 return DXGI_FORMAT_R8G8B8A8_UNORM;
00368             }
00369
00370             if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000))
00371             {
00372                 return DXGI_FORMAT_B8G8R8A8_UNORM;
00373             }
00374
00375             if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0x00000000))
00376             {
00377                 return DXGI_FORMAT_B8G8R8X8_UNORM;
00378             }
00379
00380             // No DXGI format maps to ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0x00000000) aka D3DFMT_X8B8G8R8
00381
00382             // Note that many common DDS reader/writers (including D3DX) swap the
00383             // the RED/BLUE masks for 10:10:10:2 formats. We assumme
00384             // below that the 'backwards' header mask is being used since it is most
00385             // likely written by D3DX. The more robust solution is to use the 'DX10'
00386             // header extension and specify the DXGI_FORMAT_R10G10B10A2_UNORM format directly
00387
00388             // For 'correct' writers, this should be 0x000003ff, 0x000ffc00, 0x3ff00000 for RGB data
00389             if (ISBITMASK(0x3ff00000, 0x000ffc00, 0x000003ff, 0xc0000000))
00390             {
00391                 return DXGI_FORMAT_R10G10B10A2_UNORM;
00392             }
00393
00394             // No DXGI format maps to ISBITMASK(0x000003ff, 0x000ffc00, 0x3ff00000, 0xc0000000) aka D3DFMT_A2R10G10B10
00395
00396             if (ISBITMASK(0x0000ffff, 0xffff0000, 0x00000000, 0x00000000))
00397             {
00398                 return DXGI_FORMAT_R16G16_UNORM;
00399             }
00400
00401             if (ISBITMASK(0xffffffff, 0x00000000, 0x00000000, 0x00000000))
00402             {
00403                 // Only 32-bit color channel format in D3D9 was R32F
00404                 return DXGI_FORMAT_R32_FLOAT; // D3DX writes this out as a FourCC of 114
00405             }
00406             break;
00407
00408         case 24:
00409             // No 24bpp DXGI formats aka D3DFMT_R8G8B8
00410             break;
00411
00412         case 16:
00413             if (ISBITMASK(0x7c00, 0x03e0, 0x001f, 0x8000))
00414             {
00415                 return DXGI_FORMAT_B5G5R5A1_UNORM;
00416             }
00417             if (ISBITMASK(0xf800, 0x07e0, 0x001f, 0x0000))
00418             {
00419                 return DXGI_FORMAT_B5G6R5_UNORM;
00420             }
00421
00422             // No DXGI format maps to ISBITMASK(0x7c00, 0x03e0, 0x001f, 0x0000) aka D3DFMT_X1R5G5B5
00423             if (ISBITMASK(0x0f00, 0x00f0, 0x000f, 0xf000))
00424             {
00425                 return DXGI_FORMAT_B4G4R4A4_UNORM;
00426             }
00427
00428             // No DXGI format maps to ISBITMASK(0x0f00, 0x00f0, 0x000f, 0x0000) aka D3DFMT_X4R4G4B4
00429
00430             // No 3:3:2, 3:3:2:8, or paletted DXGI formats aka D3DFMT_A8R3G3B2, D3DFMT_R3G3B2, D3DFMT_P8, D3DFMT_A8P8, etc.
00431             break;
00432         }
00433     }
00434     else if (ddpf.flags & DDS_LUMINANCE)
00435     {
00436         if (8 == ddpf.RGBBitCount)
00437         {
00438             if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x00000000))
00439             {
00440                 return DXGI_FORMAT_R8_UNORM; // D3DX10/11 writes this out as DX10 extension
00441             }
00442
00443             // No DXGI format maps to ISBITMASK(0x0f, 0x00, 0x00, 0xf0) aka D3DFMT_A4L4
00444         }
00445
00446         if (16 == ddpf.RGBBitCount)
00447         {
00448             if (ISBITMASK(0x0000ffff, 0x00000000, 0x00000000, 0x00000000))
00449             {
00450                 return DXGI_FORMAT_R16_UNORM; // D3DX10/11 writes this out as DX10 extension
00451             }
00452             if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x0000ff00))
00453             {
00454                 return DXGI_FORMAT_R8G8_UNORM; // D3DX10/11 writes this out as DX10 extension
00455             }
00456         }
00457     }
00458     else if (ddpf.flags & DDS_ALPHA)
00459     {
00460         if (8 == ddpf.RGBBitCount)
00461         {
00462             return DXGI_FORMAT_A8_UNORM;
00463         }
00464     }
00465     else if (ddpf.flags & DDS_FOURCC)
00466     {
00467         if (MAKEFOURCC('D', 'X', 'T', '1') == ddpf.fourCC)
00468         {
00469             return DXGI_FORMAT_BC1_UNORM;
00470         }
00471         if (MAKEFOURCC('D', 'X', 'T', '3') == ddpf.fourCC)
00472         {
00473             return DXGI_FORMAT_BC2_UNORM;
00474         }
00475         if (MAKEFOURCC('D', 'X', 'T', '5') == ddpf.fourCC)
00476         {
00477             return DXGI_FORMAT_BC3_UNORM;
00478         }
00479
00480         // While pre-mulitplied alpha isn't directly supported by the DXGI formats,
00481         // they are basically the same as these BC formats so they can be mapped
00482         if (MAKEFOURCC('D', 'X', 'T', '2') == ddpf.fourCC)
00483         {
00484             return DXGI_FORMAT_BC2_UNORM;
00485         }
00486         if (MAKEFOURCC('D', 'X', 'T', '4') == ddpf.fourCC)
00487         {
00488             return DXGI_FORMAT_BC3_UNORM;
00489         }
00490
00491         if (MAKEFOURCC('A', 'T', 'I', '1') == ddpf.fourCC)
00492         {
00493             return DXGI_FORMAT_BC4_UNORM;
00494         }
00495         if (MAKEFOURCC('B', 'C', '4', 'U') == ddpf.fourCC)
00496         {
00497             return DXGI_FORMAT_BC4_UNORM;
00498         }
00499         if (MAKEFOURCC('B', 'C', '4', 'S') == ddpf.fourCC)
00500         {
00501             return DXGI_FORMAT_BC4_SNORM;
00502         }
00503
00504         if (MAKEFOURCC('A', 'T', 'I', '2') == ddpf.fourCC)
00505         {
00506             return DXGI_FORMAT_BC5_UNORM;
00507         }
00508         if (MAKEFOURCC('B', 'C', '5', 'U') == ddpf.fourCC)
00509         {
00510             return DXGI_FORMAT_BC5_UNORM;
00511         }
00512         if (MAKEFOURCC('B', 'C', '5', 'S') == ddpf.fourCC)
00513         {
00514             return DXGI_FORMAT_BC5_SNORM;
00515         }
00516
00517         // BC6H and BC7 are written using the "DX10" extended header
00518
00519         if (MAKEFOURCC('R', 'G', 'B', 'G') == ddpf.fourCC)
00520         {
00521             return DXGI_FORMAT_R8G8_B8G8_UNORM;
00522         }
00523         if (MAKEFOURCC('G', 'R', 'G', 'B') == ddpf.fourCC)
00524         {
00525             return DXGI_FORMAT_G8R8_G8B8_UNORM;
00526         }
00527
00528         // Check for D3DFORMAT enums being set here
00529         switch (ddpf.fourCC)
00530         {
00531         case 36: // D3DFMT_A16B16G16R16
00532             return DXGI_FORMAT_R16G16B16A16_UNORM;
00533
00534         case 110: // D3DFMT_Q16W16V16U16
00535             return DXGI_FORMAT_R16G16B16A16_SNORM;
00536
00537         case 111: // D3DFMT_R16F
00538             return DXGI_FORMAT_R16_FLOAT;
00539
00540         case 112: // D3DFMT_G16R16F
00541             return DXGI_FORMAT_R16G16_FLOAT;
00542
00543         case 113: // D3DFMT_A16B16G16R16F
00544             return DXGI_FORMAT_R16G16B16A16_FLOAT;
00545
00546         case 114: // D3DFMT_R32F
00547             return DXGI_FORMAT_R32_FLOAT;
00548
00549         case 115: // D3DFMT_G32R32F
00550             return DXGI_FORMAT_R32G32_FLOAT;
00551
00552         case 116: // D3DFMT_A32B32G32R32F
00553             return DXGI_FORMAT_R32G32B32A32_FLOAT;
00554         }
00555     }
00556
00557     return DXGI_FORMAT_UNKNOWN;
00558 }
00559
00560
00561 //--------------------------------------------------------------------------------------
00562 static void FillInitData(
00563     _In_ size_t width,
00564     _In_ size_t height,
00565     _In_ size_t depth,
00566     _In_ size_t mipCount,
00567     _In_ size_t arraySize,
00568     _In_ DXGI_FORMAT format,
00569     _In_ size_t maxsize,
00570     _In_ size_t bitSize,
00571     _In_reads_bytes_(bitSize) const byte* bitData,
00572     _Out_ size_t& twidth,
00573     _Out_ size_t& theight,
00574     _Out_ size_t& tdepth,
00575     _Out_ size_t& skipMip,
00576     _Out_writes_(mipCount*arraySize) D3D11_SUBRESOURCE_DATA* initData
00577     )
00578 {
00579     if (!bitData || !initData)
00580     {
00581         throw ref new Platform::InvalidArgumentException();
00582     }
00583
00584     skipMip = 0;
00585     twidth = 0;
00586     theight = 0;
00587     tdepth = 0;
00588
00589     size_t NumBytes = 0;
00590     size_t RowBytes = 0;
00591     size_t NumRows = 0;
00592     const byte* pSrcBits = bitData;
00593     const byte* pEndBits = bitData + bitSize;
00594
00595     size_t index = 0;
00596     for (size_t j = 0; j < arraySize; j++)
00597     {
00598         size_t w = width;
00599         size_t h = height;
00600         size_t d = depth;
00601         for (size_t i = 0; i < mipCount; i++)
00602         {
00603             GetSurfaceInfo(w, h, format, &NumBytes, &RowBytes, &NumRows);
00604
00605             if ((mipCount <= 1) || !maxsize || (w <= maxsize && h <= maxsize && d <= maxsize))
00606             {
00607                 if (!twidth)
00608                 {
00609                     twidth = w;
00610                     theight = h;
00611                     tdepth = d;
00612                 }
00613
00614                 initData[index].pSysMem = (const void*)pSrcBits;
00615                 initData[index].SysMemPitch = static_cast<UINT>(RowBytes);
00616                 initData[index].SysMemSlicePitch = static_cast<UINT>(NumBytes);
00617                 ++index;
00618             }
00619             else
00620             {
00621                 ++skipMip;
00622             }
00623
00624             if (pSrcBits + (NumBytes*d) > pEndBits)
00625             {
00626                 throw ref new Platform::OutOfBoundsException();
00627             }
00628
00629             pSrcBits += NumBytes * d;
00630
00631             w = w >> 1;
00632             h = h >> 1;
00633             d = d >> 1;
00634             if (w == 0)
00635             {
00636                 w = 1;
00637             }
00638             if (h == 0)
00639             {
00640                 h = 1;
00641             }
00642             if (d == 0)
00643             {
00644                 d = 1;
00645             }
00646         }
00647     }
00648
00649     if (!index)
00650     {
00651         throw ref new Platform::FailureException();
00652     }
00653 }
00654
00655
00656 //--------------------------------------------------------------------------------------
00657 static HRESULT CreateD3DResources(
00658     _In_ ID3D11Device* d3dDevice,
00659     _In_ uint32 resDim,
00660     _In_ size_t width,
00661     _In_ size_t height,
00662     _In_ size_t depth,
00663     _In_ size_t mipCount,
00664     _In_ size_t arraySize,
00665     _In_ DXGI_FORMAT format,
00666     _In_ bool isCubeMap,
00667     _In_reads_(mipCount*arraySize) D3D11_SUBRESOURCE_DATA* initData,
00668     _Out_opt_ ID3D11Resource** texture,
00669     _Out_opt_ ID3D11ShaderResourceView** textureView
00670     )
00671 {
00672     if (!d3dDevice || !initData)
00673     {
00674         return E_INVALIDARG;
00675     }
00676
00677     HRESULT hr = E_FAIL;
00678
00679     switch (resDim)
00680     {
00681         case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
00682             {
00683                 D3D11_TEXTURE1D_DESC desc;
00684                 desc.Width = static_cast<UINT>(width);
00685                 desc.MipLevels = static_cast<UINT>(mipCount);
00686                 desc.ArraySize = static_cast<UINT>(arraySize);
00687                 desc.Format = format;
00688                 desc.Usage = D3D11_USAGE_DEFAULT;
00689                 desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
00690                 desc.CPUAccessFlags = 0;
00691                 desc.MiscFlags = 0;
00692
00693                 ID3D11Texture1D* tex = nullptr;
00694                 hr = d3dDevice->CreateTexture1D(&desc, initData, &tex);
00695
00696                 if (SUCCEEDED(hr) && tex != 0)
00697                 {
00698                     if (textureView != 0)
00699                     {
00700                         D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
00701                         memset(&SRVDesc, 0, sizeof(SRVDesc));
00702                         SRVDesc.Format = format;
00703
00704                         if (arraySize > 1)
00705                         {
00706                             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE1DARRAY;
00707                             SRVDesc.Texture1DArray.MipLevels = desc.MipLevels;
00708                             SRVDesc.Texture1DArray.ArraySize = static_cast<UINT>(arraySize);
00709                         }
00710                         else
00711                         {
00712                             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE1D;
00713                             SRVDesc.Texture1D.MipLevels = desc.MipLevels;
00714                         }
00715
00716                         hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView);
00717
00718                         if (FAILED(hr))
00719                         {
00720                             tex->Release();
00721                             return hr;
00722                         }
00723                     }
00724
00725                     if (texture != 0)
00726                     {
00727                         *texture = tex;
00728                     }
00729                     else
00730                     {
00731                         tex->Release();
00732                     }
00733                 }
00734             }
00735             break;
00736
00737         case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
00738             {
00739                 D3D11_TEXTURE2D_DESC desc;
00740                 desc.Width = static_cast<UINT>(width);
00741                 desc.Height = static_cast<UINT>(height);
00742                 desc.MipLevels = static_cast<UINT>(mipCount);
00743                 desc.ArraySize = static_cast<UINT>(arraySize);
00744                 desc.Format = format;
00745                 desc.SampleDesc.Count = 1;
00746                 desc.SampleDesc.Quality = 0;
00747                 desc.Usage = D3D11_USAGE_DEFAULT;
00748                 desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
00749                 desc.CPUAccessFlags = 0;
00750                 desc.MiscFlags = (isCubeMap) ? D3D11_RESOURCE_MISC_TEXTURECUBE : 0;
00751
00752                 ID3D11Texture2D* tex = nullptr;
00753                 hr = d3dDevice->CreateTexture2D(&desc, initData, &tex);
00754
00755                 if (SUCCEEDED(hr) && tex != 0)
00756                 {
00757                     if (textureView != 0)
00758                     {
00759                         D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
00760                         memset(&SRVDesc, 0, sizeof(SRVDesc));
00761                         SRVDesc.Format = format;
00762
00763                         if (isCubeMap)
00764                         {
00765                             if (arraySize > 6)
00766                             {
00767                                 SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURECUBEARRAY;
00768                                 SRVDesc.TextureCubeArray.MipLevels = desc.MipLevels;
00769
00770                                 // Earlier we set arraySize to (NumCubes * 6)
00771                                 SRVDesc.TextureCubeArray.NumCubes = static_cast<UINT>(arraySize / 6);
00772                             }
00773                             else
00774                             {
00775                                 SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURECUBE;
00776                                 SRVDesc.TextureCube.MipLevels = desc.MipLevels;
00777                             }
00778                         }
00779                         else if (arraySize > 1)
00780                         {
00781                             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE2DARRAY;
00782                             SRVDesc.Texture2DArray.MipLevels = desc.MipLevels;
00783                             SRVDesc.Texture2DArray.ArraySize = static_cast<UINT>(arraySize);
00784                         }
00785                         else
00786                         {
00787                             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE2D;
00788                             SRVDesc.Texture2D.MipLevels = desc.MipLevels;
00789                         }
00790
00791                         hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView);
00792
00793                         if (FAILED(hr))
00794                         {
00795                             tex->Release();
00796                             return hr;
00797                         }
00798                     }
00799
00800                     if (texture != 0)
00801                     {
00802                         *texture = tex;
00803                     }
00804                     else
00805                     {
00806                         tex->Release();
00807                     }
00808                 }
00809             }
00810             break;
00811
00812         case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
00813             {
00814                 D3D11_TEXTURE3D_DESC desc;
00815                 desc.Width = static_cast<UINT>(width);
00816                 desc.Height = static_cast<UINT>(height);
00817                 desc.Depth = static_cast<UINT>(depth);
00818                 desc.MipLevels = static_cast<UINT>(mipCount);
00819                 desc.Format = format;
00820                 desc.Usage = D3D11_USAGE_DEFAULT;
00821                 desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
00822                 desc.CPUAccessFlags = 0;
00823                 desc.MiscFlags = 0;
00824
00825                 ID3D11Texture3D* tex = nullptr;
00826                 hr = d3dDevice->CreateTexture3D(&desc, initData, &tex);
00827
00828                 if (SUCCEEDED(hr) && tex != 0)
00829                 {
00830                     if (textureView != 0)
00831                     {
00832                         D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
00833                         memset(&SRVDesc, 0, sizeof(SRVDesc));
00834                         SRVDesc.Format = format;
00835                         SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE3D;
00836                         SRVDesc.Texture3D.MipLevels = desc.MipLevels;
00837
00838                         hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView);
00839
00840                         if (FAILED(hr))
00841                         {
00842                             tex->Release();
00843                             return hr;
00844                         }
00845                     }
00846
00847                     if (texture != 0)
00848                     {
00849                         *texture = tex;
00850                     }
00851                     else
00852                     {
00853                         tex->Release();
00854                     }
00855                 }
00856             }
00857             break;
00858     }
00859
00860     return hr;
00861 }
00862
00863
00864 //--------------------------------------------------------------------------------------
00865 static void CreateTextureFromDDS(
00866     _In_ ID3D11Device* d3dDevice,
00867     _In_ const DDS_HEADER* header,
00868     _In_reads_bytes_(bitSize) const byte* bitData,
00869     _In_ size_t bitSize,
00870     _Out_opt_ ID3D11Resource** texture,
00871     _Out_opt_ ID3D11ShaderResourceView** textureView,
00872     _In_ size_t maxsize
00873     )
00874 {
00875     HRESULT hr = S_OK;
00876
00877     size_t width = header->width;
00878     size_t height = header->height;
00879     size_t depth = header->depth;
00880
00881     uint32 resDim = D3D11_RESOURCE_DIMENSION_UNKNOWN;
00882     size_t arraySize = 1;
00883     DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;
00884     bool isCubeMap = false;
00885
00886     size_t mipCount = header->mipMapCount;
00887     if (0 == mipCount)
00888     {
00889         mipCount = 1;
00890     }
00891
00892     if ((header->ddspf.flags & DDS_FOURCC) &&
00893         (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC))
00894     {
00895         const DDS_HEADER_DXT10* d3d10ext = reinterpret_cast<const DDS_HEADER_DXT10*>((const char*)header + sizeof(DDS_HEADER));
00896
00897         arraySize = d3d10ext->arraySize;
00898         if (arraySize == 0)
00899         {
00900             throw ref new Platform::FailureException();
00901         }
00902
00903         if (BitsPerPixel(d3d10ext->dxgiFormat) == 0)
00904         {
00905             throw ref new Platform::FailureException();
00906         }
00907
00908         format = d3d10ext->dxgiFormat;
00909
00910         switch (d3d10ext->resourceDimension)
00911         {
00912         case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
00913             // D3DX writes 1D textures with a fixed Height of 1
00914             if ((header->flags & DDS_HEIGHT) && height != 1)
00915             {
00916                 throw ref new Platform::FailureException();
00917             }
00918             height = depth = 1;
00919             break;
00920
00921         case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
00922             if (d3d10ext->miscFlag & D3D11_RESOURCE_MISC_TEXTURECUBE)
00923             {
00924                 arraySize *= 6;
00925                 isCubeMap = true;
00926             }
00927             depth = 1;
00928             break;
00929
00930         case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
00931             if (!(header->flags & DDS_HEADER_FLAGS_VOLUME))
00932             {
00933                 throw ref new Platform::FailureException();
00934             }
00935
00936             if (arraySize > 1)
00937             {
00938                 throw ref new Platform::FailureException();
00939             }
00940             break;
00941
00942         default:
00943             return throw ref new Platform::FailureException();
00944         }
00945
00946         resDim = d3d10ext->resourceDimension;
00947     }
00948     else
00949     {
00950         format = GetDXGIFormat(header->ddspf);
00951
00952         if (format == DXGI_FORMAT_UNKNOWN)
00953         {
00954             return throw ref new Platform::FailureException();
00955         }
00956
00957         if (header->flags & DDS_HEADER_FLAGS_VOLUME)
00958         {
00959             resDim = D3D11_RESOURCE_DIMENSION_TEXTURE3D;
00960         }
00961         else
00962         {
00963             if (header->caps2 & DDS_CUBEMAP)
00964             {
00965                 // We require all six faces to be defined
00966                 if ((header->caps2 & DDS_CUBEMAP_ALLFACES) != DDS_CUBEMAP_ALLFACES)
00967                 {
00968                     return throw ref new Platform::FailureException();
00969                 }
00970
00971                 arraySize = 6;
00972                 isCubeMap = true;
00973             }
00974
00975             depth = 1;
00976             resDim = D3D11_RESOURCE_DIMENSION_TEXTURE2D;
00977
00978             // Note there's no way for a legacy Direct3D 9 DDS to express a '1D' texture
00979         }
00980
00981         assert(BitsPerPixel(format) != 0);
00982     }
00983
00984     // Bound sizes (for security purposes we don't trust DDS file metadata larger than the D3D 11.x hardware requirements)
00985     if (mipCount > D3D11_REQ_MIP_LEVELS)
00986     {
00987         return throw ref new Platform::FailureException();
00988     }
00989
00990     switch (resDim)
00991     {
00992         case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
00993             if ((arraySize > D3D11_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION) ||
00994                 (width > D3D11_REQ_TEXTURE1D_U_DIMENSION))
00995             {
00996                 return throw ref new Platform::FailureException();
00997             }
00998             break;
00999
01000         case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
01001             if (isCubeMap)
01002             {
01003                 // This is the right bound because we set arraySize to (NumCubes*6) above
01004                 if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) ||
01005                     (width > D3D11_REQ_TEXTURECUBE_DIMENSION) ||
01006                     (height > D3D11_REQ_TEXTURECUBE_DIMENSION))
01007                 {
01008                     return throw ref new Platform::FailureException();
01009                 }
01010             }
01011             else if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) ||
01012                     (width > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION) ||
01013                     (height > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION))
01014             {
01015                 return throw ref new Platform::FailureException();
01016             }
01017             break;
01018
01019         case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
01020             if ((arraySize > 1) ||
01021                 (width > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) ||
01022                 (height > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) ||
01023                 (depth > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION))
01024             {
01025                 return throw ref new Platform::FailureException();
01026             }
01027             break;
01028     }
01029
01030     // Create the texture
01031     std::unique_ptr<D3D11_SUBRESOURCE_DATA> initData(new D3D11_SUBRESOURCE_DATA[mipCount * arraySize]);
01032
01033     size_t skipMip = 0;
01034     size_t twidth = 0;
01035     size_t theight = 0;
01036     size_t tdepth = 0;
01037     FillInitData(width, height, depth, mipCount, arraySize, format, maxsize, bitSize, bitData, twidth, theight, tdepth, skipMip, initData.get());
01038
01039     hr = CreateD3DResources(d3dDevice, resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize, format, isCubeMap, initData.get(), texture, textureView);
01040
01041     if (FAILED(hr) && !maxsize && (mipCount > 1))
01042     {
01043         // Retry with a maxsize determined by feature level
01044         switch (d3dDevice->GetFeatureLevel())
01045         {
01046         case D3D_FEATURE_LEVEL_9_1:
01047         case D3D_FEATURE_LEVEL_9_2:
01048             if (isCubeMap)
01049             {
01050                 maxsize = D3D_FL9_1_REQ_TEXTURECUBE_DIMENSION;
01051             }
01052             else
01053             {
01054                 maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D)
01055                     ? D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION
01056                     : D3D_FL9_1_REQ_TEXTURE2D_U_OR_V_DIMENSION;
01057             }
01058             break;
01059
01060         case D3D_FEATURE_LEVEL_9_3:
01061             maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D)
01062                 ? D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION
01063                 : D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION;
01064             break;
01065
01066         default: // D3D_FEATURE_LEVEL_10_0 & D3D_FEATURE_LEVEL_10_1
01067             maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D)
01068                 ? D3D10_REQ_TEXTURE3D_U_V_OR_W_DIMENSION
01069                 : D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION;
01070             break;
01071         }
01072
01073         FillInitData(width, height, depth, mipCount, arraySize, format, maxsize, bitSize, bitData, twidth, theight, tdepth, skipMip, initData.get());
01074
01075         hr = CreateD3DResources(d3dDevice, resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize, format, isCubeMap, initData.get(), texture, textureView);
01076     }
01077
01078     DX::ThrowIfFailed(hr);
01079 }
01080
01081 //--------------------------------------------------------------------------------------
01082 void CreateDDSTextureFromMemory(
01083     _In_ ID3D11Device* d3dDevice,
01084     _In_reads_bytes_(ddsDataSize) const byte* ddsData,
01085     _In_ size_t ddsDataSize,
01086     _Out_opt_ ID3D11Resource** texture,
01087     _Out_opt_ ID3D11ShaderResourceView** textureView,
01088     _In_ size_t maxsize
01089     )
01090 {
01091     if (!d3dDevice || !ddsData || (!texture && !textureView))
01092     {
01093         throw ref new Platform::InvalidArgumentException();
01094     }
01095
01096     // Validate DDS file in memory
01097     if (ddsDataSize < (sizeof(uint32) + sizeof(DDS_HEADER)))
01098     {
01099         throw ref new Platform::FailureException();
01100     }
01101
01102     uint32 dwMagicNumber = *(const uint32*)(ddsData);
01103     if (dwMagicNumber != DDS_MAGIC)
01104     {
01105         throw ref new Platform::FailureException();
01106     }
01107
01108     const DDS_HEADER* header = reinterpret_cast<const DDS_HEADER*>(ddsData + sizeof(uint32));
01109
01110     // Verify header to validate DDS file
01111     if (header->size != sizeof(DDS_HEADER) ||
01112         header->ddspf.size != sizeof(DDS_PIXELFORMAT))
01113     {
01114         throw ref new Platform::FailureException();
01115     }
01116
01117     // Check for DX10 extension
01118     bool bDXT10Header = false;
01119     if ((header->ddspf.flags & DDS_FOURCC) &&
01120         (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC))
01121     {
01122         // Must be long enough for both headers and magic value
01123         if (ddsDataSize < (sizeof(DDS_HEADER) + sizeof(uint32) + sizeof(DDS_HEADER_DXT10)))
01124         {
01125             throw ref new Platform::FailureException();
01126         }
01127
01128         bDXT10Header = true;
01129     }
01130
01131     ptrdiff_t offset = sizeof(uint32) + sizeof(DDS_HEADER) + (bDXT10Header ? sizeof(DDS_HEADER_DXT10) : 0);
01132
01133     CreateTextureFromDDS(d3dDevice, header, ddsData + offset, ddsDataSize - offset, texture, textureView, maxsize);
01134 }
Generated on Sat Nov 23 2024 16:08:10 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DWriteCustomTextRenderer Member List

This is the complete list of members for DWriteCustomTextRenderer, including all inherited members.
__pad0__ | DWriteCustomTextRenderer |
CreateDeviceIndependentResources() override | DWriteCustomTextRenderer | [virtual]
CreateDeviceResources() override | DWriteCustomTextRenderer | [virtual]
CreateWindowSizeDependentResources() override | DWriteCustomTextRenderer | [virtual]
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | DWriteCustomTextRenderer | [virtual]
Load(_In_ Platform::String^entryPoint) | DWriteCustomTextRenderer | [virtual]
m_bitmapBrush | DWriteCustomTextRenderer | [private]
m_blackBrush | DWriteCustomTextRenderer | [private]
m_logoBitmap | DWriteCustomTextRenderer | [private]
m_sampleOverlay | DWriteCustomTextRenderer | [private]
m_textFormat | DWriteCustomTextRenderer | [private]
m_textLayout | DWriteCustomTextRenderer | [private]
m_textRenderer | DWriteCustomTextRenderer | [private]
m_textTypography | DWriteCustomTextRenderer | [private]
m_wicBitmapDecoder | DWriteCustomTextRenderer | [private]
m_wicBitmapFrame | DWriteCustomTextRenderer | [private]
m_wicFormatConverter | DWriteCustomTextRenderer | [private]
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | DWriteCustomTextRenderer | [private]
OnDisplayContentsInvalidated(_In_ Platform::Object^sender) | DWriteCustomTextRenderer | [private]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | DWriteCustomTextRenderer | [private]
OnResuming(_In_ Platform::Object^sender, _In_ Platform::Object^args) | DWriteCustomTextRenderer | [private]
OnSuspending(_In_ Platform::Object^sender, _In_ Windows::ApplicationModel::SuspendingEventArgs^args) | DWriteCustomTextRenderer | [private]
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | DWriteCustomTextRenderer | [private]
Render() override | DWriteCustomTextRenderer | [virtual]
Run() | DWriteCustomTextRenderer | [virtual]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | DWriteCustomTextRenderer | [virtual]
Uninitialize() | DWriteCustomTextRenderer | [virtual]
Generated on Sat Nov 23 2024 16:09:12 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Compass sensor/C++/MainPage.xaml.h Source File

  • Compass sensor

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Portable device API/C++/S2_Enumeration.xaml.h Source File

  • Portable device API

S2_Enumeration.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 // S2_Enumeration.xaml.h
00013 // Declaration of the S2_Enumeration class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "S2_Enumeration.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace PortableDeviceCPP
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 S2_Enumeration sealed
00031         {
00032         public:
00033             S2_Enumeration();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037
00038         private:
00039             void Run_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040             void ShowDeviceSelectorAsync();
00041             void DeviceList_Tapped(Platform::Object^ sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^ e);
00042             void EnumerateObjects(Windows::Devices::Enumeration::DeviceInformation^ deviceInfoElement);
00043
00044             MainPage^ rootPage;
00045             // Contains the device information used for populating the device selection list
00046             Windows::Devices::Enumeration::DeviceInformationCollection^ _deviceInfoCollection;
00047         };
00048     }
00049 }
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

AudioController Member List

This is the complete list of members for AudioController, including all inherited members.
__pad0__ | AudioController |
CreateAudioVoices(_In_ const char16 *deviceEndpointId) | AudioController |
CreateDeviceResources() override | AudioController | [virtual]
CreateWindowSizeDependentResources() override | AudioController | [virtual]
FetchControllerInput() | AudioController |
m_aButtonWasPressed | AudioController | [private]
m_audioEngine | AudioController | [private]
m_dataTextFormat | AudioController | [private]
m_isControllerConnected | AudioController | [private]
m_isHeadsetConnected | AudioController | [private]
m_lastEnumTime | AudioController | [private]
m_lastHeadsetCheckTime | AudioController | [private]
m_masteringVoice | AudioController | [private]
m_sampleOverlay | AudioController | [private]
m_soundEffectBuffer | AudioController | [private]
m_sourceVoice | AudioController | [private]
m_textBrush | AudioController | [private]
m_xinputCaps | AudioController | [private]
m_xinputState | AudioController | [private]
OnResuming() | AudioController |
OnSuspending() | AudioController |
ReleaseAudioResources() | AudioController |
Render() override | AudioController | [virtual]
TriggerSoundEffect() | AudioController |
Update(float TimeTotal, float TimeDelta) | AudioController |
~AudioController() | AudioController | [private]
Generated on Sat Nov 23 2024 16:09:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Language font mapping/C++/App.xaml.h Source File

  • Language font mapping

App.xaml.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 //
00009 // App.xaml.h
00010 // Declaration of the App.xaml class.
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "App.g.h"
00017
00018 namespace LanguageFontCPP
00019 {
00020     ref class App sealed
00021     {
00022     public:
00023         App();
00024         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00025         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00026     };
00027 }
00028
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D geometry realization/C++/GeometryRealizationPackage.cpp Source File

  • Direct2D geometry realization

GeometryRealizationPackage.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 //
00009 // The following is a relatively simple implementation of realizations, built
00010 // on top of Direct2D's mesh and opacity mask primitives (meshes for aliased and
00011 // multi-sampled anti-aliased rendering and opacity masks for per-primitive
00012 // anti-aliased rendering).
00013 //
00014 // One IGeometryRealization object can hold up to 4 "sub-realizations",
00015 // corresponding to the matrix {Aliased, PPAA} x {Filled, Stroked}. The user
00016 // can specify which sub-realizations to generate by passing in the appropriate
00017 // REALIZATION_CREATION_OPTIONS.
00018 //
00019 // The implementation of the PPAA realizations is somewhat primitive. It will
00020 // attempt to reuse existing bitmaps when possible, but it will not, for
00021 // instance, attempt to use a single bitmap to store multiple realizations
00022 // ("atlasing"). An atlased implementation would be somewhat more performant,
00023 // as the number of state switches that Direct2D would have to make when
00024 // interleaving realizations of different geometries would be greatly reduced.
00025 //
00026 // Another limitation in the PPAA implementation below is that it can use very
00027 // large amounts of video-memory even for very simple primitives. Consider, for
00028 // instance, a thin diagonal line stretching from the top-left corner of the
00029 // render-target to the bottom-right. To store this as a single opacity mask, a
00030 // bitmap the size of the entire render target must be created, even though the
00031 // area of the stroke is very small. This can also have a severe impact on
00032 // performance, as the video card has to waste numerous cycles rendering fully-
00033 // transparent pixels.
00034 //
00035 // A more sophisticated implementation of PPAA realizations would divide the
00036 // geometry up into a grid of bitmaps. Grid cells that contained no
00037 // content or were fully covered by the geometry could be optimized away. The
00038 // partially covered grid cells could be atlased for a further boost in
00039 // performance.
00040 //
00041
00042
00043 #include "pch.h"
00044 #ifndef _NO_PRECOMPILED_HEADER_
00045 #include "GeometryRealizationPackage.h"
00046 #endif
00047
00048
00049 //+-----------------------------------------------------------------------------
00050 //
00051 //  Class:
00052 //      GeometryRealization
00053 //
00054 //------------------------------------------------------------------------------
00055 class GeometryRealization : public IGeometryRealization
00056 {
00057 public:
00058     STDMETHOD(Fill)(
00059         ID2D1DeviceContext *deviceContext,
00060         ID2D1Brush *brush,
00061         REALIZATION_RENDER_MODE mode
00062         );
00063
00064     STDMETHOD(Draw)(
00065         ID2D1DeviceContext *deviceContext,
00066         ID2D1Brush *brush,
00067         REALIZATION_RENDER_MODE mode
00068         );
00069
00070     STDMETHOD(Update)(
00071         ID2D1Geometry *geometry,
00072         REALIZATION_CREATION_OPTIONS options,
00073         CONST D2D1_MATRIX_3X2_F *worldTransform,
00074         float strokeWidth,
00075         ID2D1StrokeStyle *strokeStyle
00076         );
00077
00078     STDMETHOD_(ULONG, AddRef)();
00079     STDMETHOD_(ULONG, Release)();
00080
00081     STDMETHOD(QueryInterface)(
00082         REFIID iid,
00083         void ** ppvObject
00084         );
00085
00086     static HRESULT Create(
00087         ID2D1DeviceContext *deviceContext,
00088         UINT maxRealizationDimension,
00089         ID2D1Geometry *geometry,
00090         REALIZATION_CREATION_OPTIONS options,
00091         CONST D2D1_MATRIX_3X2_F *worldTransform,
00092         float strokeWidth,
00093         ID2D1StrokeStyle *strokeStyle,
00094         IGeometryRealization **realization
00095         );
00096
00097 // These methods are declared protected for white-box unit-testing.
00098 protected:
00099     // Non-interface methods
00100     GeometryRealization();
00101     ~GeometryRealization();
00102
00103     HRESULT Initialize(
00104         ID2D1DeviceContext *deviceContext,
00105         UINT maxRealizationDimension,
00106         ID2D1Geometry *geometry,
00107         REALIZATION_CREATION_OPTIONS options,
00108         CONST D2D1_MATRIX_3X2_F *worldTransform,
00109         float strokeWidth,
00110         ID2D1StrokeStyle *strokeStyle
00111         );
00112
00113     static HRESULT GenerateOpacityMask(
00114         bool fill,
00115         ID2D1DeviceContext *baseRT,
00116         UINT maxRealizationDimension,
00117         ID2D1BitmapRenderTarget **bitmapRT,
00118         ID2D1Geometry *geometry,
00119         const D2D1_MATRIX_3X2_F *worldTransform,
00120         float strokeWidth,
00121         ID2D1StrokeStyle *strokeStyle,
00122         D2D1_RECT_F *maskDestBounds,
00123         D2D1_RECT_F *maskSourceBounds
00124         );
00125
00126     HRESULT RenderToTarget(
00127         bool fill,
00128         ID2D1DeviceContext *deviceContext,
00129         ID2D1Brush *brush,
00130         REALIZATION_RENDER_MODE mode
00131         );
00132
00133     ID2D1Mesh *m_fillMesh;
00134     ID2D1Mesh *m_strokeMesh;
00135
00136     ID2D1BitmapRenderTarget *m_fillRT;
00137     ID2D1BitmapRenderTarget *m_strokeRT;
00138
00139     ID2D1Geometry *m_geometry;
00140     ID2D1StrokeStyle *m_strokeStyle;
00141     float m_strokeWidth;
00142
00143     D2D1_RECT_F m_fillMaskDestBounds;
00144     D2D1_RECT_F m_fillMaskSourceBounds;
00145
00146     D2D1_RECT_F m_strokeMaskDestBounds;
00147     D2D1_RECT_F m_strokeMaskSourceBounds;
00148
00149     ID2D1DeviceContext *m_deviceContext;
00150
00151     bool m_realizationTransformIsIdentity;
00152     D2D1::Matrix3x2F m_realizationTransform;
00153     D2D1::Matrix3x2F m_realizationTransformInv;
00154
00155     BOOL m_swRT;
00156
00157     UINT m_maxRealizationDimension;
00158
00159     ULONG volatile m_ref;
00160 };
00161
00162 //+-----------------------------------------------------------------------------
00163 //
00164 //  Class:
00165 //      GeometryRealizationFactory
00166 //
00167 //------------------------------------------------------------------------------
00168 class GeometryRealizationFactory : public IGeometryRealizationFactory
00169 {
00170 public:
00171     STDMETHOD(CreateGeometryRealization)(
00172         IGeometryRealization **realization
00173         );
00174
00175     STDMETHOD(CreateGeometryRealization)(
00176         ID2D1Geometry *geometry,
00177         REALIZATION_CREATION_OPTIONS options,
00178         CONST D2D1_MATRIX_3X2_F *worldTransform,
00179         float strokeWidth,
00180         ID2D1StrokeStyle *strokeStyle,
00181         IGeometryRealization **realization
00182         );
00183
00184     STDMETHOD_(ULONG, AddRef)();
00185     STDMETHOD_(ULONG, Release)();
00186
00187     STDMETHOD(QueryInterface)(
00188         REFIID iid,
00189         void ** object
00190         );
00191
00192     // Non-interface methods
00193     static HRESULT Create(
00194         ID2D1DeviceContext *deviceContext,
00195         UINT maxRealizationDimension,
00196         IGeometryRealizationFactory **factory
00197         );
00198
00199 // These methods are declared protected for white-box unit-testing.
00200 protected:
00201
00202     GeometryRealizationFactory();
00203     ~GeometryRealizationFactory();
00204
00205     HRESULT Initialize(
00206         ID2D1DeviceContext *deviceContext,
00207         UINT maxRealizationDimension
00208         );
00209
00210     ID2D1DeviceContext *m_deviceContext;
00211
00212     ULONG volatile m_ref;
00213
00214     UINT m_maxRealizationDimension;
00215 };
00216
00217 // The maximum granularity of bitmap sizes we allow for AA realizations.
00218 static const UINT sc_bitmapChunkSize = 64;
00219
00220 //+-----------------------------------------------------------------------------
00221 //
00222 //  Function:
00223 //      CreateGeometryRealizationFactory
00224 //
00225 //------------------------------------------------------------------------------
00226 HRESULT CreateGeometryRealizationFactory(
00227     ID2D1DeviceContext *deviceContext,
00228     UINT maxRealizationDimension,
00229     IGeometryRealizationFactory **factory
00230     )
00231 {
00232     return GeometryRealizationFactory::Create(
00233         deviceContext,
00234         maxRealizationDimension,
00235         factory
00236         );
00237 }
00238
00239 //+-----------------------------------------------------------------------------
00240 //
00241 //  Function:
00242 //      CreateGeometryRealizationFactory
00243 //
00244 //------------------------------------------------------------------------------
00245 HRESULT CreateGeometryRealizationFactory(
00246     ID2D1DeviceContext *deviceContext,
00247     IGeometryRealizationFactory **factory
00248     )
00249 {
00250     return CreateGeometryRealizationFactory(
00251         deviceContext,
00252         0xffffffff, // maxRealizationDimension
00253         factory
00254         );
00255 }
00256
00257 //+-----------------------------------------------------------------------------
00258 //
00259 //  Method:
00260 //      GeometryRealizationFactory::Create
00261 //
00262 //------------------------------------------------------------------------------
00263 /* static */
00264 HRESULT GeometryRealizationFactory::Create(
00265     ID2D1DeviceContext *deviceContext,
00266     UINT maxRealizationDimension,
00267     IGeometryRealizationFactory **factory
00268 )
00269 {
00270     HRESULT hr = S_OK;
00271
00272     GeometryRealizationFactory *realizationFactory = nullptr;
00273     realizationFactory = new (std::nothrow) GeometryRealizationFactory();
00274     hr = realizationFactory ? S_OK : E_OUTOFMEMORY;
00275     if (SUCCEEDED(hr))
00276     {
00277         hr = realizationFactory->Initialize(deviceContext, maxRealizationDimension);
00278
00279         if (SUCCEEDED(hr))
00280         {
00281             *factory = realizationFactory;
00282             (*factory)->AddRef();
00283         }
00284
00285         realizationFactory->Release();
00286     }
00287
00288     return hr;
00289 }
00290
00291
00292 //+-----------------------------------------------------------------------------
00293 //
00294 //  Method:
00295 //      GeometryRealizationFactory::GeometryRealizationFactory
00296 //
00297 //------------------------------------------------------------------------------
00298 GeometryRealizationFactory::GeometryRealizationFactory() :
00299     m_ref(1),
00300     m_deviceContext(nullptr)
00301 {
00302 }
00303
00304 //+-----------------------------------------------------------------------------
00305 //
00306 //  Method:
00307 //      ~GeometryRealizationFactory::GeometryRealizationFactory
00308 //
00309 //------------------------------------------------------------------------------
00310 GeometryRealizationFactory::~GeometryRealizationFactory()
00311 {
00312     SafeRelease(&m_deviceContext);
00313 }
00314
00315 //+-----------------------------------------------------------------------------
00316 //
00317 //  Method:
00318 //      GeometryRealizationFactory::Initialize
00319 //
00320 //------------------------------------------------------------------------------
00321 HRESULT GeometryRealizationFactory::Initialize(
00322     ID2D1DeviceContext *deviceContext,
00323     UINT maxRealizationDimension
00324     )
00325 {
00326     HRESULT hr = S_OK;
00327
00328     if (maxRealizationDimension == 0)
00329     {
00330         //
00331         // 0-sized bitmaps aren't very useful for realizations, and
00332         // DXGI surface render targets don't support them, anyway.
00333         //
00334         hr = E_INVALIDARG;
00335     }
00336
00337     if (SUCCEEDED(hr))
00338     {
00339         m_deviceContext = deviceContext;
00340         m_deviceContext->AddRef();
00341
00342         m_maxRealizationDimension = min(
00343             deviceContext->GetMaximumBitmapSize(),
00344             maxRealizationDimension
00345             );
00346     }
00347
00348     return hr;
00349 }
00350
00351 //+-----------------------------------------------------------------------------
00352 //
00353 //  Method:
00354 //      GeometryRealizationFactory::CreateGeometryRealization
00355 //
00356 //------------------------------------------------------------------------------
00357 STDMETHODIMP GeometryRealizationFactory::CreateGeometryRealization(
00358     ID2D1Geometry *geometry,
00359     REALIZATION_CREATION_OPTIONS options,
00360     CONST D2D1_MATRIX_3X2_F *worldTransform,
00361     float strokeWidth,
00362     ID2D1StrokeStyle *strokeStyle,
00363     IGeometryRealization **realization
00364     )
00365 {
00366     return GeometryRealization::Create(
00367         m_deviceContext,
00368         m_maxRealizationDimension,
00369         geometry,
00370         options,
00371         worldTransform,
00372         strokeWidth,
00373         strokeStyle,
00374         realization
00375         );
00376 }
00377
00378 //+-----------------------------------------------------------------------------
00379 //
00380 //  Method:
00381 //      GeometryRealizationFactory::CreateGeometryRealization
00382 //
00383 //------------------------------------------------------------------------------
00384 STDMETHODIMP GeometryRealizationFactory::CreateGeometryRealization(
00385     IGeometryRealization **realization
00386     )
00387 {
00388     return GeometryRealization::Create(
00389         m_deviceContext,
00390         m_maxRealizationDimension,
00391         nullptr, // pGeometry
00392         REALIZATION_CREATION_OPTIONS_ALIASED, // ignored.
00393         nullptr,
00394         0.0f, // strokeWidth
00395         nullptr, // pIStrokeStyle
00396         realization
00397         );
00398 }
00399
00400 //+-----------------------------------------------------------------------------
00401 //
00402 //  Method:
00403 //      GeometryRealization::Create
00404 //
00405 //------------------------------------------------------------------------------
00406 /* static */
00407 HRESULT GeometryRealization::Create(
00408     ID2D1DeviceContext *deviceContext,
00409     UINT maxRealizationDimension,
00410     ID2D1Geometry *geometry,
00411     REALIZATION_CREATION_OPTIONS options,
00412     CONST D2D1_MATRIX_3X2_F *worldTransform,
00413     float strokeWidth,
00414     ID2D1StrokeStyle *strokeStyle,
00415     IGeometryRealization **realization
00416     )
00417 {
00418     HRESULT hr = S_OK;
00419
00420     GeometryRealization *geometryRealization = nullptr;
00421
00422     geometryRealization = new (std::nothrow) GeometryRealization();
00423     hr = geometryRealization ? S_OK : E_OUTOFMEMORY;
00424     if (SUCCEEDED(hr))
00425     {
00426         hr = geometryRealization->Initialize(
00427             deviceContext,
00428             maxRealizationDimension,
00429             geometry,
00430             options,
00431             worldTransform,
00432             strokeWidth,
00433             strokeStyle
00434             );
00435         if (SUCCEEDED(hr))
00436         {
00437             *realization = geometryRealization;
00438             (*realization)->AddRef();
00439         }
00440
00441         geometryRealization->Release();
00442     }
00443
00444     return hr;
00445 }
00446
00447 //+----------------------------------------------------------------------------
00448 //
00449 //  Method:
00450 //      GeometryRealization::GeometryRealization
00451 //
00452 //-----------------------------------------------------------------------------
00453
00454 GeometryRealization::GeometryRealization() :
00455     m_ref(1),
00456     m_fillMesh(nullptr),
00457     m_strokeMesh(nullptr),
00458     m_fillRT(nullptr),
00459     m_strokeRT(nullptr),
00460     m_geometry(nullptr),
00461     m_strokeStyle(nullptr),
00462     m_deviceContext(nullptr)
00463 {
00464 }
00465
00466 //+----------------------------------------------------------------------------
00467 //
00468 //  Method:
00469 //      GeometryRealization::GeometryRealization
00470 //
00471 //-----------------------------------------------------------------------------
00472 GeometryRealization::~GeometryRealization()
00473 {
00474     SafeRelease(&m_fillMesh);
00475     SafeRelease(&m_strokeMesh);
00476     SafeRelease(&m_fillRT);
00477     SafeRelease(&m_strokeRT);
00478     SafeRelease(&m_geometry);
00479     SafeRelease(&m_strokeStyle);
00480     SafeRelease(&m_deviceContext);
00481 }
00482
00483
00484 //+-----------------------------------------------------------------------------
00485 //
00486 //  Method:
00487 //      GeometryRealization::Fill
00488 //
00489 //------------------------------------------------------------------------------
00490 STDMETHODIMP GeometryRealization::Fill(
00491     ID2D1DeviceContext *deviceContext,
00492     ID2D1Brush *brush,
00493     REALIZATION_RENDER_MODE mode
00494     )
00495 {
00496     return RenderToTarget(
00497         true, // => fill
00498         deviceContext,
00499         brush,
00500         mode
00501         );
00502 }
00503
00504
00505 //+-----------------------------------------------------------------------------
00506 //
00507 //  Method:
00508 //      GeometryRealization::Draw
00509 //
00510 //------------------------------------------------------------------------------
00511 STDMETHODIMP GeometryRealization::Draw(
00512     ID2D1DeviceContext *deviceContext,
00513     ID2D1Brush *brush,
00514     REALIZATION_RENDER_MODE mode
00515     )
00516 {
00517     return RenderToTarget(
00518         false, // => stroke
00519         deviceContext,
00520         brush,
00521         mode
00522         );
00523 }
00524
00525
00526 //+-----------------------------------------------------------------------------
00527 //
00528 //  Method:
00529 //      GeometryRealization::Update
00530 //
00531 //  Description:
00532 //      Discard the current realization's contents and replace with new
00533 //      contents.
00534 //
00535 //      Note: This method attempts to reuse the existing bitmaps (but will
00536 //      replace the bitmaps if they aren't large enough). Since the cost of
00537 //      destroying a texture can be surprisingly astronomical, using this
00538 //      method can be substantially more performant than recreating a new
00539 //      realization every time.
00540 //
00541 //      Note: Here, pWorldTransform is the transform that the realization will
00542 //      be optimized for. If, at the time of rendering, the render target's
00543 //      transform is the same as the pWorldTransform passed in here then the
00544 //      realization will look identical to the unrealized version. Otherwise,
00545 //      quality will be degraded.
00546 //
00547 //------------------------------------------------------------------------------
00548 STDMETHODIMP GeometryRealization::Update(
00549     ID2D1Geometry *geometry,
00550     REALIZATION_CREATION_OPTIONS options,
00551     CONST D2D1_MATRIX_3X2_F *worldTransform,
00552     float strokeWidth,
00553     ID2D1StrokeStyle *strokeStyle
00554     )
00555 {
00556     HRESULT hr = S_OK;
00557
00558     if (worldTransform)
00559     {
00560         m_realizationTransform = *D2D1::Matrix3x2F::ReinterpretBaseType(worldTransform);
00561         m_realizationTransformIsIdentity = (m_realizationTransform.IsIdentity());
00562     }
00563     else
00564     {
00565         m_realizationTransform = D2D1::Matrix3x2F::Identity();
00566         m_realizationTransformIsIdentity = true;
00567     }
00568
00569     //
00570     // We're about to create our realizations with the world transform applied
00571     // to them.  When we go to actually render the realization, though, we'll
00572     // want to "undo" this realization and instead apply the render target's
00573     // current transform.
00574     //
00575     // Note: we keep track to see if the passed in realization transform is the
00576     // identity.  This is a small optimization that saves us from having to
00577     // multiply matrices when we go to draw the realization.
00578     //
00579
00580     m_realizationTransformInv = m_realizationTransform;
00581     m_realizationTransformInv.Invert();
00582
00583     if ((options & REALIZATION_CREATION_OPTIONS_UNREALIZED) || m_swRT)
00584     {
00585         SafeReplace(&m_geometry, geometry);
00586         SafeReplace(&m_strokeStyle, strokeStyle);
00587         m_strokeWidth = strokeWidth;
00588     }
00589
00590     if (options & REALIZATION_CREATION_OPTIONS_ANTI_ALIASED)
00591     {
00592         //
00593         // Antialiased realizations are implemented using opacity masks.
00594         //
00595
00596         if (options & REALIZATION_CREATION_OPTIONS_FILLED)
00597         {
00598             hr = GenerateOpacityMask(
00599                 true, // => filled
00600                 m_deviceContext,
00601                 m_maxRealizationDimension,
00602                 IN OUT &m_fillRT,
00603                 geometry,
00604                 worldTransform,
00605                 strokeWidth,
00606                 strokeStyle,
00607                 &m_fillMaskDestBounds,
00608                 &m_fillMaskSourceBounds
00609                 );
00610         }
00611
00612         if (SUCCEEDED(hr) && options & REALIZATION_CREATION_OPTIONS_STROKED)
00613         {
00614             hr = GenerateOpacityMask(
00615                 false, // => stroked
00616                 m_deviceContext,
00617                 m_maxRealizationDimension,
00618                 IN OUT &m_strokeRT,
00619                 geometry,
00620                 worldTransform,
00621                 strokeWidth,
00622                 strokeStyle,
00623                 &m_strokeMaskDestBounds,
00624                 &m_strokeMaskSourceBounds
00625                 );
00626         }
00627     }
00628
00629     if (SUCCEEDED(hr) && options & REALIZATION_CREATION_OPTIONS_ALIASED)
00630     {
00631         //
00632         // Aliased realizations are implemented using meshes.
00633         //
00634
00635         if (options & REALIZATION_CREATION_OPTIONS_FILLED)
00636         {
00637             ID2D1Mesh *pMesh = nullptr;
00638             hr = m_deviceContext->CreateMesh(&pMesh);
00639             if (SUCCEEDED(hr))
00640             {
00641                 ID2D1TessellationSink *pSink = nullptr;
00642                 hr = pMesh->Open(&pSink);
00643                 if (SUCCEEDED(hr))
00644                 {
00645                     hr = geometry->Tessellate(worldTransform, pSink);
00646                     if (SUCCEEDED(hr))
00647                     {
00648                         hr = pSink->Close();
00649                         if (SUCCEEDED(hr))
00650                         {
00651                             SafeReplace(&m_fillMesh, pMesh);
00652                         }
00653                     }
00654                     pSink->Release();
00655                 }
00656                 pMesh->Release();
00657             }
00658         }
00659
00660         if (SUCCEEDED(hr) && options & REALIZATION_CREATION_OPTIONS_STROKED)
00661         {
00662             //
00663             // In order generate the mesh corresponding to the stroke of a
00664             // geometry, we first "widen" the geometry and then tessellate the
00665             // result.
00666             //
00667
00668             ID2D1Factory *pFactory = nullptr;
00669             m_deviceContext->GetFactory(&pFactory);
00670
00671             ID2D1PathGeometry *pPathGeometry = nullptr;
00672             hr = pFactory->CreatePathGeometry(&pPathGeometry);
00673             if (SUCCEEDED(hr))
00674             {
00675                 ID2D1GeometrySink *pGeometrySink = nullptr;
00676                 hr = pPathGeometry->Open(&pGeometrySink);
00677                 if (SUCCEEDED(hr))
00678                 {
00679                     hr = geometry->Widen(
00680                         strokeWidth,
00681                         strokeStyle,
00682                         worldTransform,
00683                         pGeometrySink
00684                         );
00685
00686                     if (SUCCEEDED(hr))
00687                     {
00688                         hr = pGeometrySink->Close();
00689                         if (SUCCEEDED(hr))
00690                         {
00691                             ID2D1Mesh *pMesh = nullptr;
00692                             hr = m_deviceContext->CreateMesh(&pMesh);
00693                             if (SUCCEEDED(hr))
00694                             {
00695                                 ID2D1TessellationSink *pSink = nullptr;
00696                                 hr = pMesh->Open(&pSink);
00697                                 if (SUCCEEDED(hr))
00698                                 {
00699                                     hr = pPathGeometry->Tessellate(
00700                                         nullptr, // world transform (already handled in Widen)
00701                                         pSink
00702                                         );
00703                                     if (SUCCEEDED(hr))
00704                                     {
00705                                         hr = pSink->Close();
00706                                         if (SUCCEEDED(hr))
00707                                         {
00708                                             SafeReplace(&m_strokeMesh, pMesh);
00709                                         }
00710                                     }
00711                                     pSink->Release();
00712                                 }
00713                                 pMesh->Release();
00714                             }
00715                         }
00716                     }
00717                     pGeometrySink->Release();
00718                 }
00719                 pPathGeometry->Release();
00720             }
00721             pFactory->Release();
00722         }
00723     }
00724
00725     return hr;
00726 }
00727
00728 //+-----------------------------------------------------------------------------
00729 //
00730 //  Method:
00731 //      GeometryRealization::RenderToTarget
00732 //
00733 //------------------------------------------------------------------------------
00734 HRESULT GeometryRealization::RenderToTarget(
00735     bool fill,
00736     ID2D1DeviceContext *pDeviceContext,
00737     ID2D1Brush *pBrush,
00738     REALIZATION_RENDER_MODE mode
00739     )
00740 {
00741     HRESULT hr = S_OK;
00742
00743     D2D1_ANTIALIAS_MODE originalAAMode = pDeviceContext->GetAntialiasMode();
00744     D2D1_MATRIX_3X2_F originalTransform;
00745
00746     if (((mode == REALIZATION_RENDER_MODE_DEFAULT) && m_swRT) ||
00747         (mode == REALIZATION_RENDER_MODE_FORCE_UNREALIZED)
00748         )
00749     {
00750         if (!m_geometry)
00751         {
00752             // We're being asked to render the geometry unrealized, but we
00753             // weren't created with REALIZATION_CREATION_OPTIONS_UNREALIZED.
00754             hr = E_FAIL;
00755         }
00756         if (SUCCEEDED(hr))
00757         {
00758             if (fill)
00759             {
00760                 pDeviceContext->FillGeometry(
00761                     m_geometry,
00762                     pBrush
00763                     );
00764             }
00765             else
00766             {
00767                 pDeviceContext->DrawGeometry(
00768                     m_geometry,
00769                     pBrush,
00770                     m_strokeWidth,
00771                     m_strokeStyle
00772                     );
00773             }
00774         }
00775     }
00776     else
00777     {
00778         if (originalAAMode != D2D1_ANTIALIAS_MODE_ALIASED)
00779         {
00780             pDeviceContext->SetAntialiasMode(D2D1_ANTIALIAS_MODE_ALIASED);
00781         }
00782
00783         if (!m_realizationTransformIsIdentity)
00784         {
00785             pDeviceContext->GetTransform(&originalTransform);
00786             pDeviceContext->SetTransform(m_realizationTransformInv * originalTransform);
00787         }
00788
00789         if (originalAAMode == D2D1_ANTIALIAS_MODE_PER_PRIMITIVE)
00790         {
00791             if (fill)
00792             {
00793                 if (!m_fillRT)
00794                 {
00795                     hr = E_FAIL;
00796                 }
00797                 if (SUCCEEDED(hr))
00798                 {
00799                     ID2D1Bitmap *pBitmap = nullptr;
00800                     m_fillRT->GetBitmap(&pBitmap);
00801
00802                     //
00803                     // Note: The antialias mode must be set to aliased prior to calling
00804                     // FillOpacityMask.
00805                     //
00806                     pDeviceContext->FillOpacityMask(
00807                         pBitmap,
00808                         pBrush,
00809                         D2D1_OPACITY_MASK_CONTENT_GRAPHICS,
00810                         &m_fillMaskDestBounds,
00811                         &m_fillMaskSourceBounds
00812                         );
00813
00814                     pBitmap->Release();
00815                 }
00816             }
00817             else
00818             {
00819                 if (!m_strokeRT)
00820                 {
00821                     hr = E_FAIL;
00822                 }
00823                 if (SUCCEEDED(hr))
00824                 {
00825                     ID2D1Bitmap *pBitmap = nullptr;
00826                     m_strokeRT->GetBitmap(&pBitmap);
00827
00828                     //
00829                     // Note: The antialias mode must be set to aliased prior to calling
00830                     // FillOpacityMask.
00831                     //
00832                     pDeviceContext->FillOpacityMask(
00833                         pBitmap,
00834                         pBrush,
00835                         D2D1_OPACITY_MASK_CONTENT_GRAPHICS,
00836                         &m_strokeMaskDestBounds,
00837                         &m_strokeMaskSourceBounds
00838                         );
00839
00840                     pBitmap->Release();
00841                 }
00842             }
00843         }
00844         else
00845         {
00846             if (fill)
00847             {
00848                 if (!m_fillMesh)
00849                 {
00850                     hr = E_FAIL;
00851                 }
00852                 if (SUCCEEDED(hr))
00853                 {
00854                     pDeviceContext->FillMesh(
00855                         m_fillMesh,
00856                         pBrush
00857                         );
00858                 }
00859             }
00860             else
00861             {
00862                 if (!m_strokeMesh)
00863                 {
00864                     hr = E_FAIL;
00865                 }
00866                 if (SUCCEEDED(hr))
00867                 {
00868                     pDeviceContext->FillMesh(
00869                         m_strokeMesh,
00870                         pBrush
00871                         );
00872                 }
00873             }
00874         }
00875
00876         if (SUCCEEDED(hr))
00877         {
00878             pDeviceContext->SetAntialiasMode(originalAAMode);
00879
00880             if (!m_realizationTransformIsIdentity)
00881             {
00882                 pDeviceContext->SetTransform(originalTransform);
00883             }
00884         }
00885     }
00886
00887     return hr;
00888 }
00889
00890 //+-----------------------------------------------------------------------------
00891 //
00892 //  Method:
00893 //      GeometryRealization::Initialize
00894 //
00895 //------------------------------------------------------------------------------
00896 HRESULT GeometryRealization::Initialize(
00897     ID2D1DeviceContext *deviceContext,
00898     UINT maxRealizationDimension,
00899     ID2D1Geometry *geometry,
00900     REALIZATION_CREATION_OPTIONS options,
00901     CONST D2D1_MATRIX_3X2_F *worldTransform,
00902     float strokeWidth,
00903     ID2D1StrokeStyle *strokeStyle
00904 )
00905 {
00906     HRESULT hr = S_OK;
00907
00908     m_deviceContext = deviceContext;
00909     m_deviceContext->AddRef();
00910
00911     m_swRT = deviceContext->IsSupported(
00912         D2D1::RenderTargetProperties(D2D1_RENDER_TARGET_TYPE_SOFTWARE)
00913         );
00914
00915     m_maxRealizationDimension = maxRealizationDimension;
00916
00917     if (geometry)
00918     {
00919         hr = Update(
00920             geometry,
00921             options,
00922             worldTransform,
00923             strokeWidth,
00924             strokeStyle
00925             );
00926     }
00927
00928     return hr;
00929 }
00930
00931 //+-----------------------------------------------------------------------------
00932 //
00933 //  Method:
00934 //      GeometryRealization::GenerateOpacityMask
00935 //
00936 //  Notes:
00937 //      This method is the trickiest part of doing realizations. Conceptually,
00938 //      we're creating a grayscale bitmap that represents the geometry. We'll
00939 //      reuse an existing bitmap if we can, but if not, we'll create the
00940 //      smallest possible bitmap that contains the geometry. In either, case,
00941 //      though, we'll keep track of the portion of the bitmap we actually used
00942 //      (the source bounds), so when we go to draw the realization, we don't
00943 //      end up drawing a bunch of superfluous transparent pixels.
00944 //
00945 //      We also have to keep track of the "dest" bounds, as more than likely
00946 //      the bitmap has to be translated by some amount before being drawn.
00947 //
00948 //------------------------------------------------------------------------------
00949 /* static */
00950 HRESULT GeometryRealization::GenerateOpacityMask(
00951     bool fill,
00952     ID2D1DeviceContext *baseRT,
00953     UINT maxRealizationDimension,
00954     ID2D1BitmapRenderTarget **bitmapRT,
00955     ID2D1Geometry *geometry,
00956     const D2D1_MATRIX_3X2_F *worldTransform,
00957     float strokeWidth,
00958     ID2D1StrokeStyle *strokeStyle,
00959     D2D1_RECT_F *maskDestBounds,
00960     D2D1_RECT_F *maskSourceBounds
00961     )
00962 {
00963     HRESULT hr = S_OK;
00964
00965     D2D1_RECT_F bounds;
00966     D2D1_RECT_F inflatedPixelBounds;
00967     D2D1_SIZE_U inflatedIntegerPixelSize;
00968     D2D1_SIZE_U currentRTSize;
00969     D2D1_MATRIX_3X2_F translateMatrix;
00970     float dpiX, dpiY;
00971     float scaleX = 1.0f;
00972     float scaleY = 1.0f;
00973
00974     ID2D1BitmapRenderTarget *compatRT = nullptr;
00975     SafeReplace(&compatRT, *bitmapRT);
00976
00977     ID2D1SolidColorBrush *brush = nullptr;
00978
00979     hr = baseRT->CreateSolidColorBrush(
00980         D2D1::ColorF(1.0f, 1.0f, 1.0f, 1.0f),
00981         &brush
00982         );
00983     if (SUCCEEDED(hr))
00984     {
00985         baseRT->GetDpi(&dpiX, &dpiY);
00986         if (fill)
00987         {
00988             hr = geometry->GetBounds(
00989                 worldTransform,
00990                 &bounds
00991                 );
00992         }
00993         else
00994         {
00995             hr = geometry->GetWidenedBounds(
00996                 strokeWidth,
00997                 strokeStyle,
00998                 worldTransform,
00999                 &bounds
01000                 );
01001         }
01002
01003         if (SUCCEEDED(hr))
01004         {
01005             //
01006             // A rect where left > right is defined to be empty.
01007             //
01008             // The slightly baroque expression used below is an idiom that also
01009             // correctly handles NaNs (i.e., if any of the coordinates of the bounds is
01010             // a NaN, we want to treat the bounds as empty)
01011             //
01012             if (!(bounds.left <= bounds.right) ||
01013                 !(bounds.top <= bounds.bottom)
01014                 )
01015             {
01016                 // Bounds are empty or ill-defined.
01017
01018                 // Make up a fake bounds
01019                 inflatedPixelBounds.top = 0.0f;
01020                 inflatedPixelBounds.left = 0.0f;
01021                 inflatedPixelBounds.bottom = 1.0f;
01022                 inflatedPixelBounds.right = 1.0f;
01023             }
01024             else
01025             {
01026                 //
01027                 // We inflate the pixel bounds by 1 in each direction to ensure we have
01028                 // a border of completely transparent pixels around the geometry.  This
01029                 // ensures that when the realization is stretched the alpha ramp still
01030                 // smoothly falls off to 0 rather than being clipped by the rect.
01031                 //
01032                 inflatedPixelBounds.top = floorf(bounds.top*dpiY/96)-1.0f;
01033                 inflatedPixelBounds.left = floorf(bounds.left*dpiX/96)-1.0f;
01034                 inflatedPixelBounds.bottom = ceilf(bounds.bottom*dpiY/96)+1.0f;
01035                 inflatedPixelBounds.right = ceilf(bounds.right*dpiX/96)+1.0f;
01036             }
01037
01038
01039             //
01040             // Compute the width and height of the underlying bitmap we will need.
01041             // Note: We round up the width and height to be a multiple of
01042             // sc_bitmapChunkSize. We do this primarily to ensure that we aren't
01043             // constantly reallocating bitmaps in the case where a realization is being
01044             // zoomed in on slowly and updated frequently.
01045             //
01046
01047             inflatedIntegerPixelSize = D2D1::SizeU(
01048                 static_cast<UINT>(inflatedPixelBounds.right - inflatedPixelBounds.left),
01049                 static_cast<UINT>(inflatedPixelBounds.bottom - inflatedPixelBounds.top)
01050                 );
01051
01052             // Round up
01053             inflatedIntegerPixelSize.width =
01054                 (inflatedIntegerPixelSize.width + sc_bitmapChunkSize - 1)/sc_bitmapChunkSize * sc_bitmapChunkSize;
01055
01056             // Round up
01057             inflatedIntegerPixelSize.height =
01058                 (inflatedIntegerPixelSize.height + sc_bitmapChunkSize - 1)/sc_bitmapChunkSize * sc_bitmapChunkSize;
01059
01060             //
01061             // Compute the bounds we will pass to FillOpacityMask (which are in Device
01062             // Independent Pixels).
01063             //
01064             // Note: The DIP bounds do *not* use the rounded coordinates, since this
01065             // would cause us to render superfluous, fully-transparent pixels, which
01066             // would hurt fill rate.
01067             //
01068             D2D1_RECT_F inflatedDipBounds = D2D1::RectF(
01069                 inflatedPixelBounds.left * 96/dpiX,
01070                 inflatedPixelBounds.top * 96/dpiY,
01071                 inflatedPixelBounds.right * 96/dpiX,
01072                 inflatedPixelBounds.bottom * 96/dpiY
01073                 );
01074
01075             if (compatRT)
01076             {
01077                 currentRTSize = compatRT->GetPixelSize();
01078             }
01079             else
01080             {
01081                 // This will force the creation of a new target
01082                 currentRTSize = D2D1::SizeU(0, 0);
01083             }
01084
01085             //
01086             // We need to ensure that our desired render target size isn't larger than
01087             // the max allowable bitmap size. If it is, we need to scale the bitmap
01088             // down by the appropriate amount.
01089             //
01090
01091             if (inflatedIntegerPixelSize.width > maxRealizationDimension)
01092             {
01093                 scaleX = maxRealizationDimension/static_cast<float>(inflatedIntegerPixelSize.width);
01094                 inflatedIntegerPixelSize.width = maxRealizationDimension;
01095             }
01096
01097             if (inflatedIntegerPixelSize.height > maxRealizationDimension)
01098             {
01099                 scaleY = maxRealizationDimension/static_cast<float>(inflatedIntegerPixelSize.height);
01100                 inflatedIntegerPixelSize.height = maxRealizationDimension;
01101             }
01102
01103
01104             //
01105             // If the necessary pixel dimensions are less than half the existing
01106             // bitmap's dimensions (in either direction), force the bitmap to be
01107             // reallocated to save memory.
01108             //
01109             // Note: The fact that we use > rather than >= is important for a subtle
01110             // reason: We'd like to have the property that repeated small changes in
01111             // geometry size do not cause repeated reallocations of memory. >= does not
01112             // ensure this property in the case where the geometry size is close to
01113             // sc_bitmapChunkSize, but > does.
01114             //
01115             // Example:
01116             //
01117             // Assume sc_bitmapChunkSize is 64 and the initial geometry width is 63
01118             // pixels. This will get rounded up to 64, and we will allocate a bitmap
01119             // with width 64. Now, say, we zoom in slightly, so the new geometry width
01120             // becomes 65 pixels. This will get rounded up to 128 pixels, and a new
01121             // bitmap will be allocated. Now, say the geometry drops back down to 63
01122             // pixels. This will get rounded up to 64. If we used >=, this would cause
01123             // another reallocation.  Since we use >, on the other hand, the 128 pixel
01124             // bitmap will be reused.
01125             //
01126
01127             if (currentRTSize.width > 2*inflatedIntegerPixelSize.width ||
01128                 currentRTSize.height > 2*inflatedIntegerPixelSize.height
01129                 )
01130             {
01131                 SafeRelease(&compatRT);
01132                 currentRTSize.width = currentRTSize.height = 0;
01133             }
01134
01135             if (inflatedIntegerPixelSize.width > currentRTSize.width ||
01136                 inflatedIntegerPixelSize.height > currentRTSize.height
01137                 )
01138             {
01139                 SafeRelease(&compatRT);
01140             }
01141
01142             if (!compatRT)
01143             {
01144                 //
01145                 // Make sure our new rendertarget is strictly larger than before.
01146                 //
01147                 currentRTSize.width =
01148                     max(inflatedIntegerPixelSize.width, currentRTSize.width);
01149
01150                 currentRTSize.height =
01151                     max(inflatedIntegerPixelSize.height, currentRTSize.height);
01152
01153                 D2D1_PIXEL_FORMAT alphaOnlyFormat =
01154                     D2D1::PixelFormat(
01155                         DXGI_FORMAT_A8_UNORM,
01156                         D2D1_ALPHA_MODE_PREMULTIPLIED
01157                         );
01158
01159                 hr = baseRT->CreateCompatibleRenderTarget(
01160                     nullptr, // desiredSize
01161                     &currentRTSize,
01162                     &alphaOnlyFormat,
01163                     D2D1_COMPATIBLE_RENDER_TARGET_OPTIONS_NONE,
01164                     &compatRT
01165                     );
01166             }
01167
01168             if (SUCCEEDED(hr))
01169             {
01170                 //
01171                 // Translate the geometry so it is flush against the left and top
01172                 // sides of the render target.
01173                 //
01174
01175                 translateMatrix =
01176                     D2D1::Matrix3x2F::Translation(
01177                         -inflatedDipBounds.left,
01178                         -inflatedDipBounds.top
01179                         ) *
01180                     D2D1::Matrix3x2F::Scale(
01181                         scaleX,
01182                         scaleY
01183                         );
01184
01185                 if (worldTransform)
01186                 {
01187                     compatRT->SetTransform(
01188                         *worldTransform * translateMatrix
01189                         );
01190                 }
01191                 else
01192                 {
01193                     compatRT->SetTransform(
01194                         translateMatrix
01195                         );
01196                 }
01197
01198                 //
01199                 // Render the geometry.
01200                 //
01201
01202                 compatRT->BeginDraw();
01203
01204                 compatRT->Clear(
01205                     D2D1::ColorF(0.0f, 0.0f, 0.0f, 0.0f)
01206                     );
01207
01208                 if (fill)
01209                 {
01210                     compatRT->FillGeometry(
01211                         geometry,
01212                         brush
01213                         );
01214                 }
01215                 else
01216                 {
01217                     compatRT->DrawGeometry(
01218                         geometry,
01219                         brush,
01220                         strokeWidth,
01221                         strokeStyle
01222                         );
01223                 }
01224
01225                 hr = compatRT->EndDraw();
01226                 if (hr == D2DERR_RECREATE_TARGET)
01227                 {
01228                     // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
01229                     // is lost. It will be handled during the next call to Present.
01230                     hr = S_OK;
01231                 }
01232                 if (SUCCEEDED(hr))
01233                 {
01234                     //
01235                     // Report back the source and dest bounds (to be used as input parameters
01236                     // to FillOpacityMask.
01237                     //
01238                     *maskDestBounds = inflatedDipBounds;
01239
01240                     *maskSourceBounds = D2D1::Rect<float>(
01241                         0.0f,
01242                         0.0f,
01243                         static_cast<float>(inflatedDipBounds.right - inflatedDipBounds.left)*scaleX,
01244                         static_cast<float>(inflatedDipBounds.bottom - inflatedDipBounds.top)*scaleY
01245                         );
01246
01247                     if (*bitmapRT != compatRT)
01248                     {
01249                         SafeReplace(bitmapRT, compatRT);
01250                     }
01251                 }
01252             }
01253         }
01254         brush->Release();
01255     }
01256
01257     SafeRelease(&compatRT);
01258
01259     return hr;
01260 }
01261
01262 //+-----------------------------------------------------------------------------
01263 //
01264 //  Method:
01265 //      GeometryRealizationFactory::AddRef
01266 //
01267 //------------------------------------------------------------------------------
01268 STDMETHODIMP_(ULONG) GeometryRealizationFactory::AddRef()
01269 {
01270     return InterlockedIncrement(reinterpret_cast<LONG volatile *>(&m_ref));
01271 }
01272
01273 //+-----------------------------------------------------------------------------
01274 //
01275 //  Method:
01276 //      GeometryRealizationFactory::Release
01277 //
01278 //------------------------------------------------------------------------------
01279 STDMETHODIMP_(ULONG) GeometryRealizationFactory::Release()
01280 {
01281     ULONG ref = static_cast<ULONG>(
01282         InterlockedDecrement(reinterpret_cast<LONG volatile *>(&m_ref)));
01283
01284     if (0 == ref)
01285     {
01286         delete this;
01287     }
01288
01289     return ref;
01290 }
01291
01292 //+-----------------------------------------------------------------------------
01293 //
01294 //  Method:
01295 //      GeometryRealizationFactory::QueryInterface
01296 //
01297 //------------------------------------------------------------------------------
01298 STDMETHODIMP GeometryRealizationFactory::QueryInterface(
01299     REFIID iid,
01300     void ** object
01301     )
01302 {
01303     HRESULT hr = S_OK;
01304
01305     if (__uuidof(IUnknown) == iid)
01306     {
01307         *object = static_cast<IUnknown*>(this);
01308         AddRef();
01309     }
01310     else if (__uuidof(IGeometryRealizationFactory) == iid)
01311     {
01312         *object = static_cast<IGeometryRealizationFactory*>(this);
01313         AddRef();
01314     }
01315     else
01316     {
01317         *object = nullptr;
01318         hr = E_NOINTERFACE;
01319     }
01320
01321     return hr;
01322 }
01323
01324 //+-----------------------------------------------------------------------------
01325 //
01326 //  Method:
01327 //      GeometryRealization::AddRef
01328 //
01329 //------------------------------------------------------------------------------
01330 STDMETHODIMP_(ULONG)
01331 GeometryRealization::AddRef()
01332 {
01333     return InterlockedIncrement(reinterpret_cast<LONG volatile *>(&m_ref));
01334 }
01335
01336 //+-----------------------------------------------------------------------------
01337 //
01338 //  Method:
01339 //      GeometryRealization::Release
01340 //
01341 //------------------------------------------------------------------------------
01342 STDMETHODIMP_(ULONG)
01343 GeometryRealization::Release()
01344 {
01345     ULONG ref = static_cast<ULONG>(
01346         InterlockedDecrement(reinterpret_cast<LONG volatile *>(&m_ref)));
01347
01348     if (0 == ref)
01349     {
01350         delete this;
01351     }
01352
01353     return ref;
01354 }
01355
01356 //+-----------------------------------------------------------------------------
01357 //
01358 //  Method:
01359 //      GeometryRealization::QueryInterface
01360 //
01361 //------------------------------------------------------------------------------
01362 STDMETHODIMP
01363 GeometryRealization::QueryInterface(
01364     REFIID iid,
01365     void ** object
01366     )
01367 {
01368     HRESULT hr = S_OK;
01369
01370     if (__uuidof(IUnknown) == iid)
01371     {
01372         *object = static_cast<IUnknown*>(this);
01373         AddRef();
01374     }
01375     else if (__uuidof(IGeometryRealization) == iid)
01376     {
01377         *object = static_cast<IGeometryRealization*>(this);
01378         AddRef();
01379     }
01380     else
01381     {
01382         *object = nullptr;
01383         hr = E_NOINTERFACE;
01384     }
01385
01386     return hr;
01387 }
01388
Generated on Sat Nov 23 2024 16:08:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: AtomPub/C++/Scenario1.xaml.cpp Source File

  • AtomPub

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::AtomPub;
00020
00021 using namespace Windows::UI::Xaml::Controls;
00022 using namespace Concurrency;
00023
00024 Scenario1::Scenario1()
00025 {
00026     InitializeComponent();
00027
00028     // Helps iterating through feeds.
00029     this->feedIterator = ref new SyndicationItemIterator();
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 void Scenario1::OnNavigatedTo(NavigationEventArgs^ e)
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     rootPage = MainPage::Current;
00042
00043     CommonData::Restore(this);
00044 }
00045
00046 void Scenario1::OnNavigatingFrom(NavigatingCancelEventArgs^ e)
00047 {
00048     CommonData::Save(ServiceAddressField->Text, UserNameField->Text, PasswordField->Password);
00049 }
00050
00051 void Scenario1::GetFeed_Click(Object^ sender, RoutedEventArgs^ e)
00052 {
00053     // Note that this feed is public by default and will not require authentication.
00054     // We will only get back a limited use feed, without information about editing.
00055
00056     // Since the value of 'ServiceAddressField' was provided by the user it is untrusted input. We'll validate it
00057     // by using TryGetUri().
00058     // Note that this app has both "Internet (Client)" and "Home and Work Networking" capabilities set, since
00059     // the user may provide URIs for servers located on the intErnet or intrAnet. If apps only communicate
00060     // with servers on the intErnet, only the "Internet (Client)" capability should be set. Similarly if an
00061     // app is only intended to communicate on the intrAnet, only the "Home and Work Networking" capability should be set.
00062     Uri^ resourceUri;
00063     if (!rootPage->TryGetUri(StringHelper::Trim(ServiceAddressField->Text) + CommonData::FeedUri, &resourceUri))
00064     {
00065         return;
00066     }
00067
00068     rootPage->NotifyUser("Fetching resource...", NotifyType::StatusMessage);
00069     OutputField->Text = "Requested resource: " + resourceUri->DisplayUri + "\r\n";
00070
00071     task<SyndicationFeed^>(CommonData::GetClient()->RetrieveFeedAsync(resourceUri)).then([this] (SyndicationFeed^ feed)
00072     {
00073         this->feedIterator->AttachFeed(feed);
00074
00075         rootPage->NotifyUser("Fetching resource completed.", NotifyType::StatusMessage);
00076         DisplayItem();
00077     }).then([this] (task<void> t)
00078     {
00079         try
00080         {
00081             t.get();
00082         }
00083         catch (Exception^ exception)
00084         {
00085             if (!rootPage->HandleException(exception, OutputField))
00086             {
00087                 throw;
00088             }
00089         }
00090     });
00091 }
00092
00093 void Scenario1::PreviousItem_Click(Object^ sender, RoutedEventArgs^ e)
00094 {
00095     this->feedIterator->MovePrevious();
00096     DisplayItem();
00097 }
00098
00099 void Scenario1::NextItem_Click(Object^ sender, RoutedEventArgs^ e)
00100 {
00101     this->feedIterator->MoveNext();
00102     DisplayItem();
00103 }
00104
00105 void Scenario1::UserNameField_TextChanged(Object^ sender, TextChangedEventArgs^ e)
00106 {
00107     CommonData::Save(ServiceAddressField->Text, UserNameField->Text, PasswordField->Password);
00108 }
00109
00110 void Scenario1::PasswordField_PasswordChanged(Object^ sender, RoutedEventArgs^ e)
00111 {
00112     CommonData::Save(ServiceAddressField->Text, UserNameField->Text, PasswordField->Password);
00113 }
00114
00115 void Scenario1::DisplayItem()
00116 {
00117     IndexField->Text = this->feedIterator->GetIndexDescription();
00118     TitleField->Text = this->feedIterator->GetTitle();
00119     ContentWebView->NavigateToString(this->feedIterator->GetContent());
00120 }
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CameraCaptureUI/C++/App.xaml.h Source File

  • CameraCaptureUI

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D post-processing effects/C++/BasicReaderWriter.h Source File

  • Direct3D post-processing effects

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     Platform::String^ m_locationPath;
00019
00020 internal:
00021     BasicReaderWriter();
00022     BasicReaderWriter(
00023         _In_ Windows::Storage::StorageFolder^ folder
00024         );
00025
00026     Platform::Array<byte>^ ReadData(
00027         _In_ Platform::String^ filename
00028         );
00029
00030     concurrency::task<Platform::Array<byte>^> ReadDataAsync(
00031         _In_ Platform::String^ filename
00032         );
00033
00034     uint32 WriteData(
00035         _In_ Platform::String^ filename,
00036         _In_ const Platform::Array<byte>^ fileData
00037         );
00038
00039     concurrency::task<void> WriteDataAsync(
00040         _In_ Platform::String^ filename,
00041         _In_ const Platform::Array<byte>^ fileData
00042         );
00043 };
Generated on Sat Nov 23 2024 16:08:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Geolocation/C++/Scenario1_TrackPosition.xaml.cpp Source File

  • Geolocation

Scenario1_TrackPosition.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_TrackPosition.xaml.cpp
00013 // Implementation of the Scenario1 class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario1_TrackPosition.xaml.h"
00018
00019 using namespace SDKSample::GeolocationCPP;
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::Devices::Geolocation;
00025 using namespace Windows::Foundation;
00026 using namespace Windows::UI::Core;
00027 using namespace Platform;
00028
00029 Scenario1::Scenario1() : rootPage(MainPage::Current)
00030 {
00031     InitializeComponent();
00032
00033     geolocator = ref new Geolocator();
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 Scenario1::OnNavigatedTo(NavigationEventArgs^ e)
00042 {
00043     StartTrackingButton->IsEnabled = true;
00044     StopTrackingButton->IsEnabled = false;
00045 }
00046
00047 /// <summary>
00048 /// Invoked when this page is no longer displayed.
00049 /// </summary>
00050 /// <param name="e"></param>
00051 void Scenario1::OnNavigatedFrom(NavigationEventArgs^ e)
00052 {
00053     if (StopTrackingButton->IsEnabled)
00054     {
00055         geolocator->PositionChanged::remove(positionToken);
00056         geolocator->StatusChanged::remove(statusToken);
00057     }
00058 }
00059
00060 void Scenario1::OnPositionChanged(Geolocator^ sender, PositionChangedEventArgs^ e)
00061 {
00062     // We need to dispatch to the UI thread to display the output
00063     Dispatcher->RunAsync(
00064         CoreDispatcherPriority::Normal,
00065         ref new DispatchedHandler(
00066             [this, e]()
00067             {
00068                 auto coordinate = e->Position->Coordinate;
00069
00070                 rootPage->NotifyUser("Updated", NotifyType::StatusMessage);
00071
00072                 ScenarioOutput_Latitude->Text = coordinate->Latitude.ToString();
00073                 ScenarioOutput_Longitude->Text = coordinate->Longitude.ToString();
00074                 ScenarioOutput_Accuracy->Text = coordinate->Accuracy.ToString();
00075             },
00076             CallbackContext::Any
00077             )
00078         );
00079 }
00080
00081 void Scenario1::OnStatusChanged(Geolocator^ sender, StatusChangedEventArgs^ e)
00082 {
00083     // We need to dispatch to the UI thread to display the output
00084     Dispatcher->RunAsync(
00085         CoreDispatcherPriority::Normal,
00086         ref new DispatchedHandler(
00087             [this, e]()
00088             {
00089                 switch (e->Status)
00090                 {
00091                 case Windows::Devices::Geolocation::PositionStatus::Ready :
00092                     // Location platform is providing valid data.
00093                     ScenarioOutput_Status->Text = "Ready";
00094                     break;
00095
00096                 case Windows::Devices::Geolocation::PositionStatus::Initializing :
00097                     // Location platform is acquiring a fix. It may or may not have data. Or the data may be less accurate.
00098                     ScenarioOutput_Status->Text = "Initializing";
00099                     break;
00100
00101                 case Windows::Devices::Geolocation::PositionStatus::NoData :
00102                     // Location platform could not obtain location data.
00103                     ScenarioOutput_Status->Text = "No data";
00104                     break;
00105
00106                 case Windows::Devices::Geolocation::PositionStatus::Disabled :
00107                     // The permission to access location data is denied by the user or other policies.
00108                     ScenarioOutput_Status->Text = "Disabled";
00109
00110                     // Clear cached location data if any
00111                     ScenarioOutput_Latitude->Text = "No data";
00112                     ScenarioOutput_Longitude->Text = "No data";
00113                     ScenarioOutput_Accuracy->Text = "No data";
00114                     break;
00115
00116                 case Windows::Devices::Geolocation::PositionStatus::NotInitialized :
00117                     // The location platform is not initialized. This indicates that the application has not made a request for location data.
00118                     ScenarioOutput_Status->Text = "Not initialized";
00119                     break;
00120
00121                 case Windows::Devices::Geolocation::PositionStatus::NotAvailable :
00122                     // The location platform is not available on this version of the OS.
00123                     ScenarioOutput_Status->Text = "Not available";
00124                     break;
00125
00126                 default:
00127                     ScenarioOutput_Status->Text = "Unknown";
00128                     break;
00129                 }
00130             },
00131             CallbackContext::Any
00132             )
00133         );
00134 }
00135
00136 void Scenario1::StartTracking(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00137 {
00138     rootPage->NotifyUser("Waiting for update...", NotifyType::StatusMessage);
00139
00140     positionToken = geolocator->PositionChanged::add(ref new TypedEventHandler<Geolocator^, PositionChangedEventArgs^>(this, &Scenario1::OnPositionChanged));
00141     statusToken = geolocator->StatusChanged::add(ref new TypedEventHandler<Geolocator^, StatusChangedEventArgs^>(this, &Scenario1::OnStatusChanged));
00142
00143     StartTrackingButton->IsEnabled = false;
00144     StopTrackingButton->IsEnabled = true;
00145 }
00146
00147 void Scenario1::StopTracking(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00148 {
00149     geolocator->PositionChanged::remove(positionToken);
00150     geolocator->StatusChanged::remove(statusToken);
00151
00152     StartTrackingButton->IsEnabled = true;
00153     StopTrackingButton->IsEnabled = false;
00154 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::TileContent::TileWideImageAndText01 Member List

This is the complete list of members for NotificationsExtensions::TileContent::TileWideImageAndText01, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
Branding | NotificationsExtensions::TileContent::TileNotificationBase |
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Image | NotificationsExtensions::TileContent::TileWideImageAndText01 |
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
RequireSquareContent | NotificationsExtensions::TileContent::TileWideBase |
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SquareContent | NotificationsExtensions::TileContent::TileWideBase |
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextCaptionWrap | NotificationsExtensions::TileContent::TileWideImageAndText01 |
TextFields | NotificationsExtensions::NotificationBase |
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWideImageAndText01() | NotificationsExtensions::TileContent::TileWideImageAndText01 | [inline]
TileWideImageAndText01() | NotificationsExtensions::TileContent::TileWideImageAndText01 | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:44 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/ExceptionPolicy.h Source File

  • Hilo C++
  • Hilo

ExceptionPolicy.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
00009 namespace Hilo
00010 {
00011     class ExceptionPolicy
00012     {
00013     public:
00014         virtual void HandleException(Platform::Exception^ exception) = 0;
00015     };
00016 }
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: EAS policies for mail clients/C++/Constants.cpp Source File

  • EAS policies for mail clients

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
00021     { "Get Device Information", "SDKSample.EAS.Scenario1" },
00022     { "Check Compliance", "SDKSample.EAS.Scenario2" },
00023     { "Apply EAS Policy", "SDKSample.EAS.Scenario3" }
00024
00025 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: OrientationSensor/C++/Scenario2.xaml.h Source File

  • OrientationSensor

Scenario2.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.xaml.h
00013 // Declaration of the Scenario2 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario2.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace OrientationSensorCPP
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 sealed
00031         {
00032         public:
00033             Scenario2();
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             MainPage^ rootPage;
00041             Windows::UI::Core::CoreDispatcher^ dispatcher;
00042             Windows::Devices::Sensors::OrientationSensor^ sensor;
00043             Windows::Foundation::EventRegistrationToken visibilityToken;
00044             uint32 desiredReportInterval;
00045             Windows::UI::Xaml::DispatcherTimer^ dispatcherTimer;
00046
00047             void VisibilityChanged(Platform::Object^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ e);
00048             void DisplayCurrentReading(Platform::Object^ sender, Platform::Object^ e);
00049             void ScenarioEnable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00050             void ScenarioDisable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00051         };
00052     }
00053 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX touch input/C++/BasicCamera.cpp Source File

  • DirectX touch input

BasicCamera.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 "BasicCamera.h"
00010
00011 void BasicCamera::GetViewMatrix(_Out_ float4x4 *viewMatrix)
00012 {
00013     *viewMatrix = m_view;
00014 }
00015
00016 void BasicCamera::GetProjectionMatrix(_Out_ float4x4 *projectionMatrix)
00017 {
00018     *projectionMatrix = m_projection;
00019 }
00020
00021 // this method updates the view matrix based on new position and focus coordinates
00022 void BasicCamera::SetViewParameters(
00023     _In_ float3 eyePosition,    // the position of the camera
00024     _In_ float3 lookPosition,   // the point the camera should look at
00025     _In_ float3 up              // the durection vector for up
00026     )
00027 {
00028     m_position = eyePosition;
00029     m_direction = normalize(lookPosition - eyePosition);
00030     float3 zAxis = -m_direction;
00031     float3 xAxis = normalize(cross(up, zAxis));
00032     float3 yAxis = cross(zAxis, xAxis);
00033     float xOffset = -dot(xAxis, m_position);
00034     float yOffset = -dot(yAxis, m_position);
00035     float zOffset = -dot(zAxis, m_position);
00036     m_view = float4x4(
00037         xAxis.x, xAxis.y, xAxis.z, xOffset,
00038         yAxis.x, yAxis.y, yAxis.z, yOffset,
00039         zAxis.x, zAxis.y, zAxis.z, zOffset,
00040         0.0f,    0.0f,    0.0f,    1.0f
00041         );
00042 }
00043     // this method updates the projection matrix based on new parameters
00044 void BasicCamera::SetProjectionParameters(
00045     _In_ float minimumFieldOfView,  // the minimum horizontal or vertical field of view, in degrees
00046     _In_ float aspectRatio,         // the aspect ratio of the projection (width / height)
00047     _In_ float nearPlane,           // depth to map to 0
00048     _In_ float farPlane             // depth to map to 1
00049     )
00050 {
00051     float minScale = 1.0f / tan(minimumFieldOfView * PI_F / 360.0f);
00052     float xScale = 1.0f;
00053     float yScale = 1.0f;
00054     if (aspectRatio < 1.0f)
00055     {
00056         xScale = minScale;
00057         yScale = minScale * aspectRatio;
00058     }
00059     else
00060     {
00061         xScale = minScale / aspectRatio;
00062         yScale = minScale;
00063     }
00064     float zScale = farPlane / (farPlane - nearPlane);
00065     m_projection = float4x4(
00066         xScale, 0.0f,   0.0f,    0.0f,
00067         0.0f,   yScale, 0.0f,    0.0f,
00068         0.0f,   0.0f,   -zScale, -nearPlane*zScale,
00069         0.0f,   0.0f,   -1.0f,   0.0f
00070         );
00071 }
Generated on Sat Nov 23 2024 16:08:07 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML two-dimensional transforms/C++/MainPage.xaml.cpp Source File

  • XAML two-dimensional transforms

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Splash screen/C++/Scenario2.xaml.h Source File

  • Splash screen

Scenario2.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.xaml.h
00013 // Declaration of the Scenario2 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario2.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace SplashScreen
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 sealed
00031         {
00032         public:
00033             Scenario2();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         };
00038     }
00039 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D basic image effects/C++/SampleOverlay.h Source File

  • Direct2D basic image effects

SampleOverlay.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 "DirectXSample.h"
00011
00012 // This class is responsible for initializing and rendering the title overlay visible
00013 // at the top of the DirectX SDK samples.
00014 ref class SampleOverlay
00015 {
00016 internal:
00017     SampleOverlay();
00018
00019     void Initialize(
00020         _In_ ID2D1Device*         d2dDevice,
00021         _In_ ID2D1DeviceContext*  d2dContext,
00022         _In_ IWICImagingFactory*  wicFactory,
00023         _In_ IDWriteFactory*      dwriteFactory,
00024         _In_ Platform::String^    caption
00025         );
00026
00027     void ResetDirectXResources();
00028
00029     void UpdateForWindowSizeChange();
00030
00031     void Render();
00032
00033     float GetTitleHeightInDips();
00034
00035 private:
00036
00037     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00038     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00039     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00040     Microsoft::WRL::ComPtr<IDWriteFactory>          m_dwriteFactory;
00041     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_whiteBrush;
00042     Microsoft::WRL::ComPtr<ID2D1DrawingStateBlock>  m_stateBlock;
00043
00044     Microsoft::WRL::ComPtr<IWICImagingFactory>      m_wicFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Bitmap>             m_logoBitmap;
00046     Microsoft::WRL::ComPtr<IDWriteTextLayout>       m_textLayout;
00047
00048     UINT                                            m_idIncrement;
00049     bool                                            m_drawOverlay;
00050     Platform::String^                               m_sampleName;
00051     float                                           m_padding;
00052     float                                           m_textVerticalOffset;
00053     D2D1_SIZE_F                                     m_logoSize;
00054     float                                           m_overlayWidth;
00055 };
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

_SDKMESHVERTEXELEMENT Member List

This is the complete list of members for _SDKMESHVERTEXELEMENT, including all inherited members.
Method | _SDKMESHVERTEXELEMENT
Offset | _SDKMESHVERTEXELEMENT
Stream | _SDKMESHVERTEXELEMENT
Type | _SDKMESHVERTEXELEMENT
Usage | _SDKMESHVERTEXELEMENT
UsageIndex | _SDKMESHVERTEXELEMENT
Generated on Sat Nov 23 2024 16:09:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::BackgroundTask::sealed Member List

This is the complete list of members for SDKSample::BackgroundTask::sealed, including all inherited members.
AttachProgressAndCompletedHandlers(Windows::ApplicationModel::Background::IBackgroundTaskRegistration^task) | SDKSample::BackgroundTask::sealed | [private]
AttachProgressAndCompletedHandlers(Windows::ApplicationModel::Background::IBackgroundTaskRegistration^task) | SDKSample::BackgroundTask::sealed | [private]
AttachProgressAndCompletedHandlers(Windows::ApplicationModel::Background::IBackgroundTaskRegistration^task) | SDKSample::BackgroundTask::sealed | [private]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::BackgroundTask::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::BackgroundTask::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::BackgroundTask::sealed | [protected, virtual]
RegisterBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::BackgroundTask::sealed | [private]
RegisterBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::BackgroundTask::sealed | [private]
RegisterBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::BackgroundTask::sealed | [private]
rootPage | SDKSample::BackgroundTask::sealed | [private]
SampleBackgroundTask() | SDKSample::BackgroundTask::sealed |
ServicingCompleteTask() | SDKSample::BackgroundTask::sealed |
TimeTriggeredTask() | SDKSample::BackgroundTask::sealed |
UnregisterBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::BackgroundTask::sealed | [private]
UnregisterBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::BackgroundTask::sealed | [private]
UnregisterBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::BackgroundTask::sealed | [private]
UpdateUI() | SDKSample::BackgroundTask::sealed | [private]
UpdateUI() | SDKSample::BackgroundTask::sealed | [private]
UpdateUI() | SDKSample::BackgroundTask::sealed | [private]
Generated on Sat Nov 23 2024 16:09:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::AnimationMetrics::sealed Member List

This is the complete list of members for SDKSample::AnimationMetrics::sealed, including all inherited members.
Animations_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | SDKSample::AnimationMetrics::sealed | [private]
DisplayMetrics(Windows::UI::Core::AnimationMetrics::AnimationEffect effect, Windows::UI::Core::AnimationMetrics::AnimationEffectTarget target) | SDKSample::AnimationMetrics::sealed | [private]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::AnimationMetrics::sealed | [protected, virtual]
rootPage | SDKSample::AnimationMetrics::sealed | [private]
Scenario1() | SDKSample::AnimationMetrics::sealed |
Generated on Sat Nov 23 2024 16:09:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Globalization preferences/C++/Constants.cpp Source File

  • Globalization preferences

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
00021     { "User Preferences", "SDKSample.GlobalizationPreferencesSample.UserPreferences" },
00022     { "Language characteristics", "SDKSample.GlobalizationPreferencesSample.LanguageScenario" },
00023     { "Geographic Region characteristics", "SDKSample.GlobalizationPreferencesSample.GeographicRegionScenario" },
00024     { "Current input language", "SDKSample.GlobalizationPreferencesSample.CurrentInputLanguage" }
00025 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Extended Linguistic Services (ELS)/C++/MainPage.xaml.cpp Source File

  • Extended Linguistic Services (ELS)
  • C++

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:42 for Win8-Examples by doxygen 1.7.1


Win8-Examples: USSD message management/C++/common/LayoutAwarePage.cpp Source File

  • USSD message management
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:33 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows account authorization/C++/common/suspensionmanager.cpp Source File

  • Windows account authorization
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:37 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Credential picker/C++/ScenarioOutput3.xaml.h Source File

  • Credential picker

ScenarioOutput3.xaml.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 //
00009 // Scenario3Output.xaml.h
00010 // Declaration of the Scenario3Output class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioOutput3.g.h"
00017 #include "MainPage.g.h"
00018
00019 namespace CredentialPickerCPP
00020 {
00021   [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class ScenarioOutput3 sealed
00023     {
00024     public:
00025         ScenarioOutput3();
00026
00027     protected:
00028         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030
00031     private:
00032         MainPage^ rootPage;
00033         void Page_Loaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00034         void rootPage_InputFrameLoaded(Object^ sender, Object^ e);
00035         void Page_SizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00036         void DisplayProperties_LogicalDpiChanged(Object^ sender);
00037         Windows::Foundation::EventRegistrationToken _frameLoadedToken;
00038         void CheckResolutionAndViewState();
00039         ~ScenarioOutput3();
00040     };
00041 }
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D tutorial/C++/Lesson5.Components/SampleOverlay.cpp Source File

  • Direct3D tutorial
  • Lesson5.Components

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 Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::UI::ViewManagement;
00015 using namespace Windows::Graphics::Display;
00016 using namespace D2D1;
00017
00018 SampleOverlay::SampleOverlay() :
00019     m_drawOverlay(true)
00020 {
00021 }
00022
00023 void SampleOverlay::Initialize(
00024     _In_ ID2D1Device*         d2dDevice,
00025     _In_ ID2D1DeviceContext*  d2dContext,
00026     _In_ IWICImagingFactory*  wicFactory,
00027     _In_ IDWriteFactory*      dwriteFactory,
00028     _In_ Platform::String^    caption
00029     )
00030 {
00031     m_wicFactory = wicFactory;
00032     m_dwriteFactory = dwriteFactory;
00033     m_sampleName = caption;
00034     m_d2dDevice = d2dDevice;
00035     m_d2dContext = d2dContext;
00036     m_padding = 3.0f;
00037     m_textVerticalOffset = 5.0f;
00038     m_logoSize = D2D1::SizeF(0.0f, 0.0f);
00039     m_overlayWidth = 0.0f;
00040
00041     ComPtr<ID2D1Factory> factory;
00042     d2dDevice->GetFactory(&factory);
00043
00044     DX::ThrowIfFailed(
00045         factory.As(&m_d2dFactory)
00046         );
00047
00048     ResetDirectXResources();
00049 }
00050
00051 void SampleOverlay::ResetDirectXResources()
00052 {
00053     DX::ThrowIfFailed(
00054         m_d2dContext->CreateSolidColorBrush(ColorF(ColorF::White), &m_whiteBrush)
00055         );
00056
00057     ComPtr<IWICBitmapDecoder> wicBitmapDecoder;
00058     DX::ThrowIfFailed(
00059         m_wicFactory->CreateDecoderFromFilename(
00060             L"windowsbig-sdk.png",
00061             nullptr,
00062             GENERIC_READ,
00063             WICDecodeMetadataCacheOnDemand,
00064             &wicBitmapDecoder
00065             )
00066         );
00067
00068     ComPtr<IWICBitmapFrameDecode> wicBitmapFrame;
00069     DX::ThrowIfFailed(
00070         wicBitmapDecoder->GetFrame(0, &wicBitmapFrame)
00071         );
00072
00073     ComPtr<IWICFormatConverter> wicFormatConverter;
00074     DX::ThrowIfFailed(
00075         m_wicFactory->CreateFormatConverter(&wicFormatConverter)
00076         );
00077
00078     DX::ThrowIfFailed(
00079         wicFormatConverter->Initialize(
00080             wicBitmapFrame.Get(),
00081             GUID_WICPixelFormat32bppPBGRA,
00082             WICBitmapDitherTypeNone,
00083             nullptr,
00084             0.0,
00085             WICBitmapPaletteTypeCustom  // the BGRA format has no palette so this value is ignored
00086             )
00087         );
00088
00089     double dpiX = 96.0f;
00090     double dpiY = 96.0f;
00091     DX::ThrowIfFailed(
00092         wicFormatConverter->GetResolution(&dpiX, &dpiY)
00093         );
00094
00095     DX::ThrowIfFailed(
00096         m_d2dContext->CreateBitmapFromWicBitmap(
00097             wicFormatConverter.Get(),
00098             BitmapProperties(
00099                 PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00100                 static_cast<float>(dpiX),
00101                 static_cast<float>(dpiY)
00102                 ),
00103             &m_logoBitmap
00104             )
00105         );
00106
00107     m_logoSize = m_logoBitmap->GetSize();
00108
00109     ComPtr<IDWriteTextFormat> nameTextFormat;
00110     DX::ThrowIfFailed(
00111         m_dwriteFactory->CreateTextFormat(
00112             L"Segoe UI",
00113             nullptr,
00114             DWRITE_FONT_WEIGHT_LIGHT,
00115             DWRITE_FONT_STYLE_NORMAL,
00116             DWRITE_FONT_STRETCH_NORMAL,
00117             36.0f,
00118             L"en-US",
00119             &nameTextFormat
00120             )
00121         );
00122
00123     DX::ThrowIfFailed(
00124         nameTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)
00125         );
00126
00127     DX::ThrowIfFailed(
00128         nameTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)
00129         );
00130
00131     DX::ThrowIfFailed(
00132         m_dwriteFactory->CreateTextLayout(
00133             m_sampleName->Data(),
00134             m_sampleName->Length(),
00135             nameTextFormat.Get(),
00136             4096.0f,
00137             4096.0f,
00138             &m_textLayout
00139             )
00140         );
00141
00142     DWRITE_TEXT_METRICS metrics = {0};
00143     DX::ThrowIfFailed(
00144         m_textLayout->GetMetrics(&metrics)
00145         );
00146
00147     m_overlayWidth = m_padding * 3.0f + m_logoSize.width + metrics.width;
00148
00149     DX::ThrowIfFailed(
00150         m_d2dFactory->CreateDrawingStateBlock(&m_stateBlock)
00151         );
00152
00153     UpdateForWindowSizeChange();
00154 }
00155
00156 void SampleOverlay::UpdateForWindowSizeChange()
00157 {
00158     if (CoreWindow::GetForCurrentThread()->Bounds.Width < m_overlayWidth)
00159     {
00160         m_drawOverlay = false;
00161     }
00162     else
00163     {
00164         m_drawOverlay = true;
00165     }
00166 }
00167
00168 void SampleOverlay::Render()
00169 {
00170     if (m_drawOverlay)
00171     {
00172         m_d2dContext->SaveDrawingState(m_stateBlock.Get());
00173
00174         m_d2dContext->BeginDraw();
00175         m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00176         m_d2dContext->DrawBitmap(
00177             m_logoBitmap.Get(),
00178             D2D1::RectF(m_padding, 0.0f, m_logoSize.width + m_padding, m_logoSize.height)
00179             );
00180
00181         m_d2dContext->DrawTextLayout(
00182             Point2F(m_logoSize.width + 2.0f * m_padding, m_textVerticalOffset),
00183             m_textLayout.Get(),
00184             m_whiteBrush.Get()
00185             );
00186
00187         // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00188         // is lost. It will be handled during the next call to Present.
00189         HRESULT hr = m_d2dContext->EndDraw();
00190         if (hr != D2DERR_RECREATE_TARGET)
00191         {
00192             DX::ThrowIfFailed(hr);
00193         }
00194
00195         m_d2dContext->RestoreDrawingState(m_stateBlock.Get());
00196     }
00197 }
00198
00199 float SampleOverlay::GetTitleHeightInDips()
00200 {
00201     return m_logoSize.height;
00202 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D tutorial/C++/Lesson5.Components/DDSTextureLoader.h Source File

  • Direct3D tutorial
  • Lesson5.Components

DDSTextureLoader.h

Go to the documentation of this file.
00001 //--------------------------------------------------------------------------------------
00002 // File: DDSTextureLoader.h
00003 //
00004 // Function for loading a DDS texture and creating a Direct3D 11 runtime resource for it
00005 //
00006 // Note this function is 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
00018 #pragma once
00019
00020 void CreateDDSTextureFromMemory(
00021     _In_ ID3D11Device* d3dDevice,
00022     _In_reads_bytes_(ddsDataSize) const byte* ddsData,
00023     _In_ size_t ddsDataSize,
00024     _Out_opt_ ID3D11Resource** texture,
00025     _Out_opt_ ID3D11ShaderResourceView** textureView,
00026     _In_ size_t maxsize = 0
00027     );
Generated on Sat Nov 23 2024 16:08:11 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/MediaExtensions/Common/CritSec.h Source File

  • Media extensions
  • MediaExtensions
  • Common

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 Sat Nov 23 2024 16:08:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Credential picker/C++/App.xaml.h Source File

  • Credential picker

App.xaml.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 //
00009 // App.xaml.h
00010 // Declaration of the App.xaml class.
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "App.g.h"
00017
00018 namespace CredentialPickerCPP
00019 {
00020     ref class App sealed
00021     {
00022     public:
00023
00024         App();
00025         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00026         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00027     };
00028 }
00029
00030
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Lock screen personalization/C++/pch.cpp Source File

  • Lock screen personalization

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Background Transfer/C++/App.xaml.h Source File

  • Background Transfer

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Toast notifications/C#,C++/ScenarioInput5.xaml.cpp Source File

  • Toast notifications
  • C#,C++

ScenarioInput5.xaml.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 //
00009 // Scenario1Input.xaml.cpp
00010 // Implementation of the Scenario1Input class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioInput5.xaml.h"
00015
00016 using namespace ToastsSampleCPP;
00017
00018 using namespace NotificationsExtensions::ToastContent;
00019 using namespace Platform;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Graphics::Display;
00023 using namespace Windows::UI::Core;
00024 using namespace Windows::UI::Notifications;
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::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
00034 ScenarioInput5::ScenarioInput5()
00035 {
00036     InitializeComponent();
00037     Scenario5DisplayToastWithCallbacks->Click += ref new RoutedEventHandler(this, &ScenarioInput5::Scenario5DisplayToastWithCallbacks_Click);
00038     Scenario5HideToast->Click += ref new RoutedEventHandler(this, &ScenarioInput5::Scenario5HideToast_Click);
00039     dispatcher = Window::Current->Dispatcher;
00040 }
00041
00042 ScenarioInput5::~ScenarioInput5()
00043 {
00044 }
00045
00046 #pragma region Template-Related Code - Do not remove
00047 void ScenarioInput5::OnNavigatedTo(NavigationEventArgs^ e)
00048 {
00049     // Get a pointer to our main page.
00050     auto pageAndContext = dynamic_cast<MainPageAndContext^>(e->Parameter);
00051     rootPage = pageAndContext->MainPage;
00052     toastContext = pageAndContext->ToastContext;
00053
00054     // We want to be notified with the OutputFrame is loaded so we can get to the content.
00055     _frameLoadedToken = rootPage->OutputFrameLoaded += ref new Windows::Foundation::EventHandler<Platform::Object^>(this, &ScenarioInput5::rootPage_OutputFrameLoaded);
00056 }
00057
00058 void ScenarioInput5::OnNavigatedFrom(NavigationEventArgs^ e)
00059 {
00060     rootPage->OutputFrameLoaded -= _frameLoadedToken;
00061 }
00062
00063 void ScenarioInput5::rootPage_OutputFrameLoaded(Object^ sender, Object^ e)
00064 {
00065     // Get a pointer to the content within the OutputFrame.
00066     Page^ outputFrame = dynamic_cast<Page^>(rootPage->OutputFrame->Content);
00067
00068     if (toastContext != "")
00069     {
00070         OutputText("A toast was clicked on with activation arguments: " + toastContext);
00071     }
00072 }
00073
00074 #pragma endregion
00075
00076 void ScenarioInput5::OutputText(String^ text) {
00077     if (outputText == nullptr)
00078     {
00079         // Get a pointer to the content within the OutputFrame.
00080         Page^ outputFrame = dynamic_cast<Page^>(rootPage->OutputFrame->Content);
00081
00082         // Go find the elements that we need for this scenario
00083         outputText = dynamic_cast<TextBlock^>(outputFrame->FindName("Scenario5OutputText"));
00084     }
00085
00086     outputText->Text = text;
00087 }
00088
00089 void ScenarioInput5::Scenario5DisplayToastWithCallbacks_Click(Object^ sender, RoutedEventArgs^ e)
00090 {
00091     IToastText02^ toastContent = ToastContentFactory::CreateToastText02();
00092     toastContent->TextHeading->Text = "Tap toast";
00093     toastContent->TextBodyWrap->Text = "Or swipe to dismiss";
00094
00095     toastContent->Launch = "Context123";
00096
00097     OutputText(toastContent->GetContent());
00098
00099     // You can listen for the "Activated" event provided on the toast object
00100     // or listen to the "OnLaunched" event off Windows::UI::Xaml::Application
00101     // object to tell when the user clicks the toast.
00102     //
00103     // The difference is that the OnLaunched event will
00104     // be raised by local, scheduled and cloud toasts, while the event provided by the
00105     // toast object will only be raised by local toasts.
00106     //
00107     // In this example, we'll use the event off the CoreApplication object.
00108     _toast = toastContent->CreateNotification();
00109
00110     _toast->Dismissed += ref new TypedEventHandler<ToastNotification^, ToastDismissedEventArgs^>(this, &ScenarioInput5::toast_Dismissed);
00111     _toast->Failed += ref new TypedEventHandler<ToastNotification^, ToastFailedEventArgs^>(this, &ScenarioInput5::toast_Failed);
00112
00113     ToastNotificationManager::CreateToastNotifier()->Show(_toast);
00114 }
00115
00116 void ScenarioInput5::toast_Failed(ToastNotification^ sender, ToastFailedEventArgs^ e)
00117 {
00118     dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this]()
00119     {
00120         OutputText("The toast encountered an error");
00121     }, CallbackContext::Any));
00122 }
00123
00124 void ScenarioInput5::toast_Dismissed(ToastNotification^ sender, ToastDismissedEventArgs^ e)
00125 {
00126     String^ output = "";
00127
00128     switch (e->Reason)
00129     {
00130         case ToastDismissalReason::ApplicationHidden:
00131             output = "The app hid the toast using ToastNotifier->Hide(toast)";
00132             break;
00133         case ToastDismissalReason::UserCanceled:
00134             output = "The user dismissed this toast";
00135             break;
00136         case ToastDismissalReason::TimedOut:
00137             output = "The toast has timed out";
00138             break;
00139     }
00140
00141     dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, output]()
00142     {
00143         OutputText(output);
00144     }, CallbackContext::Any));
00145 }
00146
00147 void ScenarioInput5::Scenario5HideToast_Click(Object^ sender, RoutedEventArgs^ e)
00148 {
00149     if (_toast != nullptr)
00150     {
00151         ToastNotificationManager::CreateToastNotifier()->Hide(_toast);
00152         _toast = nullptr;
00153     }
00154     else
00155     {
00156         OutputText("No toast has been displayed from Scenario 5");
00157     }
00158 }
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Credential picker/C++/pch.cpp Source File

  • Credential picker

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 //
00009 // pch.cpp
00010 // Include the standard header and generate the precompiled header.
00011 //
00012
00013 #include "pch.h"
Generated on Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Device auto rotation preferences/C++/LandscapeFlipped.xaml.cpp Source File

  • Device auto rotation preferences

LandscapeFlipped.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 // LandscapeFlipped.xaml.cpp
00013 // Implementation of the LandscapeFlipped class
00014 //
00015
00016 #include "pch.h"
00017 #include "LandscapeFlipped.xaml.h"
00018
00019 using namespace SDKSample::Rotation;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 LandscapeFlipped::LandscapeFlipped()
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 LandscapeFlipped::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 SDKSample::Rotation::LandscapeFlipped::SetLandscapeFlipped_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00043 {
00044     Button^ b = safe_cast<Button^>(sender);
00045     if (b != nullptr)
00046     {
00047         Windows::Graphics::Display::DisplayProperties::AutoRotationPreferences = Windows::Graphics::Display::DisplayOrientations::LandscapeFlipped;
00048
00049         if (Windows::Graphics::Display::DisplayProperties::AutoRotationPreferences == Windows::Graphics::Display::DisplayOrientations::LandscapeFlipped)
00050         {
00051             rootPage->NotifyUser("Succeeded: Preference set to Landscape Flipped.", NotifyType::StatusMessage);
00052         }
00053         else
00054         {
00055             rootPage->NotifyUser("Error: Failed to set the preference.", NotifyType::StatusMessage);
00056         }
00057     }
00058 }
Generated on Sat Nov 23 2024 16:08:02 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite inline object/C++/InlineImage.h Source File

  • DirectWrite inline object

InlineImage.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 class InlineImage
00011     :   public IDWriteInlineObject
00012 {
00013 public:
00014     InlineImage(
00015         Microsoft::WRL::ComPtr<ID2D1DeviceContext> deviceContext,
00016         Microsoft::WRL::ComPtr<IWICImagingFactory> IWICFactory,
00017         PCWSTR uri
00018         );
00019
00020     STDMETHOD(Draw)(
00021         _In_opt_ void* clientDrawingContext,
00022         IDWriteTextRenderer* renderer,
00023         FLOAT originX,
00024         FLOAT originY,
00025         BOOL isSideways,
00026         BOOL isRightToLeft,
00027         IUnknown* clientDrawingEffect
00028         );
00029
00030     STDMETHOD(GetMetrics)(
00031         _Out_ DWRITE_INLINE_OBJECT_METRICS* metrics
00032         );
00033
00034     STDMETHOD(GetOverhangMetrics)(
00035         _Out_ DWRITE_OVERHANG_METRICS* overhangs
00036         );
00037
00038     STDMETHOD(GetBreakConditions)(
00039         _Out_ DWRITE_BREAK_CONDITION* breakConditionBefore,
00040         _Out_ DWRITE_BREAK_CONDITION* breakConditionAfter
00041         );
00042
00043 public:
00044
00045     unsigned long STDMETHODCALLTYPE AddRef();
00046     unsigned long STDMETHODCALLTYPE Release();
00047     HRESULT STDMETHODCALLTYPE QueryInterface(
00048         IID const& riid,
00049         void** ppvObject
00050         );
00051
00052 private:
00053
00054     HRESULT LoadBitmapFromFile(
00055         Microsoft::WRL::ComPtr<ID2D1DeviceContext> deviceContext,
00056         Microsoft::WRL::ComPtr<IWICImagingFactory> IWICFactory,
00057         PCWSTR uri,
00058         _Outptr_ ID2D1Bitmap **ppBitmap
00059         );
00060
00061 private:
00062     Microsoft::WRL::ComPtr<ID2D1Bitmap> bitmap;
00063     Microsoft::WRL::ComPtr<ID2D1DeviceContext> deviceContext;
00064
00065     D2D1_RECT_F rect; // coordinates in image, similar to index of HIMAGE_LIST
00066     float baseline;
00067
00068     unsigned long refCount;
00069 };
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File access/C++/Scenario6.xaml.cpp Source File

  • File access

Scenario6.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.xaml.cpp
00013 // Implementation of the Scenario6 class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario6.xaml.h"
00018
00019 using namespace SDKSample::FileAccess;
00020
00021 using namespace concurrency;
00022 using namespace Platform;
00023 using namespace Windows::Storage;
00024 using namespace Windows::Storage::AccessCache;
00025 using namespace Windows::UI::Xaml;
00026 using namespace Windows::UI::Xaml::Controls;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 Scenario6::Scenario6()
00030 {
00031     InitializeComponent();
00032     rootPage = MainPage::Current;
00033     AddToListButton->Click += ref new RoutedEventHandler(this, &Scenario6::AddToListButton_Click);
00034     ShowListButton->Click += ref new RoutedEventHandler(this, &Scenario6::ShowListButton_Click);
00035     OpenFromListButton->Click += ref new RoutedEventHandler(this, &Scenario6::OpenFromListButton_Click);
00036 }
00037
00038 void Scenario6::AddToListButton_Click(Object^ sender, RoutedEventArgs^ e)
00039 {
00040     rootPage->ResetScenarioOutput(OutputTextBlock);
00041     StorageFile^ file = rootPage->SampleFile;
00042     if (file != nullptr)
00043     {
00044         if (MRURadioButton->IsChecked->Value)
00045         {
00046             // Add the file to the MRU
00047             rootPage->MruToken = StorageApplicationPermissions::MostRecentlyUsedList->Add(file, file->Name);
00048             OutputTextBlock->Text = "The file '" + file->Name + "' was added to the MRU list and a token was stored.";
00049         }
00050         else if (FALRadioButton->IsChecked->Value)
00051         {
00052             // Add the file to the MRU
00053             rootPage->FalToken = StorageApplicationPermissions::FutureAccessList->Add(file, file->Name);
00054             OutputTextBlock->Text = "The file '" + file->Name + "' was added to the FAL list and a token was stored.";
00055         }
00056     }
00057 }
00058
00059 void Scenario6::ShowListButton_Click(Object^ sender, RoutedEventArgs^ e)
00060 {
00061     rootPage->ResetScenarioOutput(OutputTextBlock);
00062     StorageFile^ file = rootPage->SampleFile;
00063     if (file != nullptr)
00064     {
00065         String^ outputText;
00066         if (MRURadioButton->IsChecked->Value)
00067         {
00068             AccessListEntryView^ entries = StorageApplicationPermissions::MostRecentlyUsedList->Entries;
00069             if (entries->Size > 0)
00070             {
00071                 outputText = "The MRU list contains the following item(s):\n\n";
00072                 std::for_each(begin(entries), end(entries), [this, &outputText](const AccessListEntry& entry)
00073                 {
00074                     outputText += entry.Metadata + "\n"; // Application previously chose to store sampleFile->Name in this field
00075                 });
00076             }
00077             else
00078             {
00079                 outputText = "The MRU list is empty, please select 'Most Recently Used' list and click 'Add to List' to add a file to the MRU list.";
00080             }
00081         }
00082         else if (FALRadioButton->IsChecked->Value)
00083         {
00084             AccessListEntryView^ entries = StorageApplicationPermissions::FutureAccessList->Entries;
00085             if (entries->Size > 0)
00086             {
00087                 outputText = "The FAL list contains the following item(s):\n\n";
00088                 std::for_each(begin(entries), end(entries), [this, &outputText](const AccessListEntry& entry)
00089                 {
00090                     outputText += entry.Metadata + "\n"; // Application previously chose to store sampleFile->Name in this field
00091                 });
00092             }
00093             else
00094             {
00095                 outputText = "The FAL list is empty, please select 'Future Access List' list and click 'Add to List' to add a file to the FAL list.";
00096             }
00097         }
00098         OutputTextBlock->Text = outputText;
00099     }
00100 }
00101
00102 void Scenario6::OpenFromListButton_Click(Object^ sender, RoutedEventArgs^ e)
00103 {
00104     rootPage->ResetScenarioOutput(OutputTextBlock);
00105     StorageFile^ file = rootPage->SampleFile;
00106     if (file != nullptr)
00107     {
00108         if (MRURadioButton->IsChecked->Value)
00109         {
00110             if (rootPage->MruToken != nullptr)
00111             {
00112                 // Open the file via the token that was stored when adding this file into the MRU list
00113                 create_task(StorageApplicationPermissions::MostRecentlyUsedList->GetFileAsync(rootPage->MruToken)).then([this](task<StorageFile^> task)
00114                 {
00115                     try
00116                     {
00117                         StorageFile^ file = task.get();
00118                         // Read the file
00119                         create_task(FileIO::ReadTextAsync(file)).then([this, file](String^ fileContent)
00120                         {
00121                             OutputTextBlock->Text = "The file '" + file->Name + "' was opened by a stored token from the MRU list, it contains the following text:\n\n" + fileContent;
00122                         });
00123                     }
00124                     catch(COMException^ ex)
00125                     {
00126                         rootPage->HandleFileNotFoundException(ex);
00127                     }
00128                 });
00129             }
00130             else
00131             {
00132                 OutputTextBlock->Text = "The MRU list is empty, please select 'Most Recently Used' list and click 'Add to List' to add a file to the MRU list.";
00133             }
00134         }
00135         else if (FALRadioButton->IsChecked->Value)
00136         {
00137             if (rootPage->FalToken != nullptr)
00138             {
00139                 // Open the file via the token that was stored when adding this file into the FAL list
00140                 create_task(StorageApplicationPermissions::FutureAccessList->GetFileAsync(rootPage->FalToken)).then([this](task<StorageFile^> task)
00141                 {
00142                     try
00143                     {
00144                         StorageFile^ file = task.get();
00145                         // Read the file
00146                         create_task(FileIO::ReadTextAsync(file)).then([this, file](String^ fileContent)
00147                         {
00148                             OutputTextBlock->Text = "The file '" + file->Name + "' was opened by a stored token from the FAL list, it contains the following text:\n\n" + fileContent;
00149                         });
00150                     }
00151                     catch(COMException^ ex)
00152                     {
00153                         rootPage->HandleFileNotFoundException(ex);
00154                     }
00155                 });
00156             }
00157             else
00158             {
00159                 OutputTextBlock->Text = "The FAL list is empty, please select 'Future Access List' list and click 'Add to List' to add a file to the FAL list.";
00160             }
00161         }
00162     }
00163 }
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D custom image effects/C++/VertexShader/BasicTimer.cpp Source File

  • Direct2D custom image effects
  • VertexShader

BasicTimer.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 "BasicTimer.h"
00010
00011 BasicTimer::BasicTimer()
00012 {
00013     if (!QueryPerformanceFrequency(&m_frequency))
00014     {
00015         throw ref new Platform::FailureException();
00016     }
00017     Reset();
00018 }
00019
00020 void BasicTimer::Reset()
00021 {
00022     Update();
00023     m_startTime = m_currentTime;
00024     m_total = 0.0f;
00025     m_delta = 1.0f / 60.0f;
00026 }
00027
00028 void BasicTimer::Update()
00029 {
00030     if (!QueryPerformanceCounter(&m_currentTime))
00031     {
00032         throw ref new Platform::FailureException();
00033     }
00034
00035     m_total = static_cast<float>(
00036         static_cast<double>(m_currentTime.QuadPart-m_startTime.QuadPart) /
00037         static_cast<double>(m_frequency.QuadPart)
00038         );
00039
00040     if (m_lastTime.QuadPart == m_startTime.QuadPart)
00041     {
00042         // If the timer was just reset, report a time delta equivalent to 60Hz frame time.
00043         m_delta = 1.0f / 60.0f;
00044     }
00045     else
00046     {
00047         m_delta = static_cast<float>(
00048             static_cast<double>(m_currentTime.QuadPart-m_lastTime.QuadPart) /
00049             static_cast<double>(m_frequency.QuadPart)
00050             );
00051     }
00052
00053     m_lastTime = m_currentTime;
00054 }
00055
00056 float BasicTimer::Total::get()
00057 {
00058     return m_total;
00059 }
00060
00061 float BasicTimer::Delta::get()
00062 {
00063     return m_delta;
00064 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::Common::SharePage Member List

This is the complete list of members for SDKSample::Common::SharePage, including all inherited members.
__pad0__ | SDKSample::Common::LayoutAwarePage |
dataRequestedToken | SDKSample::Common::SharePage | [private]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
GetShareContent(Windows::ApplicationModel::DataTransfer::DataRequest^request) | SDKSample::Common::SharePage | [protected, virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
OnDataRequested(Windows::ApplicationModel::DataTransfer::DataTransferManager^sender, Windows::ApplicationModel::DataTransfer::DataRequestedEventArgs^e) | SDKSample::Common::SharePage | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::SharePage | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::SharePage | [protected, virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
ShowUIButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::SharePage | [protected]
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
Generated on Sat Nov 23 2024 16:09:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text display/C++/Scenario2.xaml.cpp Source File

  • XAML text display

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 SDKSample::TextDisplay;
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
00042
00043 void SDKSample::TextDisplay::Scenario2::DoSomething_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00044 {
00045     Button^ b = safe_cast<Button^>(sender);
00046     if (b != nullptr)
00047     {
00048         rootPage->NotifyUser("You clicked the " + b->Name + " button", NotifyType::StatusMessage);
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Credential locker/C++/Scenario2.xaml.h Source File

  • Credential locker

Scenario2.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.xaml.h
00013 // Declaration of the Scenario2 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario2.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace PasswordVaultCPP
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 sealed
00031         {
00032         public:
00033             Scenario2();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void DoSomething_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         void Launch_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         void Signin_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00042         void ChangeUser_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00043         void Reset_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00044         void SelectUser_Click(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00045       };
00046     }
00047 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML two-dimensional transforms/C++/Constants.cpp Source File

  • XAML two-dimensional transforms

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully qualified name for the class that implements the scenario" }
00021     { "2D transforms", "SDKSample.Transforms.Scenario1" },
00022     { "Matrix transforms", "SDKSample.Transforms.Scenario2" }
00023 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Device enumeration/C++/Containers.xaml.h Source File

  • Device enumeration

Containers.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 // Containers.xaml.h
00013 // Declaration of the Containers class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Containers.g.h"
00020 #include "MainPage.xaml.h"
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::ViewManagement;
00026 using namespace Platform;
00027 using namespace concurrency;
00028 using namespace Windows::Devices::Enumeration;
00029 using namespace Windows::Devices::Enumeration::Pnp;
00030
00031 namespace SDKSample
00032 {
00033     namespace DeviceEnumeration
00034     {
00035         /// <summary>
00036         /// An empty page that can be used on its own or navigated to within a Frame.
00037         /// </summary>
00038       [Windows::Foundation::Metadata::WebHostHidden]
00039         public ref class Containers sealed
00040         {
00041         public:
00042             Containers();
00043
00044         protected:
00045             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00046         private:
00047             MainPage^ rootPage;
00048         void EnumerateDeviceContainers(Object^ sender, RoutedEventArgs^ eventArgs);
00049         void DisplayDeviceContainer(PnpObject^ container);
00050         };
00051
00052       [Windows::UI::Xaml::Data::Bindable]
00053         public ref class ContainerDisplayItem sealed
00054         {
00055             public:
00056                 ContainerDisplayItem(String^ id, String^ name, String^ properties):
00057                     id(id), name(name), properties(properties) {}
00058
00059                 property String^ Id { String^ get() { return id; }}
00060                 property String^ Name { String^ get() { return name; }}
00061                 property String^ Properties { String^ get() { return properties; }}
00062
00063             private protected:
00064                 String^ id;
00065                 String^ name;
00066                 String^ properties;
00067         };
00068     }
00069 }
Generated on Sat Nov 23 2024 16:08:02 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/FileSystemRepository.cpp Source File

  • Hilo C++
  • Hilo

FileSystemRepository.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 #include "FileSystemRepository.h"
00009 #include "CalendarExtensions.h"
00010 #include "NullPhotoGroup.h"
00011 #include "Photo.h"
00012 #include "QueryChange.h"
00013
00014 using namespace concurrency;
00015 using namespace Hilo;
00016 using namespace Platform;
00017 using namespace Platform::Collections;
00018 using namespace std;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::Storage;
00022 using namespace Windows::Storage::BulkAccess;
00023 using namespace Windows::Storage::FileProperties;
00024 using namespace Windows::Storage::Search;
00025
00026 // See http://go.microsoft.com/fwlink/?LinkId=267277 for info about the FileSystemRepository class.
00027
00028 #pragma region File System Queries
00029
00030 const std::array<String^, 6> items = { ".jpg", ".jpeg", ".png", ".bmp", ".gif", ".tif" };
00031
00032 inline task<IVectorView<StorageFile^>^> FileSystemRepository::GetPhotoStorageFilesAsync(String^ query, unsigned int maxNumberOfItems)
00033 {
00034     auto fileQuery = CreateFileQuery(KnownFolders::PicturesLibrary, query);
00035     return create_task(fileQuery->GetFilesAsync(0, maxNumberOfItems));
00036 }
00037
00038 inline StorageFileQueryResult^ FileSystemRepository::CreateFileQuery(IStorageFolderQueryOperations^ folder, String^ query, IndexerOption indexerOption)
00039 {
00040     auto fileTypeFilter = ref new Vector<String^>(items);
00041     auto queryOptions = ref new QueryOptions(CommonFileQuery::OrderByDate, fileTypeFilter);
00042     queryOptions->FolderDepth = FolderDepth::Deep;
00043     queryOptions->IndexerOption = indexerOption;
00044     queryOptions->ApplicationSearchFilter = query;
00045     queryOptions->SetThumbnailPrefetch(ThumbnailMode::PicturesView, 190, ThumbnailOptions::UseCurrentScale);
00046     queryOptions->Language = CalendarExtensions::ResolvedLanguage();
00047     return folder->CreateFileQueryWithOptions(queryOptions);
00048 }
00049
00050 #pragma endregion
00051
00052 FileSystemRepository::FileSystemRepository(shared_ptr<ExceptionPolicy> exceptionPolicy) : m_exceptionPolicy(exceptionPolicy)
00053 {
00054 }
00055
00056 #pragma region ObservableQuery Methods
00057 void FileSystemRepository::AddObserver(const std::function<void()> callback, PageType pageType)
00058 {
00059     switch (pageType)
00060     {
00061     case PageType::Hub:
00062         m_hubViewModelCallback = callback;
00063         break;
00064     case PageType::Browse:
00065         m_imageBrowserViewModelCallback = callback;
00066         break;
00067     case PageType::Image:
00068         m_imageViewModelCallback = callback;
00069         break;
00070     default:
00071         assert(false);
00072     }
00073 }
00074
00075 void FileSystemRepository::RemoveObserver(PageType pageType)
00076 {
00077     switch (pageType)
00078     {
00079     case PageType::Hub:
00080         m_pictureHubGroupQueryChange = nullptr;
00081         m_hubViewModelCallback = nullptr;
00082         break;
00083     case PageType::Browse:
00084         m_monthQueryChange = nullptr;
00085         m_imageBrowserViewModelCallback = nullptr;
00086         break;
00087     case PageType::Image:
00088         m_allPhotosQueryChange = nullptr;
00089         m_imageViewModelCallback = nullptr;
00090         break;
00091     default:
00092         assert(false);
00093     }
00094 }
00095 #pragma endregion
00096
00097
00098 void FileSystemRepository::NotifyAllObservers()
00099 {
00100     if (m_hubViewModelCallback != nullptr)
00101     {
00102         m_hubViewModelCallback();
00103     }
00104     if (m_imageBrowserViewModelCallback != nullptr)
00105     {
00106         m_imageBrowserViewModelCallback();
00107     }
00108     if (m_imageViewModelCallback = nullptr)
00109     {
00110         m_imageViewModelCallback();
00111     }
00112 }
00113
00114 // Create month groups by querying the file system.
00115 task<IVectorView<IPhotoGroup^>^> FileSystemRepository::GetMonthGroupedPhotosWithCacheAsync(shared_ptr<PhotoCache> photoCache, concurrency::cancellation_token token)
00116 {
00117     auto queryOptions = ref new QueryOptions(CommonFolderQuery::GroupByMonth);
00118     queryOptions->FolderDepth = FolderDepth::Deep;
00119     queryOptions->IndexerOption = IndexerOption::UseIndexerWhenAvailable;
00120     queryOptions->Language = CalendarExtensions::ResolvedLanguage();
00121     auto fileQuery = KnownFolders::PicturesLibrary->CreateFolderQueryWithOptions(queryOptions);
00122     auto fileInformationFactory = ref new FileInformationFactory(fileQuery, ThumbnailMode::PicturesView);
00123
00124     m_monthQueryChange = (m_imageBrowserViewModelCallback != nullptr) ? ref new QueryChange(fileQuery, m_imageBrowserViewModelCallback) : nullptr;
00125
00126     shared_ptr<ExceptionPolicy> policy = m_exceptionPolicy;
00127     auto sharedThis = shared_from_this();
00128     return create_task(fileInformationFactory->GetFoldersAsync()).then([this, fileInformationFactory, photoCache, sharedThis, policy](IVectorView<FolderInformation^>^ folders)
00129     {
00130         auto temp = ref new Vector<IPhotoGroup^>();
00131         for (auto folder : folders)
00132         {
00133             auto photoGroup = ref new MonthGroup(photoCache, folder, sharedThis, policy);
00134             temp->Append(photoGroup);
00135         }
00136         return temp->GetView();
00137     }, token);
00138 }
00139
00140 // Query the file system using a pathname.
00141 task<IPhoto^> FileSystemRepository::GetSinglePhotoAsync(String^ photoPath)
00142 {
00143     String^ query = "System.ParsingPath:=\"" + photoPath + "\"";
00144     auto fileQuery = CreateFileQuery(KnownFolders::PicturesLibrary, query, IndexerOption::DoNotUseIndexer);
00145     auto fileInformationFactory = ref new FileInformationFactory(fileQuery, ThumbnailMode::PicturesView);
00146     shared_ptr<ExceptionPolicy> policy = m_exceptionPolicy;
00147     return create_task(fileInformationFactory->GetFilesAsync(0, 1)).then([policy](IVectorView<FileInformation^>^ files)
00148     {
00149         IPhoto^ photo = nullptr;
00150         auto size = files->Size;
00151         if (size > 0)
00152         {
00153             photo = ref new Photo(files->GetAt(0), ref new NullPhotoGroup(), policy);
00154         }
00155         return photo;
00156     }, task_continuation_context::use_current());
00157 }
00158
00159 // Count the number of photos in a given folder query.
00160 task<unsigned int> FileSystemRepository::GetFolderPhotoCountAsync(IStorageFolderQueryOperations^ folderQuery)
00161 {
00162     auto fileTypeFilter = ref new Vector<String^>(items);
00163     auto queryOptions = ref new QueryOptions(CommonFileQuery::OrderByDate, fileTypeFilter);  // ordered query allows use of indexer
00164     queryOptions->FolderDepth = FolderDepth::Deep;
00165     queryOptions->IndexerOption = IndexerOption::UseIndexerWhenAvailable;
00166     queryOptions->Language = CalendarExtensions::ResolvedLanguage();
00167     auto fileQuery = folderQuery->CreateFileQueryWithOptions(queryOptions);
00168     return create_task(fileQuery->GetFilesAsync(0, 1)).then([fileQuery](IVectorView<StorageFile^>^ files)
00169     {
00170         return fileQuery->GetItemCountAsync();
00171     });
00172 }
00173
00174 // Retrieves a given number of photos from a folder query.
00175 task<IVectorView<IPhoto^>^> FileSystemRepository::GetPhotoDataForMonthGroup(IPhotoGroup^ photoGroup, IStorageFolderQueryOperations^ folderQuery, unsigned int maxNumberOfItems)
00176 {
00177     auto fileQuery = CreateFileQuery(folderQuery, "");
00178     auto fileInformationFactory = ref new FileInformationFactory(fileQuery, ThumbnailMode::PicturesView, 190, ThumbnailOptions::UseCurrentScale, true);  // speed up query by deferring thumbnails
00179     shared_ptr<ExceptionPolicy> policy = m_exceptionPolicy;
00180     return create_task(fileInformationFactory->GetFilesAsync(0, maxNumberOfItems)).then([photoGroup, policy, maxNumberOfItems](IVectorView<FileInformation^>^ files)
00181     {
00182         auto photos = ref new Vector<IPhoto^>();
00183         for (auto item : files)
00184         {
00185             auto photo = ref new Photo(item, photoGroup, policy);
00186             photos->Append(photo);
00187         }
00188         return photos->GetView();
00189     }, task_continuation_context::use_current());
00190 }
00191
00192 // Returns true if there are any photos in the given folder within the specified date range. Returns false otherwise.
00193 task<bool> FileSystemRepository::HasPhotosInRangeAsync(Platform::String^ dateRangeQuery, IStorageFolderQueryOperations^ folderQuery)
00194 {
00195     auto fileTypeFilter = ref new Vector<String^>(items);
00196     auto queryOptions = ref new QueryOptions(CommonFileQuery::OrderByDate, fileTypeFilter);  // ordered query allows use of indexer
00197     queryOptions->FolderDepth = FolderDepth::Deep;
00198     queryOptions->IndexerOption = IndexerOption::UseIndexerWhenAvailable;
00199     queryOptions->Language = CalendarExtensions::ResolvedLanguage();
00200     queryOptions->ApplicationSearchFilter = dateRangeQuery;
00201     auto fileQuery = folderQuery->CreateFileQueryWithOptions(queryOptions);
00202     return create_task(fileQuery->GetFilesAsync(0, 1)).then([](IVectorView<StorageFile^>^ files)
00203     {
00204         return (files->Size > 0);
00205     });
00206 }
00207
00208 // Retrieves the photos from the user's picture library with dates in a given range.
00209 task<IVectorView<IPhoto^>^> FileSystemRepository::GetPhotosForDateRangeQueryAsync(String^ dateRangeQuery)
00210 {
00211     auto fileQuery = CreateFileQuery(KnownFolders::PicturesLibrary, dateRangeQuery);
00212     auto fileInformationFactory = ref new FileInformationFactory(fileQuery, ThumbnailMode::PicturesView);
00213     shared_ptr<ExceptionPolicy> policy = m_exceptionPolicy;
00214
00215     m_allPhotosQueryChange = (m_imageViewModelCallback != nullptr) ? ref new QueryChange(fileQuery, m_imageViewModelCallback) : nullptr;
00216
00217     return create_task(fileInformationFactory->GetFilesAsync()).then([policy](IVectorView<FileInformation^>^ files)
00218     {
00219         auto photos = ref new Vector<IPhoto^>();
00220         for (auto file : files)
00221         {
00222             auto photo = ref new Photo(file, ref new NullPhotoGroup(), policy);
00223             photos->Append(photo);
00224         }
00225         return photos->GetView();
00226     }, task_continuation_context::use_current());
00227 }
00228
00229 // Selects a set of recent photos.
00230 task<IVectorView<IPhoto^>^> FileSystemRepository::GetPhotosForPictureHubGroupAsync(IPhotoGroup^ photoGroup, unsigned int maxNumberOfItems)
00231 {
00232     auto fileQuery = CreateFileQuery(KnownFolders::PicturesLibrary, "");
00233     auto fileInformationFactory = ref new FileInformationFactory(fileQuery, ThumbnailMode::PicturesView);
00234     m_pictureHubGroupQueryChange = (m_hubViewModelCallback != nullptr) ? ref new QueryChange(fileQuery, m_hubViewModelCallback) : nullptr;
00235     shared_ptr<ExceptionPolicy> policy = m_exceptionPolicy;
00236     return create_task(fileInformationFactory->GetFilesAsync(0, maxNumberOfItems)).then([photoGroup, policy](IVectorView<FileInformation^>^ files)
00237     {
00238         auto photos = ref new Vector<IPhoto^>();
00239         for (auto item : files)
00240         {
00241             auto photo = ref new Photo(item, photoGroup, policy);
00242             photos->Append(photo);
00243         }
00244         return photos->GetView();
00245
00246     }, task_continuation_context::use_current());
00247 }
00248
00249 // Queries the file system for photos grouped by year. There will be one year group for each year that has photos.
00250 task<IVectorView<IYearGroup^>^> FileSystemRepository::GetYearGroupedMonthsAsync(cancellation_token token)
00251 {
00252     shared_ptr<ExceptionPolicy> policy = m_exceptionPolicy;
00253     auto queryOptions = ref new QueryOptions(CommonFolderQuery::GroupByYear);
00254     queryOptions->FolderDepth = FolderDepth::Deep;
00255     queryOptions->IndexerOption = IndexerOption::UseIndexerWhenAvailable;
00256     queryOptions->Language = CalendarExtensions::ResolvedLanguage();
00257     auto fileQuery =  KnownFolders::PicturesLibrary->CreateFolderQueryWithOptions(queryOptions);
00258     auto fileInformationFactory = ref new FileInformationFactory(fileQuery, ThumbnailMode::PicturesView);
00259     return create_task(fileInformationFactory->GetFoldersAsync()).then([this, policy](IVectorView<FolderInformation^>^ folders)
00260     {
00261         vector<task<YearGroup^>> yearGroupTasks;
00262         for (auto folder : folders)
00263         {
00264             yearGroupTasks.push_back(GetDateTimeForYearFolderAsync(folder, policy));
00265         }
00266         return when_all(begin(yearGroupTasks), end(yearGroupTasks)).then([](vector<YearGroup^> groups)
00267         {
00268             auto result = ref new Vector<IYearGroup^>();
00269             for (auto group : groups)
00270             {
00271                 if (group != nullptr)
00272                 {
00273                     result->Append(group);
00274                 }
00275             }
00276             return result->GetView();
00277         });
00278     }, token, task_continuation_context::use_arbitrary());
00279 }
00280
00281 // Helper method for GetYearGroupedMonthsAsync. Creates a YearGroup object for each folder created by the year query.
00282 task<YearGroup^> FileSystemRepository::GetDateTimeForYearFolderAsync(IStorageFolderQueryOperations^ folderQuery, shared_ptr<ExceptionPolicy> exceptionPolicy)
00283 {
00284     auto maxNumberOfItems = 1;
00285     auto dateTakenProperties = ref new Vector<String^>();
00286     dateTakenProperties->Append("System.ItemDate");
00287     auto sharedThis = shared_from_this();
00288     auto fileTypeFilter = ref new Vector<String^>(items);
00289     auto queryOptions = ref new QueryOptions(CommonFileQuery::OrderByDate, fileTypeFilter);
00290     queryOptions->IndexerOption = IndexerOption::UseIndexerWhenAvailable;
00291     queryOptions->SetPropertyPrefetch(PropertyPrefetchOptions::ImageProperties, dateTakenProperties);
00292     queryOptions->Language = CalendarExtensions::ResolvedLanguage();
00293     auto fileQuery = folderQuery->CreateFileQueryWithOptions(queryOptions);
00294     auto fileInformationFactory = ref new FileInformationFactory(fileQuery, ThumbnailMode::PicturesView);
00295     return create_task(fileInformationFactory->GetFilesAsync(0, maxNumberOfItems)).then([sharedThis, folderQuery, exceptionPolicy](IVectorView<FileInformation^>^ files) -> YearGroup^
00296     {
00297         if (files->Size > 0)
00298         {
00299             auto file = files->GetAt(0);
00300             auto yearDate = file->ImageProperties->DateTaken;
00301             if (yearDate.UniversalTime == 0)
00302             {
00303                 yearDate = file->BasicProperties->DateModified;
00304             }
00305             return (yearDate.UniversalTime != 0) ? ref new YearGroup(yearDate, folderQuery, sharedThis, exceptionPolicy) : nullptr;
00306         }
00307         else
00308         {
00309             return nullptr;
00310         }
00311     }, task_continuation_context::use_arbitrary()).then(ObserveException<YearGroup^>(exceptionPolicy));
00312 }
00313
00314
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/ScenarioOutput1.xaml.h Source File

  • Media extensions

ScenarioOutput1.xaml.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 //
00009 // Scenario1Output.xaml.h
00010 // Declaration of the Scenario1Output class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioOutput1.g.h"
00017 #include "MainPage.xaml.h"
00018
00019 namespace MediaExtensionsCPP
00020 {
00021     [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class ScenarioOutput1 sealed
00023     {
00024     public:
00025         ScenarioOutput1();
00026
00027     protected:
00028         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030
00031     private:
00032         ~ScenarioOutput1();
00033         MainPage^ rootPage;
00034         Windows::Foundation::EventRegistrationToken _mediaFailedToken;
00035     };
00036 }
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D custom image effects/C++/ComputeShader/DirectXBase.h Source File

  • Direct2D custom image effects
  • ComputeShader

DirectXBase.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 "DirectXSample.h"
00011
00012 // Helper class that initializes DirectX APIs for both 2D and 3D rendering.
00013 // Some of the code in this class may be omitted if only 2D or only 3D rendering is being used.
00014 ref class DirectXBase abstract
00015 {
00016 internal:
00017     DirectXBase();
00018
00019     virtual void Initialize(Windows::UI::Core::CoreWindow^ window, float dpi);
00020     virtual void HandleDeviceLost();
00021     virtual void CreateDeviceIndependentResources();
00022     virtual void CreateDeviceResources();
00023     virtual void SetDpi(float dpi);
00024     virtual void UpdateForWindowSizeChange();
00025     virtual void CreateWindowSizeDependentResources();
00026     virtual void Render() = 0;
00027     virtual void Present();
00028     void ValidateDevice();
00029
00030 protected private:
00031     Platform::Agile<Windows::UI::Core::CoreWindow>  m_window;
00032
00033     // DirectWrite & Windows Imaging Component Objects.
00034     Microsoft::WRL::ComPtr<IDWriteFactory1>         m_dwriteFactory;
00035     Microsoft::WRL::ComPtr<IWICImagingFactory2>     m_wicFactory;
00036
00037     // DirectX Core Objects. Required for 2D and 3D.
00038     Microsoft::WRL::ComPtr<ID3D11Device1>           m_d3dDevice;
00039     Microsoft::WRL::ComPtr<ID3D11DeviceContext1>    m_d3dContext;
00040     Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00041     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00042
00043     // Direct2D Rendering Objects. Required for 2D.
00044     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00046     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00047     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmap;
00048
00049     // Direct3D Rendering Objects. Required for 3D.
00050     Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00051
00052     // Cached renderer properties.
00053     D3D_FEATURE_LEVEL                               m_featureLevel;
00054     Windows::Foundation::Size                       m_renderTargetSize;
00055     Windows::Foundation::Rect                       m_windowBounds;
00056     float                                           m_dpi;
00057     bool                                            m_windowSizeChangeInProgress;
00058 };
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text editing/C++/MainPage.xaml.h Source File

  • XAML text editing

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Connecting with WebSockets/C++/Scenario2.xaml.cpp Source File

  • Connecting with WebSockets

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 concurrency;
00020 using namespace SDKSample::WebSocket;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024 using namespace Windows::UI::Core;
00025 using namespace Windows::System::Threading;
00026 using namespace Windows::Security::Cryptography;
00027
00028 Scenario2::Scenario2()
00029 {
00030     InitializeComponent();
00031 }
00032
00033 Scenario2::~Scenario2()
00034 {
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 Scenario2::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 SDKSample::WebSocket::Scenario2::Start_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00050 {
00051     // Make a local copy to avoid races with the Closed event.
00052     StreamWebSocket^ webSocket = this->streamWebSocket;
00053
00054     // Have we connected yet?
00055     if (webSocket != nullptr)
00056     {
00057         rootPage->NotifyUser("Already connected", NotifyType::StatusMessage);
00058         return;
00059     }
00060
00061     // By default 'ServerAddressField' is disabled and URI validation is not required. When enabling the text box
00062     // validating the URI is required since it was received from an untrusted source (user input).
00063     // The URI is validated by calling TryGetUri() that will return 'false' for strings that are not
00064     // valid WebSocket URIs.
00065     // Note that when enabling the text box users may provide URIs to machines on the intrAnet or intErnet. In
00066     // these cases the app requires the "Home or Work Networking" or "Internet (Client)" capability respectively.
00067     Uri^ server;
00068     if (!rootPage->TryGetUri(ServerAddressField->Text, &server))
00069     {
00070         return;
00071     }
00072
00073     rootPage->NotifyUser("Connecting to: " + server->DisplayUri, NotifyType::StatusMessage);
00074
00075     webSocket = ref new StreamWebSocket();
00076     webSocket->Closed += ref new TypedEventHandler<IWebSocket^, WebSocketClosedEventArgs^>(this, &Scenario2::Scenario2Closed);
00077
00078     task<void>(webSocket->ConnectAsync(server)).then([this, webSocket] (task<void> previousTask)
00079     {
00080         try
00081         {
00082             // Try getting all exceptions from the continuation chain above this point.
00083             previousTask.get();
00084
00085             rootPage->NotifyUser("Connected", NotifyType::StatusMessage);
00086
00087             streamWebSocket = webSocket; // Only store it after successfully connecting.
00088
00089             this->readBuffer = ref new Buffer(1000);
00090
00091             OutputField->Text += "Background read starting.\r\n";
00092             bytesReceived = 0;
00093
00094             // Start a loop to continuously read for incoming data.
00095             Scenario2ReceiveData();
00096
00097             // Start a loop to continuously write outgoing data.
00098             BYTE bytes[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 };
00099             auto data = ref new Platform::Array<byte>(ARRAYSIZE(bytes));
00100             memcpy(data->Data, bytes, ARRAYSIZE(bytes));
00101             sendBuffer = CryptographicBuffer::CreateFromByteArray(data);
00102             MarshalText(OutputField, "Background sending data in " + sendBuffer->Length.ToString()
00103                 + " byte chunks each second.\r\n");
00104             dataSent = 0;
00105             Scenario2SendData();
00106         }
00107         catch(Exception^ exception)
00108         {
00109             HandleException(exception);
00110         }
00111     });
00112 }
00113
00114 void SDKSample::WebSocket::Scenario2::HandleException(Exception^ exception)
00115 {
00116     WebErrorStatus status = WebSocketError::GetStatus(exception->HResult);
00117
00118     if (status == WebErrorStatus::CannotConnect ||
00119         status == WebErrorStatus::NotFound ||
00120         status == WebErrorStatus::RequestTimeout)
00121     {
00122         rootPage->NotifyUser("Cannot connect to the server. Please make sure "
00123             "to run the server setup script before running the sample.", NotifyType::ErrorMessage);
00124     }
00125     else
00126     {
00127         rootPage->NotifyUser("Error: " + status.ToString(), NotifyType::ErrorMessage);
00128     }
00129
00130     OutputField->Text += exception->Message + "\r\n";
00131 }
00132
00133 void SDKSample::WebSocket::Scenario2::Scenario2SendData()
00134 {
00135     // Make a local copy to avoid races with the Closed event.
00136     StreamWebSocket^ webSocket = this->streamWebSocket;
00137     if (webSocket == nullptr)
00138     {
00139         return;
00140     }
00141
00142     try
00143     {
00144         IOutputStream^ writeStream = webSocket->OutputStream;
00145         task<UINT32>(writeStream->WriteAsync(sendBuffer)).then([this] (UINT32 sent)
00146         {
00147             dataSent += sent;
00148             MarshalText(DataSentField, dataSent.ToString(), false);
00149
00150             // Delay so the user can watch what's going on.
00151             TimeSpan time = { 10000000 }; // 1 second.
00152             ThreadPoolTimer::CreateTimer(ref new TimerElapsedHandler([this](ThreadPoolTimer^ timer) {
00153                 Scenario2SendData();
00154             }), time);
00155         }).then([this] (task<void> previousTask)
00156         {
00157             try
00158             {
00159                 // Try getting all exceptions from the continuation chain above this point.
00160                 previousTask.get();
00161             }
00162             catch (Exception^ exception)
00163             {
00164                 MarshalText(OutputField, exception->Message + "\r\n");
00165             }
00166         });
00167     }
00168     catch (Exception^ exception)
00169     {
00170         if (exception->HResult == RO_E_CLOSED)
00171         {
00172             MarshalText(OutputField, "Output stream already closed by the user\r\n");
00173         }
00174         else
00175         {
00176             throw;
00177         }
00178     }
00179 }
00180
00181 // Continuously read incoming data. For reading data we'll show how to use webSocket.InputStream.AsStream()
00182 // to get a .NET stream. Alternatively you could call readBuffer.AsBuffer() to use IBuffer with
00183 // webSocket->InputStream->ReadAsync.
00184 void SDKSample::WebSocket::Scenario2::Scenario2ReceiveData()
00185 {
00186     // Make a local copy to avoid races with the Closed event.
00187     StreamWebSocket^ webSocket = this->streamWebSocket;
00188     if (webSocket == nullptr)
00189     {
00190         return;
00191     }
00192
00193     try
00194     {
00195         IInputStream^ readStream = webSocket->InputStream;
00196
00197         task<IBuffer^>(readStream->ReadAsync(readBuffer, readBuffer->Capacity, InputStreamOptions::Partial)).then([this] (IBuffer^ buffer)
00198         {
00199             bytesReceived += buffer->Length;
00200             DataReceivedField->Text = bytesReceived.ToString();
00201
00202             // Do something with the data.
00203         }).then([this] (task<void> previousTask)
00204         {
00205             try
00206             {
00207                 // Try getting all exceptions from the continuation chain above this point.
00208                 previousTask.get();
00209             }
00210             catch (Exception^ exception)
00211             {
00212                 WebErrorStatus status = WebSocketError::GetStatus(exception->HResult);
00213                 if (status == WebErrorStatus::OperationCanceled)
00214                 {
00215                     OutputField->Text += "Background read canceled.\r\n";
00216                 }
00217                 else
00218                 {
00219                     HandleException(exception);
00220                 }
00221             }
00222
00223             // Continue reading until closed and ReadAsync fails.
00224             Scenario2ReceiveData();
00225         });
00226     }
00227     catch (Exception^ exception)
00228     {
00229         if (exception->HResult == RO_E_CLOSED)
00230         {
00231             OutputField->Text += "Input stream already closed by the user\r\n";
00232         }
00233         else
00234         {
00235             throw;
00236         }
00237     }
00238 }
00239
00240 void SDKSample::WebSocket::Scenario2::Stop_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00241 {
00242     try
00243     {
00244         if (streamWebSocket != nullptr)
00245         {
00246             rootPage->NotifyUser("Stopping", NotifyType::StatusMessage);
00247             streamWebSocket->Close(1000, "Closed due to user request.");
00248             streamWebSocket = nullptr;
00249         }
00250         else
00251         {
00252             rootPage->NotifyUser("There is no active socket to stop.", NotifyType::StatusMessage);
00253         }
00254     }
00255     catch (Exception^ exception)
00256     {
00257         HandleException(exception);
00258     }
00259 }
00260
00261 void SDKSample::WebSocket::Scenario2::Scenario2Closed(IWebSocket^ sender, WebSocketClosedEventArgs^ args)
00262 {
00263     // The method may be triggered remotely by the server sending unsolicited close frame or locally by Close()/delete operator.
00264     // Dispatch the event to the UI thread so we do not need to synchronize access to streamWebSocket.
00265     Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, args] ()
00266     {
00267         OutputField->Text += "Closed; Code: " + args->Code.ToString() + ", Reason: " + args->Reason + "\r\n";
00268
00269         if (streamWebSocket != nullptr)
00270         {
00271             delete streamWebSocket;
00272             streamWebSocket = nullptr;
00273         }
00274     }));
00275 }
00276
00277 void SDKSample::WebSocket::Scenario2::MarshalText(TextBox^ output, String^ value)
00278 {
00279     MarshalText(output, value, true);
00280 }
00281
00282 // When operations happen on a background thread we have to marshal UI updates back to the UI thread.
00283 void SDKSample::WebSocket::Scenario2::MarshalText(TextBox^ output, String^ value, bool append)
00284 {
00285     Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, output, value, append] ()
00286     {
00287         if (append)
00288         {
00289             output->Text += value;
00290         }
00291         else
00292         {
00293             output->Text = value;
00294         }
00295     }, CallbackContext::Any));
00296 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/Material.h Source File

  • DirectX 3D shooting game

Material.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 // Material:
00011 // This class maintains the properties that represent how an object will
00012 // look when it is rendered.  This includes the color of the object, the
00013 // texture used to render the object, and the vertex and pixel shader that
00014 // should be used for rendering.
00015 // The RenderSetup method sets the appropriate values into the constantBuffer
00016 // and calls the appropriate D3D11 context methods to set up the rendering pipeline
00017 // in the graphics hardware.
00018
00019 #include "ConstantBuffers.h"
00020
00021 ref class Material
00022 {
00023 internal:
00024     Material(
00025         DirectX::XMFLOAT4 meshColor,
00026         DirectX::XMFLOAT4 diffuseColor,
00027         DirectX::XMFLOAT4 specularColor,
00028         float specularExponent,
00029         _In_ ID3D11ShaderResourceView* textureResourceView,
00030         _In_ ID3D11VertexShader* vertexShader,
00031         _In_ ID3D11PixelShader* pixelShader
00032         );
00033
00034     void RenderSetup(
00035         _In_ ID3D11DeviceContext* context,
00036         _Inout_ ConstantBufferChangesEveryPrim* constantBuffer
00037         );
00038
00039     void SetTexture(_In_ ID3D11ShaderResourceView* textureResourceView)
00040     {
00041         m_textureRV = textureResourceView;
00042     }
00043
00044 protected private:
00045     DirectX::XMFLOAT4   m_meshColor;
00046     DirectX::XMFLOAT4   m_diffuseColor;
00047     DirectX::XMFLOAT4   m_hitColor;
00048     DirectX::XMFLOAT4   m_specularColor;
00049     float               m_specularExponent;
00050
00051     Microsoft::WRL::ComPtr<ID3D11VertexShader>       m_vertexShader;
00052     Microsoft::WRL::ComPtr<ID3D11PixelShader>        m_pixelShader;
00053     Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_textureRV;
00054 };
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML data binding/C++/Scenario1.xaml.h Source File

  • XAML data binding

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 SDKSample
00023 {
00024     namespace DataBinding
00025     {
00026         /// <summary>
00027         /// An empty page that can be used on its own or navigated to within a Frame.
00028         /// </summary>
00029         public ref class Scenario1 sealed
00030         {
00031         public:
00032             Scenario1();
00033         private:
00034             MainPage^ rootPage;
00035             void Scenario1Reset(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00036       };
00037     }
00038 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D tutorial/C++/Lesson1.Basics/Main.cpp Source File

  • Direct3D tutorial
  • Lesson1.Basics

Main.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 "DirectXSample.h"
00010
00011 using namespace Microsoft::WRL;
00012 using namespace Windows::UI::Core;
00013 using namespace Windows::Foundation;
00014 using namespace Windows::ApplicationModel::Core;
00015 using namespace Windows::ApplicationModel::Activation;
00016
00017 // This class defines the application as a whole.
00018 ref class Direct3DTutorialFrameworkView : public IFrameworkView
00019 {
00020 private:
00021     Platform::Agile<CoreWindow> m_window;
00022     ComPtr<IDXGISwapChain1> m_swapChain;
00023     ComPtr<ID3D11Device1> m_d3dDevice;
00024     ComPtr<ID3D11DeviceContext1> m_d3dDeviceContext;
00025     ComPtr<ID3D11RenderTargetView> m_renderTargetView;
00026
00027 public:
00028     // This method is called on application launch.
00029     virtual void Initialize(
00030         _In_ CoreApplicationView^ applicationView
00031         )
00032     {
00033         applicationView->Activated +=
00034             ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &Direct3DTutorialFrameworkView::OnActivated);
00035     }
00036
00037     // This method is called after Initialize.
00038     virtual void SetWindow(
00039         _In_ CoreWindow^ window
00040         )
00041     {
00042         m_window = window;
00043
00044         // Specify the cursor type as the standard arrow cursor.
00045         m_window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
00046
00047         // Allow the application to respond when the window size changes.
00048         m_window->SizeChanged +=
00049             ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(
00050                 this,
00051                 &Direct3DTutorialFrameworkView::OnWindowSizeChanged
00052                 );
00053     }
00054
00055     void OnActivated(
00056         _In_ CoreApplicationView^ applicationView,
00057         _In_ IActivatedEventArgs^ args
00058         )
00059     {
00060         // Activate the application window, making it visible and enabling it to receive events.
00061         CoreWindow::GetForCurrentThread()->Activate();
00062     }
00063
00064     virtual void Load(_In_ Platform::String^ entryPoint)
00065     {
00066     }
00067
00068     // This method is called after Load.
00069     virtual void Run()
00070     {
00071         // First, create the Direct3D device.
00072
00073         // This flag is required in order to enable compatibility with Direct2D.
00074         UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00075
00076 #if defined(_DEBUG)
00077         // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00078         creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00079 #endif
00080
00081         // This array defines the ordering of feature levels that D3D should attempt to create.
00082         D3D_FEATURE_LEVEL featureLevels[] =
00083         {
00084             D3D_FEATURE_LEVEL_11_1,
00085             D3D_FEATURE_LEVEL_11_0,
00086             D3D_FEATURE_LEVEL_10_1,
00087             D3D_FEATURE_LEVEL_10_0,
00088             D3D_FEATURE_LEVEL_9_3,
00089             D3D_FEATURE_LEVEL_9_1
00090         };
00091
00092         ComPtr<ID3D11Device> d3dDevice;
00093         ComPtr<ID3D11DeviceContext> d3dDeviceContext;
00094         DX::ThrowIfFailed(
00095             D3D11CreateDevice(
00096                 nullptr,                    // specify nullptr to use the default adapter
00097                 D3D_DRIVER_TYPE_HARDWARE,
00098                 nullptr,                    // leave as nullptr if hardware is used
00099                 creationFlags,              // optionally set debug and Direct2D compatibility flags
00100                 featureLevels,
00101                 ARRAYSIZE(featureLevels),
00102                 D3D11_SDK_VERSION,          // always set this to D3D11_SDK_VERSION
00103                 &d3dDevice,
00104                 nullptr,
00105                 &d3dDeviceContext
00106                 )
00107             );
00108
00109         // Retrieve the Direct3D 11.1 interfaces.
00110         DX::ThrowIfFailed(
00111             d3dDevice.As(&m_d3dDevice)
00112             );
00113
00114         DX::ThrowIfFailed(
00115             d3dDeviceContext.As(&m_d3dDeviceContext)
00116             );
00117
00118
00119         // After the D3D device is created, create additional application resources.
00120         CreateWindowSizeDependentResources();
00121
00122
00123         // Enter the render loop. Note that Windows Store apps should never exit.
00124         while (true)
00125         {
00126             // Process events incoming to the window.
00127             m_window->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
00128
00129             // Specify the render target we created as the output target.
00130             m_d3dDeviceContext->OMSetRenderTargets(
00131                 1,
00132                 m_renderTargetView.GetAddressOf(),
00133                 nullptr // use no depth stencil
00134                 );
00135
00136             // Clear the render target to a solid color.
00137             const float clearColor[4] = { 0.071f, 0.04f, 0.561f, 1.0f };
00138             m_d3dDeviceContext->ClearRenderTargetView(
00139                 m_renderTargetView.Get(),
00140                 clearColor
00141                 );
00142
00143             // Present the rendered image to the window.  Because the maximum frame latency is set to 1,
00144             // the render loop will generally be throttled to the screen refresh rate, typically around
00145             // 60Hz, by sleeping the application on Present until the screen is refreshed.
00146             DX::ThrowIfFailed(
00147                 m_swapChain->Present(1, 0)
00148                 );
00149         }
00150     }
00151
00152     // This method is called before the application exits.
00153     virtual void Uninitialize()
00154     {
00155     }
00156
00157 private:
00158
00159     // This method is called whenever the application window size changes.
00160     void OnWindowSizeChanged(
00161         _In_ CoreWindow^ sender,
00162         _In_ WindowSizeChangedEventArgs^ args
00163         )
00164     {
00165         m_renderTargetView = nullptr;
00166         CreateWindowSizeDependentResources();
00167     }
00168
00169     // This method creates all application resources that depend on
00170     // the application window size.  It is called at app initialization,
00171     // and whenever the application window size changes.
00172     void CreateWindowSizeDependentResources()
00173     {
00174         if (m_swapChain != nullptr)
00175         {
00176             // If the swap chain already exists, resize it.
00177             DX::ThrowIfFailed(
00178                 m_swapChain->ResizeBuffers(
00179                     2,
00180                     0,
00181                     0,
00182                     DXGI_FORMAT_B8G8R8A8_UNORM,
00183                     0
00184                     )
00185                 );
00186         }
00187         else
00188         {
00189             // If the swap chain does not exist, create it.
00190             DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00191
00192             swapChainDesc.Stereo = false;
00193             swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00194             swapChainDesc.Scaling = DXGI_SCALING_NONE;
00195             swapChainDesc.Flags = 0;
00196
00197             // Use automatic sizing.
00198             swapChainDesc.Width = 0;
00199             swapChainDesc.Height = 0;
00200
00201             // This is the most common swap chain format.
00202             swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
00203
00204             // Don't use multi-sampling.
00205             swapChainDesc.SampleDesc.Count = 1;
00206             swapChainDesc.SampleDesc.Quality = 0;
00207
00208             // Use two buffers to enable flip effect.
00209             swapChainDesc.BufferCount = 2;
00210
00211             // We recommend using this swap effect for all applications.
00212             swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
00213
00214
00215             // Once the swap chain description is configured, it must be
00216             // created on the same adapter as the existing D3D Device.
00217
00218             // First, retrieve the underlying DXGI Device from the D3D Device.
00219             ComPtr<IDXGIDevice2> dxgiDevice;
00220             DX::ThrowIfFailed(
00221                 m_d3dDevice.As(&dxgiDevice)
00222                 );
00223
00224             // Ensure that DXGI does not queue more than one frame at a time. This both reduces
00225             // latency and ensures that the application will only render after each VSync, minimizing
00226             // power consumption.
00227             DX::ThrowIfFailed(
00228                 dxgiDevice->SetMaximumFrameLatency(1)
00229                 );
00230
00231             // Next, get the parent factory from the DXGI Device.
00232             ComPtr<IDXGIAdapter> dxgiAdapter;
00233             DX::ThrowIfFailed(
00234                 dxgiDevice->GetAdapter(&dxgiAdapter)
00235                 );
00236
00237             ComPtr<IDXGIFactory2> dxgiFactory;
00238             DX::ThrowIfFailed(
00239                 dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00240                 );
00241
00242             // Finally, create the swap chain.
00243             CoreWindow^ window = m_window.Get();
00244             DX::ThrowIfFailed(
00245                 dxgiFactory->CreateSwapChainForCoreWindow(
00246                     m_d3dDevice.Get(),
00247                     reinterpret_cast<IUnknown*>(window),
00248                     &swapChainDesc,
00249                     nullptr, // allow on all displays
00250                     &m_swapChain
00251                     )
00252                 );
00253         }
00254
00255         // Once the swap chain is created, create a render target view.  This will
00256         // allow Direct3D to render graphics to the window.
00257
00258         ComPtr<ID3D11Texture2D> backBuffer;
00259         DX::ThrowIfFailed(
00260             m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00261             );
00262
00263         DX::ThrowIfFailed(
00264             m_d3dDevice->CreateRenderTargetView(
00265                 backBuffer.Get(),
00266                 nullptr,
00267                 &m_renderTargetView
00268                 )
00269             );
00270
00271
00272         // After the render target view is created, specify that the viewport,
00273         // which describes what portion of the window to draw to, should cover
00274         // the entire window.
00275
00276         D3D11_TEXTURE2D_DESC backBufferDesc = {0};
00277         backBuffer->GetDesc(&backBufferDesc);
00278
00279         D3D11_VIEWPORT viewport;
00280         viewport.TopLeftX = 0.0f;
00281         viewport.TopLeftY = 0.0f;
00282         viewport.Width = static_cast<float>(backBufferDesc.Width);
00283         viewport.Height = static_cast<float>(backBufferDesc.Height);
00284         viewport.MinDepth = D3D11_MIN_DEPTH;
00285         viewport.MaxDepth = D3D11_MAX_DEPTH;
00286
00287         m_d3dDeviceContext->RSSetViewports(1, &viewport);
00288     }
00289 };
00290
00291 // This class defines how to create the custom View Provider defined above.
00292 ref class Direct3DTutorialFrameworkViewSource : IFrameworkViewSource
00293 {
00294 public:
00295     virtual IFrameworkView^ CreateView()
00296     {
00297         return ref new Direct3DTutorialFrameworkView();
00298     }
00299 };
00300
00301 [Platform::MTAThread]
00302 int main(Platform::Array<Platform::String^>^)
00303 {
00304     auto frameworkViewSource = ref new Direct3DTutorialFrameworkViewSource();
00305     Windows::ApplicationModel::Core::CoreApplication::Run(frameworkViewSource);
00306     return 0;
00307 }
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media Play To/C++/MainPage.xaml.cpp Source File

  • Media Play To

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:42 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Message dialog/C++/common/suspensionmanager.h Source File

  • Message dialog
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Clipboard app/C++/Others.xaml.h Source File

  • Clipboard app

Others.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 // Others.xaml.h
00013 // Declaration of the Others class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Others.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace Clipboard
00023 {
00024     [Windows::Foundation::Metadata::WebHostHidden]
00025     public ref class Others sealed
00026     {
00027     public:
00028         Others();
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         MainPage^ rootPage;
00036
00037         void ShowFormatButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038         void EmptyClipboardButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039         void ClearOutputButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         void RegisterClipboardContentChanged_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041
00042         void OnClipboardChanged(Platform::Object^ sender, Platform::Object^ e);
00043         void OnVisibilityChanged(Platform::Object^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ e);
00044
00045         void DisplayFormats(Windows::ApplicationModel::DataTransfer::DataPackageView^ dataPackageView);
00046         void ClearOutput();
00047         void HandleClipboardChanged();
00048
00049         static Windows::Foundation::EventRegistrationToken contentChangedToken;
00050         static Windows::Foundation::EventRegistrationToken visibilityChangedToken;
00051
00052         static bool windowVisible;
00053         static bool registerContentChanged;
00054         static bool needToPrintClipboardFormat;
00055     };
00056 }
00057
Generated on Sat Nov 23 2024 16:07:59 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Toast notifications/C#,C++/ScenarioOutput2.xaml.h Source File

  • Toast notifications
  • C#,C++

ScenarioOutput2.xaml.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 //
00009 // Scenario2Output.xaml.h
00010 // Declaration of the Scenario2Output class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioOutput2.g.h"
00017 #include "MainPage.g.h"
00018
00019 namespace ToastsSampleCPP
00020 {
00021   [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class ScenarioOutput2 sealed
00023     {
00024     public:
00025         ScenarioOutput2();
00026
00027     protected:
00028         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030
00031     private:
00032         ~ScenarioOutput2();
00033
00034     MainPage^ rootPage;
00035         void rootPage_InputFrameLoaded(Object^ sender, Object^ e);
00036         Windows::Foundation::EventRegistrationToken _frameLoadedToken;
00037     };
00038 }
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Portable device API/C++/common/LayoutAwarePage.cpp Source File

  • Portable device API
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:32 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D bump mapping/C++/LonLatController.cpp Source File

  • Direct3D bump mapping

LonLatController.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
00009 #include "pch.h"
00010 #include "LonLatController.h"
00011
00012 using namespace Windows::UI::Core;
00013 using namespace Windows::System;
00014 using namespace Windows::Foundation;
00015 using namespace Windows::Foundation::Collections;
00016 using namespace Windows::Devices::Input;
00017 using namespace Windows::ApplicationModel;
00018
00019 // A basic Longitude/Latitude Controller class for navigation on a sphere
00020 // Uses touch, WASD keyboard, or mouse pointer movement
00021
00022 // method for handling touch press events or mouse clicks
00023 void LonLatController::OnPointerPressed(
00024     _In_ CoreWindow^ sender,
00025     _In_ PointerEventArgs^ args
00026     )
00027 {
00028     m_numPointersDown++;
00029     float2 position = float2(                           // position of contact
00030         args->CurrentPoint->Position.X,
00031         args->CurrentPoint->Position.Y
00032         );
00033
00034     if (m_numPointersDown == 1)                         // if this is first pointer down
00035     {
00036         m_lonLatLastPoint1 = position;                  // save for computing relative delta
00037         m_lonLatPointerID1 = args->CurrentPoint->PointerId;
00038     }
00039     else if (m_numPointersDown == 2)                    // if this is the second
00040     {
00041         m_lonLatLastPoint2 = position;                  // save for computing relative delta
00042         m_lonLatPointerID2 = args->CurrentPoint->PointerId;
00043         float2 del = m_lonLatLastPoint2 - m_lonLatLastPoint1;
00044         m_lastDistance = hypotf(del.x, del.y);
00045     }
00046     // else //  ignore any 3rd or more pointers
00047 }
00048
00049 void LonLatController::OnPointerMoved(
00050     _In_ CoreWindow^ sender,
00051     _In_ PointerEventArgs^ args
00052     )
00053 {
00054     float2 position = float2(
00055         args->CurrentPoint->Position.X,
00056         args->CurrentPoint->Position.Y
00057         );
00058
00059     uint32 pointerID = args->CurrentPoint->PointerId;       // ID of pointer that moved
00060
00061     if (m_numPointersDown == 1)   // then drag/rotate
00062     {
00063         float2 pointerDelta;
00064         pointerDelta = position - m_lonLatLastPoint1;       // how far did pointer move
00065
00066         float2 rotationDelta;
00067         rotationDelta = pointerDelta * LONLAT_GAIN;         // scale for control sensitivity
00068         m_lonLatLastPoint1 = position;                      // save for next time through
00069
00070         // update our orientation based on the command
00071         float altitude = m_radius - 1;
00072
00073         m_latitude  += rotationDelta.y *altitude*0.5f;
00074         m_longitude -= rotationDelta.x *altitude*0.5f;
00075
00076         // Limit lattitude to poles
00077         float limit = PI_F/2 - 0.01f;
00078         m_latitude = __max(-limit, m_latitude);
00079         m_latitude = __min(+limit, m_latitude);
00080
00081         // keep longitude in sane range by wrapping
00082         if (m_longitude > PI_F)
00083         {
00084             m_longitude -= PI_F*2;
00085         }
00086         else if (m_longitude < -PI_F)
00087         {
00088             m_longitude += PI_F*2;
00089         }
00090
00091         // limit us to positive radius
00092         m_radius = __max(1.011f, m_radius);
00093     }
00094     else if (m_numPointersDown >= 2)       // pinch/zoom mode
00095     {
00096         if (pointerID == m_lonLatPointerID1)
00097         {
00098             m_lonLatLastPoint1 = position;                  // save for computing relative delta
00099         }
00100         else if (pointerID == m_lonLatPointerID2)
00101         {
00102             m_lonLatLastPoint2 = position;                  // save for computing relative delta
00103         }
00104         float2 del = m_lonLatLastPoint2 - m_lonLatLastPoint1;
00105         float distance = hypotf(del.x, del.y);
00106
00107         float delta = distance - m_lastDistance;
00108         m_lonLatCommand.y += delta*0.1f;                    // zoom in/out
00109         m_lastDistance = distance;                          // save for next frame
00110     }
00111 }
00112
00113 void LonLatController::OnPointerReleased(
00114     _In_ CoreWindow^ sender,
00115     _In_ PointerEventArgs^ args
00116     )
00117 {
00118     m_numPointersDown--;
00119     if (args->CurrentPoint->PointerId == m_lonLatPointerID1)    // this was the first down pointer
00120     {
00121         m_lonLatPointerID1 = m_lonLatPointerID2;                // use remaining contact as rotate, not zoom
00122         m_lonLatLastPoint1 = m_lonLatLastPoint2;
00123     }
00124 }
00125 void LonLatController::OnPointerWheelChanged(
00126     _In_ CoreWindow^ sender,
00127     _In_ PointerEventArgs^ args
00128     )
00129 {
00130     int wheelDelta = args->CurrentPoint->Properties->MouseWheelDelta;
00131     m_lonLatCommand.y += wheelDelta*0.1f;      // zoom in/out
00132 }
00133
00134 // set up the Controls supported by this controller
00135 void LonLatController::Initialize(_In_ CoreWindow^ window)
00136 {
00137     // opt in to recieve touch/mouse/key events
00138
00139     window->PointerPressed +=
00140         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &LonLatController::OnPointerPressed);
00141
00142     window->PointerMoved +=
00143         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &LonLatController::OnPointerMoved);
00144
00145     window->PointerReleased +=
00146         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &LonLatController::OnPointerReleased);
00147
00148     window->PointerWheelChanged +=
00149         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &LonLatController::OnPointerWheelChanged);
00150
00151     // initialize controller state
00152     m_lonLatInUse = FALSE;          // no pointer is in the Look control
00153     m_lonLatPointerID1 = 0;
00154     m_lonLatPointerID2 = 0;
00155
00156     SetOrientation(0, 0);           // look straight ahead
00157
00158     m_numPointersDown = 0;
00159     m_radius = 1.0f;
00160 }
00161
00162 // accessor to set position of controller
00163 void LonLatController::SetPosition(_In_ float3 pos)
00164 {
00165     m_longitude = atan2f(pos.x, pos.z);
00166     float r = sqrtf(pos.x*pos.x + pos.z*pos.z);
00167     m_latitude = atan2f(pos.y, r);
00168     m_radius = sqrtf(pos.x*pos.x + pos.y*pos.y + pos.z*pos.z);
00169 }
00170
00171 // accessor to set position of controller
00172 void LonLatController::SetOrientation(
00173     _In_ float latitude,
00174     _In_ float longitude
00175     )
00176 {
00177     m_latitude = latitude;
00178     m_longitude = longitude;
00179 }
00180
00181 // returns the position of the controller object
00182 float3 LonLatController::get_Position()
00183 {
00184     float y = m_radius*sinf(m_latitude);    // up-down
00185     float r = m_radius*cosf(m_latitude);    // in the plane
00186     float z = r*cosf(m_longitude);          // fwd-back
00187     float x = r*sinf(m_longitude);          // left-right
00188
00189     return float3(x, y, z);
00190 }
00191
00192 // returns the point at which the camera controller is facing
00193 float3 LonLatController::get_LookPoint()
00194 {
00195     return float3(0, 0, 0);
00196 }
00197
00198 void LonLatController::Update(_In_ CoreWindow^ window)
00199 {
00200     // poll keyboard state
00201     Windows::UI::Core::CoreVirtualKeyStates KeyState;
00202
00203     // Arrow keys
00204     KeyState = window->GetAsyncKeyState(VirtualKey::Up);
00205     if (bool(KeyState & CoreVirtualKeyStates::Down))
00206     {
00207         m_lonLatCommand.z += 1.0f;
00208     }
00209
00210     KeyState = window->GetAsyncKeyState(VirtualKey::Down);
00211     if (bool(KeyState & CoreVirtualKeyStates::Down))
00212     {
00213         m_lonLatCommand.z -= 1.0f;
00214     }
00215
00216     KeyState = window->GetAsyncKeyState(VirtualKey::Left);
00217     if (bool(KeyState & CoreVirtualKeyStates::Down))
00218     {
00219         m_lonLatCommand.x -= 1.0f;
00220     }
00221
00222     KeyState = window->GetAsyncKeyState(VirtualKey::Right);
00223     if (bool(KeyState & CoreVirtualKeyStates::Down))
00224     {
00225         m_lonLatCommand.x += 1.0f;
00226     }
00227
00228     KeyState = window->GetAsyncKeyState(VirtualKey::PageUp);
00229     if (bool(KeyState & CoreVirtualKeyStates::Down))
00230     {
00231         m_lonLatCommand.y += 1.0f;
00232     }
00233
00234     KeyState = window->GetAsyncKeyState(VirtualKey::PageDown);
00235     if (bool(KeyState == CoreVirtualKeyStates::Down))
00236     {
00237         m_lonLatCommand.y -= 1.0f;
00238     }
00239
00240     // WASD keys
00241     KeyState = window->GetAsyncKeyState(VirtualKey::W);
00242     if (bool(KeyState & CoreVirtualKeyStates::Down))
00243     {
00244         m_lonLatCommand.y += 1.0f;
00245     }
00246
00247     KeyState = window->GetAsyncKeyState(VirtualKey::A);
00248     if (bool(KeyState & CoreVirtualKeyStates::Down))
00249     {
00250         m_lonLatCommand.x -= 1.0f;
00251     }
00252
00253     KeyState = window->GetAsyncKeyState(VirtualKey::S);
00254     if (bool(KeyState & CoreVirtualKeyStates::Down))
00255     {
00256         m_lonLatCommand.y -= 1.0f;
00257     }
00258
00259     KeyState = window->GetAsyncKeyState(VirtualKey::D);
00260     if (bool(KeyState & CoreVirtualKeyStates::Down))
00261     {
00262         m_lonLatCommand.x += 1.0f;
00263     }
00264
00265     KeyState = window->GetAsyncKeyState(VirtualKey::Space);
00266     if (bool(KeyState & CoreVirtualKeyStates::Down))
00267     {
00268         m_lonLatCommand.z += 1.0f;
00269     }
00270
00271     KeyState = window->GetAsyncKeyState(VirtualKey::X);
00272     if (bool(KeyState == CoreVirtualKeyStates::Down))
00273     {
00274         m_lonLatCommand.z -= 1.0f;
00275     }
00276
00277     // scale for sensitivity adjustment
00278     float3 command = m_lonLatCommand*LONLATKEY_GAIN;
00279     float altitude = m_radius - 1;
00280     command = command*altitude*0.5f;    // logarithmic gain towards unit sphere
00281
00282     // update state with command input
00283     m_latitude  += command.z;
00284     m_longitude += command.x;
00285     m_radius    -= command.y;           // fwd stick is down towards object
00286
00287     // Limit lattitude to poles
00288     float limit = PI_F/2 - 0.01f;
00289     m_latitude = __max(-limit, m_latitude);
00290     m_latitude = __min(+limit, m_latitude);
00291
00292     // keep longitude in sane range by wrapping
00293     if (m_longitude > PI_F)
00294     {
00295         m_longitude -= PI_F*2;
00296     }
00297     else if (m_longitude < -PI_F)
00298     {
00299         m_longitude += PI_F*2;
00300     }
00301
00302     // limit us to positive radius
00303     m_radius = __max(1.011f, m_radius);
00304
00305     // clear movement input accumulator for use during next frame
00306     m_lonLatCommand = float3(0.0f, 0.0f, 0.0f);
00307 }
00308
00309 void LonLatController::SaveInternalState(_In_ IPropertySet^ state)
00310 {
00311     if (state->HasKey("m_longitude"))
00312     {
00313         state->Remove("m_longitude");
00314     }
00315     if (state->HasKey("m_latitude"))
00316     {
00317         state->Remove("m_latitude");
00318     }
00319     if (state->HasKey("m_radius"))
00320     {
00321         state->Remove("m_radius");
00322     }
00323     state->Insert("m_longitude", PropertyValue::CreateSingle(m_longitude));
00324     state->Insert("m_latitude", PropertyValue::CreateSingle(m_latitude));
00325     state->Insert("m_radius", PropertyValue::CreateSingle(m_radius));
00326 }
00327
00328 void LonLatController::LoadInternalState(_In_ IPropertySet^ state)
00329 {
00330     if (state->HasKey("m_longitude") && state->HasKey("m_latitude") && state->HasKey("m_radius"))
00331     {
00332         m_longitude = safe_cast<IPropertyValue^>(state->Lookup("m_longitude"))->GetSingle();
00333         m_latitude = safe_cast<IPropertyValue^>(state->Lookup("m_latitude"))->GetSingle();
00334         m_radius = safe_cast<IPropertyValue^>(state->Lookup("m_radius"))->GetSingle();
00335     }
00336 }
Generated on Sat Nov 23 2024 16:08:11 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/Level2.cpp Source File

  • DirectX 3D shooting game

Level2.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 "Level2.h"
00010 #include "Face.h"
00011
00012 //----------------------------------------------------------------------
00013
00014 Level2::Level2()
00015 {
00016     m_timeLimit = 30.0f;
00017     m_objective = "Hit each of the targets in ORDER before time runs out.";
00018 }
00019
00020 //----------------------------------------------------------------------
00021
00022 void Level2::Initialize(std::vector<GameObject^> objects)
00023 {
00024     Level1::Initialize(objects);
00025
00026     int targetCount = 0;
00027     for (auto object = objects.begin(); object != objects.end(); object++)
00028     {
00029         if (Face^ target = dynamic_cast<Face^>(*object))
00030         {
00031             if (targetCount < 9)
00032             {
00033                 target->Target(targetCount == 0 ? true : false);
00034                 targetCount++;
00035             }
00036         }
00037     }
00038     m_nextId = 1;
00039 }
00040
00041 //----------------------------------------------------------------------
00042
00043 bool Level2::Update(
00044     float /* time */,
00045     float /* elapsedTime */,
00046     float /* timeRemaining */,
00047     std::vector<GameObject^> objects
00048     )
00049 {
00050     int left = 0;
00051     for (auto object = objects.begin(); object != objects.end(); object++)
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 //----------------------------------------------------------------------
00074
00075 void Level2::SaveState(PersistentState^ state)
00076 {
00077     state->SaveInt32(":NextTarget", m_nextId);
00078 }
00079
00080 //----------------------------------------------------------------------
00081
00082 void Level2::LoadState(PersistentState^ state)
00083 {
00084     m_nextId = state->LoadInt32(":NextTarget", 1);
00085 }
00086
00087 //----------------------------------------------------------------------
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML data binding/C++/Scenario4.xaml.cpp Source File

  • XAML data binding

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 #include "Team.h"
00019
00020 using namespace SDKSample::DataBinding;
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Navigation;
00025
00026 Scenario4::Scenario4()
00027 {
00028   InitializeComponent();
00029   Scenario4Reset(nullptr, nullptr);
00030 }
00031
00032 void SDKSample::DataBinding::Scenario4::Scenario4Reset(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00033 {
00034   Output->DataContext =ref new Teams();
00035 }
00036
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Device enumeration/C++/App.xaml.cpp Source File

  • Device enumeration

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File picker contracts/C++/FileSavePickerPage.xaml.cpp Source File

  • File picker contracts

FileSavePickerPage.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 // FileSavePickerPage.xaml.cpp
00013 // Implementation of the FileSavePickerPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "FileSavePickerPage.xaml.h"
00018 #include "Constants.h"
00019 #include "App.xaml.h"
00020
00021 #include <collection.h>
00022
00023 using namespace SDKSample;
00024 using namespace SDKSample::Common;
00025 using namespace SDKSample::FilePickerContracts;
00026 using namespace Platform;
00027 using namespace Windows::ApplicationModel::Activation;
00028 using namespace Windows::Foundation;
00029 using namespace Windows::Foundation::Collections;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035 using namespace Windows::UI::Xaml::Navigation;
00036
00037 FileSavePickerPage^ FileSavePickerPage::Current = nullptr;
00038
00039 FileSavePickerPage::FileSavePickerPage()
00040 {
00041     InitializeComponent();
00042
00043     // This frame is hidden, meaning it is never shown.  It is simply used to load
00044     // each scenario page and then pluck out the input and output sections and
00045     // place them into the UserControls on the main page.
00046     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00047     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00048     LayoutRoot->Children->Append(HiddenFrame);
00049
00050     FeatureName->Text = FEATURE_NAME;
00051
00052     this->SizeChanged += ref new SizeChangedEventHandler(this, &FileSavePickerPage::FileSavePickerPage_SizeChanged);
00053     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &FileSavePickerPage::Scenarios_SelectionChanged);
00054
00055     FileSavePickerPage::Current = this;
00056     autoSizeInputSectionWhenSnapped = true;
00057 }
00058
00059 /// <summary>
00060 /// We need to handle SizeChanged so that we can make the sample layout property
00061 /// in the various layouts.
00062 /// </summary>
00063 /// <param name="sender"></param>
00064 /// <param name="e"></param>
00065 void FileSavePickerPage::FileSavePickerPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00066 {
00067     InvalidateSize();
00068     PageSizeChangedEventArgs^ args = ref new PageSizeChangedEventArgs();
00069     args->ViewState = ApplicationView::Value;
00070     PageResized(this, args);
00071 }
00072
00073 void FileSavePickerPage::InvalidateSize()
00074 {
00075     // Get the window width
00076     double windowWidth = this->ActualWidth;
00077
00078     if (windowWidth != 0.0)
00079     {
00080         // Get the width of the ListBox.
00081         double listBoxWidth = Scenarios->ActualWidth;
00082
00083         // Is the ListBox using any margins that we need to consider?
00084         double listBoxMarginLeft = Scenarios->Margin.Left;
00085         double listBoxMarginRight = Scenarios->Margin.Right;
00086
00087         // Figure out how much room is left after considering the list box width
00088         double availableWidth = windowWidth - listBoxWidth;
00089
00090         // Is the top most child using margins?
00091         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00092         double layoutRootMarginRight = ContentRoot->Margin.Right;
00093
00094         // We have different widths to use depending on the view state
00095         if (ApplicationView::Value != ApplicationViewState::Snapped)
00096         {
00097             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00098             // and the LayoutRoot's margins
00099             InputSection->Width = ((availableWidth) -
00100                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00101         }
00102         else
00103         {
00104             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00105             if (autoSizeInputSectionWhenSnapped)
00106             {
00107                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00108             }
00109         }
00110     }
00111     InvalidateViewState();
00112 }
00113
00114 void FileSavePickerPage::InvalidateViewState()
00115 {
00116     // Are we going to snapped mode?
00117     if (ApplicationView::Value == ApplicationViewState::Snapped)
00118     {
00119         Grid::SetRow(DescriptionText, 3);
00120         Grid::SetColumn(DescriptionText, 0);
00121
00122         Grid::SetRow(InputSection, 4);
00123         Grid::SetColumn(InputSection, 0);
00124
00125         Grid::SetRow(FooterPanel, 2);
00126         Grid::SetColumn(FooterPanel, 0);
00127     }
00128     else
00129     {
00130         Grid::SetRow(DescriptionText, 1);
00131         Grid::SetColumn(DescriptionText, 1);
00132
00133         Grid::SetRow(InputSection, 2);
00134         Grid::SetColumn(InputSection, 1);
00135
00136         Grid::SetRow(FooterPanel, 1);
00137         Grid::SetColumn(FooterPanel, 1);
00138     }
00139
00140     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00141     // input and output sections from the page) we need to ensure that any VSM code used
00142     // by the scenario's input and output sections is fired.
00143     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00144     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00145 }
00146
00147 void FileSavePickerPage::PopulateScenarios()
00148 {
00149     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00150
00151     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00152     for (unsigned int i = 0; i < scenarios->Length; ++i)
00153     {
00154         Scenario s = scenarios[i];
00155         ListBoxItem^ item = ref new ListBoxItem();
00156         item->Name = s.ClassName;
00157         item->Content = (i + 1).ToString() + ") " + s.Title;
00158         ScenarioList->Append(item);
00159     }
00160
00161     // Bind the ListBox to the scenario list.
00162     Scenarios->ItemsSource = ScenarioList;
00163 }
00164
00165 /// <summary>
00166 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00167 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00168 /// and output sections into the respective UserControl on the main page.
00169 /// </summary>
00170 /// <param name="scenarioName"></param>
00171 void FileSavePickerPage::LoadScenario(String^ scenarioName)
00172 {
00173     autoSizeInputSectionWhenSnapped = true;
00174
00175     // Load the ScenarioX.xaml file into the Frame.
00176     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00177     HiddenFrame->Navigate(scenarioType, this);
00178
00179     // Get the top element, the Page, so we can look up the elements
00180     // that represent the input and output sections of the ScenarioX file.
00181     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00182
00183     // Get each element.
00184     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00185     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00186
00187     if (input == nullptr)
00188     {
00189         // Malformed input section.
00190         NotifyUser("Cannot load scenario input section for " + scenarioName +
00191             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00192         return;
00193     }
00194
00195     if (output == nullptr)
00196     {
00197         // Malformed output section.
00198         NotifyUser("Cannot load scenario output section for " + scenarioName +
00199             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00200         return;
00201     }
00202
00203     // Find the LayoutRoot which parents the input and output sections in the main page.
00204     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00205
00206     if (panel != nullptr)
00207     {
00208         unsigned int index = 0;
00209         UIElementCollection^ collection = panel->Children;
00210
00211         // Get rid of the content that is currently in the intput and output sections.
00212         collection->IndexOf(input, &index);
00213         collection->RemoveAt(index);
00214
00215         collection->IndexOf(output, &index);
00216         collection->RemoveAt(index);
00217
00218         // Populate the input and output sections with the newly loaded content.
00219         InputSection->Content = input;
00220         OutputSection->Content = output;
00221
00222         ScenarioLoaded(this, nullptr);
00223     }
00224     else
00225     {
00226         // Malformed Scenario file.
00227         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00228             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00229     }
00230 }
00231
00232 void FileSavePickerPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00233 {
00234     if (Scenarios->SelectedItem != nullptr)
00235     {
00236         NotifyUser("", NotifyType::StatusMessage);
00237
00238         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00239         InvalidateSize();
00240     }
00241 }
00242
00243 void FileSavePickerPage::NotifyUser(String^ strMessage, NotifyType type)
00244 {
00245     switch (type)
00246     {
00247     case NotifyType::StatusMessage:
00248         // Use the status message style.
00249         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00250         break;
00251     case NotifyType::ErrorMessage:
00252         // Use the error message style.
00253         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00254         break;
00255     default:
00256         break;
00257     }
00258     StatusBlock->Text = strMessage;
00259
00260     // Collapsed the StatusBlock if it has no text to conserve real estate.
00261     if (StatusBlock->Text != "")
00262     {
00263         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00264     }
00265     else
00266     {
00267         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00268     }
00269 }
00270
00271 void FileSavePickerPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00272 {
00273     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00274     Windows::System::Launcher::LaunchUriAsync(uri);
00275 }
00276
00277 /// <summary>
00278 /// Populates the page with content passed during navigation.  Any saved state is also
00279 /// provided when recreating a page from a prior session.
00280 /// </summary>
00281 /// <param name="navigationParameter">The parameter value passed to
00282 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00283 /// </param>
00284 /// <param name="pageState">A map of state preserved by this page during an earlier
00285 /// session.  This will be null the first time a page is visited.</param>
00286 void FileSavePickerPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00287 {
00288     (void) navigationParameter; // Unused parameter
00289
00290     PopulateScenarios();
00291
00292     // Starting scenario is the first or based upon a previous state.
00293     ListBoxItem^ startingScenario = nullptr;
00294     int startingScenarioIndex = -1;
00295
00296     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00297     {
00298         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00299     }
00300
00301     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00302
00303     InvalidateViewState();
00304 }
00305
00306 /// <summary>
00307 /// Preserves state associated with this page in case the application is suspended or the
00308 /// page is discarded from the navigation cache.  Values must conform to the serialization
00309 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00310 /// </summary>
00311 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00312 void FileSavePickerPage::SaveState(IMap<String^, Object^>^ pageState)
00313 {
00314     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00315     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00316 }
00317
00318 bool FileSavePickerPage::EnsureUnsnapped()
00319 {
00320     // FilePicker APIs will not work if the application is in a snapped state.
00321     // If an app wants to show a FilePicker while snapped, it must attempt to unsnap first
00322     bool unsnapped = ((ApplicationView::Value != ApplicationViewState::Snapped) || ApplicationView::TryUnsnap());
00323     if (!unsnapped)
00324     {
00325         NotifyUser("Cannot unsnap the sample application", NotifyType::StatusMessage);
00326     }
00327
00328     return unsnapped;
00329 }
00330
00331 void FileSavePickerPage::Activate(FileSavePickerActivatedEventArgs^ args)
00332 {
00333     // cache FileSavePickerUI
00334     fileSavePickerUI = args->FileSavePickerUI;
00335     Window::Current->Content = this;
00336     LoadState(nullptr, nullptr);
00337     Window::Current->Activate();
00338 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Network status background/C++/NetworkStatusApp/Constants.cpp Source File

  • Network status background
  • NetworkStatusApp

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 bool BackgroundTaskSample::SampleBackgroundTaskWithConditionRegistered = false;
00018
00019
00020 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00021 {
00022     // The format here is the following:
00023     //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
00024     { "Network Status Change with Internet Present", "SDKSample.NetworkStatusApp.NetworkStatusWithInternetPresent" }
00025 };
00026
00027 BackgroundTaskRegistration^ BackgroundTaskSample::RegisterBackgroundTask(String^ taskEntryPoint, String^ name, IBackgroundTrigger^ trigger, IBackgroundCondition^ condition)
00028 {
00029     auto builder = ref new BackgroundTaskBuilder();
00030
00031     builder->Name = name;
00032     builder->TaskEntryPoint = taskEntryPoint;
00033     builder->SetTrigger(trigger);
00034
00035     if (condition != nullptr)
00036     {
00037         builder->AddCondition(condition);
00038     }
00039
00040     auto task = builder->Register();
00041
00042     UpdateBackgroundTaskStatus(name, true);
00043
00044     return task;
00045 }
00046
00047
00048 //
00049 // Unregister background tasks with specified name.
00050 //
00051 void BackgroundTaskSample::UnregisterBackgroundTasks(String^ name)
00052 {
00053     //
00054     // Loop through all background tasks and unregister any that have a name that matches
00055     // the name passed into this function.
00056     //
00057     auto iter = BackgroundTaskRegistration::AllTasks->First();
00058     auto hascur = iter->HasCurrent;
00059     while (hascur)
00060     {
00061         auto cur = iter->Current->Value;
00062
00063         if(cur->Name == name)
00064         {
00065             cur->Unregister(true);
00066             UpdateBackgroundTaskStatus(name, false);
00067         }
00068
00069         hascur = iter->MoveNext();
00070     }
00071 }
00072
00073 void BackgroundTaskSample::UpdateBackgroundTaskStatus(Platform::String^ name, bool registered)
00074 {
00075     if (name == SampleBackgroundTaskWithConditionName)
00076     {
00077         BackgroundTaskSample::SampleBackgroundTaskWithConditionRegistered = registered;
00078     }
00079 }
00080
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Print/C++/MainPage.xaml.cpp Source File

  • Print

MainPage.xaml.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 //
00009 // MainPage.xaml.cpp
00010 // Implementation of the MainPage.xaml class.
00011 //
00012
00013 #include "pch.h"
00014 #include "MainPage.xaml.h"
00015 #include "App.xaml.h"
00016
00017 using namespace Windows::UI::Xaml;
00018 using namespace Windows::UI::Xaml::Controls;
00019 using namespace Windows::UI::Xaml::Data;
00020 using namespace Windows::System;
00021 using namespace Windows::Foundation;
00022 using namespace Platform;
00023 using namespace PrintSample;
00024 using namespace CppSamplesUtils;
00025 using namespace Windows::UI::Xaml::Navigation;
00026 using namespace Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Core;
00028
00029 MainPage::MainPage()
00030 {
00031     InitializeComponent();
00032
00033     SetFeatureName("PrintSample");
00034
00035     _scenariosFrame = ScenarioList;
00036     _inputFrame = ScenarioInput;
00037     _outputFrame = ScenarioOutput;
00038
00039     _sizeChangedHandlerToken = Window::Current->CoreWindow->SizeChanged +=
00040     ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &MainPage::Page_SizeChanged);
00041
00042     _pageLoadedHandlerToken = Loaded += ref new RoutedEventHandler(this, &MainPage::Page_Loaded);
00043     _logicalDpiChangedToken = DisplayProperties::LogicalDpiChanged += ref new DisplayPropertiesEventHandler(this, &MainPage::DisplayProperties_LogicalDpiChanged);
00044
00045 }
00046
00047 MainPage::~MainPage()
00048 {
00049 }
00050
00051 void MainPage::Page_Loaded(Object^ sender, RoutedEventArgs^ e)
00052 {
00053     // Load the ScenarioList page into the proper frame.
00054     TypeName pageType = { "PrintSample.ScenarioList", TypeKind::Custom };
00055     ScenarioList->Navigate(pageType, this);
00056
00057     // Figure out what resolution and orientation we are in and respond appropriately.
00058     CheckResolutionAndViewState();
00059 }
00060
00061 void MainPage::SetFeatureName(String^ strFeature)
00062 {
00063     FeatureName->Text = strFeature;
00064 }
00065
00066 void MainPage::Page_SizeChanged(CoreWindow^ sender, WindowSizeChangedEventArgs^ e)
00067 {
00068     CheckResolutionAndViewState();
00069 }
00070
00071 void MainPage::DisplayProperties_LogicalDpiChanged(Object^ sender)
00072 {
00073     CheckResolutionAndViewState();
00074 }
00075
00076 void MainPage::CheckResolutionAndViewState()
00077 {
00078     ApplicationViewState state = ApplicationView::Value;
00079     String^ stateString = ConvertViewState(state);
00080
00081     ResolutionScale scale = DisplayProperties::ResolutionScale;
00082     String^ scaleString = ConvertResolution(scale);
00083
00084     VisualStateManager::GoToState(this, stateString + scaleString, false);
00085 }
00086
00087 String^ MainPage::ConvertViewState(ApplicationViewState state)
00088 {
00089     switch (state)
00090     {
00091     case ApplicationViewState::Filled:
00092         return "Filled";
00093     case ApplicationViewState::FullScreenLandscape:
00094         return "FullScreenLandscape";
00095     case ApplicationViewState::FullScreenPortrait:
00096         return "FullScreenPortrait";
00097     case ApplicationViewState::Snapped:
00098         return "Snapped";
00099     }
00100     return "";
00101 }
00102
00103 String^ MainPage::ConvertResolution(ResolutionScale scale)
00104 {
00105     switch (scale)
00106     {
00107     case ResolutionScale::Scale100Percent:
00108         return "Scale100Percent";
00109     case ResolutionScale::Scale140Percent:
00110         return "Scale140Percent";
00111     case ResolutionScale::Scale180Percent:
00112         return "Scale180Percent";
00113     }
00114     return "";
00115 }
00116
00117 void MainPage::DoNavigation(TypeName pageType, Windows::UI::Xaml::Controls::Frame^ frame)
00118 {
00119     frame->Navigate(pageType, this);
00120
00121     std::wstring PageName(pageType.Name->Data());
00122     std::basic_string <wchar_t>::size_type indexSubstring;
00123     indexSubstring = PageName.find(L"Output");
00124     if (indexSubstring != std::wstring::npos)
00125     {
00126         // Raise OutputFrameLoaded so downstream pages know that the output frame content has been loaded.
00127         OutputFrameLoaded(this, nullptr);
00128     }
00129     else
00130     {
00131         // Raise InputFrameLoaded so downstream pages know that the input frame content has been loaded.
00132         InputFrameLoaded(this, nullptr);
00133     }
00134 }
00135
00136 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00137 {
00138     switch (type)
00139     {
00140     case NotifyType::StatusMessage:
00141         StatusBlock->Style = dynamic_cast<Windows::UI::Xaml::Style^>(App::Current->Resources->Lookup("StatusStyle"));
00142         break;
00143     case NotifyType::ErrorMessage:
00144         StatusBlock->Style = dynamic_cast<Windows::UI::Xaml::Style^>(App::Current->Resources->Lookup("ErrorStyle"));
00145         break;
00146     default:
00147         break;
00148     }
00149     StatusBlock->Text = strMessage;
00150 }
00151
00152 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00153 {
00154     auto _hyperlinkButton = (HyperlinkButton^)sender;
00155     auto uri = ref new Windows::Foundation::Uri((String^)_hyperlinkButton->Tag);
00156
00157     Windows::System::Launcher::LaunchUriAsync(uri);
00158 }
Generated on Sat Nov 23 2024 16:07:43 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/CartoonEffect/PPLCartoon.h Source File

  • Hilo C++
  • CartoonEffect

PPLCartoon.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
00009 void ApplyCartoonEffectPPL(byte* sourcePixels,
00010                            unsigned int width,
00011                            unsigned int height,
00012                            unsigned int neighborWindow,
00013                            unsigned int phases,
00014                            unsigned int size,
00015                            concurrency::cancellation_token token);
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D-Direct2D interop/C++/TextInterop.h Source File

  • Direct3D-Direct2D interop

TextInterop.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 "DirectXBase.h"
00011 #include "BasicMath.h"
00012 #include "BasicCamera.h"
00013 #include "SampleOverlay.h"
00014
00015 // describes the constant buffer that will be used to draw the cube
00016 struct ConstantBuffer
00017 {
00018     float4x4 model;
00019     float4x4 view;
00020     float4x4 projection;
00021 };
00022
00023 ref class TextInterop : public DirectXBase
00024 {
00025 internal:
00026     TextInterop();
00027
00028     virtual void CreateDeviceIndependentResources() override;
00029     virtual void CreateDeviceResources() override;
00030     virtual void CreateWindowSizeDependentResources() override;
00031     virtual void Render() override;
00032
00033     void Update(float TimeTotal, float TimeDelta);
00034
00035 private:
00036
00037     SampleOverlay^                                      m_sampleOverlay;
00038
00039     Microsoft::WRL::ComPtr<ID3D11InputLayout>           m_inputLayout;                // cube vertex input layout
00040     Microsoft::WRL::ComPtr<ID3D11Buffer>                m_vertexBuffer;               // cube vertex buffer
00041     Microsoft::WRL::ComPtr<ID3D11Buffer>                m_indexBuffer;                // cube index buffer
00042     Microsoft::WRL::ComPtr<ID3D11VertexShader>          m_vertexShader;               // cube vertex shader
00043     Microsoft::WRL::ComPtr<ID3D11PixelShader>           m_pixelShader;                // cube pixel shader
00044     Microsoft::WRL::ComPtr<ID3D11Texture2D>             m_texture;                    // cube texture
00045     Microsoft::WRL::ComPtr<ID3D11ShaderResourceView>    m_textureShaderResourceView;  // cube texture view
00046     Microsoft::WRL::ComPtr<ID3D11SamplerState>          m_sampler;                    // cube texture sampler
00047     Microsoft::WRL::ComPtr<ID3D11Buffer>                m_constantBuffer;             // constant buffer resource
00048
00049     unsigned int             m_indexCount;                  // cube index count
00050     ConstantBuffer           m_constantBufferData;          // constant buffer resource data
00051     BasicCamera^             m_camera;                      // scene camera
00052
00053 };
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Globalization preferences/C++/GeographicRegion.xaml.cpp Source File

  • Globalization preferences

GeographicRegion.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 // GeographicRegionScenario.xaml.cpp
00013 // Implementation of the GeographicRegionScenario class
00014 //
00015
00016 #include "pch.h"
00017 #include "GeographicRegion.xaml.h"
00018 #include "Utilities.h"
00019
00020 using namespace SDKSample::GlobalizationPreferencesSample;
00021
00022 using namespace Platform;
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::Navigation;
00028 using namespace Windows::System::UserProfile;
00029 using namespace Windows::Globalization;
00030
00031 GeographicRegionScenario::GeographicRegionScenario()
00032 {
00033     InitializeComponent();
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 GeographicRegionScenario::OnNavigatedTo(NavigationEventArgs^ e)
00042 {
00043     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00044     // as NotifyUser()
00045     rootPage = MainPage::Current;
00046 }
00047
00048 void SDKSample::GlobalizationPreferencesSample::GeographicRegionScenario::Display_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00049 {
00050   // This scenario uses the Windows.System.UserProfile.GlobalizationPreferences class to
00051   // obtain the user's preferred geographic region characteristics.
00052   auto userGeoRegion = ref new GeographicRegion();
00053
00054   // This obtains the geographic region characteristics by providing a country or region code.
00055   auto exampleGeoRegion = ref new GeographicRegion("AU");
00056
00057   // Generate the results
00058   String^ userGeoRegionCharacteristics =
00059         "User's Preferred Geographic Region\n" +
00060     "Display Name: "      + userGeoRegion->DisplayName + "\n" +
00061     "Native Name: "       + userGeoRegion->NativeName + "\n" +
00062         "Currencies in use: " + Utilities::VectorViewToString(userGeoRegion->CurrenciesInUse) + "\n" +
00063     "Codes: "             + userGeoRegion->CodeTwoLetter + ", " + userGeoRegion->CodeThreeLetter + ", " + userGeoRegion->CodeThreeDigit;
00064
00065   String^ exampleGeoRegionCharacteristics =
00066         "Example Geographic Region by region/country code (AU)\n" +
00067     "Display Name: "      + exampleGeoRegion->DisplayName + "\n" +
00068     "Native Name: "       + exampleGeoRegion->NativeName + "\n" +
00069     "Currencies in use: " + Utilities::VectorViewToString(exampleGeoRegion->CurrenciesInUse) + "\n" +
00070     "Codes: "             + exampleGeoRegion->CodeTwoLetter + ", " + exampleGeoRegion->CodeThreeLetter + " , " + exampleGeoRegion->CodeThreeDigit;
00071
00072   String^ results = userGeoRegionCharacteristics + "\n\n" + exampleGeoRegionCharacteristics;
00073
00074     // Display the results
00075     rootPage->NotifyUser(results, NotifyType::StatusMessage);
00076 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/Common/SuspensionManager.h Source File

  • Hilo C++
  • Hilo
  • Common

SuspensionManager.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 // SuspensionManager.h
00009 // Declaration of the SuspensionManager class
00010 //
00011
00012 #pragma once
00013
00014 #include <ppltasks.h>
00015
00016 namespace Hilo
00017 {
00018   namespace Common
00019   {
00020     /// <summary>
00021     /// SuspensionManager captures global session state to simplify process lifetime management
00022     /// for an application.  Note that session state will be automatically cleared under a variety
00023     /// of conditions and should only be used to store information that would be convenient to
00024     /// carry across sessions, but that should be disacarded when an application crashes or is
00025     /// upgraded.
00026     /// </summary>
00027     ref class SuspensionManager sealed
00028     {
00029     internal:
00030       static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00031       static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00032       static Concurrency::task<void> SaveAsync(void);
00033       static Concurrency::task<void> RestoreAsync(void);
00034       static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00035       {
00036         Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00037       };
00038       static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00039         Windows::UI::Xaml::Controls::Frame^ frame);
00040
00041     private:
00042       static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00043       static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00044     };
00045   }
00046 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML accessibility/C++/common/suspensionmanager.h Source File

  • XAML accessibility
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/CartoonEffect/FrameProcessing.cpp Source File

  • Hilo C++
  • CartoonEffect

FrameProcessing.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 #include <ppltasks.h>
00009 #include "FrameProcessing.h"
00010 #include "FrameData.h"
00011 #include "Utils.h"
00012
00013 using namespace concurrency;
00014
00015 const float64 Utils::Wr = 0.299;
00016 const float64 Utils::Wb = 0.114;
00017 const float64 Utils::Wg = 1 - Utils::Wr - Utils::Wb;
00018
00019 FrameProcessing::FrameProcessing()
00020     : m_size(0)
00021     , m_BPP(0)
00022     , m_pitch(0)
00023     , m_neighborWindow(3)
00024     , m_pCurrentImage(nullptr)
00025     , m_pBufferImage(nullptr)
00026     , m_token(cancellation_token::none())
00027 {
00028 }
00029
00030 FrameProcessing::~FrameProcessing()
00031 {
00032     if (m_pCurrentImage != nullptr)
00033     {
00034         concurrency::Free(m_pCurrentImage);
00035         m_pCurrentImage = nullptr;
00036     }
00037 }
00038
00039 void FrameProcessing::SetCancellationToken(cancellation_token token)
00040 {
00041     m_token = token;
00042 }
00043
00044 void FrameProcessing::SetNeighbourArea(unsigned int area)
00045 {
00046     m_neighborWindow = area;
00047 }
00048
00049 unsigned int FrameProcessing::GetNeighbourArea()
00050 {
00051     return m_neighborWindow;
00052 }
00053
00054 void FrameProcessing::ApplyFilters(int nPhases)
00055 {
00056     ApplyColorSimplifier(nPhases);
00057     ApplyEdgeDetection();
00058 }
00059
00060 void FrameProcessing::SetCurrentFrame(byte* pFrame, int size, int width, int height, int pitch, int bpp, int clrPlanes)
00061 {
00062     m_width = width;
00063     m_height = height;
00064     m_pitch = pitch;
00065     m_BPP = bpp;
00066     m_colorPlanes = clrPlanes;
00067
00068     if (m_pCurrentImage != nullptr)
00069     {
00070         concurrency::Free(m_pCurrentImage);
00071         m_pCurrentImage = nullptr;
00072     }
00073     if (m_pCurrentImage == nullptr)
00074     {
00075         m_pCurrentImage = (byte*)concurrency::Alloc(size);
00076     }
00077
00078     memcpy(m_pCurrentImage, pFrame, size);
00079     m_pBufferImage = pFrame;
00080     m_size = size;
00081 }
00082
00083 void FrameProcessing::ApplyColorSimplifier()
00084 {
00085     unsigned int shift = m_neighborWindow / 2;
00086     ApplyColorSimplifier(shift, (m_height - shift), shift, (m_width - shift));
00087 }
00088
00089 void FrameProcessing::ApplyColorSimplifier(int nPhases)
00090 {
00091     for (int i = 0; i < nPhases; ++i)
00092     {
00093         ApplyColorSimplifier();
00094     }
00095 }
00096
00097 void FrameProcessing::ApplyColorSimplifier(unsigned int startHeight, unsigned int endHeight, unsigned int startWidth, unsigned int endWidth)
00098 {
00099     if (m_pBufferImage != nullptr)
00100     {
00101         run_with_cancellation_token([this, startHeight, endHeight, startWidth, endWidth]
00102         {
00103             parallel_for(startHeight, endHeight, [&](unsigned int j)
00104             {
00105                 if (m_token.is_canceled()) return;
00106                 for (unsigned int i = startWidth; i < endWidth; ++i)
00107                 {
00108                     SimplifyIndexOptimized(m_pBufferImage, i, j);
00109                 }
00110             });
00111         }, m_token);
00112     }
00113 }
00114
00115 void FrameProcessing::SimplifyIndexOptimized(byte* pFrame, int x, int y)
00116 {
00117     COLORREF orgClr =  GetPixel(pFrame, x, y, m_pitch, m_BPP);
00118
00119     int shift = m_neighborWindow / 2;
00120     float64 sSum = 0;
00121     float64 partialSumR = 0;
00122     float64 partialSumG = 0;
00123     float64 partialSumB = 0;
00124     float64 standardDeviation = 0.025;
00125
00126     for (int j = y - shift; j <= (y + shift); ++j)
00127     {
00128         for (int i = x - shift; i <= (x + shift); ++i)
00129         {
00130             // Don't apply filter to the requested index, only to the neighbors
00131             if (i != x ||  j != y)
00132             {
00133                 COLORREF clr = GetPixel(pFrame, i, j, m_pitch, m_BPP);
00134                 float64 distance = Utils::GetDistance(orgClr, clr);
00135                 float64 sValue = pow(M_E, -0.5 * pow(distance / standardDeviation, 2));
00136                 sSum += sValue;
00137                 partialSumR += GetRValue(clr) * sValue;
00138                 partialSumG += GetGValue(clr) * sValue;
00139                 partialSumB += GetBValue(clr) * sValue;
00140             }
00141         }
00142     }
00143
00144     COLORREF simplifiedClr;
00145     int simpleRed, simpleGreen, simpleBlue;
00146
00147     simpleRed   = (int)min(max(partialSumR / sSum, 0), 255);
00148     simpleGreen = (int)min(max(partialSumG / sSum, 0), 255);
00149     simpleBlue  = (int)min(max(partialSumB / sSum, 0), 255);
00150     simplifiedClr = RGB(simpleRed, simpleGreen, simpleBlue);
00151     SetPixel(m_pBufferImage, x, y, m_pitch, m_BPP, simplifiedClr);
00152 }
00153
00154 void FrameProcessing::ApplyEdgeDetection()
00155 {
00156     ApplyEdgeDetectionParallel(1, (m_height - 1), 1, (m_width - 1));
00157 }
00158
00159 void FrameProcessing::ApplyEdgeDetectionParallel(unsigned int startHeight, unsigned int endHeight, unsigned int startWidth, unsigned int endWidth)
00160 {
00161     const float alpha = 0.3f;
00162     const float beta = 0.8f;
00163     const float s0 = 0.054f;
00164     const float s1 = 0.064f;
00165     const float a0 = 0.3f;
00166     const float a1 = 0.7f;
00167
00168     byte* pFrame = new byte[m_size];
00169     memcpy_s(pFrame, m_size, m_pBufferImage, m_size);
00170
00171     run_with_cancellation_token([=]()
00172     {
00173         parallel_for(startHeight , endHeight, [&](int y)
00174         {
00175             if (m_token.is_canceled()) return;
00176             for(unsigned int x = startWidth; x < endWidth; ++x)
00177             {
00178                 float Sy, Su, Sv;
00179                 float Ay, Au, Av;
00180
00181                 CalculateSobel(m_pBufferImage, x, y, Sy, Su, Sv);
00182                 CalculateSobel(m_pCurrentImage, x, y, Ay, Au, Av);
00183
00184                 float edgeS = (1 - alpha) * Sy + alpha * (Su + Sv) / 2;
00185                 float edgeA = (1 - alpha) * Ay + alpha * (Au + Av) / 2;
00186                 float i = (1 - beta) * Utils::SmoothStep(s0, s1, edgeS) + beta * Utils::SmoothStep(a0, a1, edgeA);
00187
00188                 float oneMinusi = 1 - i;
00189                 COLORREF clr = this->GetPixel(m_pBufferImage, x, y, m_pitch, m_BPP);
00190                 COLORREF newClr = RGB(GetRValue(clr) * oneMinusi, GetGValue(clr) * oneMinusi, GetBValue(clr) * oneMinusi);
00191                 this->SetPixel(pFrame, x, y, m_pitch, m_BPP, newClr);
00192             }
00193         });
00194     }, m_token);
00195
00196     memcpy_s(m_pBufferImage, m_size, pFrame, m_size);
00197     delete[] pFrame;
00198 }
00199
00200 void FrameProcessing::CalculateSobel(byte* pSource, int row, int column, float& dy, float& du, float& dv)
00201 {
00202     int gx[3][3] = { { -1, 0, 1 }, { -2, 0, 2 }, { -1, 0, 1 } };
00203     int gy[3][3] = { { 1, 2, 1 }, { 0, 0, 0 }, { -1, -2, -1 } };
00204
00205     float64 new_yX = 0;
00206     float64 new_yY = 0;
00207     float64 new_uX = 0;
00208     float64 new_uY = 0;
00209     float64 new_vX = 0;
00210     float64 new_vY = 0;
00211     for (int i = -1; i < 2; i++)
00212     {
00213         for (int j = -1; j < 2; j++)
00214         {
00215             const int gX = gx[i + 1][j + 1];
00216             const int gY = gy[i + 1][j + 1];
00217             float64 y;
00218             float64 u;
00219             float64 v;
00220
00221             Utils::RGBToYUV(GetPixel(pSource, row + i, column + j, m_pitch, m_BPP), y, u, v);
00222
00223             new_yX += gX * y;
00224             new_yY += gY * y;
00225             new_uX += gX * u;
00226             new_uY += gY * u;
00227             new_vX += gX * v;
00228             new_vY += gY * v;
00229         }
00230     }
00231
00232     dy = (float)sqrt((new_yX * new_yX) + (new_yY * new_yY));
00233     du = (float)sqrt((new_uX * new_uX) + (new_uY * new_uY));
00234     dv = (float)sqrt((new_vX * new_vX) + (new_vY * new_vY));
00235 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Custom driver access/C#,C++/app_cs/DeviceList.cs Source File

  • Custom driver access
  • C#,C++
  • app_cs

DeviceList.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.Collections.ObjectModel;
00007 using Windows.UI.Xaml;
00008 using Windows.UI.Xaml.Documents;
00009 using Windows.ApplicationModel;
00010
00011 using Samples.Devices.Fx2;
00012 using SDKTemplate;
00013
00014 namespace CustomDeviceAccess
00015 {
00016     public class DeviceListEntry
00017     {
00018         /// <summary>
00019         /// The DeviceInformation object (device interface) for this Fx2 device
00020         /// </summary>
00021         public Windows.Devices.Enumeration.DeviceInformation Device;
00022
00023         /// <summary>
00024         /// The device interface path
00025         /// </summary>
00026         public string Id { get { return Device.Id; } }
00027
00028         /// <summary>
00029         /// The device's instance ID
00030         /// </summary>
00031         public string InstanceId { get { return (string)Device.Properties["System.Devices.DeviceInstanceId"]; } }
00032
00033         /// <summary>
00034         /// Has the device been found during the current enumeration
00035         /// </summary>
00036         public bool Matched = true;
00037
00038         /// <summary>
00039         /// Constructor
00040         /// </summary>
00041         /// <param name="DeviceInterface">The device interface for this entry</param>
00042         public DeviceListEntry(Windows.Devices.Enumeration.DeviceInformation DeviceInterface)
00043         {
00044             this.Device = DeviceInterface;
00045         }
00046     }
00047
00048     class DeviceList
00049     {
00050         public static DeviceList Current {get; private set;}
00051
00052         static DeviceList()
00053         {
00054             DeviceList.Current = new DeviceList();
00055             DeviceList.Current.InitDeviceWatcher();
00056
00057             // Register for app suspend/resume handlers
00058             App.Current.Suspending += new SuspendingEventHandler(DeviceList.Current.SuspendDeviceWatcher);
00059             App.Current.Resuming += DeviceList.Current.ResumeDeviceWatcher;
00060         }
00061
00062         /// <summary>
00063         /// List of Fx2 devices currently attached to the system.  This
00064         /// list can be updated by the PNP watcher.
00065         /// </summary>
00066         public ObservableCollection<DeviceListEntry> Fx2Devices { get { return m_Fx2Devices; } }
00067
00068         /// <summary>
00069         /// The currently opened Fx2 device
00070         /// </summary>
00071         private Samples.Devices.Fx2.Fx2Device m_Fx2Device;
00072
00073         /// <summary>
00074         /// The currently opened Fx2 device, wrapped in a property to unregister
00075         /// event handlers when closed.
00076         /// </summary>
00077         public Samples.Devices.Fx2.Fx2Device Fx2Device
00078         {
00079             get { return m_Fx2Device; }
00080             set {
00081                 if ((m_Fx2Device != null) && (this.DeviceClosing != null))
00082                 {
00083                     this.DeviceClosing(this, new EventArgs());
00084                 }
00085                 m_Fx2Device = value;
00086             }
00087         }
00088
00089         /// <summary>
00090         /// Flag to keep track of whether the device watcher has been started.
00091         /// </summary>
00092         public bool WatcherStarted = false;
00093
00094         public void StartFx2Watcher()
00095         {
00096             MainPage.Current.NotifyUser("starting device watcher", NotifyType.StatusMessage);
00097             foreach (var entry in m_Fx2Devices)
00098             {
00099                 entry.Matched = false;
00100             }
00101
00102             WatcherStarted = true;
00103             m_Fx2Watcher.Start();
00104
00105             return;
00106         }
00107
00108         public void StopFx2Watcher()
00109         {
00110             MainPage.Current.NotifyUser("stopping fx2 watcher", NotifyType.StatusMessage);
00111             m_Fx2Watcher.Stop();
00112             WatcherStarted = false;
00113         }
00114
00115         public static void CreateBooleanTable(
00116             InlineCollection Table,
00117             bool[] NewValues,
00118             bool[] OldValues,
00119             string IndexTitle,
00120             string ValueTitle,
00121             string TrueValue,
00122             string FalseValue
00123             )
00124         {
00125             Table.Clear();
00126
00127             for (var i = 0; i < NewValues.Length; i += 1)
00128             {
00129                 var line = new Span();
00130                 var block = new Run();
00131                 block.Text = (i + 1).ToString("###");
00132                 line.Inlines.Add(block);
00133
00134                 block = new Run();
00135                 block.Text = "    ";
00136                 line.Inlines.Add(block);
00137
00138                 block = new Run();
00139                 block.Text = NewValues[i] ? TrueValue : FalseValue;
00140
00141                 if ((OldValues != null) && (OldValues[i] != NewValues[i]))
00142                 {
00143                     var bold = new Bold();
00144                     bold.Inlines.Add(block);
00145                     line.Inlines.Add(bold);
00146                 }
00147                 else
00148                 {
00149                     line.Inlines.Add(block);
00150                 }
00151
00152                 line.Inlines.Add(new LineBreak());
00153
00154                 Table.Add(line);
00155             }
00156         }
00157
00158         public event EventHandler DeviceClosing;
00159
00160         //
00161         // private internal state
00162         //
00163
00164         /// <summary>
00165         /// The device watcher that we setup to look for Fx2 devices
00166         /// </summary>
00167         Windows.Devices.Enumeration.DeviceWatcher m_Fx2Watcher = null;
00168
00169         /// <summary>
00170         /// Internal list of devices.
00171         /// </summary>
00172         ObservableCollection<DeviceListEntry> m_Fx2Devices = new ObservableCollection<DeviceListEntry>();
00173
00174         void InitDeviceWatcher()
00175         {
00176             // Define the selector to enumerate all of the fx2 device interface class instances
00177             var selector = Samples.Devices.Fx2.Fx2Device.GetDeviceSelector();
00178
00179             // Create a device watcher to look for instances of the fx2 device interface
00180             m_Fx2Watcher = Windows.Devices.Enumeration.DeviceInformation.CreateWatcher(
00181                             selector,
00182                             new string[] { "System.Devices.DeviceInstanceId" }
00183                             );
00184
00185             m_Fx2Watcher.Added += OnFx2Added;
00186             m_Fx2Watcher.Removed += OnFx2Removed;
00187             m_Fx2Watcher.EnumerationCompleted += OnFx2EnumerationComplete;
00188         }
00189
00190         /// <summary>
00191         /// Event handler for arrival of Fx2 devices
00192         /// </summary>
00193         /// <param name="sender"></param>
00194         /// <param name="devInterface">The device interface which was added</param>
00195         private async void OnFx2Added(Windows.Devices.Enumeration.DeviceWatcher sender, Windows.Devices.Enumeration.DeviceInformation devInterface)
00196         {
00197             await
00198             MainPage.Current.Dispatcher.RunAsync(
00199                 Windows.UI.Core.CoreDispatcherPriority.Normal,
00200                 () =>
00201                 {
00202                     MainPage.Current.NotifyUser(String.Format("OnFx2Added: {0}", devInterface.Id), NotifyType.StatusMessage);
00203
00204                     // search the device list for a device with a matching interface ID
00205                     DeviceListEntry match = FindInList(devInterface.Id);
00206
00207                     // If we found a match then mark it as verified and return
00208                     if (match != null)
00209                     {
00210                         match.Matched = true;
00211                         return;
00212                     }
00213
00214
00215                     // Create a new element for this device interface, and queue up the query of its
00216                     // device information
00217                     match = new DeviceListEntry(devInterface);
00218
00219                     // Add the new element to the end of the list of devices
00220                     m_Fx2Devices.Add(match);
00221                 }
00222             );
00223         }
00224
00225         /// <summary>
00226         /// Event handler for the removal of an Fx2 device
00227         /// </summary>
00228         /// <param name="sender"></param>
00229         /// <param name="devInformation">The device interface that was removed</param>
00230         private async void OnFx2Removed(Windows.Devices.Enumeration.DeviceWatcher sender, Windows.Devices.Enumeration.DeviceInformationUpdate devInformation)
00231         {
00232             await
00233             MainPage.Current.Dispatcher.RunAsync(
00234                 Windows.UI.Core.CoreDispatcherPriority.Normal,
00235                 () =>
00236                 {
00237                     var deviceId = devInformation.Id;
00238                     MainPage.Current.NotifyUser(String.Format("OnFx2Removed: {0}", deviceId), NotifyType.StatusMessage);
00239
00240                     // Search the list of devices for one with a matching ID
00241                     var match = FindInList(deviceId);
00242                     if (match != null)
00243                     {
00244                         // Remove the matched item
00245                         MainPage.Current.NotifyUser(String.Format("OnFx2Removed: {0} removed", deviceId), NotifyType.StatusMessage);
00246                         m_Fx2Devices.Remove(match);
00247                     }
00248                 }
00249             );
00250         }
00251
00252         /// <summary>
00253         /// Event handler for the end of an enumeration/reenumeration started
00254         /// by calling Start on the device watcher.  This culls out any entries
00255         /// in the list which are no longer matched.
00256         /// </summary>
00257         /// <param name="sender"></param>
00258         /// <param name="args"></param>
00259         private async void OnFx2EnumerationComplete(Windows.Devices.Enumeration.DeviceWatcher sender, object args)
00260         {
00261             await
00262             MainPage.Current.Dispatcher.RunAsync(
00263                 Windows.UI.Core.CoreDispatcherPriority.Normal,
00264                 () =>
00265                 {
00266                     MainPage.Current.NotifyUser(String.Format("OnFx2EnumerationComplete"), NotifyType.StatusMessage);
00267
00268                     DeviceListEntry removedDevice;
00269
00270                     while ((removedDevice = m_Fx2Devices.FirstOrDefault(e => e.Matched == false)) != null)
00271                     {
00272                         MainPage.Current.NotifyUser("OnFx2EnumerationComplete: Removing missing device " + removedDevice.Id, NotifyType.StatusMessage);
00273                         m_Fx2Devices.Remove(removedDevice);
00274                     }
00275                 }
00276             );
00277         }
00278
00279         private bool m_WatcherSuspended = false;
00280
00281         private DeviceListEntry FindInList(string id)
00282         {
00283             return m_Fx2Devices.FirstOrDefault(entry => entry.Id == id);
00284         }
00285
00286         private void SuspendDeviceWatcher(object sender, SuspendingEventArgs e)
00287         {
00288             if (WatcherStarted)
00289             {
00290                 m_WatcherSuspended = WatcherStarted;
00291                 StopFx2Watcher();
00292             }
00293         }
00294
00295         private void ResumeDeviceWatcher(object sender, object e)
00296         {
00297             if (m_WatcherSuspended)
00298             {
00299                 StartFx2Watcher();
00300                 m_WatcherSuspended = false;
00301             }
00302         }
00303     }
00304 }
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

TextElement Member List

This is the complete list of members for TextElement, including all inherited members.
CalculateSize() | TextElement | [protected, virtual]
CreateTextLayout() | TextElement | [protected]
ElementBase() | ElementBase | [protected]
FadeOut(float fadeOutTime) | TextElement |
GetBounds() | ElementBase |
GetTextStyle() | TextElement | [inline]
Initialize() | TextElement | [virtual]
IsVisible() const | ElementBase | [inline]
m_alignment | ElementBase | [protected]
m_container | ElementBase | [protected]
m_fadeOutTime | TextElement | [protected]
m_fadeOutTimeElapsed | TextElement | [protected]
m_fadeStartingOpacity | TextElement | [protected]
m_isFadingOut | TextElement | [protected]
m_shadowColorBrush | TextElement | [protected]
m_size | ElementBase | [protected]
m_text | TextElement | [protected]
m_textColorBrush | TextElement | [protected]
m_textExtents | TextElement | [protected]
m_textLayout | TextElement | [protected]
m_textStyle | TextElement | [protected]
m_visible | ElementBase | [protected]
Render() | TextElement | [virtual]
SetAlignment(AlignType horizontal, AlignType vertical) | ElementBase |
SetContainer(const D2D1_RECT_F &container) | ElementBase | [virtual]
SetText(__nullterminated WCHAR *text) | TextElement |
SetText(Platform::String^text) | TextElement |
SetTextColor(const D2D1_COLOR_F &textColor) | TextElement |
SetTextOpacity(float textOpacity) | TextElement |
SetVisible(bool visible) | ElementBase |
TextElement() | TextElement |
Update(float timeTotal, float timeDelta) | TextElement | [virtual]
Generated on Sat Nov 23 2024 16:09:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CameraOptionsUI/C++/Constants.h Source File

  • CameraOptionsUI

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"CameraOptionsUI CPP Sample");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044
00045
00046 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML vector-based drawing/C++/common/suspensionmanager.h Source File

  • XAML vector-based drawing
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D animation/C++/SampleOverlay.cpp Source File

  • Direct2D animation

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 Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::UI::ViewManagement;
00015 using namespace Windows::Graphics::Display;
00016 using namespace D2D1;
00017
00018 SampleOverlay::SampleOverlay() :
00019     m_drawOverlay(true)
00020 {
00021 }
00022
00023 void SampleOverlay::Initialize(
00024     _In_ ID2D1Device*         d2dDevice,
00025     _In_ ID2D1DeviceContext*  d2dContext,
00026     _In_ IWICImagingFactory*  wicFactory,
00027     _In_ IDWriteFactory*      dwriteFactory,
00028     _In_ Platform::String^    caption
00029     )
00030 {
00031     m_wicFactory = wicFactory;
00032     m_dwriteFactory = dwriteFactory;
00033     m_sampleName = caption;
00034     m_d2dDevice = d2dDevice;
00035     m_d2dContext = d2dContext;
00036     m_padding = 3.0f;
00037     m_textVerticalOffset = 5.0f;
00038     m_logoSize = D2D1::SizeF(0.0f, 0.0f);
00039     m_overlayWidth = 0.0f;
00040
00041     ComPtr<ID2D1Factory> factory;
00042     d2dDevice->GetFactory(&factory);
00043
00044     DX::ThrowIfFailed(
00045         factory.As(&m_d2dFactory)
00046         );
00047
00048     ResetDirectXResources();
00049 }
00050
00051 void SampleOverlay::ResetDirectXResources()
00052 {
00053     DX::ThrowIfFailed(
00054         m_d2dContext->CreateSolidColorBrush(ColorF(ColorF::White), &m_whiteBrush)
00055         );
00056
00057     ComPtr<IWICBitmapDecoder> wicBitmapDecoder;
00058     DX::ThrowIfFailed(
00059         m_wicFactory->CreateDecoderFromFilename(
00060             L"windowsbig-sdk.png",
00061             nullptr,
00062             GENERIC_READ,
00063             WICDecodeMetadataCacheOnDemand,
00064             &wicBitmapDecoder
00065             )
00066         );
00067
00068     ComPtr<IWICBitmapFrameDecode> wicBitmapFrame;
00069     DX::ThrowIfFailed(
00070         wicBitmapDecoder->GetFrame(0, &wicBitmapFrame)
00071         );
00072
00073     ComPtr<IWICFormatConverter> wicFormatConverter;
00074     DX::ThrowIfFailed(
00075         m_wicFactory->CreateFormatConverter(&wicFormatConverter)
00076         );
00077
00078     DX::ThrowIfFailed(
00079         wicFormatConverter->Initialize(
00080             wicBitmapFrame.Get(),
00081             GUID_WICPixelFormat32bppPBGRA,
00082             WICBitmapDitherTypeNone,
00083             nullptr,
00084             0.0,
00085             WICBitmapPaletteTypeCustom  // the BGRA format has no palette so this value is ignored
00086             )
00087         );
00088
00089     double dpiX = 96.0f;
00090     double dpiY = 96.0f;
00091     DX::ThrowIfFailed(
00092         wicFormatConverter->GetResolution(&dpiX, &dpiY)
00093         );
00094
00095     DX::ThrowIfFailed(
00096         m_d2dContext->CreateBitmapFromWicBitmap(
00097             wicFormatConverter.Get(),
00098             BitmapProperties(
00099                 PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00100                 static_cast<float>(dpiX),
00101                 static_cast<float>(dpiY)
00102                 ),
00103             &m_logoBitmap
00104             )
00105         );
00106
00107     m_logoSize = m_logoBitmap->GetSize();
00108
00109     ComPtr<IDWriteTextFormat> nameTextFormat;
00110     DX::ThrowIfFailed(
00111         m_dwriteFactory->CreateTextFormat(
00112             L"Segoe UI",
00113             nullptr,
00114             DWRITE_FONT_WEIGHT_LIGHT,
00115             DWRITE_FONT_STYLE_NORMAL,
00116             DWRITE_FONT_STRETCH_NORMAL,
00117             36.0f,
00118             L"en-US",
00119             &nameTextFormat
00120             )
00121         );
00122
00123     DX::ThrowIfFailed(
00124         nameTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)
00125         );
00126
00127     DX::ThrowIfFailed(
00128         nameTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)
00129         );
00130
00131     DX::ThrowIfFailed(
00132         m_dwriteFactory->CreateTextLayout(
00133             m_sampleName->Data(),
00134             m_sampleName->Length(),
00135             nameTextFormat.Get(),
00136             4096.0f,
00137             4096.0f,
00138             &m_textLayout
00139             )
00140         );
00141
00142     DWRITE_TEXT_METRICS metrics = {0};
00143     DX::ThrowIfFailed(
00144         m_textLayout->GetMetrics(&metrics)
00145         );
00146
00147     m_overlayWidth = m_padding * 3.0f + m_logoSize.width + metrics.width;
00148
00149     DX::ThrowIfFailed(
00150         m_d2dFactory->CreateDrawingStateBlock(&m_stateBlock)
00151         );
00152
00153     UpdateForWindowSizeChange();
00154 }
00155
00156 void SampleOverlay::UpdateForWindowSizeChange()
00157 {
00158     if (CoreWindow::GetForCurrentThread()->Bounds.Width < m_overlayWidth)
00159     {
00160         m_drawOverlay = false;
00161     }
00162     else
00163     {
00164         m_drawOverlay = true;
00165     }
00166 }
00167
00168 void SampleOverlay::Render()
00169 {
00170     if (m_drawOverlay)
00171     {
00172         m_d2dContext->SaveDrawingState(m_stateBlock.Get());
00173
00174         m_d2dContext->BeginDraw();
00175         m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00176         m_d2dContext->DrawBitmap(
00177             m_logoBitmap.Get(),
00178             D2D1::RectF(m_padding, 0.0f, m_logoSize.width + m_padding, m_logoSize.height)
00179             );
00180
00181         m_d2dContext->DrawTextLayout(
00182             Point2F(m_logoSize.width + 2.0f * m_padding, m_textVerticalOffset),
00183             m_textLayout.Get(),
00184             m_whiteBrush.Get()
00185             );
00186
00187         // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00188         // is lost. It will be handled during the next call to Present.
00189         HRESULT hr = m_d2dContext->EndDraw();
00190         if (hr != D2DERR_RECREATE_TARGET)
00191         {
00192             DX::ThrowIfFailed(hr);
00193         }
00194
00195         m_d2dContext->RestoreDrawingState(m_stateBlock.Get());
00196     }
00197 }
00198
00199 float SampleOverlay::GetTitleHeightInDips()
00200 {
00201     return m_logoSize.height;
00202 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: UI contrast and settings/C++/common/suspensionmanager.h Source File

  • UI contrast and settings
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Search contract/C++/Scenario4.xaml.cpp Source File

  • Search contract

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::SearchContract;
00020
00021 using namespace Windows::ApplicationModel::Search;
00022 using namespace Windows::Foundation;
00023 using namespace Windows::Storage;
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 void Scenario4::SetLocalContentSuggestions(bool isLocal)
00034 {
00035     // Have Windows provide suggestions from local files.
00036     // This code should be placed in your apps global scope and run as soon as your app is launched.
00037     auto settings = ref new LocalContentSuggestionSettings();
00038     settings->Enabled = isLocal;
00039     if (isLocal)
00040     {
00041         settings->Locations->Append(KnownFolders::MusicLibrary);
00042         settings->AqsFilter = "kind:Music";
00043     }
00044     SearchPane::GetForCurrentView()->SetLocalContentSuggestionSettings(settings);
00045 }
00046
00047 void Scenario4::OnNavigatedTo(NavigationEventArgs^ e)
00048 {
00049     MainPage::Current->NotifyUser("Use the search pane to submit a query", NotifyType::StatusMessage);
00050     SetLocalContentSuggestions(true);
00051 }
00052
00053 void Scenario4::OnNavigatedFrom(NavigationEventArgs^ e)
00054 {
00055     SetLocalContentSuggestions(false);
00056 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Animation metrics/C++/MainPage.xaml.cpp Source File

  • Animation metrics

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML scrolling, panning, and zooming/C++/Scenario3.xaml.cpp Source File

  • XAML scrolling, panning, and zooming

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 SDKSample::ScrollViewerCPP;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 Scenario3::Scenario3()
00026 {
00027     InitializeComponent();
00028 }
00029
00030
00031 // Invoked when this page is about to be displayed in a Frame.
00032 void Scenario3::OnNavigatedTo(NavigationEventArgs^ e)
00033 {
00034     rootPage = MainPage::Current;
00035 }
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D convolve matrix effect/C++/ConvolveMatrixEffect.cpp Source File

  • Direct2D convolve matrix effect

ConvolveMatrixEffect.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 "ConvolveMatrixEffect.h"
00010
00011 using namespace Microsoft::WRL;
00012 using namespace Windows::ApplicationModel;
00013 using namespace Windows::ApplicationModel::Core;
00014 using namespace Windows::ApplicationModel::Activation;
00015 using namespace Windows::UI::Core;
00016 using namespace Windows::UI::Input;
00017 using namespace Windows::UI::Popups;
00018 using namespace Windows::System;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::Graphics::Display;
00022 using namespace Windows::Storage;
00023
00024 ConvolveMatrixEffect::ConvolveMatrixEffect() :
00025     m_selectedKernel(KernelSelection::Passthrough),
00026     m_imageSize(D2D1::SizeF()),
00027     m_bitmapPixelSize(D2D1::SizeU())
00028 {
00029 }
00030
00031 void ConvolveMatrixEffect::CreateDeviceIndependentResources()
00032 {
00033     DirectXBase::CreateDeviceIndependentResources();
00034
00035     // Decode the image using WIC. The output of the format converter
00036     // is accessible via m_wicConvertedSource.
00037     ComPtr<IWICBitmapDecoder> decoder;
00038     DX::ThrowIfFailed(
00039         m_wicFactory->CreateDecoderFromFilename(
00040             L"beach.jpg",
00041             nullptr,
00042             GENERIC_READ,
00043             WICDecodeMetadataCacheOnDemand,
00044             &decoder
00045             )
00046         );
00047
00048     ComPtr<IWICBitmapFrameDecode> frame;
00049     DX::ThrowIfFailed(
00050         decoder->GetFrame(0, &frame)
00051         );
00052
00053     // Store the image size in pixels. This remains constant regardless of the app's DPI.
00054     UINT width, height;
00055     DX::ThrowIfFailed(
00056         frame->GetSize(&width, &height)
00057         );
00058
00059     m_bitmapPixelSize = D2D1::SizeU(width, height);
00060
00061     DX::ThrowIfFailed(
00062         m_wicFactory->CreateFormatConverter(&m_wicConvertedSource)
00063         );
00064
00065     // Format convert to a pixel format that is compatible with Direct2D.
00066     DX::ThrowIfFailed(
00067         m_wicConvertedSource->Initialize(
00068             frame.Get(),
00069             GUID_WICPixelFormat32bppPBGRA,
00070             WICBitmapDitherTypeNone,
00071             nullptr,
00072             0.0f,
00073             WICBitmapPaletteTypeCustom
00074             )
00075         );
00076 }
00077
00078 void ConvolveMatrixEffect::CreateDeviceResources()
00079 {
00080     DirectXBase::CreateDeviceResources();
00081
00082     m_sampleOverlay = ref new SampleOverlay();
00083
00084     m_sampleOverlay->Initialize(
00085         m_d2dDevice.Get(),
00086         m_d2dContext.Get(),
00087         m_wicFactory.Get(),
00088         m_dwriteFactory.Get(),
00089         "Direct2D convolve matrix effect sample"
00090         );
00091
00092     // Use the BitmapSource effect to load the image from WIC and make it usable
00093     // in the Direct2D effects graph.
00094     DX::ThrowIfFailed(
00095         m_d2dContext->CreateEffect(CLSID_D2D1BitmapSource, &m_bitmapSourceEffect)
00096         );
00097
00098     DX::ThrowIfFailed(
00099         m_bitmapSourceEffect->SetValue(
00100             D2D1_BITMAPSOURCE_PROP_WIC_BITMAP_SOURCE,
00101             m_wicConvertedSource.Get()
00102             )
00103         );
00104
00105     // Cache the BitmapSource output as it never needs to change.
00106     DX::ThrowIfFailed(
00107         m_bitmapSourceEffect->SetValue(D2D1_PROPERTY_CACHED, TRUE)
00108         );
00109
00110     // Create the ConvolveMatrix effect and add it to the end of the effect graph.
00111     DX::ThrowIfFailed(
00112         m_d2dContext->CreateEffect(CLSID_D2D1ConvolveMatrix, &m_convolveMatrixEffect)
00113         );
00114
00115     m_convolveMatrixEffect->SetInputEffect(0, m_bitmapSourceEffect.Get());
00116 }
00117
00118 void ConvolveMatrixEffect::CreateWindowSizeDependentResources()
00119 {
00120     DirectXBase::CreateWindowSizeDependentResources();
00121
00122     D2D1_SIZE_F contextSize = m_d2dContext->GetSize();
00123
00124     // m_imageSize is in DIPs and changes depending on the app DPI.
00125     // This app ignores the source bitmap's DPI and assumes it is 96.
00126     m_imageSize = D2D1::SizeF(
00127         static_cast<float>(m_bitmapPixelSize.width) * 96.0f / m_dpi,
00128         static_cast<float>(m_bitmapPixelSize.height) * 96.0f / m_dpi
00129         );
00130
00131     // Resize the image to fit the screen.
00132     float zoom = max(
00133         contextSize.width / m_imageSize.width,
00134         contextSize.height / m_imageSize.height
00135         );
00136
00137     D2D1_VECTOR_2F zoomVector = D2D1::Vector2F(zoom, zoom);
00138     DX::ThrowIfFailed(
00139         m_bitmapSourceEffect->SetValue(D2D1_BITMAPSOURCE_PROP_SCALE, zoomVector)
00140         );
00141 }
00142
00143 void ConvolveMatrixEffect::Render()
00144 {
00145     // Select the convolution kernel and set up the ConvolveMatrix properties accordingly.
00146     // The kernel definitions and parameters are defined in ConvolutionKernels.h.
00147     switch (m_selectedKernel)
00148     {
00149         case KernelSelection::Passthrough:
00150             // Because D2D1_CONVOLVEMATRIX_PROP_KERNEL_MATRIX is a "BLOB" type in the
00151             // Direct2D property type system, we need to specify the byte size of the
00152             // data as the third parameter.
00153             DX::ThrowIfFailed(
00154                 m_convolveMatrixEffect->SetValue(
00155                     D2D1_CONVOLVEMATRIX_PROP_KERNEL_MATRIX,
00156                     (byte *) ConvolutionKernels::Passthrough,
00157                     sizeof(float) * ConvolutionKernels::PassthroughWidth *
00158                         ConvolutionKernels::PassthroughWidth
00159                     )
00160                 );
00161
00162             // Specify the size of the kernel.
00163             DX::ThrowIfFailed(
00164                 m_convolveMatrixEffect->SetValue(
00165                     D2D1_CONVOLVEMATRIX_PROP_KERNEL_SIZE_X,
00166                     ConvolutionKernels::PassthroughWidth
00167                     )
00168                 );
00169
00170             DX::ThrowIfFailed(
00171                 m_convolveMatrixEffect->SetValue(
00172                     D2D1_CONVOLVEMATRIX_PROP_KERNEL_SIZE_Y,
00173                     ConvolutionKernels::PassthroughWidth
00174                     )
00175                 );
00176
00177             // The divisor allows us to easily normalize a kernel's output. Many
00178             // common kernels have a divisor of 1 (the default value).
00179             DX::ThrowIfFailed(
00180                 m_convolveMatrixEffect->SetValue(
00181                     D2D1_CONVOLVEMATRIX_PROP_DIVISOR,
00182                     ConvolutionKernels::DefaultDivisor
00183                     )
00184                 );
00185             break;
00186
00187         case KernelSelection::BoxBlur:
00188             DX::ThrowIfFailed(
00189                 m_convolveMatrixEffect->SetValue(
00190                     D2D1_CONVOLVEMATRIX_PROP_KERNEL_MATRIX,
00191                     (byte *) ConvolutionKernels::BoxBlur,
00192                     sizeof(float) * ConvolutionKernels::BoxBlurWidth *
00193                         ConvolutionKernels::BoxBlurWidth
00194                     )
00195                 );
00196
00197             DX::ThrowIfFailed(
00198                 m_convolveMatrixEffect->SetValue(
00199                     D2D1_CONVOLVEMATRIX_PROP_KERNEL_SIZE_X,
00200                     ConvolutionKernels::BoxBlurWidth
00201                     )
00202                 );
00203
00204             DX::ThrowIfFailed(
00205                 m_convolveMatrixEffect->SetValue(
00206                     D2D1_CONVOLVEMATRIX_PROP_KERNEL_SIZE_Y,
00207                     ConvolutionKernels::BoxBlurWidth
00208                     )
00209                 );
00210
00211             DX::ThrowIfFailed(
00212                 m_convolveMatrixEffect->SetValue(
00213                     D2D1_CONVOLVEMATRIX_PROP_DIVISOR,
00214                     ConvolutionKernels::BoxBlurDivisor
00215                     )
00216                 );
00217             break;
00218
00219         case KernelSelection::SimpleEdgeDetect:
00220             DX::ThrowIfFailed(
00221                 m_convolveMatrixEffect->SetValue(
00222                     D2D1_CONVOLVEMATRIX_PROP_KERNEL_MATRIX,
00223                     (byte *) ConvolutionKernels::SimpleEdgeDetect,
00224                     sizeof(float) * ConvolutionKernels::SimpleEdgeDetectWidth *
00225                         ConvolutionKernels::SimpleEdgeDetectWidth
00226                     )
00227                 );
00228
00229             DX::ThrowIfFailed(
00230                 m_convolveMatrixEffect->SetValue(
00231                     D2D1_CONVOLVEMATRIX_PROP_KERNEL_SIZE_X,
00232                     ConvolutionKernels::SimpleEdgeDetectWidth
00233                     )
00234                 );
00235
00236             DX::ThrowIfFailed(
00237                 m_convolveMatrixEffect->SetValue(
00238                     D2D1_CONVOLVEMATRIX_PROP_KERNEL_SIZE_Y,
00239                     ConvolutionKernels::SimpleEdgeDetectWidth
00240                     )
00241                 );
00242
00243             DX::ThrowIfFailed(
00244                 m_convolveMatrixEffect->SetValue(
00245                     D2D1_CONVOLVEMATRIX_PROP_DIVISOR,
00246                     ConvolutionKernels::DefaultDivisor
00247                     )
00248                 );
00249             break;
00250
00251         case KernelSelection::SimpleSharpen:
00252             DX::ThrowIfFailed(
00253                 m_convolveMatrixEffect->SetValue(
00254                     D2D1_CONVOLVEMATRIX_PROP_KERNEL_MATRIX,
00255                     (byte *) ConvolutionKernels::SimpleSharpen,
00256                     sizeof(float) * ConvolutionKernels::SimpleSharpenWidth *
00257                         ConvolutionKernels::SimpleSharpenWidth
00258                     )
00259                 );
00260
00261             DX::ThrowIfFailed(
00262                 m_convolveMatrixEffect->SetValue(
00263                     D2D1_CONVOLVEMATRIX_PROP_KERNEL_SIZE_X,
00264                     ConvolutionKernels::SimpleSharpenWidth
00265                     )
00266                 );
00267
00268             DX::ThrowIfFailed(
00269                 m_convolveMatrixEffect->SetValue(
00270                     D2D1_CONVOLVEMATRIX_PROP_KERNEL_SIZE_Y,
00271                     ConvolutionKernels::SimpleSharpenWidth
00272                     )
00273                 );
00274
00275             DX::ThrowIfFailed(
00276                 m_convolveMatrixEffect->SetValue(
00277                     D2D1_CONVOLVEMATRIX_PROP_DIVISOR,
00278                     ConvolutionKernels::SimpleSharpenDivisor
00279                     )
00280                 );
00281             break;
00282
00283         case KernelSelection::Emboss:
00284             DX::ThrowIfFailed(
00285                 m_convolveMatrixEffect->SetValue(
00286                     D2D1_CONVOLVEMATRIX_PROP_KERNEL_MATRIX,
00287                     (byte *) ConvolutionKernels::Emboss,
00288                     sizeof(float) * ConvolutionKernels::EmbossWidth *
00289                         ConvolutionKernels::EmbossWidth
00290                     )
00291                 );
00292
00293             DX::ThrowIfFailed(
00294                 m_convolveMatrixEffect->SetValue(
00295                     D2D1_CONVOLVEMATRIX_PROP_KERNEL_SIZE_X,
00296                     ConvolutionKernels::EmbossWidth
00297                     )
00298                 );
00299
00300             DX::ThrowIfFailed(
00301                 m_convolveMatrixEffect->SetValue(
00302                     D2D1_CONVOLVEMATRIX_PROP_KERNEL_SIZE_Y,
00303                     ConvolutionKernels::EmbossWidth
00304                     )
00305                 );
00306
00307             DX::ThrowIfFailed(
00308                 m_convolveMatrixEffect->SetValue(
00309                     D2D1_CONVOLVEMATRIX_PROP_DIVISOR,
00310                     ConvolutionKernels::DefaultDivisor
00311                     )
00312                 );
00313             break;
00314
00315         case KernelSelection::HorizontalSmear:
00316             DX::ThrowIfFailed(
00317                 m_convolveMatrixEffect->SetValue(
00318                     D2D1_CONVOLVEMATRIX_PROP_KERNEL_MATRIX,
00319                     (byte *) ConvolutionKernels::HorizontalSmear,
00320                     sizeof(float) * ConvolutionKernels::HorizontalSmearWidth *
00321                         ConvolutionKernels::HorizontalSmearHeight
00322                     )
00323                 );
00324
00325             DX::ThrowIfFailed(
00326                 m_convolveMatrixEffect->SetValue(
00327                     D2D1_CONVOLVEMATRIX_PROP_KERNEL_SIZE_X,
00328                     ConvolutionKernels::HorizontalSmearWidth
00329                     )
00330                 );
00331
00332             // The horizontal smear kernel has a different width and height.
00333             DX::ThrowIfFailed(
00334                 m_convolveMatrixEffect->SetValue(
00335                     D2D1_CONVOLVEMATRIX_PROP_KERNEL_SIZE_Y,
00336                     ConvolutionKernels::HorizontalSmearHeight
00337                     )
00338                 );
00339
00340             DX::ThrowIfFailed(
00341                 m_convolveMatrixEffect->SetValue(
00342                     D2D1_CONVOLVEMATRIX_PROP_DIVISOR,
00343                     ConvolutionKernels::HorizontalSmearDivisor
00344                     )
00345                 );
00346             break;
00347
00348         default:
00349             throw ref new Platform::FailureException();
00350     }
00351
00352     m_d2dContext->BeginDraw();
00353
00354     m_d2dContext->DrawImage(
00355         m_convolveMatrixEffect.Get(),
00356         D2D1_INTERPOLATION_MODE_LINEAR,
00357         D2D1_COMPOSITE_MODE_SOURCE_COPY
00358         );
00359
00360     // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00361     // is lost. It will be handled during the next call to Present.
00362     HRESULT hr = m_d2dContext->EndDraw();
00363     if (hr != D2DERR_RECREATE_TARGET)
00364     {
00365         DX::ThrowIfFailed(hr);
00366     }
00367
00368     m_sampleOverlay->Render();
00369 }
00370
00371 void ConvolveMatrixEffect::Initialize(
00372     _In_ CoreApplicationView^ applicationView
00373     )
00374 {
00375     applicationView->Activated +=
00376         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(
00377             this,
00378             &ConvolveMatrixEffect::OnActivated
00379             );
00380
00381     CoreApplication::Suspending +=
00382         ref new EventHandler<SuspendingEventArgs^>(this, &ConvolveMatrixEffect::OnSuspending);
00383
00384     CoreApplication::Resuming +=
00385         ref new EventHandler<Platform::Object^>(this, &ConvolveMatrixEffect::OnResuming);
00386 }
00387
00388 void ConvolveMatrixEffect::SetWindow(
00389     _In_ CoreWindow^ window
00390     )
00391 {
00392     window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
00393
00394     window->SizeChanged +=
00395         ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &ConvolveMatrixEffect::OnWindowSizeChanged);
00396
00397     window->PointerPressed +=
00398         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &ConvolveMatrixEffect::OnPointerPressed);
00399
00400     window->PointerReleased +=
00401         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &ConvolveMatrixEffect::OnPointerReleased);
00402
00403     window->PointerMoved +=
00404         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &ConvolveMatrixEffect::OnPointerMoved);
00405
00406     m_gestureRecognizer = ref new GestureRecognizer();
00407     m_gestureRecognizer->GestureSettings = GestureSettings::Hold;
00408
00409     m_gestureRecognizer->Holding +=
00410         ref new TypedEventHandler<GestureRecognizer^, HoldingEventArgs^>(this, &ConvolveMatrixEffect::OnHolding);
00411
00412     DisplayProperties::LogicalDpiChanged +=
00413         ref new DisplayPropertiesEventHandler(this, &ConvolveMatrixEffect::OnLogicalDpiChanged);
00414
00415     DisplayProperties::DisplayContentsInvalidated +=
00416         ref new DisplayPropertiesEventHandler(this, &ConvolveMatrixEffect::OnDisplayContentsInvalidated);
00417
00418     DirectXBase::Initialize(window, DisplayProperties::LogicalDpi);
00419 }
00420
00421 void ConvolveMatrixEffect::Load(
00422     _In_ Platform::String^ entryPoint
00423     )
00424 {
00425     IPropertySet^ appSettings = ApplicationData::Current->LocalSettings->Values;
00426
00427     if (appSettings->HasKey("kernelIndex"))
00428     {
00429         m_selectedKernel = static_cast<KernelSelection>(
00430             safe_cast<IPropertyValue^>(appSettings->Lookup("kernelIndex"))->GetUInt32()
00431             );
00432     }
00433 }
00434
00435 void ConvolveMatrixEffect::Run()
00436 {
00437     Render();
00438     Present();
00439
00440     m_window->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessUntilQuit);
00441 }
00442
00443 void ConvolveMatrixEffect::Uninitialize()
00444 {
00445 }
00446
00447 void ConvolveMatrixEffect::OnWindowSizeChanged(
00448     _In_ CoreWindow^ sender,
00449     _In_ WindowSizeChangedEventArgs^ args
00450     )
00451 {
00452     UpdateForWindowSizeChange();
00453     m_sampleOverlay->UpdateForWindowSizeChange();
00454     Render();
00455     Present();
00456 }
00457
00458 void ConvolveMatrixEffect::OnLogicalDpiChanged(
00459     _In_ Platform::Object^ sender
00460     )
00461 {
00462     SetDpi(DisplayProperties::LogicalDpi);
00463     Render();
00464     Present();
00465 }
00466
00467 void ConvolveMatrixEffect::OnDisplayContentsInvalidated(
00468     _In_ Platform::Object^ sender
00469     )
00470 {
00471     // Ensure the D3D Device is available for rendering.
00472     ValidateDevice();
00473
00474     Render();
00475     Present();
00476 }
00477
00478 void ConvolveMatrixEffect::OnActivated(
00479     _In_ CoreApplicationView^ applicationView,
00480     _In_ IActivatedEventArgs^ args
00481     )
00482 {
00483     m_window->Activate();
00484 }
00485
00486 void ConvolveMatrixEffect::OnSuspending(
00487     _In_ Platform::Object^ sender,
00488     _In_ SuspendingEventArgs^ args
00489     )
00490 {
00491     // This state is restored during Load in the event that the app is terminated.
00492
00493     IPropertySet^ appSettings = ApplicationData::Current->LocalSettings->Values;
00494
00495     if (appSettings->HasKey("kernelIndex"))
00496     {
00497         appSettings->Remove("kernelIndex");
00498     }
00499
00500     appSettings->Insert(
00501         "kernelIndex",
00502         PropertyValue::CreateUInt32(static_cast<unsigned int>(m_selectedKernel))
00503         );
00504 }
00505
00506 void ConvolveMatrixEffect::OnResuming(
00507     _In_ Platform::Object^ sender,
00508     _In_ Platform::Object^ args
00509     )
00510 {
00511 }
00512
00513 void ConvolveMatrixEffect::OnPointerPressed(
00514     _In_ CoreWindow^ sender,
00515     _In_ PointerEventArgs^ args
00516     )
00517 {
00518     m_gestureRecognizer->ProcessDownEvent(args->CurrentPoint);
00519 }
00520
00521 void ConvolveMatrixEffect::OnPointerMoved(
00522     _In_ CoreWindow^ sender,
00523     _In_ PointerEventArgs^ args
00524     )
00525 {
00526     m_gestureRecognizer->ProcessMoveEvents(args->GetIntermediatePoints());
00527 }
00528
00529 void ConvolveMatrixEffect::OnPointerReleased(
00530     _In_ CoreWindow^ sender,
00531     _In_ PointerEventArgs^ args
00532     )
00533 {
00534     m_gestureRecognizer->ProcessUpEvent(args->CurrentPoint);
00535
00536     if (args->CurrentPoint->Properties->PointerUpdateKind == PointerUpdateKind::RightButtonReleased)
00537     {
00538         ShowMenu(args->CurrentPoint->Position);
00539     }
00540 }
00541
00542 void ConvolveMatrixEffect::OnHolding(
00543     _In_ GestureRecognizer^ sender,
00544     _In_ HoldingEventArgs^ args
00545     )
00546 {
00547     if (args->HoldingState == HoldingState::Started)
00548     {
00549         ShowMenu(args->Position);
00550     }
00551 }
00552
00553 void ConvolveMatrixEffect::ShowMenu(Point position)
00554 {
00555     PopupMenu^ popupMenu = ref new PopupMenu();
00556
00557     popupMenu->Commands->Append(
00558         ref new UICommand(
00559             ConvolutionKernels::PassthroughTitle,
00560             ref new UICommandInvokedHandler(this, &ConvolveMatrixEffect::SwitchKernel)
00561             )
00562         );
00563
00564     popupMenu->Commands->Append(
00565         ref new UICommand(
00566             ConvolutionKernels::BoxBlurTitle,
00567             ref new UICommandInvokedHandler(this, &ConvolveMatrixEffect::SwitchKernel)
00568             )
00569         );
00570
00571     popupMenu->Commands->Append(
00572         ref new UICommand(
00573             ConvolutionKernels::SimpleEdgeDetectTitle,
00574             ref new UICommandInvokedHandler(this, &ConvolveMatrixEffect::SwitchKernel)
00575             )
00576         );
00577
00578     popupMenu->Commands->Append(
00579         ref new UICommand(
00580             ConvolutionKernels::SimpleSharpenTitle,
00581             ref new UICommandInvokedHandler(this, &ConvolveMatrixEffect::SwitchKernel)
00582             )
00583         );
00584
00585     popupMenu->Commands->Append(
00586         ref new UICommand(
00587             ConvolutionKernels::EmbossTitle,
00588             ref new UICommandInvokedHandler(this, &ConvolveMatrixEffect::SwitchKernel)
00589             )
00590         );
00591
00592     popupMenu->Commands->Append(
00593         ref new UICommand(
00594             ConvolutionKernels::HorizontalSmearTitle,
00595             ref new UICommandInvokedHandler(this, &ConvolveMatrixEffect::SwitchKernel)
00596             )
00597         );
00598
00599     popupMenu->ShowAsync(position);
00600 }
00601
00602 // When the user selects a convolution kernel from the popup menu, update the ConvolveMatrix
00603 // properties and render the output.
00604 void ConvolveMatrixEffect::SwitchKernel(
00605     _In_ IUICommand^ command
00606     )
00607 {
00608     if (command->Label == ConvolutionKernels::PassthroughTitle)
00609     {
00610         m_selectedKernel = KernelSelection::Passthrough;
00611     }
00612     else if (command->Label == ConvolutionKernels::BoxBlurTitle)
00613     {
00614         m_selectedKernel = KernelSelection::BoxBlur;
00615     }
00616     else if (command->Label == ConvolutionKernels::SimpleEdgeDetectTitle)
00617     {
00618         m_selectedKernel = KernelSelection::SimpleEdgeDetect;
00619     }
00620     else if (command->Label == ConvolutionKernels::SimpleSharpenTitle)
00621     {
00622         m_selectedKernel = KernelSelection::SimpleSharpen;
00623     }
00624     else if (command->Label == ConvolutionKernels::EmbossTitle)
00625     {
00626         m_selectedKernel = KernelSelection::Emboss;
00627     }
00628     else if (command->Label == ConvolutionKernels::HorizontalSmearTitle)
00629     {
00630         m_selectedKernel = KernelSelection::HorizontalSmear;
00631     }
00632
00633     Render();
00634     Present();
00635 }
00636
00637 IFrameworkView^ DirectXAppSource::CreateView()
00638 {
00639     return ref new ConvolveMatrixEffect();
00640 }
00641
00642 [Platform::MTAThread]
00643 int main(Platform::Array<Platform::String^>^)
00644 {
00645     auto directXAppSource = ref new DirectXAppSource();
00646     CoreApplication::Run(directXAppSource);
00647     return 0;
00648 }
Generated on Sat Nov 23 2024 16:08:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Reading and writing data/C++/App.xaml.h Source File

  • Reading and writing data

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/DirectXBase.h Source File

  • XAML DirectX 3D shooting game

DirectXBase.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 "DirectXSample.h"
00011
00012 ref class DirectXBase;
00013 delegate void D3DDeviceEventHandler();
00014
00015 // Helper class that initializes DirectX APIs for both 2D and 3D rendering.
00016 // Some of the code in this class may be omitted if only 2D or only 3D rendering is being used.
00017 ref class DirectXBase abstract
00018 {
00019 internal:
00020     DirectXBase();
00021
00022     virtual void Initialize(
00023         Windows::UI::Core::CoreWindow^ window,
00024         Windows::UI::Xaml::Controls::SwapChainBackgroundPanel^ swapChainPanel,
00025         float dpi
00026         );
00027     virtual void HandleDeviceLost();
00028     virtual void CreateDeviceIndependentResources();
00029     virtual void CreateDeviceResources();
00030     virtual void SetDpi(float dpi);
00031     virtual void UpdateForWindowSizeChange();
00032     virtual void CreateWindowSizeDependentResources();
00033     virtual void Render() = 0;
00034     virtual void Present();
00035     virtual float ConvertDipsToPixels(float dips);
00036
00037     event D3DDeviceEventHandler^ DeviceLost;
00038     event D3DDeviceEventHandler^ DeviceReset;
00039
00040 protected private:
00041     void OnStereoEnabledChanged(
00042         _In_ Platform::Object^ sender
00043         );
00044     void CheckStereoEnabledStatus();
00045
00046     Platform::Agile<Windows::UI::Core::CoreWindow>  m_window;
00047     Windows::UI::Xaml::Controls::SwapChainBackgroundPanel^ m_swapChainPanel;
00048
00049     // DirectWrite & Windows Imaging Component Objects.
00050     Microsoft::WRL::ComPtr<IDWriteFactory1>         m_dwriteFactory;
00051     Microsoft::WRL::ComPtr<IWICImagingFactory2>     m_wicFactory;
00052
00053     // DirectX Core Objects. Required for 2D and 3D.
00054     Microsoft::WRL::ComPtr<ID3D11Device1>           m_d3dDevice;
00055     Microsoft::WRL::ComPtr<ID3D11DeviceContext1>    m_d3dContext;
00056     Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00057     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00058     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetViewRight;
00059
00060     // Direct2D Rendering Objects. Required for 2D.
00061     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00062     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00063     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00064     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmap;
00065     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmapRight;
00066
00067     // Direct3D Rendering Objects. Required for 3D.
00068     Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00069
00070     // Cached renderer properties.
00071     D3D_FEATURE_LEVEL                               m_featureLevel;
00072     Windows::Foundation::Size                       m_renderTargetSize;
00073     Windows::Foundation::Rect                       m_windowBounds;
00074     float                                           m_dpi;
00075     Windows::Graphics::Display::DisplayOrientations m_orientation;
00076     bool                                            m_stereoEnabled;
00077
00078     // Transforms used for display orientation.
00079     D2D1::Matrix3x2F                                m_rotationTransform2D;
00080     DirectX::XMFLOAT4X4                             m_rotationTransform3D;
00081 };
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML scrolling, panning, and zooming/C++/MainPage.xaml.cpp Source File

  • XAML scrolling, panning, and zooming

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Clipboard app/C++/CopyFiles.xaml.h Source File

  • Clipboard app

CopyFiles.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 // CopyFiles.xaml.h
00013 // Declaration of the CopyFiles class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "CopyFiles.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace Clipboard
00023 {
00024     [Windows::Foundation::Metadata::WebHostHidden]
00025     public ref class CopyFiles sealed
00026     {
00027     public:
00028         CopyFiles();
00029
00030     protected:
00031         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00032
00033     private:
00034         MainPage^ rootPage;
00035
00036         void CopyButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00037         void PasteButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038     };
00039 }
Generated on Sat Nov 23 2024 16:07:58 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/Camera.h Source File

  • XAML DirectX 3D shooting game

Camera.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 // Camera:
00011 // This class defines the position, orientation and viewing frustum of a camera looking into
00012 // a 3D world.  It will generate both the View matrix and Projection matrix.  It can also
00013 // provide a pair of Projection matrices to be used when stereoscopic 3D is used.
00014
00015 ref class Camera
00016 {
00017 internal:
00018     Camera();
00019
00020     void SetViewParams(_In_ DirectX::XMFLOAT3 eye, _In_ DirectX::XMFLOAT3 lookAt, _In_ DirectX::XMFLOAT3 up);
00021     void SetProjParams(_In_ float fieldOfView, _In_ float aspectRatio, _In_ float nearPlane, _In_ float farPlane);
00022
00023     void LookDirection (_In_ DirectX::XMFLOAT3 lookDirection);
00024     void Eye (_In_ DirectX::XMFLOAT3 position);
00025
00026     DirectX::XMMATRIX View();
00027     DirectX::XMMATRIX Projection();
00028     DirectX::XMMATRIX LeftEyeProjection();
00029     DirectX::XMMATRIX RightEyeProjection();
00030     DirectX::XMMATRIX World();
00031     DirectX::XMFLOAT3 Eye();
00032     DirectX::XMFLOAT3 LookAt();
00033     DirectX::XMFLOAT3 Up();
00034     float NearClipPlane();
00035     float FarClipPlane();
00036     float Pitch();
00037     float Yaw();
00038
00039 protected private:
00040     DirectX::XMFLOAT4X4 m_viewMatrix;
00041     DirectX::XMFLOAT4X4 m_projectionMatrix;
00042     DirectX::XMFLOAT4X4 m_projectionMatrixLeft;
00043     DirectX::XMFLOAT4X4 m_projectionMatrixRight;
00044
00045     DirectX::XMFLOAT4X4 m_inverseView;
00046
00047     DirectX::XMFLOAT3 m_eye;
00048     DirectX::XMFLOAT3 m_lookAt;
00049     DirectX::XMFLOAT3 m_up;
00050     float             m_cameraYawAngle;
00051     float             m_cameraPitchAngle;
00052
00053     float             m_fieldOfView;
00054     float             m_aspectRatio;
00055     float             m_nearPlane;
00056     float             m_farPlane;
00057 };
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX postcard app/C++/pch.cpp Source File

  • DirectX postcard app

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 //
00009 // Include the standard header and generate the precompiled header.
00010 //
00011
00012 #include "pch.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/MediaExtensions/Polar/dllmain.cpp Source File

  • Media extensions
  • MediaExtensions
  • Polar

dllmain.cpp

Go to the documentation of this file.
00001 //////////////////////////////////////////////////////////////////////////
00002 //
00003 // dllmain.cpp
00004 //
00005 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00007 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00008 // PARTICULAR PURPOSE.
00009 //
00010 // Copyright (c) Microsoft Corporation. All rights reserved.
00011 //
00012 //////////////////////////////////////////////////////////////////////////
00013
00014 #include <initguid.h>
00015 #include "PolarEffect.h"
00016
00017 namespace Microsoft { namespace Samples {
00018     ActivatableClass(CPolarEffect);
00019 }}
00020
00021 BOOL WINAPI DllMain( _In_ HINSTANCE hInstance, _In_ DWORD dwReason, _In_opt_ LPVOID lpReserved )
00022 {
00023     if( DLL_PROCESS_ATTACH == dwReason )
00024     {
00025         //
00026         //  Don't need per-thread callbacks
00027         //
00028         DisableThreadLibraryCalls( hInstance );
00029
00030         Module<InProc>::GetModule().Create();
00031     }
00032     else if( DLL_PROCESS_DETACH == dwReason )
00033     {
00034         Module<InProc>::GetModule().Terminate();
00035     }
00036
00037     return TRUE;
00038 }
00039
00040 HRESULT WINAPI DllGetActivationFactory( _In_ HSTRING activatibleClassId, _Outptr_ IActivationFactory** factory )
00041 {
00042     auto &module = Microsoft::WRL::Module< Microsoft::WRL::InProc >::GetModule();
00043     return module.GetActivationFactory( activatibleClassId, factory );
00044 }
00045
00046 HRESULT WINAPI DllCanUnloadNow()
00047 {
00048     auto &module = Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule();
00049     return (module.Terminate()) ? S_OK : S_FALSE;
00050 }
00051
00052 STDAPI DllGetClassObject( _In_ REFCLSID rclsid, _In_ REFIID riid, _Outptr_ LPVOID FAR* ppv )
00053 {
00054     auto &module = Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule();
00055     return module.GetClassObject( rclsid, riid, ppv );
00056 }
Generated on Sat Nov 23 2024 16:08:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media Server client/C++/common/LayoutAwarePage.cpp Source File

  • Media Server client
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:32 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Date and time formatting/C++/pch.h Source File

  • Date and time formatting

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX marble maze game/C++/PersistentState.h Source File

  • DirectX marble maze game

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 Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Touch hit testing/C++/Shape.h Source File

  • Input Touch hit testing

Shape.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 //
00011 // Definitions
00012 //
00013 int const MAX_POLY_VERTICES = 50;  // Maximal number of points in polygonal shape
00014 int const CURSOR_ID_NONE = -1;     // Identifier of no input
00015
00016 // Polygonal shape structure
00017 struct Polygon
00018 {
00019     bool isRect;   // Is the polygon rectangle
00020     int numPoints; // Number of vertices in polgyon
00021     Windows::Foundation::Point points[MAX_POLY_VERTICES]; // Polygon vertices
00022     Windows::Foundation::Rect rcBound;                    // Polygon bounding box
00023 };
00024
00025 // Shape class represents a windowless control that are touch interactable.
00026 //
00027 // Shape has following properties:
00028 //     1) It can be control or regular object
00029 //     2) It can be draggable with pointer
00030 //     3) It has polygonal shape
00031 //
00032 // Shape can be scaled and translated on the screen.
00033 class Shape
00034 {
00035 public:
00036     Shape();
00037     ~Shape();
00038
00039     // Initialize shape
00040     void InitializeObject(_In_reads_(numPoints) Windows::Foundation::Point const* points, _In_ int numPoints,
00041                           _In_ D2D1::ColorF color);
00042
00043     // Reset shape to it's start position
00044     void ResetState(_In_ float startX, _In_ float startY,
00045                     _In_ float width, _In_ float height,
00046                     _In_ float scale);
00047
00048     // Draw the shape
00049     void Paint(_In_ ID2D1DeviceContext* d2dDeviceContext);
00050
00051     // Hit test point - returns true if point is within shape
00052     bool InRegion(Windows::Foundation::Point pt);
00053
00054     // Respond to input event
00055     void OnPointerEvent(_In_ Windows::Foundation::Point pt, bool shouldMove);
00056
00057     // Properties
00058     Polygon* GetPolygon();
00059
00060 private:
00061     // Rendering
00062     Microsoft::WRL::ComPtr<ID2D1PathGeometry> m_pathGeometry;
00063
00064     // Rendered top, left coordinates of object
00065     float m_topLeftX;
00066     float m_topLeftY;
00067
00068     // Client (parent window) width and height
00069     float m_width;
00070     float m_height;
00071
00072     // How much shape is scaled
00073     float m_scale;
00074
00075     // Object shape in relative coordinates (before scaling and translation)
00076     Polygon m_polygonRelative;
00077     // Object shape in absolute coordinates (scaling and translation applied)
00078     Polygon m_polygonAbsolute;
00079
00080     // Object colors
00081     D2D1::ColorF m_color;
00082
00083     // Pixel location where last pointer event occurred
00084     Windows::Foundation::Point m_ptPointerPosition;
00085
00086     // Move the object on the screen
00087     void EnsureVisible();
00088     void Translate(_In_ float fdx, _In_ float fdy);
00089
00090     // Helper functions to deal with scaled object
00091     void UnscaledToClient(_In_ Windows::Foundation::Point ptUnscaled, _Inout_ Windows::Foundation::Point* pptClient);
00092     void UnscaledToClient(_In_ Windows::Foundation::Rect rcUnscaled, _Inout_ Windows::Foundation::Rect* prcClient);
00093     D2D1_POINT_2F UnscaledToClient(_In_ Windows::Foundation::Point ptUnscaled);
00094     D2D1_RECT_F UnscaledToClient(_In_ Windows::Foundation::Rect rcUnscaled);
00095 };
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SimpleCommunication::sealed Member List

This is the complete list of members for SimpleCommunication::sealed, including all inherited members.
__pad0__ | SimpleCommunication::sealed | [protected]
_active | SimpleCommunication::sealed | [private]
_currentScenario | SimpleCommunication::sealed | [private]
_currentState | SimpleCommunication::sealed | [private]
_device | SimpleCommunication::sealed | [private]
_dispatcher | SimpleCommunication::sealed | [private]
_incomingConnectionEventRegistrationToken | SimpleCommunication::sealed | [private]
_initialization | SimpleCommunication::sealed | [private]
_initialized | SimpleCommunication::sealed | [private]
_isTerminator | SimpleCommunication::sealed | [private]
_latencyMode | SimpleCommunication::sealed | [private]
_localHostVideo | SimpleCommunication::sealed | [private]
_mediaCapture | SimpleCommunication::sealed | [private]
_mediaCaptureFailedEventRegistrationToken | SimpleCommunication::sealed | [private]
_mediaElementFailedEventRegistrationToken | SimpleCommunication::sealed | [private]
_mediaExtensionMgr | SimpleCommunication::sealed | [private]
_mediaSink | SimpleCommunication::sealed | [private]
_mediaSinkIncomingConnectionEventRegistrationToken | SimpleCommunication::sealed | [private]
_navigationDisabled | SimpleCommunication::sealed | [private]
_previousState | SimpleCommunication::sealed | [private]
_recordingStarted | SimpleCommunication::sealed | [private]
_role | SimpleCommunication::sealed | [private]
_rootPage | SimpleCommunication::sealed | [private]
_sdkSample | SimpleCommunication::sealed | [private]
_streamFilteringCriteria | SimpleCommunication::sealed | [private]
_videoSettingsFilter | SimpleCommunication::sealed | [private]
ActionTransition() | SimpleCommunication::sealed | [private]
actionTransitionFunctions | SimpleCommunication::sealed | [private]
active enum value | SimpleCommunication::sealed | [private]
autoSizeInputSectionWhenSnapped | SimpleCommunication::sealed | [private]
CallButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SimpleCommunication::sealed | [private]
CaptureDevice() | SimpleCommunication::sealed | [private]
CleanUp() | SimpleCommunication::sealed | [private]
Cleanup() | SimpleCommunication::sealed | [private]
CleanupAsync() | SimpleCommunication::sealed | [private]
CleanupSink() | SimpleCommunication::sealed | [private]
Deactivate() | SimpleCommunication::sealed | [private]
DoCleanup() | SimpleCommunication::sealed | [private]
end enum value | SimpleCommunication::sealed | [private]
EndCall() | SimpleCommunication::sealed | [private]
EndCallButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SimpleCommunication::sealed | [private]
Footer_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SimpleCommunication::sealed | [private]
HiddenFrame | SimpleCommunication::sealed | [private]
highLatency enum value | SimpleCommunication::sealed | [private]
Incomingconnectionevent | SimpleCommunication::sealed | [private]
Initialize() | SimpleCommunication::sealed | [private]
Initialize() | SimpleCommunication::sealed | [private]
InitializeAsync() | SimpleCommunication::sealed | [private]
InitializeUIControls() | SimpleCommunication::sealed | [private]
initializing enum value | SimpleCommunication::sealed | [private]
initializing_previewSetupCompleted() | SimpleCommunication::sealed | [private]
InvalidateSize() | SimpleCommunication::sealed | [private]
InvalidateViewState() | SimpleCommunication::sealed | [private]
LatencyModes enum name | SimpleCommunication::sealed | [private]
LatencyModeToggled(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SimpleCommunication::sealed | [private]
LoadScenario(Platform::String^scenarioName) | SimpleCommunication::sealed |
LocalClientButtonClicked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SimpleCommunication::sealed | [private]
LockScenarioChange() | SimpleCommunication::sealed |
LowLatency() | SimpleCommunication::sealed |
lowLatency enum value | SimpleCommunication::sealed | [private]
m_visibilityEventRegistrationToken | SimpleCommunication::sealed | [private]
MainPage() | SimpleCommunication::sealed |
MainPage_SizeChanged(Object^sender, Windows::UI::Xaml::SizeChangedEventArgs^e) | SimpleCommunication::sealed | [protected]
MainPageResized | SimpleCommunication::sealed |
NavigatingPrevented() | SimpleCommunication::sealed |
NotifyUser(Platform::String^strMessage, NotifyType type) | SimpleCommunication::sealed |
OnCaptureFailed(Windows::Media::Capture::MediaCapture^sender, Windows::Media::Capture::MediaCaptureFailedEventArgs^errorEventArgs) | SimpleCommunication::sealed | [inline, private]
OnIncomingConnection(Microsoft::Samples::SimpleCommunication::StspMediaSink^sender, Microsoft::Samples::SimpleCommunication::IncomingConnectionEventArgs^args) | SimpleCommunication::sealed | [private]
OnIncomingConnection(Microsoft::Samples::SimpleCommunication::StspMediaSink^sender, Microsoft::Samples::SimpleCommunication::IncomingConnectionEventArgs^args) | SimpleCommunication::sealed | [inline, private]
OnIncomingConnection(Microsoft::Samples::SimpleCommunication::StspMediaSink^sender, Microsoft::Samples::SimpleCommunication::IncomingConnectionEventArgs^args) | SimpleCommunication::sealed | [private]
OnInitializeCompleted(Windows::Foundation::HResult hr) | SimpleCommunication::sealed | [private]
OnInitializeCompletedDispatchedHandler() | SimpleCommunication::sealed | [private]
OnMediaCaptureFailed(CaptureDevice^sender, CaptureFailedEventArgs^errorEventArgs) | SimpleCommunication::sealed | [private]
OnMediaCaptureFailed(CaptureDevice^sender, CaptureFailedEventArgs^errorEventArgs) | SimpleCommunication::sealed | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SimpleCommunication::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SimpleCommunication::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SimpleCommunication::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SimpleCommunication::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SimpleCommunication::sealed | [protected, virtual]
OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^e) override | SimpleCommunication::sealed | [protected, virtual]
OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^e) override | SimpleCommunication::sealed | [protected, virtual]
passive enum value | SimpleCommunication::sealed | [private]
PopulateScenarios() | SimpleCommunication::sealed | [private]
PreviewButtonClicked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SimpleCommunication::sealed | [private]
previewing enum value | SimpleCommunication::sealed | [private]
previewing_localClientButtonClicked() | SimpleCommunication::sealed | [private]
previewing_previewButtonClicked() | SimpleCommunication::sealed | [private]
previewing_recordingStarted() | SimpleCommunication::sealed | [private]
Reset() | SimpleCommunication::sealed | [private]
Role enum name | SimpleCommunication::sealed | [private]
ScenarioList | SimpleCommunication::sealed | [private]
ScenarioLoaded | SimpleCommunication::sealed |
ScenarioOneStates enum name | SimpleCommunication::sealed | [private]
Scenarios_SelectionChanged(Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | SimpleCommunication::sealed | [protected]
SelectPreferredCameraStreamSettingAsync(Windows::Media::Capture::MediaStreamType mediaStreamType, VideoSettingsFilter^settingsFilterFunc) | SimpleCommunication::sealed | [private]
SetCurrentScenario(Platform::String^scenario) | SimpleCommunication::sealed |
SetFeatureName(Platform::String^strFeature) | SimpleCommunication::sealed | [private]
StartRecordingAsync(Windows::Media::MediaProperties::MediaEncodingProfile^mediaEncodingProfile) | SimpleCommunication::sealed | [private]
StartRecordingToCustomSink() | SimpleCommunication::sealed | [private]
StartRecordingToCustomSinkAsync() | SimpleCommunication::sealed | [private]
StopRecordingAsync() | SimpleCommunication::sealed | [private]
streaming enum value | SimpleCommunication::sealed | [private]
streaming_latencyModeToggled() | SimpleCommunication::sealed | [private]
streaming_previewButtonClicked() | SimpleCommunication::sealed | [private]
streaming_recordingStarted() | SimpleCommunication::sealed | [private]
uninitialized enum value | SimpleCommunication::sealed | [private]
UnlockScenarioChange() | SimpleCommunication::sealed |
UpdateLocalClientWindow() | SimpleCommunication::sealed | [private]
VideoChat() | SimpleCommunication::sealed |
VideoPlaybackErrorHandler(Platform::Object^sender, Windows::UI::Xaml::ExceptionRoutedEventArgs^e) | SimpleCommunication::sealed | [private]
VisibilityChanged(Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | SimpleCommunication::sealed | [protected]
waiting enum value | SimpleCommunication::sealed | [private]
waiting_previewButtonClicked() | SimpleCommunication::sealed | [private]
~MainPage() | SimpleCommunication::sealed | [private]
~VideoChat() | SimpleCommunication::sealed | [private]
Generated on Sat Nov 23 2024 16:09:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Language font mapping/C++/pch.cpp Source File

  • Language font mapping

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 //
00009 // pch.cpp
00010 // Include the standard header and generate the precompiled header.
00011 //
00012
00013 #include "pch.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D bump mapping/C++/BasicTimer.h Source File

  • Direct3D bump mapping

BasicTimer.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 timer class used to drive the render loop of the actively-animated
00011 // DirectX SDK samples. Uses the QueryPerformanceCounter function to retrieve
00012 // high-resolution timing information.
00013 ref class BasicTimer
00014 {
00015 private:
00016     LARGE_INTEGER m_frequency;
00017     LARGE_INTEGER m_currentTime;
00018     LARGE_INTEGER m_startTime;
00019     LARGE_INTEGER m_lastTime;
00020     float m_total;
00021     float m_delta;
00022
00023 internal:
00024     BasicTimer();
00025     void Reset();
00026     void Update();
00027     property float Total
00028     {
00029         float get();
00030     }
00031     property float Delta
00032     {
00033         float get();
00034     }
00035 };
Generated on Sat Nov 23 2024 16:08:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/texconv/DirectXTexCompress.cpp Source File

  • Direct3D resource loading
  • texconv

DirectXTexCompress.cpp

Go to the documentation of this file.
00001 //-------------------------------------------------------------------------------------
00002 // DirectXTexCompress.cpp
00003 //
00004 // DirectX Texture Library - Texture compression
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 #include "directxtexp.h"
00015
00016 #ifdef _OPENMP
00017 #include <omp.h>
00018 #pragma warning(disable : 4616 6001 6993)
00019 #endif
00020
00021 #include "bc.h"
00022
00023
00024 namespace DirectX
00025 {
00026
00027 inline static DWORD _GetBCFlags( _In_ DWORD compress )
00028 {
00029     static_assert( TEX_COMPRESS_RGB_DITHER == BC_FLAGS_DITHER_RGB, "TEX_COMPRESS_* flags should match BC_FLAGS_*" );
00030     static_assert( TEX_COMPRESS_A_DITHER == BC_FLAGS_DITHER_A, "TEX_COMPRESS_* flags should match BC_FLAGS_*"  );
00031     static_assert( TEX_COMPRESS_DITHER == (BC_FLAGS_DITHER_RGB | BC_FLAGS_DITHER_A), "TEX_COMPRESS_* flags should match BC_FLAGS_*"  );
00032     static_assert( TEX_COMPRESS_UNIFORM == BC_FLAGS_UNIFORM, "TEX_COMPRESS_* flags should match BC_FLAGS_*"  );
00033     return ( compress & (BC_FLAGS_DITHER_RGB|BC_FLAGS_DITHER_A|BC_FLAGS_UNIFORM) );
00034 }
00035
00036
00037 //-------------------------------------------------------------------------------------
00038 static HRESULT _CompressBC( _In_ const Image& image, _In_ const Image& result, _In_ DWORD bcflags,
00039                             _In_ float alphaRef, _In_ bool degenerate )
00040 {
00041     if ( !image.pixels || !result.pixels )
00042         return E_POINTER;
00043
00044     assert( image.width == result.width );
00045     assert( image.height == result.height );
00046
00047     const DXGI_FORMAT format = image.format;
00048     size_t sbpp = BitsPerPixel( format );
00049     if ( !sbpp )
00050         return E_FAIL;
00051
00052     if ( sbpp < 8 )
00053     {
00054         // We don't support compressing from monochrome (DXGI_FORMAT_R1_UNORM)
00055         return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
00056     }
00057
00058     // Round to bytes
00059     sbpp = ( sbpp + 7 ) / 8;
00060
00061     uint8_t *pDest = result.pixels;
00062
00063     // Determine BC format encoder
00064     BC_ENCODE pfEncode;
00065     size_t blocksize;
00066     switch(result.format)
00067     {
00068     case DXGI_FORMAT_BC1_UNORM:
00069     case DXGI_FORMAT_BC1_UNORM_SRGB:    pfEncode = nullptr;         blocksize = 8;   break;
00070     case DXGI_FORMAT_BC2_UNORM:
00071     case DXGI_FORMAT_BC2_UNORM_SRGB:    pfEncode = D3DXEncodeBC2;   blocksize = 16;  break;
00072     case DXGI_FORMAT_BC3_UNORM:
00073     case DXGI_FORMAT_BC3_UNORM_SRGB:    pfEncode = D3DXEncodeBC3;   blocksize = 16;  break;
00074     case DXGI_FORMAT_BC4_UNORM:         pfEncode = D3DXEncodeBC4U;  blocksize = 8;   break;
00075     case DXGI_FORMAT_BC4_SNORM:         pfEncode = D3DXEncodeBC4S;  blocksize = 8;   break;
00076     case DXGI_FORMAT_BC5_UNORM:         pfEncode = D3DXEncodeBC5U;  blocksize = 16;  break;
00077     case DXGI_FORMAT_BC5_SNORM:         pfEncode = D3DXEncodeBC5S;  blocksize = 16;  break;
00078     case DXGI_FORMAT_BC6H_UF16:         pfEncode = D3DXEncodeBC6HU; blocksize = 16;  break;
00079     case DXGI_FORMAT_BC6H_SF16:         pfEncode = D3DXEncodeBC6HS; blocksize = 16;  break;
00080     case DXGI_FORMAT_BC7_UNORM:
00081     case DXGI_FORMAT_BC7_UNORM_SRGB:    pfEncode = D3DXEncodeBC7;   blocksize = 16;  break;
00082     default:
00083         return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
00084     }
00085
00086     XMVECTOR temp[16];
00087     const uint8_t *pSrc = image.pixels;
00088     const size_t rowPitch = image.rowPitch;
00089     for( size_t h=0; h < image.height; h += 4 )
00090     {
00091         const uint8_t *sptr = pSrc;
00092         uint8_t* dptr = pDest;
00093         for( size_t count = 0; count < rowPitch; count += sbpp*4 )
00094         {
00095             if ( !_LoadScanline( &temp[0], 4, sptr, rowPitch, format ) )
00096                 return E_FAIL;
00097
00098             if ( image.height > 1 )
00099             {
00100                 if ( !_LoadScanline( &temp[4], 4, sptr + rowPitch, rowPitch, format ) )
00101                     return E_FAIL;
00102
00103                 if ( image.height > 2 )
00104                 {
00105                     if ( !_LoadScanline( &temp[8], 4, sptr + rowPitch*2, rowPitch, format ) )
00106                         return E_FAIL;
00107
00108                     if ( !_LoadScanline( &temp[12], 4, sptr + rowPitch*3, rowPitch, format ) )
00109                         return E_FAIL;
00110                 }
00111             }
00112
00113             if ( degenerate )
00114             {
00115                 assert( image.width < 4 || image.height < 4 );
00116                 const size_t uSrc[] = { 0, 0, 0, 1 };
00117
00118                 if ( image.width < 4 )
00119                 {
00120                     for( size_t t=0; t < image.height && t < 4; ++t )
00121                     {
00122                         for( size_t s = image.width; s < 4; ++s )
00123                         {
00124                             temp[ t*4 + s ] = temp[ t*4 + uSrc[s] ];
00125                         }
00126                     }
00127                 }
00128
00129                 if ( image.height < 4 )
00130                 {
00131                     for( size_t t=image.height; t < 4; ++t )
00132                     {
00133                         for( size_t s =0; s < 4; ++s )
00134                         {
00135                             temp[ t*4 + s ] = temp[ uSrc[t]*4 + s ];
00136                         }
00137                     }
00138                 }
00139             }
00140
00141             _ConvertScanline( temp, 16, result.format, format, 0 );
00142
00143             if ( pfEncode )
00144                 pfEncode( dptr, temp, bcflags );
00145             else
00146                 D3DXEncodeBC1( dptr, temp, alphaRef, bcflags );
00147
00148             sptr += sbpp*4;
00149             dptr += blocksize;
00150         }
00151
00152         pSrc += rowPitch*4;
00153         pDest += result.rowPitch;
00154     }
00155
00156     return S_OK;
00157 }
00158
00159
00160 //-------------------------------------------------------------------------------------
00161 #ifdef _OPENMP
00162 static HRESULT _CompressBC_Parallel( _In_ const Image& image, _In_ const Image& result, _In_ DWORD bcflags,
00163                                      _In_ float alphaRef )
00164 {
00165     if ( !image.pixels || !result.pixels )
00166         return E_POINTER;
00167
00168     // Parallel version doesn't support degenerate case
00169     assert( ((image.width % 4) == 0) && ((image.height % 4) == 0 ) );
00170
00171     assert( image.width == result.width );
00172     assert( image.height == result.height );
00173
00174     const DXGI_FORMAT format = image.format;
00175     size_t sbpp = BitsPerPixel( format );
00176     if ( !sbpp )
00177         return E_FAIL;
00178
00179     if ( sbpp < 8 )
00180     {
00181         // We don't support compressing from monochrome (DXGI_FORMAT_R1_UNORM)
00182         return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
00183     }
00184
00185     // Round to bytes
00186     sbpp = ( sbpp + 7 ) / 8;
00187
00188     // Determine BC format encoder
00189     BC_ENCODE pfEncode;
00190     size_t blocksize;
00191     switch(result.format)
00192     {
00193     case DXGI_FORMAT_BC1_UNORM:
00194     case DXGI_FORMAT_BC1_UNORM_SRGB:    pfEncode = nullptr;         blocksize = 8;   break;
00195     case DXGI_FORMAT_BC2_UNORM:
00196     case DXGI_FORMAT_BC2_UNORM_SRGB:    pfEncode = D3DXEncodeBC2;   blocksize = 16;  break;
00197     case DXGI_FORMAT_BC3_UNORM:
00198     case DXGI_FORMAT_BC3_UNORM_SRGB:    pfEncode = D3DXEncodeBC3;   blocksize = 16;  break;
00199     case DXGI_FORMAT_BC4_UNORM:         pfEncode = D3DXEncodeBC4U;  blocksize = 8;   break;
00200     case DXGI_FORMAT_BC4_SNORM:         pfEncode = D3DXEncodeBC4S;  blocksize = 8;   break;
00201     case DXGI_FORMAT_BC5_UNORM:         pfEncode = D3DXEncodeBC5U;  blocksize = 16;  break;
00202     case DXGI_FORMAT_BC5_SNORM:         pfEncode = D3DXEncodeBC5S;  blocksize = 16;  break;
00203     case DXGI_FORMAT_BC6H_UF16:         pfEncode = D3DXEncodeBC6HU; blocksize = 16;  break;
00204     case DXGI_FORMAT_BC6H_SF16:         pfEncode = D3DXEncodeBC6HS; blocksize = 16;  break;
00205     case DXGI_FORMAT_BC7_UNORM:
00206     case DXGI_FORMAT_BC7_UNORM_SRGB:    pfEncode = D3DXEncodeBC7;   blocksize = 16;  break;
00207     default:
00208         return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
00209     }
00210
00211     // Refactored version of loop to support parallel independance
00212     const size_t nBlocks = std::max<size_t>(1, image.width / 4) * std::max<size_t>(1, image.height / 4);
00213
00214     bool fail = false;
00215
00216 #pragma omp parallel for
00217     for( int nb=0; nb < static_cast<int>( nBlocks ); ++nb )
00218     {
00219         const size_t nbWidth = std::max<size_t>(1, image.width / 4);
00220
00221         const size_t y = nb / nbWidth;
00222         const size_t x = nb - (y*nbWidth);
00223
00224         assert( x < image.width && y < image.height );
00225
00226         size_t rowPitch = image.rowPitch;
00227         const uint8_t *pSrc = image.pixels + (y*4*rowPitch) + (x*4*sbpp);
00228
00229         uint8_t *pDest = result.pixels + (nb*blocksize);
00230
00231         XMVECTOR temp[16];
00232         if ( !_LoadScanline( &temp[0], 4, pSrc, rowPitch, format ) )
00233             fail = true;
00234
00235         if ( !_LoadScanline( &temp[4], 4, pSrc + rowPitch, rowPitch, format ) )
00236             fail = true;
00237
00238         if ( !_LoadScanline( &temp[8], 4, pSrc + rowPitch*2, rowPitch, format ) )
00239             fail = true;
00240
00241         if ( !_LoadScanline( &temp[12], 4, pSrc + rowPitch*3, rowPitch, format ) )
00242             fail = true;
00243
00244         _ConvertScanline( temp, 16, result.format, format, 0 );
00245
00246         if ( pfEncode )
00247             pfEncode( pDest, temp, bcflags );
00248         else
00249             D3DXEncodeBC1( pDest, temp, alphaRef, bcflags );
00250     }
00251
00252     return (fail) ? E_FAIL : S_OK;
00253 }
00254
00255 #endif // _OPENMP
00256
00257
00258 //-------------------------------------------------------------------------------------
00259 static DXGI_FORMAT _DefaultDecompress( _In_ DXGI_FORMAT format )
00260 {
00261     switch( format )
00262     {
00263     case DXGI_FORMAT_BC1_TYPELESS:
00264     case DXGI_FORMAT_BC1_UNORM:
00265     case DXGI_FORMAT_BC2_TYPELESS:
00266     case DXGI_FORMAT_BC2_UNORM:
00267     case DXGI_FORMAT_BC3_TYPELESS:
00268     case DXGI_FORMAT_BC3_UNORM:
00269     case DXGI_FORMAT_BC7_TYPELESS:
00270     case DXGI_FORMAT_BC7_UNORM:
00271         return DXGI_FORMAT_R8G8B8A8_UNORM;
00272
00273     case DXGI_FORMAT_BC1_UNORM_SRGB:
00274     case DXGI_FORMAT_BC2_UNORM_SRGB:
00275     case DXGI_FORMAT_BC3_UNORM_SRGB:
00276     case DXGI_FORMAT_BC7_UNORM_SRGB:
00277         return DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
00278
00279     case DXGI_FORMAT_BC4_TYPELESS:
00280     case DXGI_FORMAT_BC4_UNORM:
00281         return DXGI_FORMAT_R8_UNORM;
00282
00283     case DXGI_FORMAT_BC4_SNORM:
00284         return DXGI_FORMAT_R8_SNORM;
00285
00286     case DXGI_FORMAT_BC5_TYPELESS:
00287     case DXGI_FORMAT_BC5_UNORM:
00288         return DXGI_FORMAT_R8G8_UNORM;
00289
00290     case DXGI_FORMAT_BC5_SNORM:
00291         return DXGI_FORMAT_R8G8_SNORM;
00292
00293     case DXGI_FORMAT_BC6H_TYPELESS:
00294     case DXGI_FORMAT_BC6H_UF16:
00295     case DXGI_FORMAT_BC6H_SF16:
00296         // We could use DXGI_FORMAT_R32G32B32_FLOAT here since BC6H is always Alpha 1.0,
00297         // but this format is more supported by viewers
00298         return DXGI_FORMAT_R32G32B32A32_FLOAT;
00299
00300     default:
00301         return DXGI_FORMAT_UNKNOWN;
00302     }
00303 }
00304
00305
00306 //-------------------------------------------------------------------------------------
00307 static HRESULT _DecompressBC( _In_ const Image& cImage, _In_ const Image& result )
00308 {
00309     if ( !cImage.pixels || !result.pixels )
00310         return E_POINTER;
00311
00312     assert( cImage.width == result.width );
00313     assert( cImage.height == result.height );
00314
00315     // Image must be a multiple of 4 (degenerate cases of 1x1, 1x2, 2x1, and 2x2 are allowed)
00316     size_t width = cImage.width;
00317     if ( (width % 4) != 0 )
00318     {
00319         if ( width != 1 && width != 2 )
00320             return E_INVALIDARG;
00321     }
00322
00323     size_t height = cImage.height;
00324     if ( (height % 4) != 0 )
00325     {
00326         if ( height != 1 && height != 2 )
00327             return E_INVALIDARG;
00328     }
00329
00330     const DXGI_FORMAT format = result.format;
00331     size_t dbpp = BitsPerPixel( format );
00332     if ( !dbpp )
00333         return E_FAIL;
00334
00335     if ( dbpp < 8 )
00336     {
00337         // We don't support decompressing to monochrome (DXGI_FORMAT_R1_UNORM)
00338         return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
00339     }
00340
00341     // Round to bytes
00342     dbpp = ( dbpp + 7 ) / 8;
00343
00344     uint8_t *pDest = result.pixels;
00345     if ( !pDest )
00346         return E_POINTER;
00347
00348     // Promote "typeless" BC formats
00349     DXGI_FORMAT cformat;
00350     switch( cImage.format )
00351     {
00352     case DXGI_FORMAT_BC1_TYPELESS:  cformat = DXGI_FORMAT_BC1_UNORM; break;
00353     case DXGI_FORMAT_BC2_TYPELESS:  cformat = DXGI_FORMAT_BC2_UNORM; break;
00354     case DXGI_FORMAT_BC3_TYPELESS:  cformat = DXGI_FORMAT_BC3_UNORM; break;
00355     case DXGI_FORMAT_BC4_TYPELESS:  cformat = DXGI_FORMAT_BC4_UNORM; break;
00356     case DXGI_FORMAT_BC5_TYPELESS:  cformat = DXGI_FORMAT_BC5_UNORM; break;
00357     case DXGI_FORMAT_BC6H_TYPELESS: cformat = DXGI_FORMAT_BC6H_UF16; break;
00358     case DXGI_FORMAT_BC7_TYPELESS:  cformat = DXGI_FORMAT_BC7_UNORM; break;
00359     default:                        cformat = cImage.format;         break;
00360     }
00361
00362     // Determine BC format decoder
00363     BC_DECODE pfDecode;
00364     size_t sbpp;
00365     switch(cformat)
00366     {
00367     case DXGI_FORMAT_BC1_UNORM:
00368     case DXGI_FORMAT_BC1_UNORM_SRGB:    pfDecode = D3DXDecodeBC1;   sbpp = 8;   break;
00369     case DXGI_FORMAT_BC2_UNORM:
00370     case DXGI_FORMAT_BC2_UNORM_SRGB:    pfDecode = D3DXDecodeBC2;   sbpp = 16;  break;
00371     case DXGI_FORMAT_BC3_UNORM:
00372     case DXGI_FORMAT_BC3_UNORM_SRGB:    pfDecode = D3DXDecodeBC3;   sbpp = 16;  break;
00373     case DXGI_FORMAT_BC4_UNORM:         pfDecode = D3DXDecodeBC4U;  sbpp = 8;   break;
00374     case DXGI_FORMAT_BC4_SNORM:         pfDecode = D3DXDecodeBC4S;  sbpp = 8;   break;
00375     case DXGI_FORMAT_BC5_UNORM:         pfDecode = D3DXDecodeBC5U;  sbpp = 16;  break;
00376     case DXGI_FORMAT_BC5_SNORM:         pfDecode = D3DXDecodeBC5S;  sbpp = 16;  break;
00377     case DXGI_FORMAT_BC6H_UF16:         pfDecode = D3DXDecodeBC6HU; sbpp = 16;  break;
00378     case DXGI_FORMAT_BC6H_SF16:         pfDecode = D3DXDecodeBC6HS; sbpp = 16;  break;
00379     case DXGI_FORMAT_BC7_UNORM:
00380     case DXGI_FORMAT_BC7_UNORM_SRGB:    pfDecode = D3DXDecodeBC7;   sbpp = 16;  break;
00381     default:
00382         return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
00383     }
00384
00385     XMVECTOR temp[16];
00386     const uint8_t *pSrc = cImage.pixels;
00387     const size_t rowPitch = result.rowPitch;
00388     for( size_t h=0; h < cImage.height; h += 4 )
00389     {
00390         const uint8_t *sptr = pSrc;
00391         uint8_t* dptr = pDest;
00392         for( size_t count = 0; count < cImage.rowPitch; count += sbpp )
00393         {
00394             pfDecode( temp, sptr );
00395             _ConvertScanline( temp, 16, format, cformat, 0 );
00396
00397             if ( !_StoreScanline( dptr, rowPitch, format, &temp[0], 4 ) )
00398                 return E_FAIL;
00399
00400             if ( result.height > 1 )
00401             {
00402                 if ( !_StoreScanline( dptr + rowPitch, rowPitch, format, &temp[4], 4 ) )
00403                     return E_FAIL;
00404
00405                 if ( result.height > 2 )
00406                 {
00407                     if ( !_StoreScanline( dptr + rowPitch*2, rowPitch, format, &temp[8], 4 ) )
00408                         return E_FAIL;
00409
00410                     if ( !_StoreScanline( dptr + rowPitch*3, rowPitch, format, &temp[12], 4 ) )
00411                         return E_FAIL;
00412                 }
00413             }
00414
00415             sptr += sbpp;
00416             dptr += dbpp*4;
00417         }
00418
00419         pSrc += cImage.rowPitch;
00420         pDest += rowPitch*4;
00421     }
00422
00423     return S_OK;
00424 }
00425
00426
00427 //=====================================================================================
00428 // Entry-points
00429 //=====================================================================================
00430
00431 //-------------------------------------------------------------------------------------
00432 // Compression
00433 //-------------------------------------------------------------------------------------
00434 _Use_decl_annotations_
00435 HRESULT Compress( const Image& srcImage, DXGI_FORMAT format, DWORD compress, float alphaRef, ScratchImage& image )
00436 {
00437     if ( IsCompressed(srcImage.format) || !IsCompressed(format) || IsTypeless(format) )
00438         return E_INVALIDARG;
00439
00440     // Image size must be a multiple of 4 (degenerate cases for mipmaps are allowed)
00441     bool degenerate = false;
00442
00443     size_t width = srcImage.width;
00444     if ( (width % 4) != 0 )
00445     {
00446         if ( width != 1 && width != 2 )
00447             return E_INVALIDARG;
00448
00449         degenerate = true;
00450     }
00451
00452     size_t height = srcImage.height;
00453     if ( (height % 4) != 0 )
00454     {
00455         if ( height != 1 && height != 2 )
00456             return E_INVALIDARG;
00457
00458         degenerate = true;
00459     }
00460
00461     // Create compressed image
00462     HRESULT hr = image.Initialize2D( format, width, height, 1, 1 );
00463     if ( FAILED(hr) )
00464         return hr;
00465
00466     const Image *img = image.GetImage( 0, 0, 0 );
00467     if ( !img )
00468     {
00469         image.Release();
00470         return E_POINTER;
00471     }
00472
00473     // Compress single image
00474     if ( (compress & TEX_COMPRESS_PARALLEL) && !degenerate )
00475     {
00476 #ifndef _OPENMP
00477         return E_NOTIMPL;
00478 #else
00479         hr = _CompressBC_Parallel( srcImage, *img, _GetBCFlags( compress ), alphaRef );
00480 #endif // _OPENMP
00481     }
00482     else
00483     {
00484         hr = _CompressBC( srcImage, *img, _GetBCFlags( compress ), alphaRef, degenerate );
00485     }
00486
00487     if ( FAILED(hr) )
00488         image.Release();
00489
00490     return hr;
00491 }
00492
00493 _Use_decl_annotations_
00494 HRESULT Compress( const Image* srcImages, size_t nimages, const TexMetadata& metadata,
00495                   DXGI_FORMAT format, DWORD compress, float alphaRef, ScratchImage& cImages )
00496 {
00497     if ( !srcImages || !nimages )
00498         return E_INVALIDARG;
00499
00500     if ( !IsCompressed(format) || IsTypeless(format) )
00501         return E_INVALIDARG;
00502
00503     // Image size must be a multiple of 4 (degenerate cases for mipmaps are allowed)
00504     size_t width = srcImages[0].width;
00505     if ( (width % 4) != 0 )
00506     {
00507         if ( width != 1 && width != 2 )
00508             return E_INVALIDARG;
00509     }
00510
00511     size_t height = srcImages[0].height;
00512     if ( (height % 4) != 0 )
00513     {
00514         if ( height != 1 && height != 2 )
00515             return E_INVALIDARG;
00516     }
00517
00518     cImages.Release();
00519
00520     TexMetadata mdata2 = metadata;
00521     mdata2.format = format;
00522     HRESULT hr = cImages.Initialize( mdata2 );
00523     if ( FAILED(hr) )
00524         return hr;
00525
00526     if ( nimages != cImages.GetImageCount() )
00527     {
00528         cImages.Release();
00529         return E_FAIL;
00530     }
00531
00532     const Image* dest = cImages.GetImages();
00533     if ( !dest  )
00534     {
00535         cImages.Release();
00536         return E_POINTER;
00537     }
00538
00539     for( size_t index=0; index < nimages; ++index )
00540     {
00541         assert( dest[ index ].format == format );
00542
00543         const Image& src = srcImages[ index ];
00544
00545         height = src.height;
00546         width = src.width;
00547         if ( width != dest[ index ].width || height != dest[ index ].height )
00548         {
00549             cImages.Release();
00550             return E_FAIL;
00551         }
00552
00553         bool degenerate = ((height < 4) || (width < 4)) != 0;
00554
00555         if ( (compress & TEX_COMPRESS_PARALLEL) && !degenerate)
00556         {
00557 #ifndef _OPENMP
00558             return E_NOTIMPL;
00559 #else
00560             if ( compress & TEX_COMPRESS_PARALLEL )
00561             {
00562                 hr = _CompressBC_Parallel( src, dest[ index ], _GetBCFlags( compress ), alphaRef );
00563                 if ( FAILED(hr) )
00564                 {
00565                     cImages.Release();
00566                     return  hr;
00567                 }
00568             }
00569 #endif // _OPENMP
00570         }
00571         else
00572         {
00573             hr = _CompressBC( src, dest[ index ], _GetBCFlags( compress ), alphaRef, degenerate );
00574             if ( FAILED(hr) )
00575             {
00576                 cImages.Release();
00577                 return hr;
00578             }
00579         }
00580     }
00581
00582     return S_OK;
00583 }
00584
00585
00586 //-------------------------------------------------------------------------------------
00587 // Decompression
00588 //-------------------------------------------------------------------------------------
00589 _Use_decl_annotations_
00590 HRESULT Decompress( const Image& cImage, DXGI_FORMAT format, ScratchImage& image )
00591 {
00592     if ( IsCompressed(format) || IsTypeless(format) )
00593         return E_INVALIDARG;
00594
00595     if ( format == DXGI_FORMAT_UNKNOWN )
00596     {
00597         // Pick a default decompressed format based on BC input format
00598         format = _DefaultDecompress( cImage.format );
00599         if ( format == DXGI_FORMAT_UNKNOWN )
00600         {
00601             // Input is not a compressed format
00602             return E_INVALIDARG;
00603         }
00604     }
00605     else if ( !IsCompressed(cImage.format) || !IsValid(format) )
00606         return E_INVALIDARG;
00607
00608     // Create decompressed image
00609     HRESULT hr = image.Initialize2D( format, cImage.width, cImage.height, 1, 1 );
00610     if ( FAILED(hr) )
00611         return hr;
00612
00613     const Image *img = image.GetImage( 0, 0, 0 );
00614     if ( !img )
00615     {
00616         image.Release();
00617         return E_POINTER;
00618     }
00619
00620     // Decompress single image
00621     hr = _DecompressBC( cImage, *img );
00622     if ( FAILED(hr) )
00623         image.Release();
00624
00625     return hr;
00626 }
00627
00628 _Use_decl_annotations_
00629 HRESULT Decompress( const Image* cImages, size_t nimages, const TexMetadata& metadata,
00630                     DXGI_FORMAT format, ScratchImage& images )
00631 {
00632     if ( !cImages || !nimages )
00633         return E_INVALIDARG;
00634
00635     if ( IsCompressed(format) || IsTypeless(format) )
00636         return E_INVALIDARG;
00637
00638     if ( format == DXGI_FORMAT_UNKNOWN )
00639     {
00640         // Pick a default decompressed format based on BC input format
00641         format = _DefaultDecompress( cImages[0].format );
00642         if ( format == DXGI_FORMAT_UNKNOWN )
00643         {
00644             // Input is not a compressed format
00645             return E_FAIL;
00646         }
00647     }
00648     else if ( !IsValid(format) )
00649         return E_INVALIDARG;
00650
00651     images.Release();
00652
00653     TexMetadata mdata2 = metadata;
00654     mdata2.format = format;
00655     HRESULT hr = images.Initialize( mdata2 );
00656     if ( FAILED(hr) )
00657         return hr;
00658
00659     if ( nimages != images.GetImageCount() )
00660     {
00661         images.Release();
00662         return E_FAIL;
00663     }
00664
00665     const Image* dest = images.GetImages();
00666     if ( !dest )
00667     {
00668         images.Release();
00669         return E_POINTER;
00670     }
00671
00672     for( size_t index=0; index < nimages; ++index )
00673     {
00674         assert( dest[ index ].format == format );
00675
00676         const Image& src = cImages[ index ];
00677         if ( !IsCompressed( src.format ) )
00678         {
00679             images.Release();
00680             return E_FAIL;
00681         }
00682
00683         if ( src.width != dest[ index ].width || src.height != dest[ index ].height )
00684         {
00685             images.Release();
00686             return E_FAIL;
00687         }
00688
00689         hr = _DecompressBC( src, dest[ index ] );
00690         if ( FAILED(hr) )
00691         {
00692             images.Release();
00693             return hr;
00694         }
00695     }
00696
00697     return S_OK;
00698 }
00699
00700 }; // namespace
Generated on Sat Nov 23 2024 16:08:12 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Folder enumeration/C++/Scenario1.xaml.h Source File

  • Folder enumeration

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 SDKSample
00023 {
00024     namespace FolderEnumeration
00025     {
00026         public ref class Scenario1 sealed
00027         {
00028         public:
00029             Scenario1();
00030
00031         private:
00032             void GetFilesAndFolderButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00033         };
00034     }
00035 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Scaling according to DPI/C++/Scenario2.xaml.cpp Source File

  • Scaling according to DPI

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 SDKSample::Scaling;
00020
00021 using namespace Platform;
00022 using namespace Windows::Foundation;
00023 using namespace Windows::Graphics::Display;
00024 using namespace Windows::UI::Text;
00025 using namespace Windows::UI::Xaml;
00026 using namespace Windows::UI::Xaml::Controls;
00027 using namespace Windows::UI::Xaml::Media;
00028 using namespace Windows::UI::Xaml::Navigation;
00029
00030 Scenario2::Scenario2()
00031 {
00032     InitializeComponent();
00033     DisplayProperties::LogicalDpiChanged += ref new DisplayPropertiesEventHandler(this, &Scenario2::DisplayProperties_LogicalDpiChanged);
00034
00035     defaultFontFamily = ref new Windows::UI::Xaml::Media::FontFamily("Segoe UI");
00036     overrideFontFamily = ref new Windows::UI::Xaml::Media::FontFamily("Segoe Script");
00037
00038     DefaultLayoutText->FontSize = PxFromPt(20);  // xaml fontsize is in pixels.
00039     DefaultLayoutText->FontFamily = defaultFontFamily;
00040 }
00041
00042 double Scenario2::PtFromPx(double pixel)
00043 {
00044     return pixel * 72 / 96;
00045 }
00046
00047 double Scenario2::PxFromPt(double pt)
00048 {
00049     return pt * 96 / 72;
00050 }
00051
00052 void Scenario2::SetOverrideRectSize(double sizeInPhysicalPx, double scaleFactor)
00053 {
00054     // Set the size of OverrideLayoutRect based on the desired size in physical pixels and the scale factor.
00055     // The code here is to demonstrate how to override default scaling behavior to keep the physical pixel size of a control.
00056     double sizeInRelativePx = sizeInPhysicalPx / scaleFactor;
00057     OverrideLayoutRect->Width = sizeInRelativePx;
00058     OverrideLayoutRect->Height = sizeInRelativePx;
00059 }
00060
00061 void Scenario2::SetOverrideTextFont(double size, Windows::UI::Xaml::Media::FontFamily^ fontFamily)
00062 {
00063     OverrideLayoutText->FontSize = PxFromPt(size);  // xaml fontsize is in pixels.
00064     OverrideLayoutText->FontFamily = fontFamily;
00065 }
00066
00067 String^ Scenario2::StringFromDouble(double x)
00068 {
00069     // Round to the nearest tenth for display.
00070     return (((int)(x * 10 + 0.5)) / 10.0).ToString();
00071 }
00072
00073 void Scenario2::OutputSettings(double scaleFactor, FrameworkElement^ rectangle, TextBlock^ relativePxText, TextBlock^ physicalPxText, TextBlock^ fontTextBlock)
00074 {
00075     // Get the size of the rectangle in relative pixels and calulate the size in physical pixels.
00076     double sizeInRelativePx = rectangle->Width;
00077     double sizeInPhysicalPx = sizeInRelativePx * scaleFactor;
00078
00079     relativePxText->Text = StringFromDouble(sizeInRelativePx) + " relative px";
00080     physicalPxText->Text = StringFromDouble(sizeInPhysicalPx) + " physical px";
00081
00082     double fontSize = PtFromPx(fontTextBlock->FontSize);
00083     fontTextBlock->Text = StringFromDouble(fontSize) + "pt " + fontTextBlock->FontFamily->Source;
00084 }
00085
00086 void Scenario2::ResetOutput()
00087 {
00088     ResolutionTextBlock->Text = StringFromDouble(Window::Current->Bounds.Width) + "x" + StringFromDouble(Window::Current->Bounds.Height);
00089
00090     double scaleFactor;
00091     double fontSize;
00092     Windows::UI::Xaml::Media::FontFamily^ fontFamily;
00093     switch (DisplayProperties::ResolutionScale)
00094     {
00095     case ResolutionScale::Invalid:
00096     case ResolutionScale::Scale100Percent:
00097     default:
00098         scaleFactor = 1.0;
00099         fontSize = 20;
00100         fontFamily = defaultFontFamily;
00101         break;
00102
00103     case ResolutionScale::Scale140Percent:
00104         scaleFactor = 1.4;
00105         fontSize = 11;
00106         fontFamily = overrideFontFamily;
00107         break;
00108
00109     case ResolutionScale::Scale180Percent:
00110         scaleFactor = 1.8;
00111         fontSize = 9;
00112         fontFamily = overrideFontFamily;
00113         break;
00114     }
00115
00116     // Set the override rectangle size and override text font.
00117     const double rectSizeInPhysicalPx = 100;
00118     SetOverrideRectSize(rectSizeInPhysicalPx, scaleFactor);
00119     SetOverrideTextFont(fontSize, fontFamily);
00120
00121     // Output settings for controls with default scaling behavior.
00122     OutputSettings(scaleFactor, DefaultLayoutRect, DefaultRelativePx, DefaultPhysicalPx, DefaultLayoutText);
00123     // Output settings for override controls.
00124     OutputSettings(scaleFactor, OverrideLayoutRect, OverrideRelativePx, OverridePhysicalPx, OverrideLayoutText);
00125 }
00126
00127 void Scenario2::OnNavigatedTo(NavigationEventArgs^ e)
00128 {
00129     ResetOutput();
00130 }
00131
00132 void Scenario2::DisplayProperties_LogicalDpiChanged(Object^ sender)
00133 {
00134     ResetOutput();
00135 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: UI Automation core window provider/C++/InternalInterfaces.idl Source File

  • UI Automation core window provider

InternalInterfaces.idl

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 import "oaidl.idl";
00009 import "Inspectable.idl";
00010 import "Windows.Foundation.idl";
00011 import "uiautomationcore.idl";
00012 #include <sdkddkver.h>
00013
00014 namespace UiaCoreWindowProvider
00015 {
00016     // A TriColorValue for the TriColorValue control
00017     [v1_enum, version(NTDDI_WIN8)]
00018     typedef enum TriColorValue
00019     {
00020         Red,
00021         Yellow,
00022         Green
00023     } TriColorValue;
00024
00025     // Internal interface for the TriColor control
00026     [version(NTDDI_WIN8), uuid(89AC8333-DD78-4C59-82C8-2143EF293C40)]
00027     interface ITriColorControlInternal : IInspectable{
00028         [propput]
00029         HRESULT ControlValue([in] TriColorValue value);
00030         [propget]
00031         HRESULT ControlValue([out, retval] TriColorValue * pvalue);
00032         [propget]
00033         HRESULT HasFocus([out, retval] VARIANT_BOOL * hasFocus);
00034         [propget]
00035         HRESULT ControlRect([out, retval] Windows.Foundation.Rect * prc);
00036
00037         HRESULT RectFromValue([in] TriColorValue value, [out, retval] Windows.Foundation.Rect * prc);
00038         HRESULT ValueFromPoint([in] Windows.Foundation.Point pt, [out, retval] TriColorValue *value);
00039         HRESULT GetAppWindowProvider([out, retval] IInspectable ** provider);
00040         HRESULT GetTriColorControlProvider([out, retval] IInspectable ** provider);
00041         HRESULT GetTriColorFragmentProvider([in] TriColorValue value, [out, retval] IInspectable ** provider);
00042     };
00043
00044     // Interface for a UIA provider that can be
00045     // initialized to a CoreWindow and also disconnected.
00046     [version(NTDDI_WIN8), uuid(0DC8AB6E-FF48-449C-9CF4-E321C4C166A2)]
00047     interface IDisconnectableProvider : IInspectable{
00048         HRESULT Disconnect();
00049     };
00050
00051     // Initialization interface for the app window provider
00052     [version(NTDDI_WIN8), uuid(D722FFD7-484F-451E-B69C-5C88274B3062)]
00053     interface IAppWindowProvider : IInspectable{
00054         HRESULT Initialize
00055             ([in] ITriColorControlInternal* pControl,
00056              [in] IInspectable* pWindow);
00057     };
00058
00059     // Initialization interface for the control provider
00060     [version(NTDDI_WIN8), uuid(0A59600E-8B52-4E52-8949-81781B4C7D92)]
00061     interface ITriColorControlProvider : IInspectable{
00062         HRESULT Initialize
00063             ([in] ITriColorControlInternal* pControl);
00064     };
00065
00066     // Initialization interface for the fragment provider
00067     [version(NTDDI_WIN8), uuid(4F925A18-4476-43DE-AC3C-0AB21386EF1A)]
00068     interface ITriColorFragmentProvider : IInspectable{
00069         HRESULT Initialize
00070             ([in] ITriColorControlInternal* pControl,
00071              [in] TriColorValue value);
00072     };
00073
00074     [version(NTDDI_WIN8), activatable(NTDDI_WIN8)]
00075     runtimeclass AppWindowProvider
00076     {
00077         [default] interface IAppWindowProvider;
00078     }
00079
00080     [version(NTDDI_WIN8), activatable(NTDDI_WIN8)]
00081     runtimeclass TriColorControlProvider
00082     {
00083         [default] interface ITriColorControlProvider;
00084     }
00085
00086     [version(NTDDI_WIN8), activatable(NTDDI_WIN8)]
00087     runtimeclass TriColorFragmentProvider
00088     {
00089         [default] interface ITriColorFragmentProvider;
00090     }
00091 }
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX swap chain implementation/C++/CoreWindowEvents.cpp Source File

  • DirectX swap chain implementation

CoreWindowEvents.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 "CoreWindowEvents.h"
00010
00011 using namespace Microsoft::WRL;
00012 using namespace Windows::ApplicationModel;
00013 using namespace Windows::ApplicationModel::Core;
00014 using namespace Windows::ApplicationModel::Activation;
00015 using namespace Windows::UI::Core;
00016 using namespace Windows::System;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Graphics::Display;
00019
00020 void CoreWindowEvents::CreateDeviceIndependentResources()
00021 {
00022     DirectXBase::CreateDeviceIndependentResources();
00023
00024     // Create a DirectWrite text format object.
00025     DX::ThrowIfFailed(
00026         m_dwriteFactory->CreateTextFormat(
00027             L"Segoe UI",
00028             NULL,
00029             DWRITE_FONT_WEIGHT_REGULAR,
00030             DWRITE_FONT_STYLE_NORMAL,
00031             DWRITE_FONT_STRETCH_NORMAL,
00032             20.0f,
00033             L"en-US", //locale
00034             &m_eventTextFormat
00035             )
00036         );
00037
00038     // Align the text to left.
00039     m_eventTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
00040     // Center the text vertically.
00041     m_eventTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
00042 }
00043
00044 void CoreWindowEvents::CreateDeviceResources()
00045 {
00046     DirectXBase::CreateDeviceResources();
00047
00048     m_sampleOverlay = ref new SampleOverlay();
00049
00050     m_sampleOverlay->Initialize(
00051         m_d2dDevice.Get(),
00052         m_d2dContext.Get(),
00053         m_wicFactory.Get(),
00054         m_dwriteFactory.Get(),
00055         L"CoreWindow Events Sample"
00056         );
00057
00058     DX::ThrowIfFailed(
00059         m_d2dContext->CreateSolidColorBrush(
00060             D2D1::ColorF(D2D1::ColorF::Black),
00061             &m_blackBrush
00062             )
00063         );
00064 }
00065
00066 void CoreWindowEvents::Render()
00067 {
00068     m_d2dContext->BeginDraw();
00069
00070     m_d2dContext->Clear(D2D1::ColorF(D2D1::ColorF::CornflowerBlue));
00071
00072     m_d2dContext->DrawText(
00073         m_eventName->Data(),
00074         m_eventName->Length(),
00075         m_eventTextFormat.Get(),
00076         D2D1::RectF(0.0, 0.0, m_renderTargetSize.Width, m_renderTargetSize.Height),
00077         m_blackBrush.Get());
00078
00079     // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00080     // is lost. It will be handled during the next call to Present.
00081     HRESULT hr = m_d2dContext->EndDraw();
00082     if (hr != D2DERR_RECREATE_TARGET)
00083     {
00084         DX::ThrowIfFailed(hr);
00085     }
00086
00087     m_sampleOverlay->Render();
00088 }
00089
00090 void CoreWindowEvents::Initialize(
00091     _In_ CoreApplicationView^ applicationView
00092     )
00093 {
00094     applicationView->Activated +=
00095         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &CoreWindowEvents::OnActivated);
00096 }
00097
00098 void CoreWindowEvents::SetWindow(
00099     _In_ CoreWindow^ window
00100     )
00101 {
00102     window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
00103
00104     window->SizeChanged +=
00105         ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &CoreWindowEvents::OnWindowSizeChanged);
00106     window->CharacterReceived +=
00107         ref new TypedEventHandler<CoreWindow^, CharacterReceivedEventArgs^>(this, &CoreWindowEvents::OnCharacterReceived);
00108     window->KeyDown +=
00109         ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &CoreWindowEvents::OnKeyDown);
00110     window->KeyUp +=
00111         ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &CoreWindowEvents::OnKeyUp);
00112     window->PointerPressed +=
00113         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &CoreWindowEvents::OnPointerPressed);
00114     window->PointerReleased +=
00115         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &CoreWindowEvents::OnPointerReleased);
00116     window->PointerMoved +=
00117         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &CoreWindowEvents::OnPointerMoved);
00118     window->Activated +=
00119         ref new TypedEventHandler<CoreWindow^, WindowActivatedEventArgs^>(this, &CoreWindowEvents::OnWindowActivated);
00120     DisplayProperties::LogicalDpiChanged +=
00121         ref new DisplayPropertiesEventHandler(this, &CoreWindowEvents::OnLogicalDpiChanged);
00122     DisplayProperties::DisplayContentsInvalidated +=
00123         ref new DisplayPropertiesEventHandler(this, &CoreWindowEvents::OnDisplayContentsInvalidated);
00124
00125     DirectXBase::Initialize(window, DisplayProperties::LogicalDpi);
00126 }
00127
00128 void CoreWindowEvents::Load(
00129     _In_ Platform::String^ entryPoint
00130     )
00131 {
00132 }
00133
00134 void CoreWindowEvents::Run()
00135 {
00136     CoreWindow::GetForCurrentThread()->Activate();
00137
00138     Render();
00139     Present();
00140     CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessUntilQuit);
00141 }
00142
00143 void CoreWindowEvents::Uninitialize()
00144 {
00145 }
00146
00147 void CoreWindowEvents::EventPrint(
00148     _In_ Platform::String^ eventText
00149     )
00150 {
00151     m_eventName = eventText;
00152     Render();
00153     Present();
00154 }
00155
00156 void CoreWindowEvents::PrintPointerInfo(
00157     _In_ Platform::String^ eventText,
00158     _In_ PointerEventArgs^ args
00159     )
00160 {
00161     Windows::UI::Input::PointerPoint^ currentPoint = args->CurrentPoint;
00162     EventPrint(L"Event: " + eventText + "\nArgument: Pointer ID:  " + currentPoint->PointerId.ToString() +
00163                 " Position: " + ((int)currentPoint->Position.X).ToString() + ":" + ((int)currentPoint->Position.Y).ToString());
00164 }
00165
00166 void CoreWindowEvents::OnWindowSizeChanged(
00167     _In_ CoreWindow^ sender,
00168     _In_ WindowSizeChangedEventArgs^ args
00169     )
00170 {
00171     UpdateForWindowSizeChange();
00172     m_sampleOverlay->UpdateForWindowSizeChange();
00173     EventPrint("Event: Window Size Changed\nArguments: Width: " + args->Size.Width.ToString() + " Height: "  + args->Size.Height.ToString());
00174 }
00175
00176 void CoreWindowEvents::OnCharacterReceived(
00177     _In_ CoreWindow^ sender,
00178     _In_ CharacterReceivedEventArgs^ args
00179     )
00180 {
00181     EventPrint("Event: Character Received\nArgument: Character: " + ((char16)args->KeyCode).ToString());
00182 }
00183
00184 void CoreWindowEvents::OnKeyDown(
00185     _In_ CoreWindow^ sender,
00186     _In_ KeyEventArgs^ args
00187     )
00188 {
00189     EventPrint("Event: Key Down\nArgument: Virtual Key: " + ((int)args->VirtualKey).ToString());
00190 }
00191
00192 void CoreWindowEvents::OnKeyUp(
00193     _In_ CoreWindow^ sender,
00194     _In_ KeyEventArgs^ args
00195     )
00196 {
00197     EventPrint("Event: Key Up\nArgument: Virtual Key: " + ((int)args->VirtualKey).ToString());
00198 }
00199
00200 void CoreWindowEvents::OnPointerPressed(
00201     _In_ CoreWindow^ sender,
00202     _In_ PointerEventArgs^ args
00203     )
00204 {
00205     PrintPointerInfo(L"Pointer Pressed", args);
00206 }
00207
00208 void CoreWindowEvents::OnPointerReleased(
00209     _In_ CoreWindow^ sender,
00210     _In_ PointerEventArgs^ args
00211     )
00212 {
00213     PrintPointerInfo(L"Pointer Released", args);
00214 }
00215
00216 void CoreWindowEvents::OnPointerMoved(
00217     _In_ CoreWindow^ sender,
00218     _In_ PointerEventArgs^ args
00219     )
00220 {
00221     PrintPointerInfo(L"Pointer Moved", args);
00222 }
00223
00224 void CoreWindowEvents::OnWindowActivated(
00225     _In_ CoreWindow^ sender,
00226     _In_ WindowActivatedEventArgs^ args
00227     )
00228 {
00229     EventPrint("Event: Window Activated\nArgument: " + ((args->WindowActivationState == CoreWindowActivationState::Deactivated) ? "Deactivated" : "Activated"));
00230 }
00231
00232 void CoreWindowEvents::OnLogicalDpiChanged(
00233     _In_ Platform::Object^ sender
00234     )
00235 {
00236     SetDpi(DisplayProperties::LogicalDpi);
00237     Render();
00238     Present();
00239 }
00240
00241 void CoreWindowEvents::OnDisplayContentsInvalidated(
00242     _In_ Platform::Object^ sender
00243     )
00244 {
00245     // Ensure the D3D Device is available for rendering.
00246     ValidateDevice();
00247
00248     Render();
00249     Present();
00250 }
00251
00252 void CoreWindowEvents::OnActivated(
00253     _In_ CoreApplicationView^ applicationView,
00254     _In_ IActivatedEventArgs^ args
00255     )
00256 {
00257     CoreWindow::GetForCurrentThread()->Activate();
00258 }
00259
00260 IFrameworkView^ DirectXAppSource::CreateView()
00261 {
00262     return ref new CoreWindowEvents();
00263 }
00264
00265 [Platform::MTAThread]
00266 int main(Platform::Array<Platform::String^>^)
00267 {
00268     auto directXAppSource = ref new DirectXAppSource();
00269     CoreApplication::Run(directXAppSource);
00270     return 0;
00271 }
00272
Generated on Sat Nov 23 2024 16:08:15 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

AccountPictureName::MainPage Member List

This is the complete list of members for AccountPictureName::MainPage, including all inherited members.
LoadSetAccountPictureScenario() | AccountPictureName::MainPage |
scenariosInner | AccountPictureName::MainPage | [private, static]
Generated on Sat Nov 23 2024 16:09:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Touch keyboard/C++/common/suspensionmanager.h Source File

  • Input Touch keyboard
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Secondary tiles/C#,C++/NotificationsExtensions/TileContent.cs Source File

  • Secondary tiles
  • C#,C++
  • NotificationsExtensions

TileContent.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 System;
00009 using System.Text;
00010 #if !WINRT_NOT_PRESENT
00011 using Windows.Data.Xml.Dom;
00012 using Windows.UI.Notifications;
00013 #endif
00014
00015 namespace NotificationsExtensions.TileContent
00016 {
00017     internal abstract class TileNotificationBase : NotificationBase
00018     {
00019         public TileNotificationBase(string templateName, int imageCount, int textCount) : base(templateName, imageCount, textCount)
00020         {
00021         }
00022
00023         public TileBranding Branding
00024         {
00025             get { return m_Branding; }
00026             set
00027             {
00028                 if (!Enum.IsDefined(typeof(TileBranding), value))
00029                 {
00030                     throw new ArgumentOutOfRangeException("value");
00031                 }
00032                 m_Branding = value;
00033             }
00034         }
00035
00036 #if !WINRT_NOT_PRESENT
00037         public TileNotification CreateNotification()
00038         {
00039             XmlDocument xmlDoc = new XmlDocument();
00040             xmlDoc.LoadXml(GetContent());
00041             return new TileNotification(xmlDoc);
00042         }
00043 #endif
00044
00045         private TileBranding m_Branding = TileBranding.Logo;
00046     }
00047
00048     internal interface ISquareTileInternal
00049     {
00050         string SerializeBinding(string globalLang, string globalBaseUri, TileBranding globalBranding, bool globalAddImageQuery);
00051     }
00052
00053     internal class TileSquareBase : TileNotificationBase, ISquareTileInternal
00054     {
00055         public TileSquareBase(string templateName, int imageCount, int textCount) : base(templateName, imageCount, textCount)
00056         {
00057         }
00058
00059         public override string GetContent()
00060         {
00061             StringBuilder builder = new StringBuilder(String.Empty);
00062             builder.AppendFormat("<tile><visual version='{0}'", Util.NOTIFICATION_CONTENT_VERSION);
00063             if (!String.IsNullOrWhiteSpace(Lang))
00064             {
00065                 builder.AppendFormat(" lang='{0}'", Util.HttpEncode(Lang));
00066             }
00067             if (Branding != TileBranding.Logo)
00068             {
00069                 builder.AppendFormat(" branding='{0}'", Branding.ToString().ToLowerInvariant());
00070             }
00071             if (!String.IsNullOrWhiteSpace(BaseUri))
00072             {
00073                 builder.AppendFormat(" baseUri='{0}'", Util.HttpEncode(BaseUri));
00074             }
00075             if (AddImageQuery)
00076             {
00077                 builder.AppendFormat(" addImageQuery='true'");
00078             }
00079             builder.Append(">");
00080             builder.Append(SerializeBinding(Lang, BaseUri, Branding, AddImageQuery));
00081             builder.Append("</visual></tile>");
00082             return builder.ToString();
00083         }
00084
00085         public string SerializeBinding(string globalLang, string globalBaseUri, TileBranding globalBranding, bool globalAddImageQuery)
00086         {
00087             StringBuilder bindingNode = new StringBuilder(String.Empty);
00088             bindingNode.AppendFormat("<binding template='{0}'", TemplateName);
00089             if (!String.IsNullOrWhiteSpace(Lang) && !Lang.Equals(globalLang))
00090             {
00091                 bindingNode.AppendFormat(" lang='{0}'", Util.HttpEncode(Lang));
00092                 globalLang = Lang;
00093             }
00094             if (Branding != TileBranding.Logo && Branding != globalBranding)
00095             {
00096                 bindingNode.AppendFormat(" branding='{0}'", Branding.ToString().ToLowerInvariant());
00097             }
00098             if (!String.IsNullOrWhiteSpace(BaseUri) && !BaseUri.Equals(globalBaseUri))
00099             {
00100                 bindingNode.AppendFormat(" baseUri='{0}'", Util.HttpEncode(BaseUri));
00101                 globalBaseUri = BaseUri;
00102             }
00103             if (AddImageQueryNullable != null && AddImageQueryNullable != globalAddImageQuery)
00104             {
00105                 bindingNode.AppendFormat(" addImageQuery='{0}'", AddImageQuery.ToString().ToLowerInvariant());
00106                 globalAddImageQuery = AddImageQuery;
00107             }
00108             bindingNode.AppendFormat(">{0}</binding>", SerializeProperties(globalLang, globalBaseUri, globalAddImageQuery));
00109
00110             return bindingNode.ToString();
00111         }
00112     }
00113
00114     internal class TileWideBase : TileNotificationBase
00115     {
00116         public TileWideBase(string templateName, int imageCount, int textCount) : base(templateName, imageCount, textCount)
00117         {
00118         }
00119
00120         public ISquareTileNotificationContent SquareContent
00121         {
00122             get { return m_SquareContent; }
00123             set { m_SquareContent = value; }
00124         }
00125
00126         public bool RequireSquareContent
00127         {
00128             get { return m_RequireSquareContent; }
00129             set { m_RequireSquareContent = value; }
00130         }
00131
00132         public override string GetContent()
00133         {
00134             if (RequireSquareContent && SquareContent == null)
00135             {
00136                 throw new NotificationContentValidationException(
00137                     "Square tile content should be included with each wide tile. " +
00138                     "If this behavior is undesired, use the RequireSquareContent property.");
00139             }
00140
00141             StringBuilder visualNode = new StringBuilder(String.Empty);
00142             visualNode.AppendFormat("<visual version='{0}'", Util.NOTIFICATION_CONTENT_VERSION);
00143             if (!String.IsNullOrWhiteSpace(Lang))
00144             {
00145                 visualNode.AppendFormat(" lang='{0}'", Util.HttpEncode(Lang));
00146             }
00147             if (Branding != TileBranding.Logo)
00148             {
00149                 visualNode.AppendFormat(" branding='{0}'", Branding.ToString().ToLowerInvariant());
00150             }
00151             if (!String.IsNullOrWhiteSpace(BaseUri))
00152             {
00153                 visualNode.AppendFormat(" baseUri='{0}'", Util.HttpEncode(BaseUri));
00154             }
00155             if (AddImageQuery)
00156             {
00157                 visualNode.AppendFormat(" addImageQuery='true'");
00158             }
00159             visualNode.Append(">");
00160
00161             StringBuilder builder = new StringBuilder(String.Empty);
00162             builder.AppendFormat("<tile>{0}<binding template='{1}'>{2}</binding>", visualNode, TemplateName, SerializeProperties(Lang, BaseUri, AddImageQuery));
00163             if (SquareContent != null)
00164             {
00165                 ISquareTileInternal squareBase = SquareContent as ISquareTileInternal;
00166                 if (squareBase == null)
00167                 {
00168                     throw new NotificationContentValidationException("The provided square tile content class is unsupported.");
00169                 }
00170                 builder.Append(squareBase.SerializeBinding(Lang, BaseUri, Branding, AddImageQuery));
00171             }
00172             builder.Append("</visual></tile>");
00173
00174             return builder.ToString();
00175         }
00176
00177         private ISquareTileNotificationContent m_SquareContent = null;
00178         private bool m_RequireSquareContent = true;
00179     }
00180
00181     internal class TileSquareBlock : TileSquareBase, ITileSquareBlock
00182     {
00183         public TileSquareBlock() : base(templateName: "TileSquareBlock", imageCount: 0, textCount: 2)
00184         {
00185         }
00186
00187         public INotificationContentText TextBlock { get { return TextFields[0]; } }
00188         public INotificationContentText TextSubBlock { get { return TextFields[1]; } }
00189     }
00190
00191     internal class TileSquareImage : TileSquareBase, ITileSquareImage
00192     {
00193         public TileSquareImage() : base(templateName: "TileSquareImage", imageCount: 1, textCount: 0)
00194         {
00195         }
00196
00197         public INotificationContentImage Image { get { return Images[0]; } }
00198     }
00199
00200     internal class TileSquarePeekImageAndText01 : TileSquareBase, ITileSquarePeekImageAndText01
00201     {
00202         public TileSquarePeekImageAndText01() : base(templateName: "TileSquarePeekImageAndText01", imageCount: 1, textCount: 4)
00203         {
00204         }
00205
00206         public INotificationContentImage Image { get { return Images[0]; } }
00207
00208         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00209         public INotificationContentText TextBody1 { get { return TextFields[1]; } }
00210         public INotificationContentText TextBody2 { get { return TextFields[2]; } }
00211         public INotificationContentText TextBody3 { get { return TextFields[3]; } }
00212     }
00213
00214     internal class TileSquarePeekImageAndText02 : TileSquareBase, ITileSquarePeekImageAndText02
00215     {
00216         public TileSquarePeekImageAndText02() : base(templateName: "TileSquarePeekImageAndText02", imageCount: 1, textCount: 2)
00217         {
00218         }
00219
00220         public INotificationContentImage Image { get { return Images[0]; } }
00221
00222         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00223         public INotificationContentText TextBodyWrap { get { return TextFields[1]; } }
00224     }
00225
00226     internal class TileSquarePeekImageAndText03 : TileSquareBase, ITileSquarePeekImageAndText03
00227     {
00228         public TileSquarePeekImageAndText03() : base(templateName: "TileSquarePeekImageAndText03", imageCount: 1, textCount: 4)
00229         {
00230         }
00231
00232         public INotificationContentImage Image { get { return Images[0]; } }
00233
00234         public INotificationContentText TextBody1 { get { return TextFields[0]; } }
00235         public INotificationContentText TextBody2 { get { return TextFields[1]; } }
00236         public INotificationContentText TextBody3 { get { return TextFields[2]; } }
00237         public INotificationContentText TextBody4 { get { return TextFields[3]; } }
00238     }
00239
00240     internal class TileSquarePeekImageAndText04 : TileSquareBase, ITileSquarePeekImageAndText04
00241     {
00242         public TileSquarePeekImageAndText04() : base(templateName: "TileSquarePeekImageAndText04", imageCount: 1, textCount: 1)
00243         {
00244         }
00245
00246         public INotificationContentImage Image { get { return Images[0]; } }
00247
00248         public INotificationContentText TextBodyWrap { get { return TextFields[0]; } }
00249     }
00250
00251     internal class TileSquareText01 : TileSquareBase, ITileSquareText01
00252     {
00253         public TileSquareText01() : base(templateName: "TileSquareText01", imageCount: 0, textCount: 4)
00254         {
00255         }
00256
00257         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00258         public INotificationContentText TextBody1 { get { return TextFields[1]; } }
00259         public INotificationContentText TextBody2 { get { return TextFields[2]; } }
00260         public INotificationContentText TextBody3 { get { return TextFields[3]; } }
00261     }
00262
00263     internal class TileSquareText02 : TileSquareBase, ITileSquareText02
00264     {
00265         public TileSquareText02() : base(templateName: "TileSquareText02", imageCount: 0, textCount: 2)
00266         {
00267         }
00268
00269         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00270         public INotificationContentText TextBodyWrap { get { return TextFields[1]; } }
00271     }
00272
00273     internal class TileSquareText03 : TileSquareBase, ITileSquareText03
00274     {
00275         public TileSquareText03() : base(templateName: "TileSquareText03", imageCount: 0, textCount: 4)
00276         {
00277         }
00278
00279         public INotificationContentText TextBody1 { get { return TextFields[0]; } }
00280         public INotificationContentText TextBody2 { get { return TextFields[1]; } }
00281         public INotificationContentText TextBody3 { get { return TextFields[2]; } }
00282         public INotificationContentText TextBody4 { get { return TextFields[3]; } }
00283     }
00284
00285     internal class TileSquareText04 : TileSquareBase, ITileSquareText04
00286     {
00287         public TileSquareText04() : base(templateName: "TileSquareText04", imageCount: 0, textCount: 1)
00288         {
00289         }
00290
00291         public INotificationContentText TextBodyWrap { get { return TextFields[0]; } }
00292     }
00293
00294     internal class TileWideBlockAndText01 : TileWideBase, ITileWideBlockAndText01
00295     {
00296         public TileWideBlockAndText01() : base(templateName: "TileWideBlockAndText01", imageCount: 0, textCount: 6)
00297         {
00298         }
00299
00300         public INotificationContentText TextBody1 { get { return TextFields[0]; } }
00301         public INotificationContentText TextBody2 { get { return TextFields[1]; } }
00302         public INotificationContentText TextBody3 { get { return TextFields[2]; } }
00303         public INotificationContentText TextBody4 { get { return TextFields[3]; } }
00304         public INotificationContentText TextBlock { get { return TextFields[4]; } }
00305         public INotificationContentText TextSubBlock { get { return TextFields[5]; } }
00306     }
00307
00308     internal class TileWideBlockAndText02 : TileWideBase, ITileWideBlockAndText02
00309     {
00310         public TileWideBlockAndText02() : base(templateName: "TileWideBlockAndText02", imageCount: 0, textCount: 6)
00311         {
00312         }
00313
00314         public INotificationContentText TextBodyWrap { get { return TextFields[0]; } }
00315         public INotificationContentText TextBlock { get { return TextFields[1]; } }
00316         public INotificationContentText TextSubBlock { get { return TextFields[2]; } }
00317     }
00318
00319     internal class TileWideImage : TileWideBase, ITileWideImage
00320     {
00321         public TileWideImage() : base(templateName: "TileWideImage", imageCount: 1, textCount: 0)
00322         {
00323         }
00324
00325         public INotificationContentImage Image { get { return Images[0]; } }
00326     }
00327
00328     internal class TileWideImageAndText01 : TileWideBase, ITileWideImageAndText01
00329     {
00330         public TileWideImageAndText01() : base(templateName: "TileWideImageAndText01", imageCount: 1, textCount: 1)
00331         {
00332         }
00333
00334         public INotificationContentImage Image { get { return Images[0]; } }
00335
00336         public INotificationContentText TextCaptionWrap { get { return TextFields[0]; } }
00337     }
00338
00339     internal class TileWideImageAndText02 : TileWideBase, ITileWideImageAndText02
00340     {
00341         public TileWideImageAndText02() : base(templateName: "TileWideImageAndText02", imageCount: 1, textCount: 2)
00342         {
00343         }
00344
00345         public INotificationContentImage Image { get { return Images[0]; } }
00346
00347         public INotificationContentText TextCaption1 { get { return TextFields[0]; } }
00348         public INotificationContentText TextCaption2 { get { return TextFields[1]; } }
00349     }
00350
00351     internal class TileWideImageCollection : TileWideBase, ITileWideImageCollection
00352     {
00353         public TileWideImageCollection() : base(templateName: "TileWideImageCollection", imageCount: 5, textCount: 0)
00354         {
00355         }
00356
00357         public INotificationContentImage ImageMain { get { return Images[0]; } }
00358         public INotificationContentImage ImageSmallColumn1Row1 { get { return Images[1]; } }
00359         public INotificationContentImage ImageSmallColumn2Row1 { get { return Images[2]; } }
00360         public INotificationContentImage ImageSmallColumn1Row2 { get { return Images[3]; } }
00361         public INotificationContentImage ImageSmallColumn2Row2 { get { return Images[4]; } }
00362     }
00363
00364     internal class TileWidePeekImage01 : TileWideBase, ITileWidePeekImage01
00365     {
00366         public TileWidePeekImage01() : base(templateName: "TileWidePeekImage01", imageCount: 1, textCount: 2)
00367         {
00368         }
00369
00370         public INotificationContentImage Image { get { return Images[0]; } }
00371
00372         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00373         public INotificationContentText TextBodyWrap { get { return TextFields[1]; } }
00374     }
00375
00376     internal class TileWidePeekImage02 : TileWideBase, ITileWidePeekImage02
00377     {
00378         public TileWidePeekImage02() : base(templateName: "TileWidePeekImage02", imageCount: 1, textCount: 5)
00379         {
00380         }
00381
00382         public INotificationContentImage Image { get { return Images[0]; } }
00383
00384         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00385         public INotificationContentText TextBody1 { get { return TextFields[1]; } }
00386         public INotificationContentText TextBody2 { get { return TextFields[2]; } }
00387         public INotificationContentText TextBody3 { get { return TextFields[3]; } }
00388         public INotificationContentText TextBody4 { get { return TextFields[4]; } }
00389     }
00390
00391     internal class TileWidePeekImage03 : TileWideBase, ITileWidePeekImage03
00392     {
00393         public TileWidePeekImage03() : base(templateName: "TileWidePeekImage03", imageCount: 1, textCount: 1)
00394         {
00395         }
00396
00397         public INotificationContentImage Image { get { return Images[0]; } }
00398
00399         public INotificationContentText TextHeadingWrap { get { return TextFields[0]; } }
00400     }
00401
00402     internal class TileWidePeekImage04 : TileWideBase, ITileWidePeekImage04
00403     {
00404         public TileWidePeekImage04() : base(templateName: "TileWidePeekImage04", imageCount: 1, textCount: 1)
00405         {
00406         }
00407
00408         public INotificationContentImage Image { get { return Images[0]; } }
00409
00410         public INotificationContentText TextBodyWrap { get { return TextFields[0]; } }
00411     }
00412
00413     internal class TileWidePeekImage05 : TileWideBase, ITileWidePeekImage05
00414     {
00415         public TileWidePeekImage05() : base(templateName: "TileWidePeekImage05", imageCount: 2, textCount: 2)
00416         {
00417         }
00418
00419         public INotificationContentImage ImageMain { get { return Images[0]; } }
00420         public INotificationContentImage ImageSecondary { get { return Images[1]; } }
00421
00422         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00423         public INotificationContentText TextBodyWrap { get { return TextFields[1]; } }
00424     }
00425
00426     internal class TileWidePeekImage06 : TileWideBase, ITileWidePeekImage06
00427     {
00428         public TileWidePeekImage06() : base(templateName: "TileWidePeekImage06", imageCount: 2, textCount: 1)
00429         {
00430         }
00431
00432         public INotificationContentImage ImageMain { get { return Images[0]; } }
00433         public INotificationContentImage ImageSecondary { get { return Images[1]; } }
00434
00435         public INotificationContentText TextHeadingWrap { get { return TextFields[0]; } }
00436     }
00437
00438     internal class TileWidePeekImageAndText01 : TileWideBase, ITileWidePeekImageAndText01
00439     {
00440         public TileWidePeekImageAndText01() : base(templateName: "TileWidePeekImageAndText01", imageCount: 1, textCount: 1)
00441         {
00442         }
00443
00444         public INotificationContentImage Image { get { return Images[0]; } }
00445
00446         public INotificationContentText TextBodyWrap { get { return TextFields[0]; } }
00447     }
00448
00449     internal class TileWidePeekImageAndText02 : TileWideBase, ITileWidePeekImageAndText02
00450     {
00451         public TileWidePeekImageAndText02() : base(templateName: "TileWidePeekImageAndText02", imageCount: 1, textCount: 5)
00452         {
00453         }
00454
00455         public INotificationContentImage Image { get { return Images[0]; } }
00456
00457         public INotificationContentText TextBody1 { get { return TextFields[0]; } }
00458         public INotificationContentText TextBody2 { get { return TextFields[1]; } }
00459         public INotificationContentText TextBody3 { get { return TextFields[2]; } }
00460         public INotificationContentText TextBody4 { get { return TextFields[3]; } }
00461         public INotificationContentText TextBody5 { get { return TextFields[4]; } }
00462     }
00463
00464     internal class TileWidePeekImageCollection01 : TileWideBase, ITileWidePeekImageCollection01
00465     {
00466         public TileWidePeekImageCollection01() : base(templateName: "TileWidePeekImageCollection01", imageCount: 5, textCount: 2)
00467         {
00468         }
00469
00470         public INotificationContentImage ImageMain { get { return Images[0]; } }
00471         public INotificationContentImage ImageSmallColumn1Row1 { get { return Images[1]; } }
00472         public INotificationContentImage ImageSmallColumn2Row1 { get { return Images[2]; } }
00473         public INotificationContentImage ImageSmallColumn1Row2 { get { return Images[3]; } }
00474         public INotificationContentImage ImageSmallColumn2Row2 { get { return Images[4]; } }
00475
00476         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00477         public INotificationContentText TextBodyWrap { get { return TextFields[1]; } }
00478     }
00479
00480     internal class TileWidePeekImageCollection02 : TileWideBase, ITileWidePeekImageCollection02
00481     {
00482         public TileWidePeekImageCollection02() : base(templateName: "TileWidePeekImageCollection02", imageCount: 5, textCount: 5)
00483         {
00484         }
00485
00486         public INotificationContentImage ImageMain { get { return Images[0]; } }
00487         public INotificationContentImage ImageSmallColumn1Row1 { get { return Images[1]; } }
00488         public INotificationContentImage ImageSmallColumn2Row1 { get { return Images[2]; } }
00489         public INotificationContentImage ImageSmallColumn1Row2 { get { return Images[3]; } }
00490         public INotificationContentImage ImageSmallColumn2Row2 { get { return Images[4]; } }
00491
00492         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00493         public INotificationContentText TextBody1 { get { return TextFields[1]; } }
00494         public INotificationContentText TextBody2 { get { return TextFields[2]; } }
00495         public INotificationContentText TextBody3 { get { return TextFields[3]; } }
00496         public INotificationContentText TextBody4 { get { return TextFields[4]; } }
00497     }
00498
00499     internal class TileWidePeekImageCollection03 : TileWideBase, ITileWidePeekImageCollection03
00500     {
00501         public TileWidePeekImageCollection03() : base(templateName: "TileWidePeekImageCollection03", imageCount: 5, textCount: 1)
00502         {
00503         }
00504
00505         public INotificationContentImage ImageMain { get { return Images[0]; } }
00506         public INotificationContentImage ImageSmallColumn1Row1 { get { return Images[1]; } }
00507         public INotificationContentImage ImageSmallColumn2Row1 { get { return Images[2]; } }
00508         public INotificationContentImage ImageSmallColumn1Row2 { get { return Images[3]; } }
00509         public INotificationContentImage ImageSmallColumn2Row2 { get { return Images[4]; } }
00510
00511         public INotificationContentText TextHeadingWrap { get { return TextFields[0]; } }
00512     }
00513
00514     internal class TileWidePeekImageCollection04 : TileWideBase, ITileWidePeekImageCollection04
00515     {
00516         public TileWidePeekImageCollection04() : base(templateName: "TileWidePeekImageCollection04", imageCount: 5, textCount: 1)
00517         {
00518         }
00519
00520         public INotificationContentImage ImageMain { get { return Images[0]; } }
00521         public INotificationContentImage ImageSmallColumn1Row1 { get { return Images[1]; } }
00522         public INotificationContentImage ImageSmallColumn2Row1 { get { return Images[2]; } }
00523         public INotificationContentImage ImageSmallColumn1Row2 { get { return Images[3]; } }
00524         public INotificationContentImage ImageSmallColumn2Row2 { get { return Images[4]; } }
00525
00526         public INotificationContentText TextBodyWrap { get { return TextFields[0]; } }
00527     }
00528
00529     internal class TileWidePeekImageCollection05 : TileWideBase, ITileWidePeekImageCollection05
00530     {
00531         public TileWidePeekImageCollection05() : base(templateName: "TileWidePeekImageCollection05", imageCount: 6, textCount: 2)
00532         {
00533         }
00534
00535         public INotificationContentImage ImageMain { get { return Images[0]; } }
00536         public INotificationContentImage ImageSmallColumn1Row1 { get { return Images[1]; } }
00537         public INotificationContentImage ImageSmallColumn2Row1 { get { return Images[2]; } }
00538         public INotificationContentImage ImageSmallColumn1Row2 { get { return Images[3]; } }
00539         public INotificationContentImage ImageSmallColumn2Row2 { get { return Images[4]; } }
00540         public INotificationContentImage ImageSecondary { get { return Images[5]; } }
00541
00542         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00543         public INotificationContentText TextBodyWrap { get { return TextFields[1]; } }
00544     }
00545
00546     internal class TileWidePeekImageCollection06 : TileWideBase, ITileWidePeekImageCollection06
00547     {
00548         public TileWidePeekImageCollection06() : base(templateName: "TileWidePeekImageCollection06", imageCount: 6, textCount: 1)
00549         {
00550         }
00551
00552         public INotificationContentImage ImageMain { get { return Images[0]; } }
00553         public INotificationContentImage ImageSmallColumn1Row1 { get { return Images[1]; } }
00554         public INotificationContentImage ImageSmallColumn2Row1 { get { return Images[2]; } }
00555         public INotificationContentImage ImageSmallColumn1Row2 { get { return Images[3]; } }
00556         public INotificationContentImage ImageSmallColumn2Row2 { get { return Images[4]; } }
00557         public INotificationContentImage ImageSecondary { get { return Images[5]; } }
00558
00559         public INotificationContentText TextHeadingWrap { get { return TextFields[0]; } }
00560     }
00561
00562     internal class TileWideSmallImageAndText01 : TileWideBase, ITileWideSmallImageAndText01
00563     {
00564         public TileWideSmallImageAndText01() : base(templateName: "TileWideSmallImageAndText01", imageCount: 1, textCount: 1)
00565         {
00566         }
00567
00568         public INotificationContentImage Image { get { return Images[0]; } }
00569
00570         public INotificationContentText TextHeadingWrap { get { return TextFields[0]; } }
00571     }
00572
00573     internal class TileWideSmallImageAndText02 : TileWideBase, ITileWideSmallImageAndText02
00574     {
00575         public TileWideSmallImageAndText02() : base(templateName: "TileWideSmallImageAndText02", imageCount: 1, textCount: 5)
00576         {
00577         }
00578
00579         public INotificationContentImage Image { get { return Images[0]; } }
00580
00581         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00582         public INotificationContentText TextBody1 { get { return TextFields[1]; } }
00583         public INotificationContentText TextBody2 { get { return TextFields[2]; } }
00584         public INotificationContentText TextBody3 { get { return TextFields[3]; } }
00585         public INotificationContentText TextBody4 { get { return TextFields[4]; } }
00586     }
00587
00588     internal class TileWideSmallImageAndText03 : TileWideBase, ITileWideSmallImageAndText03
00589     {
00590         public TileWideSmallImageAndText03() : base(templateName: "TileWideSmallImageAndText03", imageCount: 1, textCount: 1)
00591         {
00592         }
00593
00594         public INotificationContentImage Image { get { return Images[0]; } }
00595
00596         public INotificationContentText TextBodyWrap { get { return TextFields[0]; } }
00597     }
00598
00599     internal class TileWideSmallImageAndText04 : TileWideBase, ITileWideSmallImageAndText04
00600     {
00601         public TileWideSmallImageAndText04() : base(templateName: "TileWideSmallImageAndText04", imageCount: 1, textCount: 2)
00602         {
00603         }
00604
00605         public INotificationContentImage Image { get { return Images[0]; } }
00606
00607         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00608         public INotificationContentText TextBodyWrap { get { return TextFields[1]; } }
00609     }
00610
00611     internal class TileWideSmallImageAndText05 : TileWideBase, ITileWideSmallImageAndText05
00612     {
00613         public TileWideSmallImageAndText05() : base(templateName: "TileWideSmallImageAndText05", imageCount: 1, textCount: 2)
00614         {
00615         }
00616
00617         public INotificationContentImage Image { get { return Images[0]; } }
00618
00619         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00620         public INotificationContentText TextBodyWrap { get { return TextFields[1]; } }
00621     }
00622
00623     internal class TileWideText01 : TileWideBase, ITileWideText01
00624     {
00625         public TileWideText01() : base(templateName: "TileWideText01", imageCount: 0, textCount: 5)
00626         {
00627         }
00628
00629         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00630         public INotificationContentText TextBody1 { get { return TextFields[1]; } }
00631         public INotificationContentText TextBody2 { get { return TextFields[2]; } }
00632         public INotificationContentText TextBody3 { get { return TextFields[3]; } }
00633         public INotificationContentText TextBody4 { get { return TextFields[4]; } }
00634     }
00635
00636     internal class TileWideText02 : TileWideBase, ITileWideText02
00637     {
00638         public TileWideText02() : base(templateName: "TileWideText02", imageCount: 0, textCount: 9)
00639         {
00640         }
00641
00642         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00643         public INotificationContentText TextColumn1Row1 { get { return TextFields[1]; } }
00644         public INotificationContentText TextColumn2Row1 { get { return TextFields[2]; } }
00645         public INotificationContentText TextColumn1Row2 { get { return TextFields[3]; } }
00646         public INotificationContentText TextColumn2Row2 { get { return TextFields[4]; } }
00647         public INotificationContentText TextColumn1Row3 { get { return TextFields[5]; } }
00648         public INotificationContentText TextColumn2Row3 { get { return TextFields[6]; } }
00649         public INotificationContentText TextColumn1Row4 { get { return TextFields[7]; } }
00650         public INotificationContentText TextColumn2Row4 { get { return TextFields[8]; } }
00651     }
00652
00653     internal class TileWideText03 : TileWideBase, ITileWideText03
00654     {
00655         public TileWideText03() : base(templateName: "TileWideText03", imageCount: 0, textCount: 1)
00656         {
00657         }
00658
00659         public INotificationContentText TextHeadingWrap { get { return TextFields[0]; } }
00660     }
00661
00662     internal class TileWideText04 : TileWideBase, ITileWideText04
00663     {
00664         public TileWideText04() : base(templateName: "TileWideText04", imageCount: 0, textCount: 1)
00665         {
00666         }
00667
00668         public INotificationContentText TextBodyWrap { get { return TextFields[0]; } }
00669     }
00670
00671     internal class TileWideText05 : TileWideBase, ITileWideText05
00672     {
00673         public TileWideText05() : base(templateName: "TileWideText05", imageCount: 0, textCount: 5)
00674         {
00675         }
00676
00677         public INotificationContentText TextBody1 { get { return TextFields[0]; } }
00678         public INotificationContentText TextBody2 { get { return TextFields[1]; } }
00679         public INotificationContentText TextBody3 { get { return TextFields[2]; } }
00680         public INotificationContentText TextBody4 { get { return TextFields[3]; } }
00681         public INotificationContentText TextBody5 { get { return TextFields[4]; } }
00682     }
00683
00684     internal class TileWideText06 : TileWideBase, ITileWideText06
00685     {
00686         public TileWideText06() : base(templateName: "TileWideText06", imageCount: 0, textCount: 10)
00687         {
00688         }
00689
00690         public INotificationContentText TextColumn1Row1 { get { return TextFields[0]; } }
00691         public INotificationContentText TextColumn2Row1 { get { return TextFields[1]; } }
00692         public INotificationContentText TextColumn1Row2 { get { return TextFields[2]; } }
00693         public INotificationContentText TextColumn2Row2 { get { return TextFields[3]; } }
00694         public INotificationContentText TextColumn1Row3 { get { return TextFields[4]; } }
00695         public INotificationContentText TextColumn2Row3 { get { return TextFields[5]; } }
00696         public INotificationContentText TextColumn1Row4 { get { return TextFields[6]; } }
00697         public INotificationContentText TextColumn2Row4 { get { return TextFields[7]; } }
00698         public INotificationContentText TextColumn1Row5 { get { return TextFields[8]; } }
00699         public INotificationContentText TextColumn2Row5 { get { return TextFields[9]; } }
00700     }
00701
00702     internal class TileWideText07 : TileWideBase, ITileWideText07
00703     {
00704         public TileWideText07() : base(templateName: "TileWideText07", imageCount: 0, textCount: 9)
00705         {
00706         }
00707
00708         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00709         public INotificationContentText TextShortColumn1Row1 { get { return TextFields[1]; } }
00710         public INotificationContentText TextColumn2Row1 { get { return TextFields[2]; } }
00711         public INotificationContentText TextShortColumn1Row2 { get { return TextFields[3]; } }
00712         public INotificationContentText TextColumn2Row2 { get { return TextFields[4]; } }
00713         public INotificationContentText TextShortColumn1Row3 { get { return TextFields[5]; } }
00714         public INotificationContentText TextColumn2Row3 { get { return TextFields[6]; } }
00715         public INotificationContentText TextShortColumn1Row4 { get { return TextFields[7]; } }
00716         public INotificationContentText TextColumn2Row4 { get { return TextFields[8]; } }
00717     }
00718
00719     internal class TileWideText08 : TileWideBase, ITileWideText08
00720     {
00721         public TileWideText08() : base(templateName: "TileWideText08", imageCount: 0, textCount: 10)
00722         {
00723         }
00724
00725         public INotificationContentText TextShortColumn1Row1 { get { return TextFields[0]; } }
00726         public INotificationContentText TextColumn2Row1 { get { return TextFields[1]; } }
00727         public INotificationContentText TextShortColumn1Row2 { get { return TextFields[2]; } }
00728         public INotificationContentText TextColumn2Row2 { get { return TextFields[3]; } }
00729         public INotificationContentText TextShortColumn1Row3 { get { return TextFields[4]; } }
00730         public INotificationContentText TextColumn2Row3 { get { return TextFields[5]; } }
00731         public INotificationContentText TextShortColumn1Row4 { get { return TextFields[6]; } }
00732         public INotificationContentText TextColumn2Row4 { get { return TextFields[7]; } }
00733         public INotificationContentText TextShortColumn1Row5 { get { return TextFields[8]; } }
00734         public INotificationContentText TextColumn2Row5 { get { return TextFields[9]; } }
00735     }
00736
00737     internal class TileWideText09 : TileWideBase, ITileWideText09
00738     {
00739         public TileWideText09() : base(templateName: "TileWideText09", imageCount: 0, textCount: 2)
00740         {
00741         }
00742
00743         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00744         public INotificationContentText TextBodyWrap { get { return TextFields[1]; } }
00745     }
00746
00747     internal class TileWideText10 : TileWideBase, ITileWideText10
00748     {
00749         public TileWideText10() : base(templateName: "TileWideText10", imageCount: 0, textCount: 9)
00750         {
00751         }
00752
00753         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00754         public INotificationContentText TextPrefixColumn1Row1 { get { return TextFields[1]; } }
00755         public INotificationContentText TextColumn2Row1 { get { return TextFields[2]; } }
00756         public INotificationContentText TextPrefixColumn1Row2 { get { return TextFields[3]; } }
00757         public INotificationContentText TextColumn2Row2 { get { return TextFields[4]; } }
00758         public INotificationContentText TextPrefixColumn1Row3 { get { return TextFields[5]; } }
00759         public INotificationContentText TextColumn2Row3 { get { return TextFields[6]; } }
00760         public INotificationContentText TextPrefixColumn1Row4 { get { return TextFields[7]; } }
00761         public INotificationContentText TextColumn2Row4 { get { return TextFields[8]; } }
00762     }
00763
00764     internal class TileWideText11 : TileWideBase, ITileWideText11
00765     {
00766         public TileWideText11() : base(templateName: "TileWideText11", imageCount: 0, textCount: 10)
00767         {
00768         }
00769
00770         public INotificationContentText TextPrefixColumn1Row1 { get { return TextFields[0]; } }
00771         public INotificationContentText TextColumn2Row1 { get { return TextFields[1]; } }
00772         public INotificationContentText TextPrefixColumn1Row2 { get { return TextFields[2]; } }
00773         public INotificationContentText TextColumn2Row2 { get { return TextFields[3]; } }
00774         public INotificationContentText TextPrefixColumn1Row3 { get { return TextFields[4]; } }
00775         public INotificationContentText TextColumn2Row3 { get { return TextFields[5]; } }
00776         public INotificationContentText TextPrefixColumn1Row4 { get { return TextFields[6]; } }
00777         public INotificationContentText TextColumn2Row4 { get { return TextFields[7]; } }
00778         public INotificationContentText TextPrefixColumn1Row5 { get { return TextFields[8]; } }
00779         public INotificationContentText TextColumn2Row5 { get { return TextFields[9]; } }
00780     }
00781
00782     /// <summary>
00783     /// A factory which creates tile content objects for all of the toast template types.
00784     /// </summary>
00785     public sealed class TileContentFactory
00786     {
00787         /// <summary>
00788         /// Creates a tile content object for the TileSquareBlock template.
00789         /// </summary>
00790         /// <returns>A tile content object for the TileSquareBlock template.</returns>
00791         public static ITileSquareBlock CreateTileSquareBlock()
00792         {
00793             return new TileSquareBlock();
00794         }
00795
00796         /// <summary>
00797         /// Creates a tile content object for the TileSquareImage template.
00798         /// </summary>
00799         /// <returns>A tile content object for the TileSquareImage template.</returns>
00800         public static ITileSquareImage CreateTileSquareImage()
00801         {
00802             return new TileSquareImage();
00803         }
00804
00805         /// <summary>
00806         /// Creates a tile content object for the TileSquarePeekImageAndText01 template.
00807         /// </summary>
00808         /// <returns>A tile content object for the TileSquarePeekImageAndText01 template.</returns>
00809         public static ITileSquarePeekImageAndText01 CreateTileSquarePeekImageAndText01()
00810         {
00811             return new TileSquarePeekImageAndText01();
00812         }
00813
00814         /// <summary>
00815         /// Creates a tile content object for the TileSquarePeekImageAndText02 template.
00816         /// </summary>
00817         /// <returns>A tile content object for the TileSquarePeekImageAndText02 template.</returns>
00818         public static ITileSquarePeekImageAndText02 CreateTileSquarePeekImageAndText02()
00819         {
00820             return new TileSquarePeekImageAndText02();
00821         }
00822
00823         /// <summary>
00824         /// Creates a tile content object for the TileSquarePeekImageAndText03 template.
00825         /// </summary>
00826         /// <returns>A tile content object for the TileSquarePeekImageAndText03 template.</returns>
00827         public static ITileSquarePeekImageAndText03 CreateTileSquarePeekImageAndText03()
00828         {
00829             return new TileSquarePeekImageAndText03();
00830         }
00831
00832         /// <summary>
00833         /// Creates a tile content object for the TileSquarePeekImageAndText04 template.
00834         /// </summary>
00835         /// <returns>A tile content object for the TileSquarePeekImageAndText04 template.</returns>
00836         public static ITileSquarePeekImageAndText04 CreateTileSquarePeekImageAndText04()
00837         {
00838             return new TileSquarePeekImageAndText04();
00839         }
00840
00841         /// <summary>
00842         /// Creates a tile content object for the TileSquareText01 template.
00843         /// </summary>
00844         /// <returns>A tile content object for the TileSquareText01 template.</returns>
00845         public static ITileSquareText01 CreateTileSquareText01()
00846         {
00847             return new TileSquareText01();
00848         }
00849
00850         /// <summary>
00851         /// Creates a tile content object for the TileSquareText02 template.
00852         /// </summary>
00853         /// <returns>A tile content object for the TileSquareText02 template.</returns>
00854         public static ITileSquareText02 CreateTileSquareText02()
00855         {
00856             return new TileSquareText02();
00857         }
00858
00859         /// <summary>
00860         /// Creates a tile content object for the TileSquareText03 template.
00861         /// </summary>
00862         /// <returns>A tile content object for the TileSquareText03 template.</returns>
00863         public static ITileSquareText03 CreateTileSquareText03()
00864         {
00865             return new TileSquareText03();
00866         }
00867
00868         /// <summary>
00869         /// Creates a tile content object for the TileSquareText04 template.
00870         /// </summary>
00871         /// <returns>A tile content object for the TileSquareText04 template.</returns>
00872         public static ITileSquareText04 CreateTileSquareText04()
00873         {
00874             return new TileSquareText04();
00875         }
00876
00877         /// <summary>
00878         /// Creates a tile content object for the TileWideBlockAndText01 template.
00879         /// </summary>
00880         /// <returns>A tile content object for the TileWideBlockAndText01 template.</returns>
00881         public static ITileWideBlockAndText01 CreateTileWideBlockAndText01()
00882         {
00883             return new TileWideBlockAndText01();
00884         }
00885
00886         /// <summary>
00887         /// Creates a tile content object for the TileWideBlockAndText02 template.
00888         /// </summary>
00889         /// <returns>A tile content object for the TileWideBlockAndText02 template.</returns>
00890         public static ITileWideBlockAndText02 CreateTileWideBlockAndText02()
00891         {
00892             return new TileWideBlockAndText02();
00893         }
00894
00895         /// <summary>
00896         /// Creates a tile content object for the TileWideImage template.
00897         /// </summary>
00898         /// <returns>A tile content object for the TileWideImage template.</returns>
00899         public static ITileWideImage CreateTileWideImage()
00900         {
00901             return new TileWideImage();
00902         }
00903
00904         /// <summary>
00905         /// Creates a tile content object for the TileWideImageAndText01 template.
00906         /// </summary>
00907         /// <returns>A tile content object for the TileWideImageAndText01 template.</returns>
00908         public static ITileWideImageAndText01 CreateTileWideImageAndText01()
00909         {
00910             return new TileWideImageAndText01();
00911         }
00912
00913         /// <summary>
00914         /// Creates a tile content object for the TileWideImageAndText02 template.
00915         /// </summary>
00916         /// <returns>A tile content object for the TileWideImageAndText02 template.</returns>
00917         public static ITileWideImageAndText02 CreateTileWideImageAndText02()
00918         {
00919             return new TileWideImageAndText02();
00920         }
00921
00922         /// <summary>
00923         /// Creates a tile content object for the TileWideImageCollection template.
00924         /// </summary>
00925         /// <returns>A tile content object for the TileWideImageCollection template.</returns>
00926         public static ITileWideImageCollection CreateTileWideImageCollection()
00927         {
00928             return new TileWideImageCollection();
00929         }
00930
00931         /// <summary>
00932         /// Creates a tile content object for the TileWidePeekImage01 template.
00933         /// </summary>
00934         /// <returns>A tile content object for the TileWidePeekImage01 template.</returns>
00935         public static ITileWidePeekImage01 CreateTileWidePeekImage01()
00936         {
00937             return new TileWidePeekImage01();
00938         }
00939
00940         /// <summary>
00941         /// Creates a tile content object for the TileWidePeekImage02 template.
00942         /// </summary>
00943         /// <returns>A tile content object for the TileWidePeekImage02 template.</returns>
00944         public static ITileWidePeekImage02 CreateTileWidePeekImage02()
00945         {
00946             return new TileWidePeekImage02();
00947         }
00948
00949         /// <summary>
00950         /// Creates a tile content object for the TileWidePeekImage03 template.
00951         /// </summary>
00952         /// <returns>A tile content object for the TileWidePeekImage03 template.</returns>
00953         public static ITileWidePeekImage03 CreateTileWidePeekImage03()
00954         {
00955             return new TileWidePeekImage03();
00956         }
00957
00958         /// <summary>
00959         /// Creates a tile content object for the TileWidePeekImage04 template.
00960         /// </summary>
00961         /// <returns>A tile content object for the TileWidePeekImage04 template.</returns>
00962         public static ITileWidePeekImage04 CreateTileWidePeekImage04()
00963         {
00964             return new TileWidePeekImage04();
00965         }
00966
00967         /// <summary>
00968         /// Creates a tile content object for the TileWidePeekImage05 template.
00969         /// </summary>
00970         /// <returns>A tile content object for the TileWidePeekImage05 template.</returns>
00971         public static ITileWidePeekImage05 CreateTileWidePeekImage05()
00972         {
00973             return new TileWidePeekImage05();
00974         }
00975
00976         /// <summary>
00977         /// Creates a tile content object for the TileWidePeekImage06 template.
00978         /// </summary>
00979         /// <returns>A tile content object for the TileWidePeekImage06 template.</returns>
00980         public static ITileWidePeekImage06 CreateTileWidePeekImage06()
00981         {
00982             return new TileWidePeekImage06();
00983         }
00984
00985         /// <summary>
00986         /// Creates a tile content object for the TileWidePeekImageAndText01 template.
00987         /// </summary>
00988         /// <returns>A tile content object for the TileWidePeekImageAndText01 template.</returns>
00989         public static ITileWidePeekImageAndText01 CreateTileWidePeekImageAndText01()
00990         {
00991             return new TileWidePeekImageAndText01();
00992         }
00993
00994         /// <summary>
00995         /// Creates a tile content object for the TileWidePeekImageAndText02 template.
00996         /// </summary>
00997         /// <returns>A tile content object for the TileWidePeekImageAndText02 template.</returns>
00998         public static ITileWidePeekImageAndText02 CreateTileWidePeekImageAndText02()
00999         {
01000             return new TileWidePeekImageAndText02();
01001         }
01002
01003         /// <summary>
01004         /// Creates a tile content object for the TileWidePeekImageCollection01 template.
01005         /// </summary>
01006         /// <returns>A tile content object for the TileWidePeekImageCollection01 template.</returns>
01007         public static ITileWidePeekImageCollection01 CreateTileWidePeekImageCollection01()
01008         {
01009             return new TileWidePeekImageCollection01();
01010         }
01011
01012         /// <summary>
01013         /// Creates a tile content object for the TileWidePeekImageCollection02 template.
01014         /// </summary>
01015         /// <returns>A tile content object for the TileWidePeekImageCollection02 template.</returns>
01016         public static ITileWidePeekImageCollection02 CreateTileWidePeekImageCollection02()
01017         {
01018             return new TileWidePeekImageCollection02();
01019         }
01020
01021         /// <summary>
01022         /// Creates a tile content object for the TileWidePeekImageCollection03 template.
01023         /// </summary>
01024         /// <returns>A tile content object for the TileWidePeekImageCollection03 template.</returns>
01025         public static ITileWidePeekImageCollection03 CreateTileWidePeekImageCollection03()
01026         {
01027             return new TileWidePeekImageCollection03();
01028         }
01029
01030         /// <summary>
01031         /// Creates a tile content object for the TileWidePeekImageCollection04 template.
01032         /// </summary>
01033         /// <returns>A tile content object for the TileWidePeekImageCollection04 template.</returns>
01034         public static ITileWidePeekImageCollection04 CreateTileWidePeekImageCollection04()
01035         {
01036             return new TileWidePeekImageCollection04();
01037         }
01038
01039         /// <summary>
01040         /// Creates a tile content object for the TileWidePeekImageCollection05 template.
01041         /// </summary>
01042         /// <returns>A tile content object for the TileWidePeekImageCollection05 template.</returns>
01043         public static ITileWidePeekImageCollection05 CreateTileWidePeekImageCollection05()
01044         {
01045             return new TileWidePeekImageCollection05();
01046         }
01047
01048         /// <summary>
01049         /// Creates a tile content object for the TileWidePeekImageCollection06 template.
01050         /// </summary>
01051         /// <returns>A tile content object for the TileWidePeekImageCollection06 template.</returns>
01052         public static ITileWidePeekImageCollection06 CreateTileWidePeekImageCollection06()
01053         {
01054             return new TileWidePeekImageCollection06();
01055         }
01056
01057         /// <summary>
01058         /// Creates a tile content object for the TileWideSmallImageAndText01 template.
01059         /// </summary>
01060         /// <returns>A tile content object for the TileWideSmallImageAndText01 template.</returns>
01061         public static ITileWideSmallImageAndText01 CreateTileWideSmallImageAndText01()
01062         {
01063             return new TileWideSmallImageAndText01();
01064         }
01065
01066         /// <summary>
01067         /// Creates a tile content object for the TileWideSmallImageAndText02 template.
01068         /// </summary>
01069         /// <returns>A tile content object for the TileWideSmallImageAndText02 template.</returns>
01070         public static ITileWideSmallImageAndText02 CreateTileWideSmallImageAndText02()
01071         {
01072             return new TileWideSmallImageAndText02();
01073         }
01074
01075         /// <summary>
01076         /// Creates a tile content object for the TileWideSmallImageAndText03 template.
01077         /// </summary>
01078         /// <returns>A tile content object for the TileWideSmallImageAndText03 template.</returns>
01079
01080         public static ITileWideSmallImageAndText03 CreateTileWideSmallImageAndText03()
01081         {
01082             return new TileWideSmallImageAndText03();
01083         }
01084
01085         /// <summary>
01086         /// Creates a tile content object for the TileWideSmallImageAndText04 template.
01087         /// </summary>
01088         /// <returns>A tile content object for the TileWideSmallImageAndText04 template.</returns>
01089         public static ITileWideSmallImageAndText04 CreateTileWideSmallImageAndText04()
01090         {
01091             return new TileWideSmallImageAndText04();
01092         }
01093
01094         /// <summary>
01095         /// Creates a tile content object for the TileWideSmallImageAndText05 template.
01096         /// </summary>
01097         /// <returns>A tile content object for the TileWideSmallImageAndText05 template.</returns>
01098         public static ITileWideSmallImageAndText05 CreateTileWideSmallImageAndText05()
01099         {
01100             return new TileWideSmallImageAndText05();
01101         }
01102
01103         /// <summary>
01104         /// Creates a tile content object for the TileWideText01 template.
01105         /// </summary>
01106         /// <returns>A tile content object for the TileWideText01 template.</returns>
01107         public static ITileWideText01 CreateTileWideText01()
01108         {
01109             return new TileWideText01();
01110         }
01111
01112         /// <summary>
01113         /// Creates a tile content object for the TileWideText02 template.
01114         /// </summary>
01115         /// <returns>A tile content object for the TileWideText02 template.</returns>
01116         public static ITileWideText02 CreateTileWideText02()
01117         {
01118             return new TileWideText02();
01119         }
01120
01121         /// <summary>
01122         /// Creates a tile content object for the TileWideText03 template.
01123         /// </summary>
01124         /// <returns>A tile content object for the TileWideText03 template.</returns>
01125         public static ITileWideText03 CreateTileWideText03()
01126         {
01127             return new TileWideText03();
01128         }
01129
01130         /// <summary>
01131         /// Creates a tile content object for the TileWideText04 template.
01132         /// </summary>
01133         /// <returns>A tile content object for the TileWideText04 template.</returns>
01134         public static ITileWideText04 CreateTileWideText04()
01135         {
01136             return new TileWideText04();
01137         }
01138
01139         /// <summary>
01140         /// Creates a tile content object for the TileWideText05 template.
01141         /// </summary>
01142         /// <returns>A tile content object for the TileWideText05 template.</returns>
01143         public static ITileWideText05 CreateTileWideText05()
01144         {
01145             return new TileWideText05();
01146         }
01147
01148         /// <summary>
01149         /// Creates a tile content object for the TileWideText06 template.
01150         /// </summary>
01151         /// <returns>A tile content object for the TileWideText06 template.</returns>
01152         public static ITileWideText06 CreateTileWideText06()
01153         {
01154             return new TileWideText06();
01155         }
01156
01157         /// <summary>
01158         /// Creates a tile content object for the TileWideText07 template.
01159         /// </summary>
01160         /// <returns>A tile content object for the TileWideText07 template.</returns>
01161         public static ITileWideText07 CreateTileWideText07()
01162         {
01163             return new TileWideText07();
01164         }
01165
01166         /// <summary>
01167         /// Creates a tile content object for the TileWideText08 template.
01168         /// </summary>
01169         /// <returns>A tile content object for the TileWideText08 template.</returns>
01170         public static ITileWideText08 CreateTileWideText08()
01171         {
01172             return new TileWideText08();
01173         }
01174
01175         /// <summary>
01176         /// Creates a tile content object for the TileWideText09 template.
01177         /// </summary>
01178         /// <returns>A tile content object for the TileWideText09 template.</returns>
01179         public static ITileWideText09 CreateTileWideText09()
01180         {
01181             return new TileWideText09();
01182         }
01183
01184         /// <summary>
01185         /// Creates a tile content object for the TileWideText10 template.
01186         /// </summary>
01187         /// <returns>A tile content object for the TileWideText10 template.</returns>
01188         public static ITileWideText10 CreateTileWideText10()
01189         {
01190             return new TileWideText10();
01191         }
01192
01193         /// <summary>
01194         /// Creates a tile content object for the TileWideText11 template.
01195         /// </summary>
01196         /// <returns>A tile content object for the TileWideText11 template.</returns>
01197         public static ITileWideText11 CreateTileWideText11()
01198         {
01199             return new TileWideText11();
01200         }
01201     }
01202 }
Generated on Sat Nov 23 2024 16:08:19 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Trial app and in-app purchase/C++/common/suspensionmanager.h Source File

  • Trial app and in-app purchase
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D-Direct2D interop/C++/DirectXBase.cpp Source File

  • Direct3D-Direct2D interop

DirectXBase.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 "DirectXBase.h"
00010
00011 using namespace Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::Graphics::Display;
00015 using namespace D2D1;
00016
00017 // Constructor.
00018 DirectXBase::DirectXBase() :
00019     m_windowSizeChangeInProgress(false),
00020     m_dpi(-1.0f)
00021 {
00022 }
00023
00024 // Initialize the DirectX resources required to run.
00025 void DirectXBase::Initialize(CoreWindow^ window, float dpi)
00026 {
00027     m_window = window;
00028
00029     CreateDeviceIndependentResources();
00030     CreateDeviceResources();
00031     SetDpi(dpi);
00032 }
00033
00034 // Recreate all device resources and set them back to the current state.
00035 void DirectXBase::HandleDeviceLost()
00036 {
00037     // Reset these member variables to ensure that SetDpi recreates all resources.
00038     float dpi = m_dpi;
00039     m_dpi = -1.0f;
00040     m_windowBounds.Width = 0;
00041     m_windowBounds.Height = 0;
00042     m_swapChain = nullptr;
00043
00044     CreateDeviceResources();
00045     SetDpi(dpi);
00046 }
00047
00048 // These are the resources required independent of the device.
00049 void DirectXBase::CreateDeviceIndependentResources()
00050 {
00051     D2D1_FACTORY_OPTIONS options;
00052     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00053
00054 #if defined(_DEBUG)
00055     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00056     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00057 #endif
00058
00059     DX::ThrowIfFailed(
00060         D2D1CreateFactory(
00061             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00062             __uuidof(ID2D1Factory1),
00063             &options,
00064             &m_d2dFactory
00065             )
00066         );
00067
00068     DX::ThrowIfFailed(
00069         DWriteCreateFactory(
00070             DWRITE_FACTORY_TYPE_SHARED,
00071             __uuidof(IDWriteFactory),
00072             &m_dwriteFactory
00073             )
00074         );
00075
00076     DX::ThrowIfFailed(
00077         CoCreateInstance(
00078             CLSID_WICImagingFactory,
00079             nullptr,
00080             CLSCTX_INPROC_SERVER,
00081             IID_PPV_ARGS(&m_wicFactory)
00082             )
00083         );
00084 }
00085
00086 // These are the resources that depend on the device.
00087 void DirectXBase::CreateDeviceResources()
00088 {
00089     // This flag adds support for surfaces with a different color channel ordering
00090     // than the API default. It is required for compatibility with Direct2D.
00091     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00092     ComPtr<IDXGIDevice> dxgiDevice;
00093
00094 #if defined(_DEBUG)
00095     // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00096     creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00097 #endif
00098
00099     // This array defines the set of DirectX hardware feature levels this app will support.
00100     // Note the ordering should be preserved.
00101     // Don't forget to declare your application's minimum required feature level in its
00102     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00103     D3D_FEATURE_LEVEL featureLevels[] =
00104     {
00105         D3D_FEATURE_LEVEL_11_1,
00106         D3D_FEATURE_LEVEL_11_0,
00107         D3D_FEATURE_LEVEL_10_1,
00108         D3D_FEATURE_LEVEL_10_0,
00109         D3D_FEATURE_LEVEL_9_3,
00110         D3D_FEATURE_LEVEL_9_2,
00111         D3D_FEATURE_LEVEL_9_1
00112     };
00113
00114     // Create the Direct3D 11 API device object and a corresponding context.
00115     ComPtr<ID3D11Device> device;
00116     ComPtr<ID3D11DeviceContext> context;
00117     DX::ThrowIfFailed(
00118         D3D11CreateDevice(
00119             nullptr,                    // Specify nullptr to use the default adapter.
00120             D3D_DRIVER_TYPE_HARDWARE,
00121             0,
00122             creationFlags,              // Set debug and Direct2D compatibility flags.
00123             featureLevels,              // List of feature levels this app can support.
00124             ARRAYSIZE(featureLevels),
00125             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Metro style apps.
00126             &device,                    // Returns the Direct3D device created.
00127             &m_featureLevel,            // Returns feature level of device created.
00128             &context                    // Returns the device immediate context.
00129             )
00130         );
00131
00132     // Get the Direct3D 11.1 API device and context interfaces.
00133     DX::ThrowIfFailed(
00134         device.As(&m_d3dDevice)
00135         );
00136
00137     DX::ThrowIfFailed(
00138         context.As(&m_d3dContext)
00139         );
00140
00141     // Get the underlying DXGI device of the Direct3D device.
00142     DX::ThrowIfFailed(
00143         m_d3dDevice.As(&dxgiDevice)
00144         );
00145
00146     // Create the Direct2D device object and a corresponding context.
00147     DX::ThrowIfFailed(
00148         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00149         );
00150
00151     DX::ThrowIfFailed(
00152         m_d2dDevice->CreateDeviceContext(
00153             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00154             &m_d2dContext
00155             )
00156         );
00157 }
00158
00159 // Helps track the DPI in the helper class.
00160 // This is called in the dpiChanged event handler in the view class.
00161 void DirectXBase::SetDpi(float dpi)
00162 {
00163     if (dpi != m_dpi)
00164     {
00165         // Save the DPI of this display in our class.
00166         m_dpi = dpi;
00167
00168         // Update Direct2D's stored DPI.
00169         m_d2dContext->SetDpi(m_dpi, m_dpi);
00170
00171         // Often a DPI change implies a window size change. In some cases Windows will issue
00172         // both a size changed event and a DPI changed event. In this case, the resulting bounds
00173         // will not change, and the window resize code will only be executed once.
00174         UpdateForWindowSizeChange();
00175     }
00176 }
00177
00178 // This routine is called in the event handler for the view SizeChanged event.
00179 void DirectXBase::UpdateForWindowSizeChange()
00180 {
00181     // Only handle window size changed if there is no pending DPI change.
00182     if (m_dpi != DisplayProperties::LogicalDpi)
00183     {
00184         return;
00185     }
00186
00187     if (m_window->Bounds.Width  != m_windowBounds.Width ||
00188         m_window->Bounds.Height != m_windowBounds.Height)
00189     {
00190         m_d2dContext->SetTarget(nullptr);
00191         m_d2dTargetBitmap = nullptr;
00192         m_d3dRenderTargetView = nullptr;
00193         m_d3dDepthStencilView = nullptr;
00194         m_windowSizeChangeInProgress = true;
00195         CreateWindowSizeDependentResources();
00196     }
00197 }
00198
00199 // Allocate all memory resources that change on a window SizeChanged event.
00200 void DirectXBase::CreateWindowSizeDependentResources()
00201 {
00202     // Store the window bounds so the next time we get a SizeChanged event we can
00203     // avoid rebuilding everything if the size is identical.
00204     m_windowBounds = m_window->Bounds;
00205
00206     if (m_swapChain != nullptr)
00207     {
00208         // If the swap chain already exists, resize it.
00209         HRESULT hr = m_swapChain->ResizeBuffers(2, 0, 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0);
00210
00211         if (hr == DXGI_ERROR_DEVICE_REMOVED)
00212         {
00213             // If the device was removed for any reason, a new device and swapchain will need to be created.
00214             HandleDeviceLost();
00215
00216             // Everything is set up now. Do not continue execution of this method.
00217             return;
00218         }
00219         else
00220         {
00221             DX::ThrowIfFailed(hr);
00222         }
00223     }
00224     else
00225     {
00226         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00227         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00228         swapChainDesc.Width = 0;                                     // Use automatic sizing.
00229         swapChainDesc.Height = 0;
00230         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;           // This is the most common swap chain format.
00231         swapChainDesc.Stereo = false;
00232         swapChainDesc.SampleDesc.Count = 1;                          // Don't use multi-sampling.
00233         swapChainDesc.SampleDesc.Quality = 0;
00234         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00235         swapChainDesc.BufferCount = 2;                               // Use double-buffering to minimize latency.
00236         swapChainDesc.Scaling = DXGI_SCALING_NONE;
00237         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Metro style apps must use this SwapEffect.
00238         swapChainDesc.Flags = 0;
00239
00240         ComPtr<IDXGIDevice1> dxgiDevice;
00241         DX::ThrowIfFailed(
00242             m_d3dDevice.As(&dxgiDevice)
00243             );
00244
00245         ComPtr<IDXGIAdapter> dxgiAdapter;
00246         DX::ThrowIfFailed(
00247             dxgiDevice->GetAdapter(&dxgiAdapter)
00248             );
00249
00250         ComPtr<IDXGIFactory2> dxgiFactory;
00251         DX::ThrowIfFailed(
00252             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00253             );
00254
00255         CoreWindow^ window = m_window.Get();
00256         DX::ThrowIfFailed(
00257             dxgiFactory->CreateSwapChainForCoreWindow(
00258                 m_d3dDevice.Get(),
00259                 reinterpret_cast<IUnknown*>(window),
00260                 &swapChainDesc,
00261                 nullptr,
00262                 &m_swapChain
00263                 )
00264             );
00265
00266         // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
00267         // ensures that the application will only render after each VSync, minimizing power consumption.
00268         DX::ThrowIfFailed(
00269             dxgiDevice->SetMaximumFrameLatency(1)
00270             );
00271     }
00272
00273     // Create a Direct3D render target view of the swap chain back buffer.
00274     ComPtr<ID3D11Texture2D> backBuffer;
00275     DX::ThrowIfFailed(
00276         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00277         );
00278
00279     DX::ThrowIfFailed(
00280         m_d3dDevice->CreateRenderTargetView(
00281             backBuffer.Get(),
00282             nullptr,
00283             &m_d3dRenderTargetView
00284             )
00285         );
00286
00287     // Cache the rendertarget dimensions in our helper class for convenient use.
00288     D3D11_TEXTURE2D_DESC backBufferDesc = {0};
00289     backBuffer->GetDesc(&backBufferDesc);
00290     m_renderTargetSize.Width  = static_cast<float>(backBufferDesc.Width);
00291     m_renderTargetSize.Height = static_cast<float>(backBufferDesc.Height);
00292
00293     // Create a depth stencil view for use with 3D rendering if needed.
00294     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00295         DXGI_FORMAT_D24_UNORM_S8_UINT,
00296         backBufferDesc.Width,
00297         backBufferDesc.Height,
00298         1,
00299         1,
00300         D3D11_BIND_DEPTH_STENCIL
00301         );
00302
00303     ComPtr<ID3D11Texture2D> depthStencil;
00304     DX::ThrowIfFailed(
00305         m_d3dDevice->CreateTexture2D(
00306             &depthStencilDesc,
00307             nullptr,
00308             &depthStencil
00309             )
00310         );
00311
00312     auto viewDesc = CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D);
00313     DX::ThrowIfFailed(
00314         m_d3dDevice->CreateDepthStencilView(
00315             depthStencil.Get(),
00316             &viewDesc,
00317             &m_d3dDepthStencilView
00318             )
00319         );
00320
00321     // Set the 3D rendering viewport to target the entire window.
00322     CD3D11_VIEWPORT viewport(
00323         0.0f,
00324         0.0f,
00325         static_cast<float>(backBufferDesc.Width),
00326         static_cast<float>(backBufferDesc.Height)
00327         );
00328
00329     m_d3dContext->RSSetViewports(1, &viewport);
00330
00331     // Create a Direct2D target bitmap associated with the
00332     // swap chain back buffer and set it as the current target.
00333     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00334         BitmapProperties1(
00335             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00336             PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00337             m_dpi,
00338             m_dpi
00339             );
00340
00341     ComPtr<IDXGISurface> dxgiBackBuffer;
00342     DX::ThrowIfFailed(
00343         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00344         );
00345
00346     DX::ThrowIfFailed(
00347         m_d2dContext->CreateBitmapFromDxgiSurface(
00348             dxgiBackBuffer.Get(),
00349             &bitmapProperties,
00350             &m_d2dTargetBitmap
00351             )
00352         );
00353
00354     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00355
00356     // Grayscale text anti-aliasing is recommended for all Metro style apps.
00357     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00358 }
00359
00360 // Method to deliver the final image to the display.
00361 void DirectXBase::Present()
00362 {
00363     // The application may optionally specify "dirty" or "scroll" rects to improve efficiency
00364     // in certain scenarios.  In this sample, however, we do not utilize those features.
00365     DXGI_PRESENT_PARAMETERS parameters = {0};
00366     parameters.DirtyRectsCount = 0;
00367     parameters.pDirtyRects = nullptr;
00368     parameters.pScrollRect = nullptr;
00369     parameters.pScrollOffset = nullptr;
00370
00371     // The first argument instructs DXGI to block until VSync, putting the application
00372     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00373     // frames that will never be displayed to the screen.
00374     HRESULT hr = m_swapChain->Present1(1, 0, &parameters);
00375
00376     // Discard the contents of the render target.
00377     // This is a valid operation only when the existing contents will be entirely
00378     // overwritten. If dirty or scroll rects are used, this call should be removed.
00379     m_d3dContext->DiscardView(m_d3dRenderTargetView.Get());
00380
00381     // Discard the contents of the depth stencil.
00382     m_d3dContext->DiscardView(m_d3dDepthStencilView.Get());
00383
00384     // If the device was removed either by a disconnect or a driver upgrade, we
00385     // must recreate all device resources.
00386     if (hr == DXGI_ERROR_DEVICE_REMOVED)
00387     {
00388         HandleDeviceLost();
00389     }
00390     else
00391     {
00392         DX::ThrowIfFailed(hr);
00393     }
00394
00395     if (m_windowSizeChangeInProgress)
00396     {
00397         // A window size change has been initiated and the app has just completed presenting
00398         // the first frame with the new size. Notify the resize manager so we can short
00399         // circuit any resize animation and prevent unnecessary delays.
00400         CoreWindowResizeManager::GetForCurrentView()->NotifyLayoutCompleted();
00401         m_windowSizeChangeInProgress = false;
00402     }
00403 }
00404
00405 void DirectXBase::ValidateDevice()
00406 {
00407     // The D3D Device is no longer valid if the default adapter changes or if
00408     // the device has been removed.
00409
00410     // First, get the information for the adapter related to the current device.
00411
00412     ComPtr<IDXGIDevice1> dxgiDevice;
00413     ComPtr<IDXGIAdapter> deviceAdapter;
00414     DXGI_ADAPTER_DESC deviceDesc;
00415     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00416     DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter));
00417     DX::ThrowIfFailed(deviceAdapter->GetDesc(&deviceDesc));
00418
00419     // Next, get the information for the default adapter.
00420
00421     ComPtr<IDXGIFactory2> dxgiFactory;
00422     ComPtr<IDXGIAdapter1> currentAdapter;
00423     DXGI_ADAPTER_DESC currentDesc;
00424     DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)));
00425     DX::ThrowIfFailed(dxgiFactory->EnumAdapters1(0, &currentAdapter));
00426     DX::ThrowIfFailed(currentAdapter->GetDesc(&currentDesc));
00427
00428     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00429     // a new D3D device must be created.
00430
00431     if ((deviceDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart) ||
00432         (deviceDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart) ||
00433         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00434     {
00435         // Release references to resources related to the old device.
00436         dxgiDevice = nullptr;
00437         deviceAdapter = nullptr;
00438
00439         // Create a new device and swap chain.
00440         HandleDeviceLost();
00441     }
00442 }
Generated on Sat Nov 23 2024 16:08:02 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File picker contracts/C++/CachedFileUpdater_Local.xaml.h Source File

  • File picker contracts

CachedFileUpdater_Local.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 // CachedFileUpdater_Local.xaml.h
00013 // Declaration of the CachedFileUpdater_Local class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "CachedFileUpdater_Local.g.h"
00020
00021 namespace SDKSample
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 ref class CachedFileUpdater_Local sealed
00029         {
00030         public:
00031             CachedFileUpdater_Local();
00032
00033         private:
00034             void FileIsCurrentButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00035             void ProvideUpdatedVersionButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00036             void UpdateUI(Windows::Storage::Provider::UIStatus uiStatus);
00037             void OutputFileAsync(Windows::Storage::StorageFile^ file);
00038         };
00039     }
00040 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: HttpClient/C++/Scenario4.xaml.cpp Source File

  • HttpClient

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::HttpClientSample;
00020
00021 using namespace concurrency;
00022 using namespace Platform;
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 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
00046 void SDKSample::HttpClientSample::Scenario4::Start_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00047 {
00048     // 'BaseAddress' is a disabled text box, so the value is considered trusted input. When enabling
00049     // the text box make sure to validate the string (e.g., by using Uri.TryCreate()).
00050     Uri^ baseAddress = ref new Uri(BaseAddress->Text);
00051
00052     Helpers::ScenarioStarted(StartButton, CancelButton);
00053     rootPage->NotifyUser("In progress", NotifyType::StatusMessage);
00054     OutputField->Text = "";
00055
00056     // 'AddressField' is a disabled text box, so the value is considered trusted input. When enabling the
00057     // text box make sure to validate user input (e.g., by catching exceptions with TryGetUri as shown in scenario 1).
00058     Uri^ resourceAddress = baseAddress->CombineUri(AddressField->Text);
00059
00060     cancellationTokenSource = cancellation_token_source();
00061
00062     // Do an asynchronous POST.  We need to use use_current() with the continuations since the tasks are completed on
00063     // background threads and we need to run on the UI thread to update the UI.
00064     httpRequest.PostAsync(resourceAddress, RequestBodyField->Text->Data(),
00065         cancellationTokenSource.get_token()).then([this](task<std::wstring> response)
00066     {
00067         Helpers::ScenarioCompleted(StartButton, CancelButton);
00068
00069         try
00070         {
00071             DisplayTextResult(response.get(), OutputField);
00072             rootPage->NotifyUser("Completed", NotifyType::StatusMessage);
00073         }
00074         catch (const task_canceled&)
00075         {
00076             rootPage->NotifyUser("Request canceled.", NotifyType::ErrorMessage);
00077         }
00078         catch (Exception^ ex)
00079         {
00080             rootPage->NotifyUser(ex->Message, NotifyType::ErrorMessage);
00081         }
00082     }, task_continuation_context::use_current());
00083 }
00084
00085 void SDKSample::HttpClientSample::Scenario4::Cancel_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00086 {
00087     cancellationTokenSource.cancel();
00088 }
00089
00090 void SDKSample::HttpClientSample::Scenario4::DisplayTextResult(const std::wstring& response, TextBox^ output)
00091 {
00092     output->Text += httpRequest.GetStatusCode() + " " + ref new String(httpRequest.GetReasonPhrase().c_str()) + "\n";
00093
00094     // Convert all instances of <br> to newline.
00095     std::wstring ws = response;
00096     Helpers::ReplaceAll(ws, L"<br>", L"\n");
00097
00098     output->Text += ref new String(ws.c_str());
00099 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/HiloPage.h Source File

  • Hilo C++
  • Hilo

HiloPage.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 "Common\LayoutAwarePage.h"
00009 #include "PageType.h"
00010 #include "ViewModelBase.h"
00011
00012 namespace Hilo
00013 {
00014     // See http://go.microsoft.com/fwlink/?LinkId=267274 for info about the Hilo app.
00015
00016     // See http://go.microsoft.com/fwlink/?LinkId=267278 for info on how Hilo creates pages and navigates to pages.
00017
00018     // See http://go.microsoft.com/fwlink/?LinkId=267276 for info on how view classes interact
00019     // with corresponding view model classes that encapsulate the app�s state, actions, and operations.
00020
00021     // See http://go.microsoft.com/fwlink/?LinkId=267279 for info on how Hilo pages use XAML controls.
00022
00023     // The HiloPage class contains common logic used by all pages in the app.
00024     [Windows::Foundation::Metadata::WebHostHidden]
00025     public ref class HiloPage : Common::LayoutAwarePage
00026     {
00027     internal:
00028         HiloPage();
00029
00030     public:
00031         // Hilo Page
00032         static property Windows::UI::Xaml::DependencyProperty^ HiloDataContextProperty
00033         {
00034             Windows::UI::Xaml::DependencyProperty^ get();
00035         }
00036
00037     protected:
00038         // Hilo Page
00039         virtual void NavigateBack();
00040         virtual void NavigateHome();
00041         virtual void NavigateToPage(PageType page, Platform::Object^ parameter);
00042         virtual void LoadState(Platform::Object^ navigationParameter,
00043             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00044         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00045         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00046         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00047
00048     internal:
00049         static property bool IsSuspending;
00050         static void OnHiloDataContextPropertyChanged(Windows::UI::Xaml::DependencyObject^ element, Windows::UI::Xaml::DependencyPropertyChangedEventArgs^ e);
00051
00052     private:
00053         // Hilo Page
00054         Windows::Foundation::EventRegistrationToken m_navigateBackEventToken;
00055         Windows::Foundation::EventRegistrationToken m_navigateHomeEventToken;
00056         Windows::Foundation::EventRegistrationToken m_navigateToPageEventToken;
00057         bool m_hasHandlers;
00058
00059         void AttachNavigationHandlers(Hilo::ViewModelBase^ viewModel);
00060         void DetachNavigationHandlers(Hilo::ViewModelBase^ viewModel);
00061     };
00062 }
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Snap/C++/MainPage.xaml.cpp Source File

  • Snap

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:44 for Win8-Examples by doxygen 1.7.1


Win8-Examples: HomeGroup app/C++/common/suspensionmanager.cpp Source File

  • HomeGroup app
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:36 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application resources and localization/C++/Scenario1.xaml.cpp Source File

  • Application resources and localization

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::ApplicationResources;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 Scenario1::Scenario1()
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 Scenario1::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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D custom image effects/C++/VertexShader/WaveEffect.cpp Source File

  • Direct2D custom image effects
  • VertexShader

WaveEffect.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 "WaveEffect.h"
00011 #include "BasicReaderWriter.h"
00012
00013 #define XML(X) TEXT(#X)
00014
00015 static const float WaveMarginLeft = 0.25f;
00016 static const float WaveMarginTop = 0.20f;
00017 static const float WaveMarginRight = 0.25f;
00018 static const float WaveMarginBottom = 0.40f;
00019 static const float WaveHeight = 60;
00020 static const float SkewOffset = -0.4f;
00021 static const unsigned int TessellationAmount = 32;
00022
00023 HRESULT __stdcall WaveEffect::CreateWaveImpl(_Outptr_ IUnknown** ppEffectImpl)
00024 {
00025     *ppEffectImpl = static_cast<ID2D1EffectImpl*>(new (std::nothrow) WaveEffect());
00026
00027     if (*ppEffectImpl == nullptr)
00028     {
00029         return E_OUTOFMEMORY;
00030     }
00031     else
00032     {
00033         return S_OK;
00034     }
00035 }
00036
00037 HRESULT WaveEffect::Register(_In_ ID2D1Factory1* pFactory)
00038 {
00039     PCWSTR propertyXml =
00040         XML(
00041             <?xml version='1.0'?>
00042             <Effect>
00043                 <!-- System Properties -->
00044                 <Property name='DisplayName' type='string' value='Wave Effect'/>
00045                 <Property name='Author' type='string' value='Microsoft Corporation'/>
00046                 <Property name='Category' type='string' value='Sample'/>
00047                 <Property name='Description' type='string' value='Animation of a wave.'/>
00048                 <Inputs>
00049                     <Input name='Source'/>
00050                 </Inputs>
00051                 <!-- Effect-specific Properties -->
00052                 <Property name='WaveOffset' type='float' value='0'>
00053                     <Property name='DisplayName' type='string' value='Wave Offset'/>
00054                     <Property name='Default' type='float' value='0.0'/>
00055                 </Property>
00056                 <Property name='SkewX' type='float' value='0'>
00057                     <Property name='DisplayName' type='string' value='Skew (X-Axis)'/>
00058                     <Property name='Min' type='float' value='-5.0'/>
00059                     <Property name='Max' type='float' value='5.0'/>
00060                     <Property name='Default' type='float' value='0.0'/>
00061                 </Property>
00062                 <Property name='SkewY' type='float' value='0'>
00063                     <Property name='DisplayName' type='string' value='Skew (Y-Axis)'/>
00064                     <Property name='Min' type='float' value='-5.0'/>
00065                     <Property name='Max' type='float' value='5.0'/>
00066                     <Property name='Default' type='float' value='0.0'/>
00067                 </Property>
00068             </Effect>
00069             );
00070
00071     // Property bindings are performed automatically for the system properties.
00072     // For effect-specific properties (i.e. WaveOffset), you must direct
00073     // Direct2D to the specific method in your implementation for manipulating
00074     // the property. This is done by assigning each property a 'setter' and 'getter'
00075     // in this table. Direct2D provides a set of helpers for doing this in
00076     // D2D1EffectHelpers.h, such as D2D1_VALUE_TYPE_BINDING used here.
00077     D2D1_PROPERTY_BINDING bindings[] =
00078     {
00079         D2D1_VALUE_TYPE_BINDING(L"WaveOffset",  &SetWaveOffset,  &GetWaveOffset),
00080         D2D1_VALUE_TYPE_BINDING(L"SkewX",  &SetSkewX,  &GetSkewX),
00081         D2D1_VALUE_TYPE_BINDING(L"SkewY",  &SetSkewY,  &GetSkewY)
00082     };
00083
00084     // Register the effect using the data defined above.
00085     return pFactory->RegisterEffectFromString(
00086         CLSID_CustomWaveEffect,
00087         propertyXml,
00088         bindings,
00089         ARRAYSIZE(bindings),
00090         CreateWaveImpl
00091         );
00092 }
00093
00094 WaveEffect::WaveEffect() :
00095     m_refCount(1),
00096     m_waveOffset(0),
00097     m_skewX(0),
00098     m_skewY(0),
00099     m_sizeX(0),
00100     m_sizeY(0)
00101 {
00102 }
00103
00104 // This method is where as many resources should be initialized as possible.
00105 // While some resources may change over time and cannot be initialized until
00106 // the PrepareForRender() call, initializing resources in this method
00107 // reduces the amount of processing needed during rendering, improving the
00108 // performance of your effect.
00109 HRESULT WaveEffect::Initialize(
00110     _In_ ID2D1EffectContext* pEffectContext,
00111     _In_ ID2D1TransformGraph* pTransformGraph
00112     )
00113 {
00114     BasicReaderWriter^ reader = ref new BasicReaderWriter();
00115
00116     // Read compiled shader data instructions. Visual Studio automatically generates
00117     // the cso (Compiled Shader Object) file at compile time from the HLSL.
00118
00119     Platform::Array<unsigned char, 1U>^ data;
00120
00121     try
00122     {
00123         data = reader->ReadData("WaveEffect.cso");
00124     }
00125     catch (Platform::Exception^ e)
00126     {
00127         // Return error if file can not be read.
00128         return e->HResult;
00129     }
00130
00131     HRESULT hr = pEffectContext->LoadVertexShader(GUID_WaveTransformVertexShader, data->Data, data->Length);
00132
00133     if (SUCCEEDED(hr))
00134     {
00135         // Only generate the vertex buffer if it has not already been initialized.
00136         pEffectContext->FindVertexBuffer(&GUID_WaveTransformVertexBuffer, &m_vertexBuffer);
00137         if (m_vertexBuffer == nullptr)
00138         {
00139             Vertex* mesh;
00140             hr = GenerateMesh(&mesh);
00141
00142             if (SUCCEEDED(hr))
00143             {
00144                 // Updating geometry every time the effect is rendered can be costly, so it is
00145                 // recommended that vertex buffer remain static if possible (which it is in this
00146                 // sample effect).
00147                 D2D1_VERTEX_BUFFER_PROPERTIES vbProp = {0};
00148                 vbProp.byteWidth = sizeof(Vertex) * m_numVertices;
00149                 vbProp.data = reinterpret_cast<BYTE*>(mesh);
00150                 vbProp.inputCount = 1;
00151                 vbProp.usage =  D2D1_VERTEX_USAGE_STATIC;
00152
00153                 static const D2D1_INPUT_ELEMENT_DESC vertexLayout[] =
00154                 {
00155                     {"MESH_POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0},
00156                 };
00157
00158                 D2D1_CUSTOM_VERTEX_BUFFER_PROPERTIES cvbProp = {0};
00159                 cvbProp.elementCount = ARRAYSIZE(vertexLayout);
00160                 cvbProp.inputElements = vertexLayout;
00161                 cvbProp.stride = sizeof(Vertex);
00162                 cvbProp.shaderBufferWithInputSignature = data->Data;
00163                 cvbProp.shaderBufferSize = data->Length;
00164
00165                 // The GUID is optional, and is provided here to register the geometry globally.
00166                 // As mentioned above, this avoids duplication if multiple versions of the effect
00167                 // are created.
00168                 hr = pEffectContext->CreateVertexBuffer(
00169                     &vbProp,
00170                     &GUID_WaveTransformVertexBuffer,
00171                     &cvbProp,
00172                     &m_vertexBuffer
00173                     );
00174             }
00175
00176             // Since mesh has already been transferred to GPU, it can be removed.
00177             delete[] mesh;
00178         }
00179     }
00180
00181     hr = pTransformGraph->SetSingleTransformNode(this);
00182
00183     return hr;
00184 }
00185
00186 HRESULT WaveEffect::GenerateMesh(_Outptr_ Vertex** ppMesh)
00187 {
00188     m_numVertices = 6 * TessellationAmount * TessellationAmount;
00189
00190     Vertex *mesh = new (std::nothrow) Vertex[m_numVertices];
00191
00192     if (mesh == nullptr)
00193     {
00194         return E_OUTOFMEMORY;
00195     }
00196
00197     float offset = 1.0f / TessellationAmount;
00198
00199     for (int i = 0; i < TessellationAmount; i++)
00200     {
00201         for (int j = TessellationAmount - 1; j >= 0; j--)
00202         {
00203             int index = (i * TessellationAmount + j) * 6;
00204
00205             // This mesh consists of pairs of triangles forming squares. Each square contains
00206             // six vertices, three for each triangle. 'offset' represents the distance between each vertice
00207             // in the triangles. In this mesh, we only set the x and y coordinates of the vertices, since
00208             // they are the only variable part of the geometry. In the vertex shader, z is generated
00209             // based on x, and w is defined to be '1'. The actual coordinates here range from 0 to 1,
00210             // these values are scaled up based on the size of the image in the vertex shader.
00211
00212             mesh[index].x     = i * offset;
00213             mesh[index].y     = j * offset;
00214             mesh[index + 1].x = i * offset;
00215             mesh[index + 1].y = j * offset + offset;
00216             mesh[index + 2].x = i * offset + offset;
00217             mesh[index + 2].y = j * offset;
00218             mesh[index + 3].x = i * offset + offset;
00219             mesh[index + 3].y = j * offset;
00220             mesh[index + 4].x = i * offset;
00221             mesh[index + 4].y = j * offset + offset;
00222             mesh[index + 5].x = i * offset + offset;
00223             mesh[index + 5].y = j * offset + offset;
00224         }
00225     }
00226
00227     *ppMesh = mesh;
00228
00229     return S_OK;
00230 }
00231
00232 // Called on first render and/or when the context changes.
00233 IFACEMETHODIMP WaveEffect::PrepareForRender(D2D1_CHANGE_TYPE changeType)
00234 {
00235     return UpdateConstants();
00236 }
00237
00238 // The effect properties are not automatically clamped based on the
00239 // registration XML. Effects should manually implement the min and
00240 // max specified at registration. These functions are called by Direct2D itself,
00241 // based on the property specified in the ID2D1Effect::SetValue call.
00242 HRESULT WaveEffect::SetSkewX(float skew)
00243 {
00244     m_skewX = Clamp(skew, -5.0f, 5.0f);
00245     return S_OK;
00246 }
00247
00248 HRESULT WaveEffect::SetSkewY(float skew)
00249 {
00250     m_skewY = Clamp(skew, -5.0f, 5.0f);
00251     return S_OK;
00252 }
00253
00254 // The wave offset is not clamped since no min or max is specified.
00255 HRESULT WaveEffect::SetWaveOffset(float waveOffset)
00256 {
00257     m_waveOffset = waveOffset;
00258     return S_OK;
00259 }
00260
00261 float WaveEffect::GetSkewX() const
00262 {
00263     return m_skewX;
00264 }
00265
00266 float WaveEffect::GetSkewY() const
00267 {
00268     return m_skewY;
00269 }
00270
00271 float WaveEffect::GetWaveOffset() const
00272 {
00273     return m_waveOffset;
00274 }
00275
00276 HRESULT WaveEffect::UpdateConstants()
00277 {
00278     // Update constant buffer 1 (the first constant buffer available to the effect)
00279     // with the progress, skew, and size values.
00280
00281     m_constants.matrix = D2D1::Matrix4x4F::RotationX(3);
00282     m_constants.sizeX = m_sizeX;
00283     m_constants.sizeY = m_sizeY;
00284     m_constants.waveOffset = m_waveOffset;
00285     m_constants.skewX = m_skewX;
00286     m_constants.skewY = m_skewY;
00287
00288     return m_drawInfo->SetVertexShaderConstantBuffer(reinterpret_cast<const BYTE*>(&m_constants), sizeof(m_constants));
00289
00290 }
00291
00292 IFACEMETHODIMP WaveEffect::MapOutputRectToInputRects(
00293     _In_ const D2D1_RECT_L* pOutputRect,
00294     _Out_writes_(inputRectCount) D2D1_RECT_L* pInputRects,
00295     UINT32 inputRectCount
00296     ) const
00297 {
00298     if (inputRectCount != 1)
00299     {
00300         return E_FAIL;
00301     }
00302
00303     pInputRects[0] = m_inputRect;
00304
00305     return S_OK;
00306 }
00307
00308 IFACEMETHODIMP WaveEffect::MapInputRectsToOutputRect(
00309     _In_reads_(inputRectCount) CONST D2D1_RECT_L* pInputRects,
00310     _In_reads_(inputRectCount) CONST D2D1_RECT_L* pInputOpaqueSubRects,
00311     UINT32 inputRectCount,
00312     _Out_ D2D1_RECT_L* pOutputRect,
00313     _Out_ D2D1_RECT_L* pOutputOpaqueSubRect
00314     )
00315 {
00316     HRESULT hr = S_OK;
00317
00318     if (inputRectCount != 1)
00319     {
00320         return E_FAIL;
00321     }
00322
00323     m_inputRect = pInputRects[0];
00324
00325     // Store the size of the rect so we can pass it into the vertex shader later.
00326     int newSizeX = pInputRects[0].right - pInputRects[0].left;
00327     int newSizeY = pInputRects[0].bottom - pInputRects[0].top;
00328
00329     if (m_sizeX != newSizeX || m_sizeY != newSizeY)
00330     {
00331         m_sizeX = static_cast<float>(newSizeX);
00332         m_sizeY = static_cast<float>(newSizeY);
00333         hr = UpdateConstants();
00334     }
00335
00336     if (SUCCEEDED(hr))
00337     {
00338         // Based on how the vertex shader is deforming the image, we can adjust the output rect to
00339         // avoid unnecessary rendering/blending. While simply setting the output rect to the input
00340         // rect is the simplest solution, there will be rendering errors if the custom effect is
00341         // subsequently transformed such that content that was previously outside screen bounds
00342         // should now be visible (i.e. a translation). If no geometric transformation is done to
00343         // an image, the outputRect can simply be assigned to the inputRect (*outputRect = m_inputRect)
00344
00345         long inputRectHeight = m_inputRect.bottom - m_inputRect.top;
00346         long inputRectWidth = m_inputRect.right - m_inputRect.left;
00347
00348         // These values are based on the transforms done in the vertex shader itself.
00349
00350         // SkewOffset is the point where the wave is perpendicular to the screen.
00351         if (m_skewY > SkewOffset)
00352         {
00353             pOutputRect->top    = static_cast<long>(m_inputRect.top +    (inputRectHeight * WaveMarginTop) - WaveHeight);
00354             pOutputRect->bottom = static_cast<long>(m_inputRect.bottom - (inputRectHeight * WaveMarginBottom) + WaveHeight + (inputRectHeight * m_skewY));
00355         }
00356         else
00357         {
00358             pOutputRect->top    = static_cast<long>(m_inputRect.top + (inputRectHeight * WaveMarginTop) - WaveHeight + (inputRectHeight * (m_skewY - SkewOffset)));
00359             pOutputRect->bottom = static_cast<long>(m_inputRect.top + (inputRectHeight * WaveMarginTop) + WaveHeight);
00360         }
00361
00362         if (m_skewX > 0)
00363         {
00364             pOutputRect->left  = static_cast<long>(m_inputRect.left   + (inputRectWidth * WaveMarginLeft));
00365             pOutputRect->right = static_cast<long>(m_inputRect.right  - (inputRectWidth * WaveMarginRight) + (inputRectWidth * m_skewX));
00366         }
00367         else
00368         {
00369             pOutputRect->left  = static_cast<long>(m_inputRect.left  + (inputRectWidth * WaveMarginLeft) + (inputRectWidth * m_skewX));
00370             pOutputRect->right = static_cast<long>(m_inputRect.right - (inputRectWidth * WaveMarginRight));
00371         }
00372
00373         // Indicate that entire output might contain transparency
00374         ZeroMemory(pOutputOpaqueSubRect, sizeof(*pOutputOpaqueSubRect));
00375     }
00376
00377     return hr;
00378 }
00379
00380 IFACEMETHODIMP WaveEffect::MapInvalidRect(
00381     UINT32 inputIndex,
00382     D2D1_RECT_L invalidInputRect,
00383     _Out_ D2D1_RECT_L* pInvalidOutputRect
00384     ) const
00385 {
00386     // Indicate that the entire output may be invalid.
00387     *pInvalidOutputRect = m_inputRect;
00388
00389     return S_OK;
00390 }
00391
00392 IFACEMETHODIMP WaveEffect::SetDrawInfo(
00393     _In_ ID2D1DrawInfo* pDrawInfo
00394     )
00395 {
00396     m_drawInfo = pDrawInfo;
00397
00398     D2D1_VERTEX_RANGE range;
00399     range.startVertex = 0;
00400     range.vertexCount = m_numVertices;
00401
00402     return m_drawInfo->SetVertexProcessing(
00403         m_vertexBuffer.Get(),
00404         D2D1_VERTEX_OPTIONS_USE_DEPTH_BUFFER,
00405         nullptr, // Setting the blend description to nullptr draws the geometry using a simple source-over blend.
00406         &range,
00407         &GUID_WaveTransformVertexShader
00408         );
00409 }
00410
00411 // D2D ensures that that effects are only referenced from one thread at a time.
00412 // To improve performance, we simply increment/decrement our reference count
00413 // rather than use atomic InterlockedIncrement()/InterlockedDecrement() functions.
00414 IFACEMETHODIMP_(ULONG) WaveEffect::AddRef()
00415 {
00416     m_refCount++;
00417     return m_refCount;
00418 }
00419
00420 IFACEMETHODIMP_(ULONG) WaveEffect::Release()
00421 {
00422     m_refCount--;
00423
00424     if (m_refCount == 0)
00425     {
00426         delete this;
00427         return 0;
00428     }
00429     else
00430     {
00431         return m_refCount;
00432     }
00433 }
00434
00435 // This enables the stack of parent interfaces to be queried. In the instance
00436 // of the Wave interface, this method simply enables casting a Wave
00437 // instance to an ID2D1EffectImpl or IUnknown instance.
00438 IFACEMETHODIMP WaveEffect::QueryInterface(
00439     _In_ REFIID riid,
00440     _Outptr_ void** ppOutput
00441     )
00442 {
00443     *ppOutput = nullptr;
00444     HRESULT hr = S_OK;
00445
00446     if (riid == __uuidof(ID2D1EffectImpl))
00447     {
00448         *ppOutput = reinterpret_cast<ID2D1EffectImpl*>(this);
00449     }
00450     else if (riid == __uuidof(ID2D1DrawTransform))
00451     {
00452         *ppOutput = static_cast<ID2D1DrawTransform*>(this);
00453     }
00454     else if (riid == __uuidof(ID2D1Transform))
00455     {
00456         *ppOutput = static_cast<ID2D1Transform*>(this);
00457     }
00458     else if (riid == __uuidof(ID2D1TransformNode))
00459     {
00460         *ppOutput = static_cast<ID2D1TransformNode*>(this);
00461     }
00462     else if (riid == __uuidof(IUnknown))
00463     {
00464         *ppOutput = this;
00465     }
00466     else
00467     {
00468         hr = E_NOINTERFACE;
00469     }
00470
00471     if (*ppOutput != nullptr)
00472     {
00473         AddRef();
00474     }
00475
00476     return hr;
00477 }
Generated on Sat Nov 23 2024 16:08:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

TextAnalysis::Run Member List

This is the complete list of members for TextAnalysis::Run, including all inherited members.
bidiLevel | TextAnalysis::Run |
ContainsTextPosition(UINT32 desiredTextPosition) const | TextAnalysis::Run | [inline]
glyphCount | TextAnalysis::Run |
glyphOrientation | TextAnalysis::Run |
glyphStart | TextAnalysis::Run |
isNumberSubstituted | TextAnalysis::Run |
isReversed | TextAnalysis::Run |
isSideways | TextAnalysis::Run |
operator==(UINT32 desiredTextPosition) const | TextAnalysis::Run | [inline]
Run() | TextAnalysis::Run | [inline]
script | TextAnalysis::Run |
textLength | TextAnalysis::Run |
textStart | TextAnalysis::Run |
Generated on Sat Nov 23 2024 16:09:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/ResourceLoading.h Source File

  • Direct3D resource loading

ResourceLoading.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 "SampleOverlay.h"
00011
00012 #include "DirectXBase.h"
00013 #include "BasicMath.h"
00014 #include "BasicCamera.h"
00015 #include "LonLatController.h"
00016
00017 struct ConstantBuffer
00018 {
00019     float4x4 model;
00020     float4x4 view;
00021     float4x4 projection;
00022 };
00023
00024 ref class ResourceLoading : public DirectXBase
00025 {
00026 internal:
00027     ResourceLoading();
00028
00029     virtual void CreateDeviceIndependentResources() override;
00030     virtual void CreateDeviceResources() override;
00031     virtual void CreateWindowSizeDependentResources() override;
00032     virtual void Render() override;
00033     void Update(float timeTotal, float timeDelta);
00034     void SaveInternalState(_In_ Windows::Foundation::Collections::IPropertySet^ state);
00035     void LoadInternalState(_In_ Windows::Foundation::Collections::IPropertySet^ state);
00036
00037 private:
00038     SampleOverlay^ m_sampleOverlay;
00039
00040     Microsoft::WRL::ComPtr<ID3D11InputLayout>        m_inputLayout;
00041     Microsoft::WRL::ComPtr<ID3D11Buffer>             m_vertexBuffer;
00042     Microsoft::WRL::ComPtr<ID3D11Buffer>             m_indexBuffer;
00043     Microsoft::WRL::ComPtr<ID3D11VertexShader>       m_vertexShader;
00044     Microsoft::WRL::ComPtr<ID3D11PixelShader>        m_pixelShader;
00045     Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_textureSRV;
00046     Microsoft::WRL::ComPtr<ID3D11SamplerState>       m_sampler;
00047     Microsoft::WRL::ComPtr<ID3D11Buffer>             m_constantBuffer;
00048
00049     uint32            m_indexCount;
00050     ConstantBuffer    m_constantBufferData;
00051     BasicCamera^      m_camera;
00052     LonLatController^ m_controller;
00053
00054     bool              m_loadingComplete;
00055 };
Generated on Sat Nov 23 2024 16:08:11 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/texconv/BC.cpp Source File

  • Direct3D resource loading
  • texconv

BC.cpp

Go to the documentation of this file.
00001 //-------------------------------------------------------------------------------------
00002 // BC.cpp
00003 //
00004 // Block-compression (BC) functionality for BC1, BC2, BC3 (orginal DXTn formats)
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 #include "directxtexp.h"
00015
00016 // Experiemental encoding variants, not enabled by default
00017 //#define COLOR_WEIGHTS
00018 //#define COLOR_AVG_0WEIGHTS
00019
00020 #include "BC.h"
00021
00022 namespace DirectX
00023 {
00024
00025 //-------------------------------------------------------------------------------------
00026 // Constants
00027 //-------------------------------------------------------------------------------------
00028
00029 // Perceptual weightings for the importance of each channel.
00030 static const HDRColorA g_Luminance   (0.2125f / 0.7154f, 1.0f, 0.0721f / 0.7154f, 1.0f);
00031 static const HDRColorA g_LuminanceInv(0.7154f / 0.2125f, 1.0f, 0.7154f / 0.0721f, 1.0f);
00032
00033 //-------------------------------------------------------------------------------------
00034 // Decode/Encode RGB 5/6/5 colors
00035 //-------------------------------------------------------------------------------------
00036 inline static void Decode565(_Out_ HDRColorA *pColor, _In_ const uint16_t w565)
00037 {
00038     pColor->r = (float) ((w565 >> 11) & 31) * (1.0f / 31.0f);
00039     pColor->g = (float) ((w565 >>  5) & 63) * (1.0f / 63.0f);
00040     pColor->b = (float) ((w565 >>  0) & 31) * (1.0f / 31.0f);
00041     pColor->a = 1.0f;
00042 }
00043
00044 inline static uint16_t Encode565(_In_ const HDRColorA *pColor)
00045 {
00046     HDRColorA Color;
00047
00048     Color.r = (pColor->r < 0.0f) ? 0.0f : (pColor->r > 1.0f) ? 1.0f : pColor->r;
00049     Color.g = (pColor->g < 0.0f) ? 0.0f : (pColor->g > 1.0f) ? 1.0f : pColor->g;
00050     Color.b = (pColor->b < 0.0f) ? 0.0f : (pColor->b > 1.0f) ? 1.0f : pColor->b;
00051
00052     uint16_t w;
00053
00054     w = (uint16_t) ((static_cast<int32_t>(Color.r * 31.0f + 0.5f) << 11) |
00055                     (static_cast<int32_t>(Color.g * 63.0f + 0.5f) <<  5) |
00056                     (static_cast<int32_t>(Color.b * 31.0f + 0.5f) <<  0));
00057
00058     return w;
00059 }
00060
00061
00062 //-------------------------------------------------------------------------------------
00063 static void OptimizeRGB(_Out_ HDRColorA *pX, _Out_ HDRColorA *pY,
00064                         _In_reads_(NUM_PIXELS_PER_BLOCK) const HDRColorA *pPoints, _In_ size_t cSteps, _In_ DWORD flags)
00065 {
00066     static const float fEpsilon = (0.25f / 64.0f) * (0.25f / 64.0f);
00067     static const float pC3[] = { 2.0f/2.0f, 1.0f/2.0f, 0.0f/2.0f };
00068     static const float pD3[] = { 0.0f/2.0f, 1.0f/2.0f, 2.0f/2.0f };
00069     static const float pC4[] = { 3.0f/3.0f, 2.0f/3.0f, 1.0f/3.0f, 0.0f/3.0f };
00070     static const float pD4[] = { 0.0f/3.0f, 1.0f/3.0f, 2.0f/3.0f, 3.0f/3.0f };
00071
00072     const float *pC = (3 == cSteps) ? pC3 : pC4;
00073     const float *pD = (3 == cSteps) ? pD3 : pD4;
00074
00075     // Find Min and Max points, as starting point
00076     HDRColorA X = (flags & BC_FLAGS_UNIFORM) ? HDRColorA(1.f, 1.f, 1.f, 1.f) : g_Luminance;
00077     HDRColorA Y = HDRColorA(0.0f, 0.0f, 0.0f, 1.0f);
00078
00079     for(size_t iPoint = 0; iPoint < NUM_PIXELS_PER_BLOCK; iPoint++)
00080     {
00081 #ifdef COLOR_WEIGHTS
00082         if(pPoints[iPoint].a > 0.0f)
00083 #endif // COLOR_WEIGHTS
00084         {
00085             if(pPoints[iPoint].r < X.r)
00086                 X.r = pPoints[iPoint].r;
00087
00088             if(pPoints[iPoint].g < X.g)
00089                 X.g = pPoints[iPoint].g;
00090
00091             if(pPoints[iPoint].b < X.b)
00092                 X.b = pPoints[iPoint].b;
00093
00094             if(pPoints[iPoint].r > Y.r)
00095                 Y.r = pPoints[iPoint].r;
00096
00097             if(pPoints[iPoint].g > Y.g)
00098                 Y.g = pPoints[iPoint].g;
00099
00100             if(pPoints[iPoint].b > Y.b)
00101                 Y.b = pPoints[iPoint].b;
00102         }
00103     }
00104
00105     // Diagonal axis
00106     HDRColorA AB;
00107
00108     AB.r = Y.r - X.r;
00109     AB.g = Y.g - X.g;
00110     AB.b = Y.b - X.b;
00111
00112     float fAB = AB.r * AB.r + AB.g * AB.g + AB.b * AB.b;
00113
00114     // Single color block.. no need to root-find
00115     if(fAB < FLT_MIN)
00116     {
00117         pX->r = X.r; pX->g = X.g; pX->b = X.b;
00118         pY->r = Y.r; pY->g = Y.g; pY->b = Y.b;
00119         return;
00120     }
00121
00122     // Try all four axis directions, to determine which diagonal best fits data
00123     float fABInv = 1.0f / fAB;
00124
00125     HDRColorA Dir;
00126     Dir.r = AB.r * fABInv;
00127     Dir.g = AB.g * fABInv;
00128     Dir.b = AB.b * fABInv;
00129
00130     HDRColorA Mid;
00131     Mid.r = (X.r + Y.r) * 0.5f;
00132     Mid.g = (X.g + Y.g) * 0.5f;
00133     Mid.b = (X.b + Y.b) * 0.5f;
00134
00135     float fDir[4];
00136     fDir[0] = fDir[1] = fDir[2] = fDir[3] = 0.0f;
00137
00138
00139     for(size_t iPoint = 0; iPoint < NUM_PIXELS_PER_BLOCK; iPoint++)
00140     {
00141         HDRColorA Pt;
00142         Pt.r = (pPoints[iPoint].r - Mid.r) * Dir.r;
00143         Pt.g = (pPoints[iPoint].g - Mid.g) * Dir.g;
00144         Pt.b = (pPoints[iPoint].b - Mid.b) * Dir.b;
00145
00146         float f;
00147
00148 #ifdef COLOR_WEIGHTS
00149         f = Pt.r + Pt.g + Pt.b;
00150         fDir[0] += pPoints[iPoint].a * f * f;
00151
00152         f = Pt.r + Pt.g - Pt.b;
00153         fDir[1] += pPoints[iPoint].a * f * f;
00154
00155         f = Pt.r - Pt.g + Pt.b;
00156         fDir[2] += pPoints[iPoint].a * f * f;
00157
00158         f = Pt.r - Pt.g - Pt.b;
00159         fDir[3] += pPoints[iPoint].a * f * f;
00160 #else
00161         f = Pt.r + Pt.g + Pt.b;
00162         fDir[0] += f * f;
00163
00164         f = Pt.r + Pt.g - Pt.b;
00165         fDir[1] += f * f;
00166
00167         f = Pt.r - Pt.g + Pt.b;
00168         fDir[2] += f * f;
00169
00170         f = Pt.r - Pt.g - Pt.b;
00171         fDir[3] += f * f;
00172 #endif // COLOR_WEIGHTS
00173     }
00174
00175     float fDirMax = fDir[0];
00176     size_t  iDirMax = 0;
00177
00178     for(size_t iDir = 1; iDir < 4; iDir++)
00179     {
00180         if(fDir[iDir] > fDirMax)
00181         {
00182             fDirMax = fDir[iDir];
00183             iDirMax = iDir;
00184         }
00185     }
00186
00187     if(iDirMax & 2)
00188     {
00189         float f = X.g; X.g = Y.g; Y.g = f;
00190     }
00191
00192     if(iDirMax & 1)
00193     {
00194         float f = X.b; X.b = Y.b; Y.b = f;
00195     }
00196
00197
00198     // Two color block.. no need to root-find
00199     if(fAB < 1.0f / 4096.0f)
00200     {
00201         pX->r = X.r; pX->g = X.g; pX->b = X.b;
00202         pY->r = Y.r; pY->g = Y.g; pY->b = Y.b;
00203         return;
00204     }
00205
00206
00207     // Use Newton's Method to find local minima of sum-of-squares error.
00208     float fSteps = (float) (cSteps - 1);
00209
00210     for(size_t iIteration = 0; iIteration < 8; iIteration++)
00211     {
00212         // Calculate new steps
00213         HDRColorA pSteps[4];
00214
00215         for(size_t iStep = 0; iStep < cSteps; iStep++)
00216         {
00217             pSteps[iStep].r = X.r * pC[iStep] + Y.r * pD[iStep];
00218             pSteps[iStep].g = X.g * pC[iStep] + Y.g * pD[iStep];
00219             pSteps[iStep].b = X.b * pC[iStep] + Y.b * pD[iStep];
00220         }
00221
00222
00223         // Calculate color direction
00224         Dir.r = Y.r - X.r;
00225         Dir.g = Y.g - X.g;
00226         Dir.b = Y.b - X.b;
00227
00228         float fLen = (Dir.r * Dir.r + Dir.g * Dir.g + Dir.b * Dir.b);
00229
00230         if(fLen < (1.0f / 4096.0f))
00231             break;
00232
00233         float fScale = fSteps / fLen;
00234
00235         Dir.r *= fScale;
00236         Dir.g *= fScale;
00237         Dir.b *= fScale;
00238
00239
00240         // Evaluate function, and derivatives
00241         float d2X, d2Y;
00242         HDRColorA dX, dY;
00243         d2X = d2Y = dX.r = dX.g = dX.b = dY.r = dY.g = dY.b = 0.0f;
00244
00245         for(size_t iPoint = 0; iPoint < NUM_PIXELS_PER_BLOCK; iPoint++)
00246         {
00247             float fDot = (pPoints[iPoint].r - X.r) * Dir.r +
00248                          (pPoints[iPoint].g - X.g) * Dir.g +
00249                          (pPoints[iPoint].b - X.b) * Dir.b;
00250
00251
00252             size_t iStep;
00253             if(fDot <= 0.0f)
00254                 iStep = 0;
00255             if(fDot >= fSteps)
00256                 iStep = cSteps - 1;
00257             else
00258                 iStep = static_cast<size_t>(fDot + 0.5f);
00259
00260
00261             HDRColorA Diff;
00262             Diff.r = pSteps[iStep].r - pPoints[iPoint].r;
00263             Diff.g = pSteps[iStep].g - pPoints[iPoint].g;
00264             Diff.b = pSteps[iStep].b - pPoints[iPoint].b;
00265
00266 #ifdef COLOR_WEIGHTS
00267             float fC = pC[iStep] * pPoints[iPoint].a * (1.0f / 8.0f);
00268             float fD = pD[iStep] * pPoints[iPoint].a * (1.0f / 8.0f);
00269 #else
00270             float fC = pC[iStep] * (1.0f / 8.0f);
00271             float fD = pD[iStep] * (1.0f / 8.0f);
00272 #endif // COLOR_WEIGHTS
00273
00274             d2X  += fC * pC[iStep];
00275             dX.r += fC * Diff.r;
00276             dX.g += fC * Diff.g;
00277             dX.b += fC * Diff.b;
00278
00279             d2Y  += fD * pD[iStep];
00280             dY.r += fD * Diff.r;
00281             dY.g += fD * Diff.g;
00282             dY.b += fD * Diff.b;
00283         }
00284
00285
00286         // Move endpoints
00287         if(d2X > 0.0f)
00288         {
00289             float f = -1.0f / d2X;
00290
00291             X.r += dX.r * f;
00292             X.g += dX.g * f;
00293             X.b += dX.b * f;
00294         }
00295
00296         if(d2Y > 0.0f)
00297         {
00298             float f = -1.0f / d2Y;
00299
00300             Y.r += dY.r * f;
00301             Y.g += dY.g * f;
00302             Y.b += dY.b * f;
00303         }
00304
00305         if((dX.r * dX.r < fEpsilon) && (dX.g * dX.g < fEpsilon) && (dX.b * dX.b < fEpsilon) &&
00306            (dY.r * dY.r < fEpsilon) && (dY.g * dY.g < fEpsilon) && (dY.b * dY.b < fEpsilon))
00307         {
00308             break;
00309         }
00310     }
00311
00312     pX->r = X.r; pX->g = X.g; pX->b = X.b;
00313     pY->r = Y.r; pY->g = Y.g; pY->b = Y.b;
00314 }
00315
00316
00317 //-------------------------------------------------------------------------------------
00318 inline static void DecodeBC1( _Out_writes_(NUM_PIXELS_PER_BLOCK) XMVECTOR *pColor, _In_ const D3DX_BC1 *pBC )
00319 {
00320     assert( pColor && pBC );
00321     static_assert( sizeof(D3DX_BC1) == 8, "D3DX_BC1 should be 8 bytes" );
00322
00323     static XMVECTORF32 s_Scale = { 1.f/31.f, 1.f/63.f, 1.f/31.f, 1.f };
00324
00325     XMVECTOR clr0 = XMLoadU565( reinterpret_cast<const PackedVector::XMU565*>(&pBC->rgb[0]) );
00326     XMVECTOR clr1 = XMLoadU565( reinterpret_cast<const PackedVector::XMU565*>(&pBC->rgb[1]) );
00327
00328     clr0 = XMVectorMultiply( clr0, s_Scale );
00329     clr1 = XMVectorMultiply( clr1, s_Scale );
00330
00331     clr0 = XMVectorSwizzle<2, 1, 0, 3>( clr0 );
00332     clr1 = XMVectorSwizzle<2, 1, 0, 3>( clr1 );
00333
00334     clr0 = XMVectorSelect( g_XMIdentityR3, clr0, g_XMSelect1110 );
00335     clr1 = XMVectorSelect( g_XMIdentityR3, clr1, g_XMSelect1110 );
00336
00337     XMVECTOR clr2, clr3;
00338     if(pBC->rgb[0] <= pBC->rgb[1])
00339     {
00340         clr2 = XMVectorLerp( clr0, clr1, 0.5f );
00341         clr3 = XMVectorZero();  // Alpha of 0
00342     }
00343     else
00344     {
00345         clr2 = XMVectorLerp( clr0, clr1, 1.f/3.f );
00346         clr3 = XMVectorLerp( clr0, clr1, 2.f/3.f );
00347     }
00348
00349     uint32_t dw = pBC->bitmap;
00350
00351     for(size_t i = 0; i < NUM_PIXELS_PER_BLOCK; ++i, dw >>= 2)
00352     {
00353         switch(dw & 3)
00354         {
00355         case 0: pColor[i] = clr0; break;
00356         case 1: pColor[i] = clr1; break;
00357         case 2: pColor[i] = clr2; break;
00358
00359         case 3:
00360         default: pColor[i] = clr3; break;
00361         }
00362     }
00363 }
00364
00365
00366 //-------------------------------------------------------------------------------------
00367 #pragma warning(disable: 4616 6001 6201)
00368
00369 static void EncodeBC1(_Out_ D3DX_BC1 *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const HDRColorA *pColor,
00370                       _In_ bool bColorKey, _In_ float alphaRef, _In_ DWORD flags)
00371 {
00372     assert( pBC && pColor );
00373     static_assert( sizeof(D3DX_BC1) == 8, "D3DX_BC1 should be 8 bytes" );
00374
00375     // Determine if we need to colorkey this block
00376     size_t uSteps;
00377
00378     if (bColorKey)
00379     {
00380         size_t uColorKey = 0;
00381
00382         for(size_t i = 0; i < NUM_PIXELS_PER_BLOCK; ++i)
00383         {
00384             if(pColor[i].a < alphaRef)
00385                 uColorKey++;
00386         }
00387
00388         if(NUM_PIXELS_PER_BLOCK == uColorKey)
00389         {
00390             pBC->rgb[0] = 0x0000;
00391             pBC->rgb[1] = 0xffff;
00392             pBC->bitmap = 0xffffffff;
00393             return;
00394         }
00395
00396         uSteps = (uColorKey > 0) ? 3 : 4;
00397     }
00398     else
00399     {
00400         uSteps = 4;
00401     }
00402
00403     // Quantize block to R56B5, using Floyd Stienberg error diffusion.  This
00404     // increases the chance that colors will map directly to the quantized
00405     // axis endpoints.
00406     HDRColorA Color[NUM_PIXELS_PER_BLOCK];
00407     HDRColorA Error[NUM_PIXELS_PER_BLOCK];
00408
00409     if (flags & BC_FLAGS_DITHER_RGB)
00410         memset(Error, 0x00, NUM_PIXELS_PER_BLOCK * sizeof(HDRColorA));
00411
00412     size_t i;
00413     for(i = 0; i < NUM_PIXELS_PER_BLOCK; ++i)
00414     {
00415         HDRColorA Clr;
00416         Clr.r = pColor[i].r;
00417         Clr.g = pColor[i].g;
00418         Clr.b = pColor[i].b;
00419
00420         if (flags & BC_FLAGS_DITHER_RGB)
00421         {
00422             Clr.r += Error[i].r;
00423             Clr.g += Error[i].g;
00424             Clr.b += Error[i].b;
00425         }
00426
00427         Color[i].r = (float) static_cast<int32_t>(Clr.r * 31.0f + 0.5f) * (1.0f / 31.0f);
00428         Color[i].g = (float) static_cast<int32_t>(Clr.g * 63.0f + 0.5f) * (1.0f / 63.0f);
00429         Color[i].b = (float) static_cast<int32_t>(Clr.b * 31.0f + 0.5f) * (1.0f / 31.0f);
00430
00431 #ifdef COLOR_WEIGHTS
00432         Color[i].a = pColor[i].a;
00433 #else
00434         Color[i].a = 1.0f;
00435 #endif // COLOR_WEIGHTS
00436
00437         if (flags & BC_FLAGS_DITHER_RGB)
00438         {
00439             HDRColorA Diff;
00440             Diff.r = Color[i].a * (Clr.r - Color[i].r);
00441             Diff.g = Color[i].a * (Clr.g - Color[i].g);
00442             Diff.b = Color[i].a * (Clr.b - Color[i].b);
00443
00444             if(3 != (i & 3))
00445             {
00446                 assert( i < 15 );
00447                 _Analysis_assume_( i < 15 );
00448                 Error[i + 1].r += Diff.r * (7.0f / 16.0f);
00449                 Error[i + 1].g += Diff.g * (7.0f / 16.0f);
00450                 Error[i + 1].b += Diff.b * (7.0f / 16.0f);
00451             }
00452
00453             if(i < 12)
00454             {
00455                 if(i & 3)
00456                 {
00457                     Error[i + 3].r += Diff.r * (3.0f / 16.0f);
00458                     Error[i + 3].g += Diff.g * (3.0f / 16.0f);
00459                     Error[i + 3].b += Diff.b * (3.0f / 16.0f);
00460                 }
00461
00462                 Error[i + 4].r += Diff.r * (5.0f / 16.0f);
00463                 Error[i + 4].g += Diff.g * (5.0f / 16.0f);
00464                 Error[i + 4].b += Diff.b * (5.0f / 16.0f);
00465
00466                 if(3 != (i & 3))
00467                 {
00468                     assert( i < 11 );
00469                     _Analysis_assume_( i < 11 );
00470                     Error[i + 5].r += Diff.r * (1.0f / 16.0f);
00471                     Error[i + 5].g += Diff.g * (1.0f / 16.0f);
00472                     Error[i + 5].b += Diff.b * (1.0f / 16.0f);
00473                 }
00474             }
00475         }
00476
00477         if ( !( flags & BC_FLAGS_UNIFORM ) )
00478         {
00479             Color[i].r *= g_Luminance.r;
00480             Color[i].g *= g_Luminance.g;
00481             Color[i].b *= g_Luminance.b;
00482         }
00483     }
00484
00485     // Perform 6D root finding function to find two endpoints of color axis.
00486     // Then quantize and sort the endpoints depending on mode.
00487     HDRColorA ColorA, ColorB, ColorC, ColorD;
00488
00489     OptimizeRGB(&ColorA, &ColorB, Color, uSteps, flags);
00490
00491     if ( flags & BC_FLAGS_UNIFORM )
00492     {
00493         ColorC = ColorA;
00494         ColorD = ColorB;
00495     }
00496     else
00497     {
00498         ColorC.r = ColorA.r * g_LuminanceInv.r;
00499         ColorC.g = ColorA.g * g_LuminanceInv.g;
00500         ColorC.b = ColorA.b * g_LuminanceInv.b;
00501
00502         ColorD.r = ColorB.r * g_LuminanceInv.r;
00503         ColorD.g = ColorB.g * g_LuminanceInv.g;
00504         ColorD.b = ColorB.b * g_LuminanceInv.b;
00505     }
00506
00507     uint16_t wColorA = Encode565(&ColorC);
00508     uint16_t wColorB = Encode565(&ColorD);
00509
00510     if((uSteps == 4) && (wColorA == wColorB))
00511     {
00512         pBC->rgb[0] = wColorA;
00513         pBC->rgb[1] = wColorB;
00514         pBC->bitmap = 0x00000000;
00515         return;
00516     }
00517
00518     Decode565(&ColorC, wColorA);
00519     Decode565(&ColorD, wColorB);
00520
00521     if ( flags & BC_FLAGS_UNIFORM )
00522     {
00523         ColorA = ColorC;
00524         ColorB = ColorD;
00525     }
00526     else
00527     {
00528         ColorA.r = ColorC.r * g_Luminance.r;
00529         ColorA.g = ColorC.g * g_Luminance.g;
00530         ColorA.b = ColorC.b * g_Luminance.b;
00531
00532         ColorB.r = ColorD.r * g_Luminance.r;
00533         ColorB.g = ColorD.g * g_Luminance.g;
00534         ColorB.b = ColorD.b * g_Luminance.b;
00535     }
00536
00537     // Calculate color steps
00538     HDRColorA Step[4];
00539
00540     if((3 == uSteps) == (wColorA <= wColorB))
00541     {
00542         pBC->rgb[0] = wColorA;
00543         pBC->rgb[1] = wColorB;
00544
00545         Step[0] = ColorA;
00546         Step[1] = ColorB;
00547     }
00548     else
00549     {
00550         pBC->rgb[0] = wColorB;
00551         pBC->rgb[1] = wColorA;
00552
00553         Step[0] = ColorB;
00554         Step[1] = ColorA;
00555     }
00556
00557     static const size_t pSteps3[] = { 0, 2, 1 };
00558     static const size_t pSteps4[] = { 0, 2, 3, 1 };
00559     const size_t *pSteps;
00560
00561     if(3 == uSteps)
00562     {
00563         pSteps = pSteps3;
00564
00565         HDRColorALerp(&Step[2], &Step[0], &Step[1], 0.5f);
00566     }
00567     else
00568     {
00569         pSteps = pSteps4;
00570
00571         HDRColorALerp(&Step[2], &Step[0], &Step[1], 1.0f / 3.0f);
00572         HDRColorALerp(&Step[3], &Step[0], &Step[1], 2.0f / 3.0f);
00573     }
00574
00575     // Calculate color direction
00576     HDRColorA Dir;
00577
00578     Dir.r = Step[1].r - Step[0].r;
00579     Dir.g = Step[1].g - Step[0].g;
00580     Dir.b = Step[1].b - Step[0].b;
00581
00582     float fSteps = (float) (uSteps - 1);
00583     float fScale = (wColorA != wColorB) ? (fSteps / (Dir.r * Dir.r + Dir.g * Dir.g + Dir.b * Dir.b)) : 0.0f;
00584
00585     Dir.r *= fScale;
00586     Dir.g *= fScale;
00587     Dir.b *= fScale;
00588
00589     // Encode colors
00590     uint32_t dw = 0;
00591     if (flags & BC_FLAGS_DITHER_RGB)
00592         memset(Error, 0x00, NUM_PIXELS_PER_BLOCK * sizeof(HDRColorA));
00593
00594     for(i = 0; i < NUM_PIXELS_PER_BLOCK; ++i)
00595     {
00596         if((3 == uSteps) && (pColor[i].a < alphaRef))
00597         {
00598             dw = (3 << 30) | (dw >> 2);
00599         }
00600         else
00601         {
00602             HDRColorA Clr;
00603             if ( flags & BC_FLAGS_UNIFORM )
00604             {
00605                 Clr.r = pColor[i].r;
00606                 Clr.g = pColor[i].g;
00607                 Clr.b = pColor[i].b;
00608             }
00609             else
00610             {
00611                 Clr.r = pColor[i].r * g_Luminance.r;
00612                 Clr.g = pColor[i].g * g_Luminance.g;
00613                 Clr.b = pColor[i].b * g_Luminance.b;
00614             }
00615
00616             if (flags & BC_FLAGS_DITHER_RGB)
00617             {
00618                 Clr.r += Error[i].r;
00619                 Clr.g += Error[i].g;
00620                 Clr.b += Error[i].b;
00621             }
00622
00623             float fDot = (Clr.r - Step[0].r) * Dir.r + (Clr.g - Step[0].g) * Dir.g + (Clr.b - Step[0].b) * Dir.b;
00624             uint32_t iStep;
00625
00626             if(fDot <= 0.0f)
00627                 iStep = 0;
00628             else if(fDot >= fSteps)
00629                 iStep = 1;
00630             else
00631                 iStep = static_cast<uint32_t>( pSteps[static_cast<size_t>(fDot + 0.5f)] );
00632
00633             dw = (iStep << 30) | (dw >> 2);
00634
00635             if (flags & BC_FLAGS_DITHER_RGB)
00636             {
00637                 HDRColorA Diff;
00638                 Diff.r = Color[i].a * (Clr.r - Step[iStep].r);
00639                 Diff.g = Color[i].a * (Clr.g - Step[iStep].g);
00640                 Diff.b = Color[i].a * (Clr.b - Step[iStep].b);
00641
00642                 if(3 != (i & 3))
00643                 {
00644                     Error[i + 1].r += Diff.r * (7.0f / 16.0f);
00645                     Error[i + 1].g += Diff.g * (7.0f / 16.0f);
00646                     Error[i + 1].b += Diff.b * (7.0f / 16.0f);
00647                 }
00648
00649                 if(i < 12)
00650                 {
00651                     if(i & 3)
00652                     {
00653                         Error[i + 3].r += Diff.r * (3.0f / 16.0f);
00654                         Error[i + 3].g += Diff.g * (3.0f / 16.0f);
00655                         Error[i + 3].b += Diff.b * (3.0f / 16.0f);
00656                     }
00657
00658                     Error[i + 4].r += Diff.r * (5.0f / 16.0f);
00659                     Error[i + 4].g += Diff.g * (5.0f / 16.0f);
00660                     Error[i + 4].b += Diff.b * (5.0f / 16.0f);
00661
00662                     if(3 != (i & 3))
00663                     {
00664                         Error[i + 5].r += Diff.r * (1.0f / 16.0f);
00665                         Error[i + 5].g += Diff.g * (1.0f / 16.0f);
00666                         Error[i + 5].b += Diff.b * (1.0f / 16.0f);
00667                     }
00668                 }
00669             }
00670         }
00671     }
00672
00673     pBC->bitmap = dw;
00674 }
00675
00676 //-------------------------------------------------------------------------------------
00677 #ifdef COLOR_WEIGHTS
00678 static void EncodeSolidBC1(_Out_ D3DX_BC1 *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const HDRColorA *pColor)
00679 {
00680 #ifdef COLOR_AVG_0WEIGHTS
00681     // Compute avg color
00682     HDRColorA Color;
00683     Color.r = pColor[0].r;
00684     Color.g = pColor[0].g;
00685     Color.b = pColor[0].b;
00686
00687     for(size_t i = 1; i < NUM_PIXELS_PER_BLOCK; ++i)
00688     {
00689         Color.r += pColor[i].r;
00690         Color.g += pColor[i].g;
00691         Color.b += pColor[i].b;
00692     }
00693
00694     Color.r *= 1.0f / 16.0f;
00695     Color.g *= 1.0f / 16.0f;
00696     Color.b *= 1.0f / 16.0f;
00697
00698     uint16_t wColor = Encode565(&Color);
00699 #else
00700     uint16_t wColor = 0x0000;
00701 #endif // COLOR_AVG_0WEIGHTS
00702
00703     // Encode solid block
00704     pBC->rgb[0] = wColor;
00705     pBC->rgb[1] = wColor;
00706     pBC->bitmap = 0x00000000;
00707 }
00708 #endif // COLOR_WEIGHTS
00709
00710
00711 //=====================================================================================
00712 // Entry points
00713 //=====================================================================================
00714
00715 //-------------------------------------------------------------------------------------
00716 // BC1 Compression
00717 //-------------------------------------------------------------------------------------
00718 _Use_decl_annotations_
00719 void D3DXDecodeBC1(XMVECTOR *pColor, const uint8_t *pBC)
00720 {
00721     const D3DX_BC1 *pBC1 = reinterpret_cast<const D3DX_BC1 *>(pBC);
00722     DecodeBC1( pColor, pBC1 );
00723 }
00724
00725 _Use_decl_annotations_
00726 void D3DXEncodeBC1(uint8_t *pBC, const XMVECTOR *pColor, float alphaRef, DWORD flags)
00727 {
00728     assert( pBC && pColor );
00729
00730     HDRColorA Color[NUM_PIXELS_PER_BLOCK];
00731
00732     if (flags & BC_FLAGS_DITHER_A)
00733     {
00734         float fError[NUM_PIXELS_PER_BLOCK];
00735         memset(fError, 0x00, NUM_PIXELS_PER_BLOCK * sizeof(float));
00736
00737         for(size_t i = 0; i < NUM_PIXELS_PER_BLOCK; ++i)
00738         {
00739             HDRColorA clr;
00740             XMStoreFloat4( reinterpret_cast<XMFLOAT4*>( &clr ), pColor[i] );
00741
00742             float fAlph = clr.a + fError[i];
00743
00744             Color[i].r = clr.r;
00745             Color[i].g = clr.g;
00746             Color[i].b = clr.b;
00747             Color[i].a = (float) static_cast<int32_t>(clr.a + fError[i] + 0.5f);
00748
00749             float fDiff = fAlph - Color[i].a;
00750
00751             if(3 != (i & 3))
00752             {
00753                 assert( i < 15 );
00754                 _Analysis_assume_( i < 15 );
00755                 fError[i + 1] += fDiff * (7.0f / 16.0f);
00756             }
00757
00758             if(i < 12)
00759             {
00760                 if(i & 3)
00761                     fError[i + 3] += fDiff * (3.0f / 16.0f);
00762
00763                 fError[i + 4] += fDiff * (5.0f / 16.0f);
00764
00765                 if(3 != (i & 3))
00766                 {
00767                     assert( i < 11 );
00768                     _Analysis_assume_( i < 11 );
00769                     fError[i + 5] += fDiff * (1.0f / 16.0f);
00770                 }
00771             }
00772         }
00773     }
00774     else
00775     {
00776         for(size_t i = 0; i < NUM_PIXELS_PER_BLOCK; ++i)
00777         {
00778             XMStoreFloat4( reinterpret_cast<XMFLOAT4*>( &Color[i] ), pColor[i] );
00779         }
00780     }
00781
00782     D3DX_BC1 *pBC1 = reinterpret_cast<D3DX_BC1 *>(pBC);
00783     EncodeBC1(pBC1, Color, true, alphaRef, flags);
00784 }
00785
00786
00787 //-------------------------------------------------------------------------------------
00788 // BC2 Compression
00789 //-------------------------------------------------------------------------------------
00790 _Use_decl_annotations_
00791 void D3DXDecodeBC2(XMVECTOR *pColor, const uint8_t *pBC)
00792 {
00793     assert( pColor && pBC );
00794     static_assert( sizeof(D3DX_BC2) == 16, "D3DX_BC2 should be 16 bytes" );
00795
00796     const D3DX_BC2 *pBC2 = reinterpret_cast<const D3DX_BC2 *>(pBC);
00797
00798     // RGB part
00799     DecodeBC1(pColor, &pBC2->bc1);
00800
00801     // 4-bit alpha part
00802     DWORD dw = pBC2->bitmap[0];
00803
00804     for(size_t i = 0; i < 8; ++i, dw >>= 4)
00805         pColor[i] = XMVectorSetW( pColor[i], (float) (dw & 0xf) * (1.0f / 15.0f) );
00806
00807     dw = pBC2->bitmap[1];
00808
00809     for(size_t i = 8; i < NUM_PIXELS_PER_BLOCK; ++i, dw >>= 4)
00810         pColor[i] = XMVectorSetW( pColor[i], (float) (dw & 0xf) * (1.0f / 15.0f) );
00811 }
00812
00813 _Use_decl_annotations_
00814 void D3DXEncodeBC2(uint8_t *pBC, const XMVECTOR *pColor, DWORD flags)
00815 {
00816     assert( pBC && pColor );
00817     static_assert( sizeof(D3DX_BC2) == 16, "D3DX_BC2 should be 16 bytes" );
00818
00819     HDRColorA Color[NUM_PIXELS_PER_BLOCK];
00820     for(size_t i = 0; i < NUM_PIXELS_PER_BLOCK; ++i)
00821     {
00822         XMStoreFloat4( reinterpret_cast<XMFLOAT4*>( &Color[i] ), pColor[i] );
00823     }
00824
00825     D3DX_BC2 *pBC2 = reinterpret_cast<D3DX_BC2 *>(pBC);
00826
00827     // 4-bit alpha part.  Dithered using Floyd Stienberg error diffusion.
00828     pBC2->bitmap[0] = 0;
00829     pBC2->bitmap[1] = 0;
00830
00831     float fError[NUM_PIXELS_PER_BLOCK];
00832     if (flags & BC_FLAGS_DITHER_A)
00833         memset(fError, 0x00, NUM_PIXELS_PER_BLOCK * sizeof(float));
00834
00835     for(size_t i = 0; i < NUM_PIXELS_PER_BLOCK; ++i)
00836     {
00837         float fAlph = Color[i].a;
00838         if (flags & BC_FLAGS_DITHER_A)
00839             fAlph += fError[i];
00840
00841         uint32_t u = (uint32_t) static_cast<int32_t>(fAlph * 15.0f + 0.5f);
00842
00843         pBC2->bitmap[i >> 3] >>= 4;
00844         pBC2->bitmap[i >> 3] |= (u << 28);
00845
00846         if (flags & BC_FLAGS_DITHER_A)
00847         {
00848             float fDiff = fAlph - (float) u * (1.0f / 15.0f);
00849
00850             if(3 != (i & 3))
00851             {
00852                 assert( i < 15 );
00853                 _Analysis_assume_( i < 15 );
00854                 fError[i + 1] += fDiff * (7.0f / 16.0f);
00855             }
00856
00857             if(i < 12)
00858             {
00859                 if(i & 3)
00860                     fError[i + 3] += fDiff * (3.0f / 16.0f);
00861
00862                 fError[i + 4] += fDiff * (5.0f / 16.0f);
00863
00864                 if(3 != (i & 3))
00865                 {
00866                     assert( i < 11 );
00867                     _Analysis_assume_( i < 11 );
00868                     fError[i + 5] += fDiff * (1.0f / 16.0f);
00869                 }
00870             }
00871         }
00872     }
00873
00874     // RGB part
00875 #ifdef COLOR_WEIGHTS
00876     if(!pBC2->bitmap[0] && !pBC2->bitmap[1])
00877     {
00878         EncodeSolidBC1(pBC2->dxt1, Color);
00879         return;
00880     }
00881 #endif // COLOR_WEIGHTS
00882
00883     EncodeBC1(&pBC2->bc1, Color, false, 0.f, flags);
00884 }
00885
00886
00887 //-------------------------------------------------------------------------------------
00888 // BC3 Compression
00889 //-------------------------------------------------------------------------------------
00890 _Use_decl_annotations_
00891 void D3DXDecodeBC3(XMVECTOR *pColor, const uint8_t *pBC)
00892 {
00893     assert( pColor && pBC );
00894     static_assert( sizeof(D3DX_BC3) == 16, "D3DX_BC3 should be 16 bytes" );
00895
00896     const D3DX_BC3 *pBC3 = reinterpret_cast<const D3DX_BC3 *>(pBC);
00897
00898     // RGB part
00899     DecodeBC1(pColor, &pBC3->bc1);
00900
00901     // Adaptive 3-bit alpha part
00902     float fAlpha[8];
00903
00904     fAlpha[0] = ((float) pBC3->alpha[0]) * (1.0f / 255.0f);
00905     fAlpha[1] = ((float) pBC3->alpha[1]) * (1.0f / 255.0f);
00906
00907     if(pBC3->alpha[0] > pBC3->alpha[1])
00908     {
00909         for(size_t i = 1; i < 7; ++i)
00910             fAlpha[i + 1] = (fAlpha[0] * (7 - i) + fAlpha[1] * i) * (1.0f / 7.0f);
00911     }
00912     else
00913     {
00914         for(size_t i = 1; i < 5; ++i)
00915             fAlpha[i + 1] = (fAlpha[0] * (5 - i) + fAlpha[1] * i) * (1.0f / 5.0f);
00916
00917         fAlpha[6] = 0.0f;
00918         fAlpha[7] = 1.0f;
00919     }
00920
00921     DWORD dw = pBC3->bitmap[0] | (pBC3->bitmap[1] << 8) | (pBC3->bitmap[2] << 16);
00922
00923     for(size_t i = 0; i < 8; ++i, dw >>= 3)
00924         pColor[i] = XMVectorSetW( pColor[i], fAlpha[dw & 0x7] );
00925
00926     dw = pBC3->bitmap[3] | (pBC3->bitmap[4] << 8) | (pBC3->bitmap[5] << 16);
00927
00928     for(size_t i = 8; i < NUM_PIXELS_PER_BLOCK; ++i, dw >>= 3)
00929         pColor[i] = XMVectorSetW( pColor[i], fAlpha[dw & 0x7] );
00930 }
00931
00932 _Use_decl_annotations_
00933 void D3DXEncodeBC3(uint8_t *pBC, const XMVECTOR *pColor, DWORD flags)
00934 {
00935     assert( pBC && pColor );
00936     static_assert( sizeof(D3DX_BC3) == 16, "D3DX_BC3 should be 16 bytes" );
00937
00938     HDRColorA Color[NUM_PIXELS_PER_BLOCK];
00939     for(size_t i = 0; i < NUM_PIXELS_PER_BLOCK; ++i)
00940     {
00941         XMStoreFloat4( reinterpret_cast<XMFLOAT4*>( &Color[i] ), pColor[i] );
00942     }
00943
00944     D3DX_BC3 *pBC3 = reinterpret_cast<D3DX_BC3 *>(pBC);
00945
00946     // Quantize block to A8, using Floyd Stienberg error diffusion.  This
00947     // increases the chance that colors will map directly to the quantized
00948     // axis endpoints.
00949     float fAlpha[NUM_PIXELS_PER_BLOCK];
00950     float fError[NUM_PIXELS_PER_BLOCK];
00951
00952     float fMinAlpha = Color[0].a;
00953     float fMaxAlpha = Color[0].a;
00954
00955     if (flags & BC_FLAGS_DITHER_A)
00956         memset(fError, 0x00, NUM_PIXELS_PER_BLOCK * sizeof(float));
00957
00958     for(size_t i = 0; i < NUM_PIXELS_PER_BLOCK; ++i)
00959     {
00960         float fAlph = Color[i].a;
00961         if (flags & BC_FLAGS_DITHER_A)
00962             fAlph += fError[i];
00963
00964         fAlpha[i] = static_cast<int32_t>(fAlph * 255.0f + 0.5f) * (1.0f / 255.0f);
00965
00966         if(fAlpha[i] < fMinAlpha)
00967             fMinAlpha = fAlpha[i];
00968         else if(fAlpha[i] > fMaxAlpha)
00969             fMaxAlpha = fAlpha[i];
00970
00971         if (flags & BC_FLAGS_DITHER_A)
00972         {
00973             float fDiff = fAlph - fAlpha[i];
00974
00975             if(3 != (i & 3))
00976             {
00977                 assert( i < 15 );
00978                 _Analysis_assume_( i < 15 );
00979                 fError[i + 1] += fDiff * (7.0f / 16.0f);
00980             }
00981
00982             if(i < 12)
00983             {
00984                 if(i & 3)
00985                     fError[i + 3] += fDiff * (3.0f / 16.0f);
00986
00987                 fError[i + 4] += fDiff * (5.0f / 16.0f);
00988
00989                 if(3 != (i & 3))
00990                 {
00991                     assert( i < 11 );
00992                     _Analysis_assume_( i < 11 );
00993                     fError[i + 5] += fDiff * (1.0f / 16.0f);
00994                 }
00995             }
00996         }
00997     }
00998
00999 #ifdef COLOR_WEIGHTS
01000     if(0.0f == fMaxAlpha)
01001     {
01002         EncodeSolidBC1(&pBC3->dxt1, Color);
01003         pBC3->alpha[0] = 0x00;
01004         pBC3->alpha[1] = 0x00;
01005         memset(pBC3->bitmap, 0x00, 6);
01006     }
01007 #endif
01008
01009     // RGB part
01010     EncodeBC1(&pBC3->bc1, Color, false, 0.f, flags);
01011
01012     // Alpha part
01013     if(1.0f == fMinAlpha)
01014     {
01015         pBC3->alpha[0] = 0xff;
01016         pBC3->alpha[1] = 0xff;
01017         memset(pBC3->bitmap, 0x00, 6);
01018         return;
01019     }
01020
01021     // Optimize and Quantize Min and Max values
01022     size_t uSteps = ((0.0f == fMinAlpha) || (1.0f == fMaxAlpha)) ? 6 : 8;
01023
01024     float fAlphaA, fAlphaB;
01025     OptimizeAlpha<false>(&fAlphaA, &fAlphaB, fAlpha, uSteps);
01026
01027     uint8_t bAlphaA = (uint8_t) static_cast<int32_t>(fAlphaA * 255.0f + 0.5f);
01028     uint8_t bAlphaB = (uint8_t) static_cast<int32_t>(fAlphaB * 255.0f + 0.5f);
01029
01030     fAlphaA = (float) bAlphaA * (1.0f / 255.0f);
01031     fAlphaB = (float) bAlphaB * (1.0f / 255.0f);
01032
01033     // Setup block
01034     if((8 == uSteps) && (bAlphaA == bAlphaB))
01035     {
01036         pBC3->alpha[0] = bAlphaA;
01037         pBC3->alpha[1] = bAlphaB;
01038         memset(pBC3->bitmap, 0x00, 6);
01039         return;
01040     }
01041
01042     static const size_t pSteps6[] = { 0, 2, 3, 4, 5, 1 };
01043     static const size_t pSteps8[] = { 0, 2, 3, 4, 5, 6, 7, 1 };
01044
01045     const size_t *pSteps;
01046     float fStep[8];
01047
01048     if(6 == uSteps)
01049     {
01050         pBC3->alpha[0] = bAlphaA;
01051         pBC3->alpha[1] = bAlphaB;
01052
01053         fStep[0] = fAlphaA;
01054         fStep[1] = fAlphaB;
01055
01056         for(size_t i = 1; i < 5; ++i)
01057             fStep[i + 1] = (fStep[0] * (5 - i) + fStep[1] * i) * (1.0f / 5.0f);
01058
01059         fStep[6] = 0.0f;
01060         fStep[7] = 1.0f;
01061
01062         pSteps = pSteps6;
01063     }
01064     else
01065     {
01066         pBC3->alpha[0] = bAlphaB;
01067         pBC3->alpha[1] = bAlphaA;
01068
01069         fStep[0] = fAlphaB;
01070         fStep[1] = fAlphaA;
01071
01072         for(size_t i = 1; i < 7; ++i)
01073             fStep[i + 1] = (fStep[0] * (7 - i) + fStep[1] * i) * (1.0f / 7.0f);
01074
01075         pSteps = pSteps8;
01076     }
01077
01078     // Encode alpha bitmap
01079     float fSteps = (float) (uSteps - 1);
01080     float fScale = (fStep[0] != fStep[1]) ? (fSteps / (fStep[1] - fStep[0])) : 0.0f;
01081
01082     if (flags & BC_FLAGS_DITHER_A)
01083         memset(fError, 0x00, NUM_PIXELS_PER_BLOCK * sizeof(float));
01084
01085     for(size_t iSet = 0; iSet < 2; iSet++)
01086     {
01087         uint32_t dw = 0;
01088
01089         size_t iMin = iSet * 8;
01090         size_t iLim = iMin + 8;
01091
01092         for(size_t i = iMin; i < iLim; ++i)
01093         {
01094             float fAlph = Color[i].a;
01095             if (flags & BC_FLAGS_DITHER_A)
01096                 fAlph += fError[i];
01097             float fDot = (fAlph - fStep[0]) * fScale;
01098
01099             uint32_t iStep;
01100             if(fDot <= 0.0f)
01101                 iStep = ((6 == uSteps) && (fAlph <= fStep[0] * 0.5f)) ? 6 : 0;
01102             else if(fDot >= fSteps)
01103                 iStep = ((6 == uSteps) && (fAlph >= (fStep[1] + 1.0f) * 0.5f)) ? 7 : 1;
01104             else
01105                 iStep = static_cast<uint32_t>( pSteps[static_cast<size_t>(fDot + 0.5f)] );
01106
01107             dw = (iStep << 21) | (dw >> 3);
01108
01109             if (flags & BC_FLAGS_DITHER_A)
01110             {
01111                 float fDiff = (fAlph - fStep[iStep]);
01112
01113                 if(3 != (i & 3))
01114                     fError[i + 1] += fDiff * (7.0f / 16.0f);
01115
01116                 if(i < 12)
01117                 {
01118                     if(i & 3)
01119                         fError[i + 3] += fDiff * (3.0f / 16.0f);
01120
01121                     fError[i + 4] += fDiff * (5.0f / 16.0f);
01122
01123                     if(3 != (i & 3))
01124                         fError[i + 5] += fDiff * (1.0f / 16.0f);
01125                 }
01126             }
01127         }
01128
01129         pBC3->bitmap[0 + iSet * 3] = ((uint8_t *) &dw)[0];
01130         pBC3->bitmap[1 + iSet * 3] = ((uint8_t *) &dw)[1];
01131         pBC3->bitmap[2 + iSet * 3] = ((uint8_t *) &dw)[2];
01132     }
01133 }
01134
01135 } // namespace
Generated on Sat Nov 23 2024 16:08:11 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C#,C++/MediaExtensions/Invert/dllmain.cpp Source File

  • Media extensions
  • C#,C++
  • MediaExtensions
  • Invert

dllmain.cpp

Go to the documentation of this file.
00001 //////////////////////////////////////////////////////////////////////////
00002 //
00003 // dllmain.cpp
00004 //
00005 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00007 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00008 // PARTICULAR PURPOSE.
00009 //
00010 // Copyright (c) Microsoft Corporation. All rights reserved.
00011 //
00012 //////////////////////////////////////////////////////////////////////////
00013
00014 #include <initguid.h>
00015 #include "Invert.h"
00016
00017 using namespace Microsoft::WRL;
00018
00019 namespace Microsoft { namespace Samples {
00020     ActivatableClass(CInvert);
00021 }}
00022
00023 BOOL WINAPI DllMain( __in_opt HINSTANCE hInstance, __in DWORD dwReason, __in_opt LPVOID lpReserved )
00024 {
00025     if( DLL_PROCESS_ATTACH == dwReason )
00026     {
00027         //
00028         //  Don't need per-thread callbacks
00029         //
00030         if( hInstance != NULL )
00031         {
00032             DisableThreadLibraryCalls( hInstance );
00033         }
00034
00035         Module<InProc>::GetModule().Create();
00036     }
00037     else if( DLL_PROCESS_DETACH == dwReason )
00038     {
00039         Module<InProc>::GetModule().Terminate();
00040     }
00041
00042     return TRUE;
00043 }
00044
00045 HRESULT WINAPI DllGetActivationFactory( __in HSTRING activatibleClassId, __deref_out IActivationFactory** factory )
00046 {
00047     auto &module = Microsoft::WRL::Module< Microsoft::WRL::InProc >::GetModule();
00048     return module.GetActivationFactory( activatibleClassId, factory );
00049 }
00050
00051 HRESULT WINAPI DllCanUnloadNow()
00052 {
00053     auto &module = Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule();
00054     return (module.Terminate()) ? S_OK : S_FALSE;
00055 }
00056
00057 STDAPI DllGetClassObject( __in REFCLSID rclsid, __in REFIID riid, __deref_out LPVOID FAR* ppv )
00058 {
00059     auto &module = Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule();
00060     return module.GetClassObject( rclsid, riid, ppv );
00061 }
Generated on Sat Nov 23 2024 16:08:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D sprite/C++/pch.cpp Source File

  • Direct3D sprite

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D tutorial/C++/Lesson4.Textures/pch.h Source File

  • Direct3D tutorial
  • Lesson4.Textures

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 <d3d11_1.h>
00012 #include <agile.h>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/MonthBlock.h Source File

  • Hilo C++
  • Hilo

MonthBlock.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
00009 #include "IMonthBlock.h"
00010
00011 namespace Hilo
00012 {
00013     interface class IYearGroup;
00014     interface class IResourceLoader;
00015     class ExceptionPolicy;
00016     class Repository;
00017
00018     // The MonthBlock class provides per-month data used by the image browser's
00019     // zoomed-out view of the user's picture library. XAML controls bind
00020     // to objects of this type.
00021     [Windows::Foundation::Metadata::WebHostHidden]
00022     [Windows::UI::Xaml::Data::Bindable]
00023     public ref class MonthBlock sealed : public IMonthBlock, public Windows::UI::Xaml::Data::INotifyPropertyChanged
00024     {
00025     internal:
00026         MonthBlock(IYearGroup^ yearGroup, int month, Windows::Storage::Search::IStorageFolderQueryOperations^ folderQuery, std::shared_ptr<Repository> repository, std::shared_ptr<ExceptionPolicy> exceptionPolicy);
00027         concurrency::task<void> QueryPhotoCount();
00028
00029     public:
00030         virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler^ PropertyChanged;
00031
00032         property Platform::String^ Name
00033         {
00034             virtual Platform::String^ get();
00035         }
00036
00037         property bool HasPhotos
00038         {
00039             virtual bool get();
00040         }
00041
00042         property unsigned int Month
00043         {
00044             virtual unsigned int get();
00045         }
00046
00047         property IYearGroup^ Group
00048         {
00049             virtual IYearGroup^ get();
00050         }
00051
00052     private:
00053         Platform::WeakReference m_weakYearGroup;
00054         int m_month;
00055         Platform::String^ m_name;
00056         Windows::Storage::Search::IStorageFolderQueryOperations^ m_folderQuery;
00057         std::shared_ptr<Repository> m_repository;
00058         std::shared_ptr<ExceptionPolicy> m_exceptionPolicy;
00059         unsigned int m_count;
00060         bool m_runOperation;
00061         bool m_runningOperation;
00062
00063         Platform::String^ BuildDateQuery();
00064         void OnPropertyChanged(Platform::String^ propertyName);
00065     };
00066 }
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Trial app and in-app purchase/C++/MainPage.xaml.h Source File

  • Trial app and in-app purchase

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Message dialog/C++/pch.h Source File

  • Message dialog

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application data/C++/common/LayoutAwarePage.cpp Source File

  • Application data
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:30 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Custom driver access/C++/app_cpp/MainPage.xaml.cpp Source File

  • Custom driver access
  • app_cpp

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:41 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML AppBar control/C++/Scenario1.xaml.cpp Source File

  • XAML AppBar control

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 AppBarControl;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 Scenario1::Scenario1()
00026 {
00027     InitializeComponent();
00028 }
00029
00030
00031 // Invoked when this page is about to be displayed in a Frame.
00032 void Scenario1::OnNavigatedTo(NavigationEventArgs^ e)
00033 {
00034     rootPage = MainPage::Current;
00035 }
00036
00037
Generated on Sat Nov 23 2024 16:07:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Edge gesture invocation/C++/MainPage.xaml.h Source File

  • Edge gesture invocation

MainPage.xaml.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 //
00009 // MainPage.xaml.h
00010 // Declaration of the MainPage.xaml class.
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "MainPage.g.h"
00017
00018 using namespace Windows::UI::Xaml;
00019 using namespace Windows::UI::Xaml::Controls;
00020 using namespace Windows::UI::Xaml::Input;
00021 using namespace Windows::Graphics::Display;
00022 using namespace Windows::UI::ViewManagement;
00023 using namespace Windows::UI::Xaml::Navigation;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::System;
00026 using namespace Platform;
00027 using namespace Windows::UI::Xaml::Interop;
00028 using namespace Windows::UI::Input;
00029
00030 namespace EdgeGestureSample
00031 {
00032     public enum class NotifyType
00033     {
00034         StatusMessage,
00035         ErrorMessage
00036     };
00037
00038   [Windows::Foundation::Metadata::WebHostHidden]
00039     public ref class MainPage sealed
00040     {
00041     public:
00042         MainPage();
00043
00044         property Windows::UI::Xaml::Controls::Frame^ ScenariosFrame
00045         {
00046             Windows::UI::Xaml::Controls::Frame^ get() { return _scenariosFrame; }
00047         }
00048         property Windows::UI::Xaml::Controls::Frame^ InputFrame
00049         {
00050             Windows::UI::Xaml::Controls::Frame^ get() { return _inputFrame; }
00051         }
00052         property Windows::UI::Xaml::Controls::Frame^ OutputFrame
00053         {
00054             Windows::UI::Xaml::Controls::Frame^ get() { return _outputFrame; }
00055         }
00056
00057         event Windows::Foundation::EventHandler<Platform::Object^>^ InputFrameLoaded;
00058         event Windows::Foundation::EventHandler<Platform::Object^>^ OutputFrameLoaded;
00059
00060         void NotifyUser(String^ strMessage, NotifyType type);
00061         void DoNavigation(TypeName pageType, Windows::UI::Xaml::Controls::Frame^ frame);
00062         String^ ConvertViewState(ApplicationViewState state);
00063         String^ ConvertResolution(ResolutionScale scale);
00064
00065     private:
00066         Windows::UI::Xaml::Controls::Frame^ _scenariosFrame;
00067         Windows::UI::Xaml::Controls::Frame^ _inputFrame;
00068         Windows::UI::Xaml::Controls::Frame^ _outputFrame;
00069         void Footer_Click(Object^ sender, RoutedEventArgs^ e);
00070         Windows::Foundation::EventRegistrationToken _displayHandlerToken;
00071         Windows::Foundation::EventRegistrationToken _layoutHandlerToken;
00072         Windows::Foundation::EventRegistrationToken _pageLoadedHandlerToken;
00073         Windows::Foundation::EventRegistrationToken _logicalDpiChangedToken;
00074         Windows::Foundation::EventRegistrationToken _inputFrameLoadedToken;
00075         Windows::Foundation::EventRegistrationToken _outputFrameLoadedToken;
00076         void Page_SizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00077         void DisplayProperties_LogicalDpiChanged(Object^ sender);
00078         void Page_Loaded(Object^ sender, RoutedEventArgs^ e);
00079         void CheckResolutionAndViewState();
00080         void SetFeatureName(Platform::String^ strFeature);
00081         void inputFrameNavigated(Object^ sender, NavigationEventArgs^ e);
00082         void outputFrameNavigated(Object^ sender, NavigationEventArgs^ e);
00083     ~MainPage();
00084     };
00085 }
Generated on Sat Nov 23 2024 16:07:46 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D printing images and effects/C++/SampleOverlay.cpp Source File

  • Direct2D printing images and effects

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 Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::UI::ViewManagement;
00015 using namespace Windows::Graphics::Display;
00016 using namespace D2D1;
00017
00018 SampleOverlay::SampleOverlay() :
00019     m_drawOverlay(true)
00020 {
00021 }
00022
00023 void SampleOverlay::Initialize(
00024     _In_ ID2D1Device*         d2dDevice,
00025     _In_ ID2D1DeviceContext*  d2dContext,
00026     _In_ IWICImagingFactory*  wicFactory,
00027     _In_ IDWriteFactory*      dwriteFactory,
00028     _In_ Platform::String^    caption
00029     )
00030 {
00031     m_wicFactory = wicFactory;
00032     m_dwriteFactory = dwriteFactory;
00033     m_sampleName = caption;
00034     m_d2dDevice = d2dDevice;
00035     m_d2dContext = d2dContext;
00036     m_padding = 3.0f;
00037     m_textVerticalOffset = 5.0f;
00038     m_logoSize = D2D1::SizeF(0.0f, 0.0f);
00039     m_overlayWidth = 0.0f;
00040
00041     ComPtr<ID2D1Factory> factory;
00042     d2dDevice->GetFactory(&factory);
00043
00044     DX::ThrowIfFailed(
00045         factory.As(&m_d2dFactory)
00046         );
00047
00048     ResetDirectXResources();
00049 }
00050
00051 void SampleOverlay::ResetDirectXResources()
00052 {
00053     DX::ThrowIfFailed(
00054         m_d2dContext->CreateSolidColorBrush(ColorF(ColorF::White), &m_whiteBrush)
00055         );
00056
00057     ComPtr<IWICBitmapDecoder> wicBitmapDecoder;
00058     DX::ThrowIfFailed(
00059         m_wicFactory->CreateDecoderFromFilename(
00060             L"windowsbig-sdk.png",
00061             nullptr,
00062             GENERIC_READ,
00063             WICDecodeMetadataCacheOnDemand,
00064             &wicBitmapDecoder
00065             )
00066         );
00067
00068     ComPtr<IWICBitmapFrameDecode> wicBitmapFrame;
00069     DX::ThrowIfFailed(
00070         wicBitmapDecoder->GetFrame(0, &wicBitmapFrame)
00071         );
00072
00073     ComPtr<IWICFormatConverter> wicFormatConverter;
00074     DX::ThrowIfFailed(
00075         m_wicFactory->CreateFormatConverter(&wicFormatConverter)
00076         );
00077
00078     DX::ThrowIfFailed(
00079         wicFormatConverter->Initialize(
00080             wicBitmapFrame.Get(),
00081             GUID_WICPixelFormat32bppPBGRA,
00082             WICBitmapDitherTypeNone,
00083             nullptr,
00084             0.0,
00085             WICBitmapPaletteTypeCustom  // the BGRA format has no palette so this value is ignored
00086             )
00087         );
00088
00089     double dpiX = 96.0f;
00090     double dpiY = 96.0f;
00091     DX::ThrowIfFailed(
00092         wicFormatConverter->GetResolution(&dpiX, &dpiY)
00093         );
00094
00095     DX::ThrowIfFailed(
00096         m_d2dContext->CreateBitmapFromWicBitmap(
00097             wicFormatConverter.Get(),
00098             BitmapProperties(
00099                 PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00100                 static_cast<float>(dpiX),
00101                 static_cast<float>(dpiY)
00102                 ),
00103             &m_logoBitmap
00104             )
00105         );
00106
00107     m_logoSize = m_logoBitmap->GetSize();
00108
00109     ComPtr<IDWriteTextFormat> nameTextFormat;
00110     DX::ThrowIfFailed(
00111         m_dwriteFactory->CreateTextFormat(
00112             L"Segoe UI",
00113             nullptr,
00114             DWRITE_FONT_WEIGHT_LIGHT,
00115             DWRITE_FONT_STYLE_NORMAL,
00116             DWRITE_FONT_STRETCH_NORMAL,
00117             36.0f,
00118             L"en-US",
00119             &nameTextFormat
00120             )
00121         );
00122
00123     DX::ThrowIfFailed(
00124         nameTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)
00125         );
00126
00127     DX::ThrowIfFailed(
00128         nameTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)
00129         );
00130
00131     DX::ThrowIfFailed(
00132         m_dwriteFactory->CreateTextLayout(
00133             m_sampleName->Data(),
00134             m_sampleName->Length(),
00135             nameTextFormat.Get(),
00136             4096.0f,
00137             4096.0f,
00138             &m_textLayout
00139             )
00140         );
00141
00142     DWRITE_TEXT_METRICS metrics = {0};
00143     DX::ThrowIfFailed(
00144         m_textLayout->GetMetrics(&metrics)
00145         );
00146
00147     m_overlayWidth = m_padding * 3.0f + m_logoSize.width + metrics.width;
00148
00149     DX::ThrowIfFailed(
00150         m_d2dFactory->CreateDrawingStateBlock(&m_stateBlock)
00151         );
00152
00153     UpdateForWindowSizeChange();
00154 }
00155
00156 void SampleOverlay::UpdateForWindowSizeChange()
00157 {
00158     if (CoreWindow::GetForCurrentThread()->Bounds.Width < m_overlayWidth)
00159     {
00160         m_drawOverlay = false;
00161     }
00162     else
00163     {
00164         m_drawOverlay = true;
00165     }
00166 }
00167
00168 void SampleOverlay::Render()
00169 {
00170     if (m_drawOverlay)
00171     {
00172         m_d2dContext->SaveDrawingState(m_stateBlock.Get());
00173
00174         m_d2dContext->BeginDraw();
00175         m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00176         m_d2dContext->DrawBitmap(
00177             m_logoBitmap.Get(),
00178             D2D1::RectF(m_padding, 0.0f, m_logoSize.width + m_padding, m_logoSize.height)
00179             );
00180
00181         m_d2dContext->DrawTextLayout(
00182             Point2F(m_logoSize.width + 2.0f * m_padding, m_textVerticalOffset),
00183             m_textLayout.Get(),
00184             m_whiteBrush.Get()
00185             );
00186
00187         // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00188         // is lost. It will be handled during the next call to Present.
00189         HRESULT hr = m_d2dContext->EndDraw();
00190         if (hr != D2DERR_RECREATE_TARGET)
00191         {
00192             DX::ThrowIfFailed(hr);
00193         }
00194
00195         m_d2dContext->RestoreDrawingState(m_stateBlock.Get());
00196     }
00197 }
00198
00199 float SampleOverlay::GetTitleHeightInDips()
00200 {
00201     return m_logoSize.height;
00202 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::DateTimeFormatting::sealed Member List

This is the complete list of members for SDKSample::DateTimeFormatting::sealed, including all inherited members.
Display_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::DateTimeFormatting::sealed | [private]
Display_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::DateTimeFormatting::sealed | [private]
Display_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::DateTimeFormatting::sealed | [private]
Display_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::DateTimeFormatting::sealed | [private]
LongAndShortFormats() | SDKSample::DateTimeFormatting::sealed |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::DateTimeFormatting::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::DateTimeFormatting::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::DateTimeFormatting::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::DateTimeFormatting::sealed | [protected, virtual]
OverrideSettings() | SDKSample::DateTimeFormatting::sealed |
ParametrizedTemplate() | SDKSample::DateTimeFormatting::sealed |
rootPage | SDKSample::DateTimeFormatting::sealed | [private]
StringTemplate() | SDKSample::DateTimeFormatting::sealed |
Generated on Sat Nov 23 2024 16:09:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D printing images and effects/C++/pch.h Source File

  • Direct2D printing images and effects

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 <d3d11_1.h>
00012 #include <d2d1_1.h>
00013 #include <d2d1effects.h>
00014 #include <dwrite_1.h>
00015 #include <wincodec.h>
00016 #include <agile.h>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: HttpClient/C++/Scenario2.xaml.h Source File

  • HttpClient

Scenario2.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.xaml.h
00013 // Declaration of the Scenario2 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario2.g.h"
00020 #include "MainPage.xaml.h"
00021 #include "HttpRequest.h"
00022
00023 namespace SDKSample
00024 {
00025     namespace HttpClientSample
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
00039         private:
00040             MainPage^ rootPage;
00041             Web::HttpRequest httpRequest;
00042             concurrency::cancellation_token_source cancellationTokenSource;
00043             Windows::Storage::Streams::IBuffer^ readBuffer;
00044             void Start_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00045             void Cancel_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00046             concurrency::task<void> Scenario2ReadData();
00047         };
00048     }
00049 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D magazine app/C++/ImageFrame.h Source File

  • Direct2D magazine app

ImageFrame.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 "Element.h"
00011
00012 ref class Image;
00013
00014 //  <image-frame> represents a document of an image loaded from an image file.
00015 //  Image frame is a primitive drawing element. It doesn't have children.
00016 //
00017 //  Image frame accepts the following markup attributes:
00018 //      source = "url(#<string>)"
00019 //          A unique resource identifier of the source image of the document
00020 //      image-pixel-left = "<float>"
00021 //          Offset to the left of the area of the image to render in pixels
00022 //      image-pixel-top = "<float>"
00023 //          Offset to the top of the area of the image to render in pixels
00024 //      image-pixel-width = "<float>"
00025 //          Width of the area of the image to render in pixels
00026 //      image-pixel-height = "<float>"
00027 //          Height of the area of the image to render in pixels
00028 //
00029 ref class ImageFrame : public Element
00030 {
00031 internal:
00032     ImageFrame();
00033
00034     virtual bool Initialize(
00035         _In_ Document^ document,
00036         _In_ Windows::Data::Xml::Dom::XmlElement^ xmlElement
00037         ) override;
00038
00039     virtual bool BindResource(_In_ Element^ rootElement) override;
00040
00041     virtual void Measure(
00042         _In_ Document^ document,
00043         D2D1_SIZE_F const& parentSize,
00044         _Out_ D2D1_RECT_F* bounds
00045         ) override;
00046
00047     virtual bool Draw(
00048         _In_ Document^ document,
00049         D2D1::Matrix3x2F const& transform
00050         ) override;
00051
00052 private:
00053     // Name string of the source image
00054     Platform::String^ m_sourceName;
00055
00056     // Source image of the image frame
00057     ::Image^ m_sourceImage;
00058
00059     // Bounding rectangle of portion of the bitmap to render in pixels
00060     D2D1_RECT_F m_bitmapPixelBounds;
00061 };
00062
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Sharing content source app/C++/ShareFiles.xaml.h Source File

  • Sharing content source app

ShareFiles.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 // ShareFiles.xaml.h
00013 // Declaration of the ShareFiles class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "SharePage.h"
00020 #include "ShareFiles.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKSample
00024 {
00025     namespace ShareSource
00026     {
00027         public ref class ShareFiles sealed
00028         {
00029         public:
00030             ShareFiles();
00031
00032         protected:
00033             virtual bool GetShareContent(Windows::ApplicationModel::DataTransfer::DataRequest^ request) override;
00034
00035         private:
00036             MainPage^ rootPage;
00037             Windows::Foundation::Collections::IVectorView<Windows::Storage::StorageFile^>^ storageItems;
00038
00039             void SelectFilesButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Credential locker/C++/common/suspensionmanager.h Source File

  • Credential locker
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite custom text renderer/C++/DirectXBase.h Source File

  • DirectWrite custom text renderer

DirectXBase.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 "DirectXSample.h"
00011
00012 // Helper class that initializes DirectX APIs for both 2D and 3D rendering.
00013 // Some of the code in this class may be omitted if only 2D or only 3D rendering is being used.
00014 ref class DirectXBase abstract
00015 {
00016 internal:
00017     DirectXBase();
00018
00019     virtual void Initialize(Windows::UI::Core::CoreWindow^ window, float dpi);
00020     virtual void HandleDeviceLost();
00021     virtual void CreateDeviceIndependentResources();
00022     virtual void CreateDeviceResources();
00023     virtual void SetDpi(float dpi);
00024     virtual void UpdateForWindowSizeChange();
00025     virtual void CreateWindowSizeDependentResources();
00026     virtual void Render() = 0;
00027     virtual void Present();
00028     void ValidateDevice();
00029
00030 protected private:
00031     Platform::Agile<Windows::UI::Core::CoreWindow>  m_window;
00032
00033     // DirectWrite & Windows Imaging Component Objects.
00034     Microsoft::WRL::ComPtr<IDWriteFactory1>         m_dwriteFactory;
00035     Microsoft::WRL::ComPtr<IWICImagingFactory2>     m_wicFactory;
00036
00037     // DirectX Core Objects. Required for 2D and 3D.
00038     Microsoft::WRL::ComPtr<ID3D11Device1>           m_d3dDevice;
00039     Microsoft::WRL::ComPtr<ID3D11DeviceContext1>    m_d3dContext;
00040     Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00041     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00042
00043     // Direct2D Rendering Objects. Required for 2D.
00044     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00046     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00047     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmap;
00048
00049     // Direct3D Rendering Objects. Required for 3D.
00050     Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00051
00052     // Cached renderer properties.
00053     D3D_FEATURE_LEVEL                               m_featureLevel;
00054     Windows::Foundation::Size                       m_renderTargetSize;
00055     Windows::Foundation::Rect                       m_windowBounds;
00056     float                                           m_dpi;
00057     bool                                            m_windowSizeChangeInProgress;
00058 };
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C#,C++/MediaExtensions/Invert/Invert.h Source File

  • Media extensions
  • C#,C++
  • MediaExtensions
  • Invert

Invert.h

Go to the documentation of this file.
00001 // Defines the transform class.
00002 //
00003 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00004 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00005 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00006 // PARTICULAR PURPOSE.
00007 //
00008 // Copyright (c) Microsoft Corporation. All rights reserved.
00009
00010 #pragma once
00011
00012 #include <new>
00013 #include <mfapi.h>
00014 #include <mftransform.h>
00015 #include <mfidl.h>
00016 #include <mferror.h>
00017 #include <strsafe.h>
00018 #include <assert.h>
00019 #include <wrl\implements.h>
00020 #include <wrl\module.h>
00021 #include <wrl\client.h>
00022 #include <windows.media.h>
00023 #include <D3D11.h>
00024
00025 #include "DirectXVideoTransform.h"
00026 #include "InvertTransform.h"
00027
00028 using namespace Microsoft::WRL;
00029
00030 // CLSID of the MFT.
00031 // {F1BF74F0-65F4-4F47-925C-E8B564A9A87E}
00032 DEFINE_GUID(CLSID_InvertMFT,
00033 0xf1bf74f0, 0x65f4, 0x4f47, 0x92, 0x5c, 0xe8, 0xb5, 0x64, 0xa9, 0xa8, 0x7e);
00034
00035 class CInvert
00036     : public RuntimeClass<
00037            RuntimeClassFlags< Microsoft::WRL::RuntimeClassType::WinRtClassicComMix >,
00038            ABI::Windows::Media::IMediaExtension,
00039            IMFTransform >
00040 {
00041     InspectableClass(RuntimeClass_InvertTransform_InvertEffect, BaseTrust)
00042
00043 public:
00044     CInvert();
00045     ~CInvert();
00046
00047     STDMETHOD(RuntimeClassInitialize)();
00048
00049     // IMediaExtension
00050     STDMETHODIMP SetProperties(ABI::Windows::Foundation::Collections::IPropertySet *pConfiguration);
00051
00052     // IMFTransform
00053     STDMETHODIMP GetStreamLimits(
00054         DWORD   *pdwInputMinimum,
00055         DWORD   *pdwInputMaximum,
00056         DWORD   *pdwOutputMinimum,
00057         DWORD   *pdwOutputMaximum
00058     );
00059
00060     STDMETHODIMP GetStreamCount(
00061         DWORD   *pcInputStreams,
00062         DWORD   *pcOutputStreams
00063     );
00064
00065     STDMETHODIMP GetInputStreamInfo(
00066         DWORD                     dwInputStreamID,
00067         MFT_INPUT_STREAM_INFO *   pStreamInfo
00068     );
00069
00070     STDMETHODIMP GetOutputStreamInfo(
00071         DWORD                     dwOutputStreamID,
00072         MFT_OUTPUT_STREAM_INFO *  pStreamInfo
00073     );
00074
00075     STDMETHODIMP GetAttributes(IMFAttributes** pAttributes);
00076
00077     STDMETHODIMP GetInputAvailableType(
00078         DWORD           dwInputStreamID,
00079         DWORD           dwTypeIndex, // 0-based
00080         IMFMediaType    **ppType
00081     );
00082
00083     STDMETHODIMP GetOutputAvailableType(
00084         DWORD           dwOutputStreamID,
00085         DWORD           dwTypeIndex, // 0-based
00086         IMFMediaType    **ppType
00087     );
00088
00089     STDMETHODIMP SetInputType(
00090         DWORD           dwInputStreamID,
00091         IMFMediaType    *pType,
00092         DWORD           dwFlags
00093     );
00094
00095     STDMETHODIMP SetOutputType(
00096         DWORD           dwOutputStreamID,
00097         IMFMediaType    *pType,
00098         DWORD           dwFlags
00099     );
00100
00101     STDMETHODIMP GetInputCurrentType(
00102         DWORD           dwInputStreamID,
00103         IMFMediaType    **ppType
00104     );
00105
00106     STDMETHODIMP GetOutputCurrentType(
00107         DWORD           dwOutputStreamID,
00108         IMFMediaType    **ppType
00109     );
00110
00111     STDMETHODIMP GetInputStatus(
00112         DWORD           dwInputStreamID,
00113         DWORD           *pdwFlags
00114     );
00115
00116     STDMETHODIMP GetOutputStatus(DWORD *pdwFlags);
00117
00118     STDMETHODIMP ProcessMessage(
00119         MFT_MESSAGE_TYPE    eMessage,
00120         ULONG_PTR           ulParam
00121     );
00122
00123     STDMETHODIMP ProcessInput(
00124         DWORD               dwInputStreamID,
00125         IMFSample           *pSample,
00126         DWORD               dwFlags
00127     );
00128
00129     STDMETHODIMP ProcessOutput(
00130         DWORD                   dwFlags,
00131         DWORD                   cOutputBufferCount,
00132         MFT_OUTPUT_DATA_BUFFER  *pOutputSamples, // one per stream
00133         DWORD                   *pdwStatus
00134     );
00135
00136     STDMETHODIMP GetOutputStreamAttributes(
00137         DWORD           dwOutputStreamID,
00138         IMFAttributes   **ppAttributes
00139         );
00140
00141     // Optional Methods
00142     STDMETHODIMP GetStreamIDs(
00143         DWORD   dwInputIDArraySize,
00144         DWORD   *pdwInputIDs,
00145         DWORD   dwOutputIDArraySize,
00146         DWORD   *pdwOutputIDs
00147         ) { return E_NOTIMPL; }
00148
00149     STDMETHODIMP GetInputStreamAttributes(
00150         DWORD           dwInputStreamID,
00151         IMFAttributes   **ppAttributes
00152         ) { return E_NOTIMPL; }
00153
00154     STDMETHODIMP DeleteInputStream(DWORD dwStreamID){ return E_NOTIMPL; }
00155
00156     STDMETHODIMP AddInputStreams(
00157         DWORD   cStreams,
00158         DWORD   *adwStreamIDs
00159         ) { return E_NOTIMPL; }
00160
00161     STDMETHODIMP SetOutputBounds(
00162         LONGLONG        hnsLowerBound,
00163         LONGLONG        hnsUpperBound
00164         ) { return E_NOTIMPL; }
00165
00166     STDMETHODIMP ProcessEvent(
00167         DWORD              dwInputStreamID,
00168         IMFMediaEvent      *pEvent
00169         ) { return E_NOTIMPL; }
00170
00171 private:
00172
00173     HRESULT OnGetPartialType(DWORD dwTypeIndex, IMFMediaType **ppmt);
00174
00175     HRESULT OnCheckInputType(IMFMediaType *pmt);
00176     HRESULT OnCheckOutputType(IMFMediaType *pmt);
00177     HRESULT OnCheckMediaType(IMFMediaType *pmt);
00178     HRESULT BeginStreaming();
00179     HRESULT OnProcessOutput(IMFMediaBuffer *pIn, IMFMediaBuffer *pOut);
00180     HRESULT UpdateFormatInfo();
00181     HRESULT UpdateDX11Device();
00182     HRESULT CheckDX11Device();
00183     void InvalidateDX11Resources();
00184
00185     CRITICAL_SECTION            m_critSec;
00186
00187     // Streaming
00188     bool                        m_bStreamingInitialized;
00189     ComPtr<IMFSample>           m_pSample;                 // Input sample.
00190     ComPtr<IMFMediaType>        m_pInputType;              // Input media type.
00191     ComPtr<IMFMediaType>        m_pOutputType;             // Output media type.
00192
00193     // Fomat information
00194     UINT32                      m_imageWidthInPixels;
00195     UINT32                      m_imageHeightInPixels;
00196     DWORD                       m_cbImageSize;              // Image size, in bytes.
00197
00198     ComPtr<IMFAttributes>       m_pAttributes;
00199
00200     // DirectX manager
00201     ComPtr<IMFDXGIDeviceManager> m_pDX11Manager;
00202     HANDLE m_hDeviceHandle;
00203
00204     // Device resources
00205     ComPtr<ID3D11Device> m_pDevice;
00206     ComPtr<ID3D11DeviceContext> m_pContext;
00207     ComPtr<ID3D11Texture2D> m_pInBufferTex;
00208     ComPtr<ID3D11Texture2D> m_pOutBufferTex;
00209     ComPtr<ID3D11Texture2D> m_pOutBufferStage;
00210
00211     // Output
00212     ComPtr<IMFVideoSampleAllocatorEx> m_spOutputSampleAllocator;
00213     ComPtr<IMFAttributes> m_spOutputAttributes;
00214
00215     // Transform
00216     DirectXVideoTransform *m_pTransform;
00217 };
Generated on Sat Nov 23 2024 16:08:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: App tiles and badges/C#,C++/App.xaml.cpp Source File

  • App tiles and badges
  • C#,C++

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Touch keyboard/C++/Constants.cpp Source File

  • Input Touch keyboard

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     // { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
00021     { "Launch Touch Keyboard", "SDKSample.TouchKeyboard.Launch" }
00022 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Lock screen apps/C#,C++/NotificationsExtensions/Common.cs Source File

  • Lock screen apps
  • C#,C++
  • NotificationsExtensions

Common.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 System;
00009 using System.Collections.ObjectModel;
00010 using System.Runtime.InteropServices;
00011 using System.Text;
00012 #if !WINRT_NOT_PRESENT
00013 using Windows.Data.Xml.Dom;
00014 #endif
00015
00016 namespace NotificationsExtensions
00017 {
00018     internal sealed class NotificationContentText : INotificationContentText
00019     {
00020         internal NotificationContentText() { }
00021
00022         public string Text
00023         {
00024             get { return m_Text; }
00025             set { m_Text = value; }
00026         }
00027
00028         public string Lang
00029         {
00030             get { return m_Lang; }
00031             set { m_Lang = value; }
00032         }
00033
00034         private string m_Text;
00035         private string m_Lang;
00036     }
00037
00038     internal sealed class NotificationContentImage : INotificationContentImage
00039     {
00040         internal NotificationContentImage() { }
00041
00042         public string Src
00043         {
00044             get { return m_Src; }
00045             set { m_Src = value; }
00046         }
00047
00048         public string Alt
00049         {
00050             get { return m_Alt; }
00051             set { m_Alt = value; }
00052         }
00053
00054         public bool AddImageQuery
00055         {
00056             get
00057             {
00058                 if (m_AddImageQueryNullable == null || m_AddImageQueryNullable.Value == false)
00059                 {
00060                     return false;
00061                 }
00062                 else
00063                 {
00064                     return true;
00065                 }
00066             }
00067             set { m_AddImageQueryNullable = value; }
00068         }
00069
00070         public bool? AddImageQueryNullable
00071         {
00072             get { return m_AddImageQueryNullable; }
00073             set { m_AddImageQueryNullable = value; }
00074         }
00075
00076         private string m_Src;
00077         private string m_Alt;
00078         private bool? m_AddImageQueryNullable;
00079     }
00080
00081     internal static class Util
00082     {
00083         public const int NOTIFICATION_CONTENT_VERSION = 1;
00084
00085         public static string HttpEncode(string value)
00086         {
00087             return value.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("\"", "&quot;").Replace("'", "&apos;");
00088         }
00089     }
00090
00091     /// <summary>
00092     /// Base class for the notification content creation helper classes.
00093     /// </summary>
00094 #if !WINRT_NOT_PRESENT
00095     internal abstract class NotificationBase
00096 #else
00097     abstract partial class NotificationBase
00098 #endif
00099     {
00100         protected NotificationBase(string templateName, int imageCount, int textCount)
00101         {
00102             m_TemplateName = templateName;
00103
00104             m_Images = new NotificationContentImage[imageCount];
00105             for (int i = 0; i < m_Images.Length; i++)
00106             {
00107                 m_Images[i] = new NotificationContentImage();
00108             }
00109
00110             m_TextFields = new INotificationContentText[textCount];
00111             for (int i = 0; i < m_TextFields.Length; i++)
00112             {
00113                 m_TextFields[i] = new NotificationContentText();
00114             }
00115         }
00116
00117         public bool StrictValidation
00118         {
00119             get { return m_StrictValidation; }
00120             set { m_StrictValidation = value; }
00121         }
00122         public abstract string GetContent();
00123
00124         public override string ToString()
00125         {
00126             return GetContent();
00127         }
00128
00129 #if !WINRT_NOT_PRESENT
00130         public XmlDocument GetXml()
00131         {
00132             XmlDocument xml = new XmlDocument();
00133             xml.LoadXml(GetContent());
00134             return xml;
00135         }
00136 #endif
00137
00138         /// <summary>
00139         /// Retrieves the list of images that can be manipulated on the notification content.
00140         /// </summary>
00141         public INotificationContentImage[] Images
00142         {
00143             get { return m_Images; }
00144         }
00145
00146         /// <summary>
00147         /// Retrieves the list of text fields that can be manipulated on the notification content.
00148         /// </summary>
00149         public INotificationContentText[] TextFields
00150         {
00151             get { return m_TextFields; }
00152         }
00153
00154         /// <summary>
00155         /// The base Uri path that should be used for all image references in the notification.
00156         /// </summary>
00157         public string BaseUri
00158         {
00159             get { return m_BaseUri; }
00160             set
00161             {
00162                 if (this.StrictValidation && !String.IsNullOrEmpty(value))
00163                 {
00164                     Uri uri;
00165                     try
00166                     {
00167                         uri = new Uri(value);
00168                     }
00169                     catch (Exception e)
00170                     {
00171                         throw new ArgumentException("Invalid URI. Use a valid URI or turn off StrictValidation", e);
00172                     }
00173                     if (!(uri.Scheme.Equals("http", StringComparison.OrdinalIgnoreCase)
00174                         || uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase)
00175                         || uri.Scheme.Equals("ms-appx", StringComparison.OrdinalIgnoreCase)
00176                         || (uri.Scheme.Equals("ms-appdata", StringComparison.OrdinalIgnoreCase)
00177                             && (String.IsNullOrEmpty(uri.Authority)) // check to make sure the Uri isn't ms-appdata://foo/local
00178                             && (uri.AbsolutePath.StartsWith("/local/") || uri.AbsolutePath.StartsWith("local/"))))) // both ms-appdata:local/ and ms-appdata:/local/ are valid
00179                     {
00180                         throw new ArgumentException("The BaseUri must begin with http://, https://, ms-appx:///, or ms-appdata:///local/.", "value");
00181                     }
00182                 }
00183                 m_BaseUri = value;
00184             }
00185         }
00186
00187         public string Lang
00188         {
00189             get { return m_Lang; }
00190             set { m_Lang = value; }
00191         }
00192
00193         public bool AddImageQuery
00194         {
00195             get
00196             {
00197                 if (m_AddImageQueryNullable == null || m_AddImageQueryNullable.Value == false)
00198                 {
00199                     return false;
00200                 }
00201                 else
00202                 {
00203                     return true;
00204                 }
00205             }
00206             set { m_AddImageQueryNullable = value; }
00207         }
00208
00209         public bool? AddImageQueryNullable
00210         {
00211             get { return m_AddImageQueryNullable; }
00212             set { m_AddImageQueryNullable = value; }
00213         }
00214
00215         protected string SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery)
00216         {
00217             globalLang = (globalLang != null) ? globalLang : String.Empty;
00218             globalBaseUri = String.IsNullOrWhiteSpace(globalBaseUri) ? null : globalBaseUri;
00219
00220             StringBuilder builder = new StringBuilder(String.Empty);
00221             for (int i = 0; i < m_Images.Length; i++)
00222             {
00223                 if (!String.IsNullOrEmpty(m_Images[i].Src))
00224                 {
00225                     string escapedSrc = Util.HttpEncode(m_Images[i].Src);
00226                     if (!String.IsNullOrWhiteSpace(m_Images[i].Alt))
00227                     {
00228                         string escapedAlt = Util.HttpEncode(m_Images[i].Alt);
00229                         if (m_Images[i].AddImageQueryNullable == null || m_Images[i].AddImageQueryNullable == globalAddImageQuery)
00230                         {
00231                             builder.AppendFormat("<image id='{0}' src='{1}' alt='{2}'/>", i + 1, escapedSrc, escapedAlt);
00232                         }
00233                         else
00234                         {
00235                             builder.AppendFormat("<image addImageQuery='{0}' id='{1}' src='{2}' alt='{3}'/>", m_Images[i].AddImageQuery.ToString().ToLowerInvariant(), i + 1, escapedSrc, escapedAlt);
00236                         }
00237                     }
00238                     else
00239                     {
00240                         if (m_Images[i].AddImageQueryNullable == null || m_Images[i].AddImageQueryNullable == globalAddImageQuery)
00241                         {
00242                             builder.AppendFormat("<image id='{0}' src='{1}'/>", i + 1, escapedSrc);
00243                         }
00244                         else
00245                         {
00246                             builder.AppendFormat("<image addImageQuery='{0}' id='{1}' src='{2}'/>", m_Images[i].AddImageQuery.ToString().ToLowerInvariant(), i + 1, escapedSrc);
00247                         }
00248                     }
00249                 }
00250             }
00251
00252             for (int i = 0; i < m_TextFields.Length; i++)
00253             {
00254                 if (!String.IsNullOrWhiteSpace(m_TextFields[i].Text))
00255                 {
00256                     string escapedValue = Util.HttpEncode(m_TextFields[i].Text);
00257                     if (!String.IsNullOrWhiteSpace(m_TextFields[i].Lang) && !m_TextFields[i].Lang.Equals(globalLang))
00258                     {
00259                         string escapedLang = Util.HttpEncode(m_TextFields[i].Lang);
00260                         builder.AppendFormat("<text id='{0}' lang='{1}'>{2}</text>", i + 1, escapedLang, escapedValue);
00261                     }
00262                     else
00263                     {
00264                         builder.AppendFormat("<text id='{0}'>{1}</text>", i + 1, escapedValue);
00265                     }
00266                 }
00267             }
00268
00269             return builder.ToString();
00270         }
00271
00272         public string TemplateName { get { return m_TemplateName; } }
00273
00274         private bool m_StrictValidation = true;
00275         private NotificationContentImage[] m_Images;
00276         private INotificationContentText[] m_TextFields;
00277
00278         private string m_Lang;
00279         private string m_BaseUri;
00280         private string m_TemplateName;
00281         private bool? m_AddImageQueryNullable;
00282     }
00283
00284     /// <summary>
00285     /// Exception returned when invalid notification content is provided.
00286     /// </summary>
00287     internal sealed class NotificationContentValidationException : COMException
00288     {
00289         public NotificationContentValidationException(string message)
00290             : base(message, unchecked((int)0x80070057))
00291         {
00292         }
00293     }
00294 }
Generated on Sat Nov 23 2024 16:07:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playlist/C++/Add.xaml.cpp Source File

  • Playlist

Add.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 // Add.xaml.cpp
00013 // Implementation of the Add class
00014 //
00015
00016 #include "pch.h"
00017 #include "Add.xaml.h"
00018
00019 using namespace SDKSample::Playlists;
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::Navigation;
00024
00025 Add::Add()
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 Add::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 Add::PickPlaylistButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00043 {
00044     // Make sure app is unsnapped before invoking the file picker
00045     if(!MainPage::EnsureUnsnapped())
00046     {
00047         OutputStatus->Text = "Unable to unsnap the app.";
00048         return;
00049     }
00050
00051     MainPage::PickPlaylist().then([this](task<Playlist^> playlistTask)
00052     {
00053         try
00054         {
00055             MainPage::playlist = playlistTask.get();
00056             OutputStatus->Text = "Playlist loaded";
00057         }
00058         catch (NullReferenceException^ ex)
00059         {
00060             OutputStatus->Text = "No playlist picked.";
00061         }
00062         catch(AccessDeniedException^ ex)
00063         {
00064             OutputStatus->Text = "Access is denied, cannot load playlist.";
00065         }
00066     });
00067 }
00068
00069 void Add::PickAudioButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00070 {
00071     if (MainPage::playlist != nullptr)
00072     {
00073         // Make sure app is unsnapped before invoking the file picker
00074         if(!MainPage::EnsureUnsnapped())
00075         {
00076             OutputStatus->Text = "Unable to unsnap the app.";
00077             return;
00078         }
00079
00080         // Pick some files, then add them to the playlist.
00081         FileOpenPicker^ picker = MainPage::CreateFilePicker(MainPage::audioExtensions);
00082         task<IVectorView<StorageFile^>^>(picker->PickMultipleFilesAsync()).then([this](IVectorView<StorageFile^>^ files)
00083         {
00084             if(files->Size > 0)
00085             {
00086                 for each (StorageFile^ file in files)
00087                 {
00088                     MainPage::playlist->Files->Append(file);
00089                 }
00090
00091                 // [this, files] allows the use of local variable "files" in lambda context
00092                 task<void>(MainPage::playlist->SaveAsync()).then([this, files]()
00093                 {
00094                     OutputStatus->Text = files->Size + " files added to the playlist.";
00095                 });
00096             }
00097             else
00098             {
00099                 OutputStatus->Text = "No file was selected.";
00100             }
00101         });
00102     }
00103     else
00104     {
00105         OutputStatus->Text = "Pick playlist first.";
00106     }
00107 }
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Date and time formatting/C++/common/suspensionmanager.h Source File

  • Date and time formatting
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DXGI swap chain rotation/C++/DDSTextureLoader.h Source File

  • DXGI swap chain rotation

DDSTextureLoader.h

Go to the documentation of this file.
00001 //--------------------------------------------------------------------------------------
00002 // File: DDSTextureLoader.h
00003 //
00004 // Function for loading a DDS texture and creating a Direct3D 11 runtime resource for it
00005 //
00006 // Note this function is 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
00018 #pragma once
00019
00020 void CreateDDSTextureFromMemory(
00021     _In_ ID3D11Device* d3dDevice,
00022     _In_reads_bytes_(ddsDataSize) const byte* ddsData,
00023     _In_ size_t ddsDataSize,
00024     _Out_opt_ ID3D11Resource** texture,
00025     _Out_opt_ ID3D11ShaderResourceView** textureView,
00026     _In_ size_t maxsize = 0
00027     );
Generated on Sat Nov 23 2024 16:08:11 for Win8-Examples by doxygen 1.7.1


Win8-Examples: App package information/C++/App.xaml.h Source File

  • App package information

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML vector-based drawing/C++/Scenario1.xaml.h Source File

  • XAML vector-based drawing

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 SDKSample
00023 {
00024     namespace Drawing
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 Scenario1 sealed
00031         {
00032         public:
00033             Scenario1();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040             void Other_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         };
00042     }
00043 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Sharing content target app/C++/DefaultPage.xaml.h Source File

  • Sharing content target app

DefaultPage.xaml.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 //
00009 // DefaultPage.xaml.h
00010 // Declaration of the DefaultPage class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "DefaultPage.g.h"
00017
00018 namespace ShareTarget
00019 {
00020     public ref class DefaultPage sealed
00021     {
00022     public:
00023         DefaultPage();
00024
00025     private:
00026         void Footer_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00027     };
00028 }
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKANIMATION_FILE_HEADER Member List

This is the complete list of members for SDKANIMATION_FILE_HEADER, including all inherited members.
AnimationDataOffset | SDKANIMATION_FILE_HEADER
AnimationDataSize | SDKANIMATION_FILE_HEADER
AnimationFPS | SDKANIMATION_FILE_HEADER
FrameTransformType | SDKANIMATION_FILE_HEADER
IsBigEndian | SDKANIMATION_FILE_HEADER
NumAnimationKeys | SDKANIMATION_FILE_HEADER
NumFrames | SDKANIMATION_FILE_HEADER
Version | SDKANIMATION_FILE_HEADER
Generated on Sat Nov 23 2024 16:09:21 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/ScenarioInput4.xaml.h Source File

  • Media extensions

ScenarioInput4.xaml.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 // ScenarioInput4.xaml.h
00009 // Declaration of the ScenarioInput4 class.
00010 //
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "ScenarioInput4.g.h"
00016 #include "MainPage.xaml.h"
00017
00018 using namespace Windows::UI::Xaml;
00019
00020 namespace MediaExtensionsCPP
00021 {
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class ScenarioInput4 sealed
00024     {
00025     public:
00026         ScenarioInput4();
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         ~ScenarioInput4();
00034         MainPage^ rootPage;
00035         MediaElement^ outputVideo;
00036
00037         void rootPage_OutputFrameLoaded(Object^ sender, Object^ e);
00038         void OpenGrayscale_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039         void OpenFisheye_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         void OpenPinch_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         void OpenWarp_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00042         void OpenInvert_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00043         void Stop_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00044         Windows::Foundation::EventRegistrationToken _frameLoadedToken;
00045
00046         void OpenVideoWithPolarEffect(String^ effectName);
00047     };
00048 }
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Extended Linguistic Services (ELS)/C++/App.xaml.h Source File

  • Extended Linguistic Services (ELS)
  • C++

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Globalization preferences/C++/Constants.h Source File

  • Globalization preferences

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"Globalization Preferences");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044
00045
00046 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

MediaExtensionsCS::ScenarioInput1 Member List

This is the complete list of members for MediaExtensionsCS::ScenarioInput1, including all inherited members.
__pad0__ | Element |
AcceptChildNode(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^childXmlNode) override | Page | [virtual]
AddChild(_In_ Element^element) | Element |
AddSibling(_In_ Element^element) | Element |
BindResource(_In_ Element^rootElement) | Element | [virtual]
Create(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^xmlNode) | Element | [static]
Draw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
GetFirstChild() | Element | [inline]
GetName() | Element | [inline]
GetNextSibling() | Element | [inline]
GetOpacity() | Element | [inline, virtual]
GetParent() | Element | [inline]
GetSize() | Element | [inline]
Initialize(_In_ Document^document, _In_ Windows::Data::Xml::Dom::XmlElement^xmlElement) | Element | [virtual]
Measure(_In_ Document^document, D2D1_SIZE_F const &parentSize, _Out_ D2D1_RECT_F *bounds) | Element | [virtual]
MFVideoFormat_MPG1 | MediaExtensionsCS::ScenarioInput1 | [private]
OnNavigatedFrom(NavigationEventArgs e) | MediaExtensionsCS::ScenarioInput1 | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | MediaExtensionsCS::ScenarioInput1 | [inline, protected]
Open_Click(object sender, RoutedEventArgs e) | MediaExtensionsCS::ScenarioInput1 | [inline, private]
outputVideo | MediaExtensionsCS::ScenarioInput1 | [private]
PrepareToDraw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
ReleaseParent() | Element | [virtual]
rootPage | MediaExtensionsCS::ScenarioInput1 | [private]
rootPage_OutputFrameLoaded(object sender, object e) | MediaExtensionsCS::ScenarioInput1 | [inline, private]
ScenarioInput1() | MediaExtensionsCS::ScenarioInput1 | [inline]
Stop_Click(object sender, RoutedEventArgs e) | MediaExtensionsCS::ScenarioInput1 | [inline, private]
Generated on Sat Nov 23 2024 16:09:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File picker contracts/C++/common/LayoutAwarePage.cpp Source File

  • File picker contracts
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:31 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

BasicCamera Member List

This is the complete list of members for BasicCamera, including all inherited members.
__pad0__ | BasicCamera | [private]
GetProjectionMatrix(_Out_ float4x4 *projectionMatrix) | BasicCamera | [private]
GetProjectionMatrix(_Out_ float4x4 *projectionMatrix) | BasicCamera | [private]
GetProjectionMatrix(_Out_ float4x4 *projectionMatrix) | BasicCamera | [private]
GetProjectionMatrix(_Out_ float4x4 *projectionMatrix) | BasicCamera | [private]
GetProjectionMatrix(_Out_ float4x4 *projectionMatrix) | BasicCamera | [private]
GetProjectionMatrix(_Out_ float4x4 *projectionMatrix) | BasicCamera | [private]
GetProjectionMatrix(_Out_ float4x4 *projectionMatrix) | BasicCamera | [private]
GetProjectionMatrix(_Out_ float4x4 *projectionMatrix) | BasicCamera | [private]
GetProjectionMatrix(_Out_ float4x4 *projectionMatrix) | BasicCamera | [private]
m_direction | BasicCamera | [private]
m_position | BasicCamera | [private]
m_projection | BasicCamera | [private]
m_view | BasicCamera | [private]
SetProjectionParameters(_In_ float minimumFieldOfView, _In_ float aspectRatio, _In_ float nearPlane, _In_ float farPlane) | BasicCamera | [private]
SetProjectionParameters(_In_ float minimumFieldOfView, _In_ float aspectRatio, _In_ float nearPlane, _In_ float farPlane) | BasicCamera | [private]
SetProjectionParameters(_In_ float minimumFieldOfView, _In_ float aspectRatio, _In_ float nearPlane, _In_ float farPlane) | BasicCamera | [private]
SetProjectionParameters(_In_ float minimumFieldOfView, _In_ float aspectRatio, _In_ float nearPlane, _In_ float farPlane) | BasicCamera | [private]
SetProjectionParameters(_In_ float minimumFieldOfView, _In_ float aspectRatio, _In_ float nearPlane, _In_ float farPlane) | BasicCamera | [private]
SetProjectionParameters(_In_ float minimumFieldOfView, _In_ float aspectRatio, _In_ float nearPlane, _In_ float farPlane) | BasicCamera | [private]
SetProjectionParameters(_In_ float minimumFieldOfView, _In_ float aspectRatio, _In_ float nearPlane, _In_ float farPlane) | BasicCamera | [private]
SetProjectionParameters(_In_ float minimumFieldOfView, _In_ float aspectRatio, _In_ float nearPlane, _In_ float farPlane) | BasicCamera | [private]
SetProjectionParameters(_In_ float minimumFieldOfView, _In_ float aspectRatio, _In_ float nearPlane, _In_ float farPlane) | BasicCamera | [private]
SetViewParameters(_In_ float3 eyePosition, _In_ float3 lookPosition, _In_ float3 up) | BasicCamera | [private]
SetViewParameters(_In_ float3 eyePosition, _In_ float3 lookPosition, _In_ float3 up) | BasicCamera | [private]
SetViewParameters(_In_ float3 eyePosition, _In_ float3 lookPosition, _In_ float3 up) | BasicCamera | [private]
SetViewParameters(_In_ float3 eyePosition, _In_ float3 lookPosition, _In_ float3 up) | BasicCamera | [private]
SetViewParameters(_In_ float3 eyePosition, _In_ float3 lookPosition, _In_ float3 up) | BasicCamera | [private]
SetViewParameters(_In_ float3 eyePosition, _In_ float3 lookPosition, _In_ float3 up) | BasicCamera | [private]
SetViewParameters(_In_ float3 eyePosition, _In_ float3 lookPosition, _In_ float3 up) | BasicCamera | [private]
SetViewParameters(_In_ float3 eyePosition, _In_ float3 lookPosition, _In_ float3 up) | BasicCamera | [private]
SetViewParameters(_In_ float3 eyePosition, _In_ float3 lookPosition, _In_ float3 up) | BasicCamera | [private]
Generated on Sat Nov 23 2024 16:09:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Gyrometer sensor/C++/common/suspensionmanager.cpp Source File

  • Gyrometer sensor
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:36 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML personality animations/C++/Scenario2.xaml.cpp Source File

  • XAML personality animations

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 SDKSample::PersonalityAnimations;
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   messageData = ref new MessageData();
00030   ItemListView->ItemsSource = messageData->Items;
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 //}
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

OutlineRenderer Member List

This is the complete list of members for OutlineRenderer, including all inherited members.
AddGeometry(ID2D1Geometry *pGeometry) | OutlineRenderer | [private]
CreateOutlineRenderer(_In_ ID2D1Factory *pFactory, _Outptr_ OutlineRenderer **ppOutlineRenderer) | OutlineRenderer | [static]
DrawGlyphRun(void *, FLOAT baselineOriginX, FLOAT baselineOriginY, DWRITE_MEASURING_MODE, DWRITE_GLYPH_RUN const *glyphRun, DWRITE_GLYPH_RUN_DESCRIPTION const *, IUnknown *) | OutlineRenderer |
DrawInlineObject(void *, FLOAT, FLOAT, IDWriteInlineObject *, BOOL, BOOL, IUnknown *) | OutlineRenderer |
DrawStrikethrough(void *, FLOAT, FLOAT, DWRITE_STRIKETHROUGH const *, IUnknown *) | OutlineRenderer |
DrawUnderline(void *, FLOAT, FLOAT, DWRITE_UNDERLINE const *, IUnknown *) | OutlineRenderer |
GetCurrentTransform(void *, DWRITE_MATRIX *transform) | OutlineRenderer |
GetGeometry(ID2D1Geometry **ppGeometry) | OutlineRenderer |
GetPixelsPerDip(void *, FLOAT *pixelsPerDip) | OutlineRenderer |
IsPixelSnappingDisabled(void *, BOOL *isDisabled) | OutlineRenderer |
m_pFactory | OutlineRenderer | [private]
m_pGeometry | OutlineRenderer | [private]
m_ref | OutlineRenderer | [private]
OutlineRenderer(_In_ ID2D1Factory *pFactory) | OutlineRenderer | [private]
QueryInterface(REFIID riid, _Outptr_ void **object) override | OutlineRenderer |
STDMETHOD_(ULONG, AddRef)() override | OutlineRenderer |
STDMETHOD_(ULONG, Release)() override | OutlineRenderer |
Generated on Sat Nov 23 2024 16:09:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

ScreenVertex Member List

This is the complete list of members for ScreenVertex, including all inherited members.
pos | ScreenVertex
tex | ScreenVertex
Generated on Sat Nov 23 2024 16:09:21 for Win8-Examples by doxygen 1.7.1


Win8-Examples: App settings/C++/common/suspensionmanager.h Source File

  • App settings
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Audio Session (WASAPI)/C++/Common.h Source File

  • Windows Audio Session (WASAPI)
  • C++

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017 #include <Windows.h>
00018 #include <wrl\implements.h>
00019 #include <mmreg.h>
00020 #include <mfapi.h>
00021
00022 using namespace Microsoft::WRL;
00023
00024 // release and zero out a possible NULL pointer. note this will
00025 // do the release on a temp copy to avoid reentrancy issues that can result from
00026 // callbacks durring the release
00027 template <class T> void SafeRelease( __deref_inout_opt T **ppT )
00028 {
00029     T *pTTemp = *ppT;    // temp copy
00030     *ppT = nullptr;      // zero the input
00031     if (pTTemp)
00032     {
00033         pTTemp->Release();
00034     }
00035 }
00036
00037 // Exception Helper Method
00038 inline void ThrowIfFailed( HRESULT hr )
00039 {
00040     if (FAILED( hr ))
00041     {
00042         // Set a breakpoint on this line to catch API errors.
00043         throw Platform::Exception::CreateException( hr );
00044     }
00045 }
00046
00047 #ifndef SAFE_RELEASE
00048 #define SAFE_RELEASE(x) { SafeRelease(&x); }
00049 #endif
00050
00051 #ifndef SAFE_DELETE
00052 #define SAFE_DELETE(x) { delete x; x = nullptr; }
00053 #endif
00054
00055 #ifndef SAFE_ARRAYDELETE
00056 #define SAFE_ARRAYDELETE(x) { delete[] x; x = nullptr; }
00057 #endif
00058
00059 #ifndef METHODASYNCCALLBACK
00060 #define METHODASYNCCALLBACK(Parent, AsyncCallback, pfnCallback) \
00061 class Callback##AsyncCallback :\
00062     public IMFAsyncCallback \
00063 { \
00064 public: \
00065     Callback##AsyncCallback() : \
00066         _parent(((Parent*)((BYTE*)this - offsetof(Parent, m_x##AsyncCallback)))), \
00067         _dwQueueID( MFASYNC_CALLBACK_QUEUE_MULTITHREADED ) \
00068     { \
00069     } \
00070 \
00071     STDMETHOD_( ULONG, AddRef )() \
00072     { \
00073         return _parent->AddRef(); \
00074     } \
00075     STDMETHOD_( ULONG, Release )() \
00076     { \
00077         return _parent->Release(); \
00078     } \
00079     STDMETHOD( QueryInterface )( REFIID riid, void **ppvObject ) \
00080     { \
00081         if (riid == IID_IMFAsyncCallback || riid == IID_IUnknown) \
00082         { \
00083             (*ppvObject) = this; \
00084             AddRef(); \
00085             return S_OK; \
00086         } \
00087         *ppvObject = NULL; \
00088         return E_NOINTERFACE; \
00089     } \
00090     STDMETHOD( GetParameters )( \
00091         /* [out] */ __RPC__out DWORD *pdwFlags, \
00092         /* [out] */ __RPC__out DWORD *pdwQueue) \
00093     { \
00094         *pdwFlags = 0; \
00095         *pdwQueue = _dwQueueID; \
00096         return S_OK; \
00097     } \
00098     STDMETHOD( Invoke )( /* [out] */ __RPC__out IMFAsyncResult * pResult ) \
00099     { \
00100         _parent->pfnCallback( pResult ); \
00101         return S_OK; \
00102     } \
00103     void SetQueueID( DWORD dwQueueID ) { _dwQueueID = dwQueueID; } \
00104 \
00105 protected: \
00106     Parent* _parent; \
00107     DWORD   _dwQueueID; \
00108            \
00109 } m_x##AsyncCallback;
00110 #endif
00111
00112 //
00113 // CAsyncState
00114 //
00115 // Used to maintain state during MF Work Item callbacks
00116 class CAsyncState :
00117     public RuntimeClass<RuntimeClassFlags<ClassicCom>, IUnknown>
00118 {
00119 public:
00120     CAsyncState( Platform::Array<int,1>^ data, UINT32 size ) :
00121         m_Data(data),
00122         m_Size(size)
00123     {
00124     };
00125
00126 public:
00127     Platform::Array<int,1>^  m_Data;
00128     UINT32                   m_Size;
00129
00130 private:
00131     virtual ~CAsyncState() {};
00132 };
00133
00134 struct RenderBuffer
00135 {
00136     UINT32          BufferSize;
00137     UINT32          BytesFilled;
00138     BYTE           *Buffer;
00139     RenderBuffer   *Next;
00140
00141     RenderBuffer() :
00142         BufferSize(0),
00143         BytesFilled(0),
00144         Buffer( nullptr ),
00145         Next( nullptr )
00146     {
00147     }
00148
00149     ~RenderBuffer()
00150     {
00151         SAFE_ARRAYDELETE( Buffer );
00152     }
00153 };
00154
00155 enum RenderSampleType
00156 {
00157     SampleTypeUnknown,
00158     SampleTypeFloat,
00159     SampleType16BitPCM,
00160 };
00161
00162 //
00163 //  CalculateMixFormatType()
00164 //
00165 //  Determine IEEE Float or PCM samples based on media type
00166 //
00167 inline RenderSampleType CalculateMixFormatType( WAVEFORMATEX *wfx )
00168 {
00169     if ( (wfx->wFormatTag == WAVE_FORMAT_PCM) ||
00170          (  (wfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
00171             (reinterpret_cast<WAVEFORMATEXTENSIBLE *>(wfx)->SubFormat == KSDATAFORMAT_SUBTYPE_PCM) ) )
00172     {
00173         if (wfx->wBitsPerSample == 16)
00174         {
00175             return RenderSampleType::SampleType16BitPCM;
00176         }
00177     }
00178     else if ( (wfx->wFormatTag == WAVE_FORMAT_IEEE_FLOAT) ||
00179               ( (wfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
00180                 (reinterpret_cast<WAVEFORMATEXTENSIBLE *>(wfx)->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT) ) )
00181     {
00182         return RenderSampleType::SampleTypeFloat;
00183     }
00184
00185     return RenderSampleType::SampleTypeUnknown;
00186 }
Generated on Sat Nov 23 2024 16:08:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: SMS background task/C++/SmsBackgroundTaskSample/Constants.cpp Source File

  • SMS background task
  • SmsBackgroundTaskSample

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
00021     { "Using SMS background task", "SDKSample.SmsBackgroundTaskSample.BackgroundTask" }
00022 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

ScopedObject< T > Member List

This is the complete list of members for ScopedObject< T >, including all inherited members.
_pointer | ScopedObject< T > | [private]
Get() const | ScopedObject< T > | [inline]
IsNull() const | ScopedObject< T > | [inline]
operator&() | ScopedObject< T > | [inline]
operator*() | ScopedObject< T > | [inline]
operator->() | ScopedObject< T > | [inline]
operator=(const ScopedObject &) | ScopedObject< T > | [private]
Reset(T *p=0) | ScopedObject< T > | [inline]
ScopedObject(T *p=0) | ScopedObject< T > | [inline, explicit]
ScopedObject(const ScopedObject &) | ScopedObject< T > | [private]
~ScopedObject() | ScopedObject< T > | [inline]
Generated on Sat Nov 23 2024 16:09:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::TileContent::TileSquareText03 Member List

This is the complete list of members for NotificationsExtensions::TileContent::TileSquareText03, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
Branding | NotificationsExtensions::TileContent::TileNotificationBase |
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
NotificationsExtensions::GetContent() | NotificationsExtensions::TileContent::TileSquareBase | [inline]
NotificationsExtensions::GetContent() | NotificationsExtensions::TileContent::TileSquareBase | [inline]
NotificationsExtensions::TileContent::TileNotificationBase::GetContent() | NotificationsExtensions::NotificationBase | [pure virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeBinding(string globalLang, string globalBaseUri, TileBranding globalBranding, bool globalAddImageQuery) | NotificationsExtensions::TileContent::TileSquareBase | [inline]
SerializeBinding(string globalLang, string globalBaseUri, TileBranding globalBranding, bool globalAddImageQuery) | NotificationsExtensions::TileContent::TileSquareBase | [inline]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextBody1 | NotificationsExtensions::TileContent::TileSquareText03 |
TextBody2 | NotificationsExtensions::TileContent::TileSquareText03 |
TextBody3 | NotificationsExtensions::TileContent::TileSquareText03 |
TextBody4 | NotificationsExtensions::TileContent::TileSquareText03 |
TextFields | NotificationsExtensions::NotificationBase |
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileSquareBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileSquareBase | [inline]
TileSquareBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileSquareBase | [inline]
TileSquareText03() | NotificationsExtensions::TileContent::TileSquareText03 | [inline]
TileSquareText03() | NotificationsExtensions::TileContent::TileSquareText03 | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:43 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Device capabilities/C++/Touch.xaml.h Source File

  • Input Device capabilities

Touch.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 // Touch.xaml.h
00013 // Declaration of the Touch class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Touch.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace DeviceCaps
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 Touch sealed
00031         {
00032         public:
00033             Touch();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void TouchGetSettings_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/DirectXSample.h Source File

  • Direct3D resource loading

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
00010 // This header defines helper utilities to make DirectX APIs work with exceptions.
00011 namespace DX
00012 {
00013     inline void ThrowIfFailed(HRESULT hr)
00014     {
00015         if (FAILED(hr))
00016         {
00017             // Set a breakpoint on this line to catch DX API errors.
00018             throw Platform::Exception::CreateException(hr);
00019         }
00020     }
00021 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D magazine app/C++/Renderer.h Source File

  • Direct2D magazine app

Renderer.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 <initguid.h>
00011 #include <wrl.h>
00012 #include <d3d11_1.h>
00013 #include <dxgi1_2.h>
00014 #include <d2d1_1.h>
00015 #include <d2d1effects.h>
00016 #include <dwrite_1.h>
00017 #include <wincodec.h>
00018
00019 delegate void DeviceLostEventHandler();
00020
00021 // Helper class that initializes and maintains the DirectX API objects in one place.
00022 ref class Renderer
00023 {
00024 internal:
00025     Renderer(
00026         Windows::Foundation::Rect windowBounds,
00027         float dpi
00028         );
00029
00030     event DeviceLostEventHandler^ DeviceLost;
00031
00032     void HandleDeviceLost();
00033
00034     void UpdateWindowSize();
00035
00036     void SetDpi(float dpi);
00037
00038     void GetD2DDeviceContext(_Outptr_ ID2D1DeviceContext** d2dDeviceContext);
00039
00040     void GetWICImagingFactory(_Outptr_ IWICImagingFactory2** wicFactory);
00041
00042     void GetDXGIDevice(_Outptr_ IDXGIDevice** dxgiDevice);
00043
00044     inline float GetDisplayWidth()
00045     {
00046         return m_windowBounds.Width;
00047     }
00048
00049     inline float GetDisplayHeight()
00050     {
00051         return m_windowBounds.Height;
00052     }
00053
00054     inline D2D1_SIZE_F GetDisplaySize()
00055     {
00056         return D2D1::SizeF(GetDisplayWidth(), GetDisplayHeight());
00057     }
00058
00059     inline bool IsOrientationLandscape()
00060     {
00061         return GetDisplayWidth() >= GetDisplayHeight();
00062     }
00063
00064 protected private:
00065     void CreateDeviceIndependentResources();
00066     void CreateDeviceResources();
00067
00068     // Declare Direct2D objects
00069     Microsoft::WRL::ComPtr<ID2D1Factory1> m_d2dFactory;
00070     Microsoft::WRL::ComPtr<ID2D1Device> m_d2dDevice;
00071     Microsoft::WRL::ComPtr<ID2D1DeviceContext> m_d2dDeviceContext;
00072
00073     // Declare Windows Imaging Component objects
00074     Microsoft::WRL::ComPtr<IWICImagingFactory2> m_wicFactory;
00075
00076     // Direct3D objects
00077     Microsoft::WRL::ComPtr<IDXGIDevice> m_dxgiDevice;
00078
00079     // Direct3D feature level
00080     D3D_FEATURE_LEVEL m_featureLevel;
00081
00082     // Bounds of the current window
00083     Windows::Foundation::Rect m_windowBounds;
00084
00085     float m_dpi;
00086 };
00087
00088 // Helper utilities to make DX APIs work with exceptions in the samples apps.
00089 namespace DX
00090 {
00091     inline void ThrowIfFailed(HRESULT hr)
00092     {
00093         if (FAILED(hr))
00094         {
00095             // Set a breakpoint on this line to catch DX API errors.
00096             throw Platform::Exception::CreateException(hr);
00097         }
00098     }
00099 }
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media capture using capture device/C++/AdvancedCapture.xaml.h Source File

  • Media capture using capture device

AdvancedCapture.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 // AdvancedCapture.xaml.h
00013 // Declaration of the AdvancedCapture class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "AdvancedCapture.g.h"
00020 #include "MainPage.xaml.h"
00021 #include <ppl.h>
00022
00023 #define VIDEO_FILE_NAME "video.mp4"
00024 #define PHOTO_FILE_NAME "photo.jpg"
00025 #define TEMP_PHOTO_FILE_NAME "photoTmp.jpg"
00026
00027 using namespace concurrency;
00028 using namespace Windows::Devices::Enumeration;
00029
00030 namespace SDKSample
00031 {
00032     namespace MediaCapture
00033     {
00034         /// <summary>
00035         /// An empty page that can be used on its own or navigated to within a Frame.
00036         /// </summary>
00037         [Windows::Foundation::Metadata::WebHostHidden]
00038         public ref class AdvancedCapture sealed
00039         {
00040         public:
00041             AdvancedCapture();
00042
00043         protected:
00044             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00045             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00046
00047         private:
00048             MainPage^ rootPage;
00049             void ScenarioInit();
00050             void ScenarioReset();
00051
00052             void SoundLevelChanged(Object^ sender, Object^ e);
00053             void RecordLimitationExceeded(Windows::Media::Capture::MediaCapture ^ mediaCapture);
00054             void Failed(Windows::Media::Capture::MediaCapture ^ mediaCapture, Windows::Media::Capture::MediaCaptureFailedEventArgs ^ args);
00055
00056             void btnStartDevice_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00057
00058             void btnStartPreview_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00059
00060             void btnStartStopRecord_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061
00062             void btnTakePhoto_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063
00064             void lstEnumedDevices_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00065             void EnumerateWebcamsAsync();
00066
00067             void chkAddRemoveEffect_Checked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00068             void chkAddRemoveEffect_Unchecked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00069             void AddEffectToImageStream();
00070
00071             void ShowStatusMessage(Platform::String^ text);
00072             void ShowExceptionMessage(Platform::Exception^ ex);
00073
00074             void EnableButton(bool enabled, Platform::String ^name);
00075             void SwitchRecordButtonContent();
00076
00077             task<Windows::Storage::StorageFile^> ReencodePhotoAsync(
00078                 Windows::Storage::StorageFile ^tempStorageFile,
00079                 Windows::Storage::FileProperties::PhotoOrientation photoRotation);
00080             Windows::Storage::FileProperties::PhotoOrientation GetCurrentPhotoRotation();
00081             void PrepareForVideoRecording();
00082             void DisplayProperties_OrientationChanged(Platform::Object^ sender);
00083             Windows::Storage::FileProperties::PhotoOrientation PhotoRotationLookup(
00084                 Windows::Graphics::Display::DisplayOrientations displayOrientation, bool counterclockwise);
00085             Windows::Media::Capture::VideoRotation VideoRotationLookup(
00086                 Windows::Graphics::Display::DisplayOrientations displayOrientation, bool counterclockwise);
00087
00088             Platform::Agile<Windows::Media::Capture::MediaCapture> m_mediaCaptureMgr;
00089             Windows::Storage::StorageFile^ m_recordStorageFile;
00090             bool m_bRecording;
00091             bool m_bEffectAdded;
00092             bool m_bEffectAddedToRecord;
00093             bool m_bEffectAddedToPhoto;
00094             bool m_bSuspended;
00095             bool m_bPreviewing;
00096             DeviceInformationCollection^ m_devInfoCollection;
00097             Windows::Foundation::EventRegistrationToken m_eventRegistrationToken;
00098             bool m_bRotateVideoOnOrientationChange;
00099             bool m_bReversePreviewRotation;
00100             Windows::Foundation::EventRegistrationToken m_orientationChangedEventToken;
00101         };
00102     }
00103 }
Generated on Sat Nov 23 2024 16:08:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML Popup/C++/PopupInputContent.xaml.h Source File

  • XAML Popup

PopupInputContent.xaml.h

Go to the documentation of this file.
00001 ﻿//
00002 // PopupInputContent.xaml.h
00003 // Declaration of the PopupInputContent class
00004 //
00005
00006 #pragma once
00007
00008 #include "PopupInputContent.g.h"
00009
00010 namespace SDKSample
00011 {
00012     namespace XAMLPopup
00013     {
00014       public ref class PopupInputContent sealed
00015       {
00016       public:
00017         PopupInputContent();
00018       private:
00019         void SimulateSaveClicked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00020       };
00021     }
00022 }
Generated on Sat Nov 23 2024 16:08:27 for Win8-Examples by doxygen 1.7.1


Win8-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 |
CheckStereoEnabledStatus() | abstract | [private]
CheckStereoEnabledStatus() | abstract | [private]
Continuous() | abstract |
Continuous(_In_ bool continuous) | abstract |
Continuous() | abstract |
Continuous(_In_ bool continuous) | abstract |
ConvertDipsToPixels(float dips) | abstract | [virtual]
ConvertDipsToPixels(float dips) | abstract | [virtual]
ConvertDipsToPixels(float dips) | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceIndependentResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateDeviceResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
CreateWindowSizeDependentResources() | abstract | [virtual]
DeviceLost | abstract |
DeviceReset | abstract |
Duration() | abstract |
Duration(_In_ float duration) | abstract |
Duration() | abstract |
Duration(_In_ float duration) | abstract |
Evaluate(_In_ float t)=0 | abstract | [pure virtual]
Evaluate(_In_ float t)=0 | abstract | [pure virtual]
GetStereoEnabledStatus() | abstract |
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
HandleDeviceLost() | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, Windows::UI::Xaml::Controls::SwapChainBackgroundPanel^swapChainPanel, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, Windows::UI::Xaml::Controls::SwapChainBackgroundPanel^swapChainPanel, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, Windows::UI::Xaml::Controls::SwapChainBackgroundPanel^swapChainPanel, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, Windows::UI::Xaml::Controls::SwapChainBackgroundPanel^swapChainPanel, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) | abstract | [virtual]
IsActive(_In_ float t) | abstract | [inline]
IsActive(_In_ float t) | abstract | [inline]
IsFinished(_In_ float t) | abstract | [inline]
IsFinished(_In_ float t) | abstract | [inline]
LoadState(PersistentState^state) | abstract | [virtual]
LoadState(PersistentState^state) | abstract | [virtual]
m_continuous | abstract | [private]
m_d2dContext | abstract | [private]
m_d2dDevice | abstract | [private]
m_d2dFactory | abstract | [private]
m_d2dTargetBitmap | abstract | [private]
m_d2dTargetBitmapRight | abstract | [private]
m_d3dContext | abstract | [private]
m_d3dDepthStencilView | abstract | [private]
m_d3dDevice | abstract | [private]
m_d3dRenderTargetView | abstract | [private]
m_d3dRenderTargetViewRight | abstract | [private]
m_dpi | abstract | [private]
m_duration | abstract | [private]
m_dwriteFactory | abstract | [private]
m_featureLevel | abstract | [private]
m_indexBuffer | abstract | [private]
m_indexCount | abstract | [private]
m_numBuffers | abstract | [private]
m_objective | abstract | [private]
m_orientation | abstract | [private]
m_renderTargetSize | abstract | [private]
m_rotationTransform2D | abstract | [private]
m_rotationTransform3D | abstract | [private]
m_rotationTransform3D | abstract | [private]
m_startTime | abstract | [private]
m_stereoEnabled | abstract | [private]
m_swapChain | abstract | [private]
m_swapChainPanel | abstract | [private]
m_timeLimit | abstract | [private]
m_vertexBuffer | abstract | [private]
m_vertexCount | abstract | [private]
m_wicFactory | abstract | [private]
m_window | abstract | [private]
m_windowBounds | abstract | [private]
m_windowSizeChangeInProgress | abstract | [private]
Objective() | abstract |
Objective() | abstract |
OnStereoEnabledChanged(_In_ Platform::Object^sender) | abstract | [private]
OnStereoEnabledChanged(_In_ Platform::Object^sender) | abstract | [private]
OnStereoEnabledChanged(_In_ Platform::Object^sender) | abstract | [private]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Present() | abstract | [virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render(_In_ ID3D11DeviceContext *context) | abstract | [virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render(_In_ ID3D11DeviceContext *context) | abstract | [virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
Render()=0 | abstract | [pure virtual]
SaveState(PersistentState^state) | abstract | [virtual]
SaveState(PersistentState^state) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
SetDpi(float dpi) | abstract | [virtual]
Start() | abstract |
Start(_In_ float start) | abstract |
Start() | abstract |
Start(_In_ float start) | abstract |
TimeLimit() | abstract |
TimeLimit() | abstract |
Update(float time, float elapsedTime, float timeRemaining, std::vector< GameObject^> objects) | abstract | [virtual]
Update(float time, float elapsedTime, float timeRemaining, std::vector< GameObject^> objects) | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateForWindowSizeChange() | abstract | [virtual]
UpdateStereoEnabledStatus() | abstract | [private]
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
ValidateDevice() | abstract |
Generated on Sat Nov 23 2024 16:09:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File access/C++/Scenario3.xaml.cpp Source File

  • File access

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 SDKSample::FileAccess;
00020
00021 using namespace concurrency;
00022 using namespace Platform;
00023 using namespace Windows::Storage;
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 Scenario3::Scenario3()
00030 {
00031     InitializeComponent();
00032     rootPage = MainPage::Current;
00033     WriteBytesButton->Click += ref new RoutedEventHandler(this, &Scenario3::WriteBytesButton_Click);
00034     ReadBytesButton->Click  += ref new RoutedEventHandler(this, &Scenario3::ReadBytesButton_Click);
00035 }
00036
00037 IBuffer^ Scenario3::GetBufferFromString(String^ str)
00038 {
00039     InMemoryRandomAccessStream^ memoryStream = ref new InMemoryRandomAccessStream();
00040     DataWriter^ dataWriter = ref new DataWriter(memoryStream);
00041     dataWriter->WriteString(str);
00042     return dataWriter->DetachBuffer();
00043 }
00044
00045 void Scenario3::WriteBytesButton_Click(Object^ sender, RoutedEventArgs^ e)
00046 {
00047     rootPage->ResetScenarioOutput(OutputTextBlock);
00048     StorageFile^ file = rootPage->SampleFile;
00049     if (file != nullptr)
00050     {
00051         String^ userContent = InputTextBox->Text;
00052         if (userContent != nullptr && !userContent->IsEmpty())
00053         {
00054             IBuffer^ buffer = GetBufferFromString(userContent);
00055             create_task(FileIO::WriteBufferAsync(file, buffer)).then([this, file, buffer, userContent](task<void> task)
00056             {
00057                 try
00058                 {
00059                     task.get();
00060                     OutputTextBlock->Text = "The following " + buffer->Length.ToString() + " bytes of text were written to '" + file->Name + "':\n\n" + userContent;
00061                 }
00062                 catch(COMException^ ex)
00063                 {
00064                     rootPage->HandleFileNotFoundException(ex);
00065                 }
00066             });
00067         }
00068         else
00069         {
00070             OutputTextBlock->Text = "The text box is empty, please write something and then click 'Write' again.";
00071         }
00072     }
00073 }
00074
00075 void Scenario3::ReadBytesButton_Click(Object^ sender, RoutedEventArgs^ e)
00076 {
00077     rootPage->ResetScenarioOutput(OutputTextBlock);
00078     StorageFile^ file = rootPage->SampleFile;
00079     if (file != nullptr)
00080     {
00081         create_task(FileIO::ReadBufferAsync(file)).then([this, file](task<IBuffer^> task)
00082         {
00083             try
00084             {
00085                 IBuffer^ buffer = task.get();
00086                 DataReader^ dataReader = DataReader::FromBuffer(buffer);
00087                 String^ fileContent = dataReader->ReadString(buffer->Length);
00088                 OutputTextBlock->Text = "The following " + buffer->Length.ToString() + " bytes of text were read from '" + file->Name + "':\n\n" + fileContent;
00089             }
00090             catch(COMException^ ex)
00091             {
00092                 rootPage->HandleFileNotFoundException(ex);
00093             }
00094         });
00095     }
00096 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: EAS policies for mail clients/C++/common/suspensionmanager.cpp Source File

  • EAS policies for mail clients
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:36 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Custom driver access/C++,JavaScript/DLL/WUDFOsrUsbPublic.h Source File

  • Custom driver access
  • C++,JavaScript
  • DLL

WUDFOsrUsbPublic.h

Go to the documentation of this file.
00001 /*++
00002
00003 Copyright (c) Microsoft Corporation, All Rights Reserved
00004
00005 Module Name:
00006
00007     WUDFOsrUsbPublic.h
00008
00009 Abstract:
00010
00011     This module contains the common declarations shared by driver
00012     and user applications for the UMDF OSR device sample.
00013
00014     Note that this driver does NOT use the same device interface GUID
00015     as the KMDF OSR USB sample.
00016
00017 Environment:
00018
00019     user and kernel
00020
00021 --*/
00022
00023 #pragma once
00024
00025 //
00026 // Define an Interface Guid so that app can find the device and talk to it.
00027 //
00028
00029 // {573E8C73-0CB4-4471-A1BF-FAB26C31D384}
00030 DEFINE_GUID(GUID_DEVINTERFACE_OSRUSBFX2,
00031             0x573e8c73, 0xcb4, 0x4471, 0xa1, 0xbf, 0xfa, 0xb2, 0x6c, 0x31, 0xd3, 0x84);
00032
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

ComBase< InterfaceChain > Member List

This is the complete list of members for ComBase< InterfaceChain >, including all inherited members.
ComBase() | ComBase< InterfaceChain > | [inline, explicit]
ComBase(const ComBase &b) | ComBase< InterfaceChain > | [private]
IFACEMETHOD_(ULONG, AddRef)() | ComBase< InterfaceChain > | [inline]
IFACEMETHOD_(ULONG, Release)() | ComBase< InterfaceChain > | [inline]
operator=(ComBase const &) | ComBase< InterfaceChain > | [private]
QueryInterface(IID const &iid, OUT void **ppObject) | ComBase< InterfaceChain > | [inline]
refValue_ | ComBase< InterfaceChain > | [protected]
~ComBase() | ComBase< InterfaceChain > | [inline, virtual]
Generated on Sat Nov 23 2024 16:09:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Network information/C++/pch.h Source File

  • Network information

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Credential picker/C++/ScenarioInput1.xaml.cpp Source File

  • Credential picker

ScenarioInput1.xaml.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 //
00009 // Scenario1Input.xaml.cpp
00010 // Implementation of the Scenario1Input class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioInput1.xaml.h"
00015
00016 using namespace CredentialPickerCPP;
00017
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::UI::ViewManagement;
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::Security::Credentials::UI;
00031 using namespace concurrency;
00032
00033 ScenarioInput1::ScenarioInput1()
00034 {
00035     InitializeComponent();
00036 }
00037
00038 ScenarioInput1::~ScenarioInput1()
00039 {
00040 }
00041
00042 void ScenarioInput1::SetError(Platform::String^ errorText)
00043 {
00044     this->rootPage->NotifyUser(errorText,NotifyType::ErrorMessage);
00045 }
00046
00047 void ScenarioInput1::SetResult(CredentialPickerResults^ result)
00048 {
00049     auto domainName = result->CredentialDomainName;
00050     auto userName = result->CredentialUserName;
00051     auto password = result->CredentialPassword;
00052     auto savedByApi = result->CredentialSaved;
00053     auto saveOption = result->CredentialSaveOption;
00054     Page^ outputFrame = (Page^)this->rootPage->OutputFrame->Content;
00055     TextBox^ status = (TextBox^)(outputFrame->FindName("Status"));
00056     status->Text = "OK";
00057     TextBox^ domain = (TextBox^)outputFrame->FindName("Domain");
00058     domain->Text = domainName;
00059     TextBox^ username = (TextBox^)outputFrame->FindName("Username");
00060     username->Text = userName;
00061     TextBox^ passwordBox = (TextBox^)outputFrame->FindName("Password");
00062     passwordBox->Text = password;
00063     TextBox^ credsaved = (TextBox^)outputFrame->FindName("CredentialSaved");
00064     credsaved->Text = (savedByApi ? "true" : "false");
00065     TextBox^ checkboxState = (TextBox^)outputFrame->FindName("CheckboxState");
00066     switch (result->CredentialSaveOption)
00067     {
00068         case Windows::Security::Credentials::UI::CredentialSaveOption::Hidden:
00069             checkboxState->Text = "Hidden";
00070             break;
00071         case Windows::Security::Credentials::UI::CredentialSaveOption::Selected:
00072             checkboxState->Text = "Selected";
00073             break;
00074         case Windows::Security::Credentials::UI::CredentialSaveOption::Unselected:
00075             checkboxState->Text = "Unselected";
00076             break;
00077     }
00078 }
00079
00080 #pragma region Template-Related Code - Do not remove
00081 void ScenarioInput1::OnNavigatedTo(NavigationEventArgs^ e)
00082 {
00083     // Get a pointer to our main page.
00084     rootPage = dynamic_cast<MainPage^>(e->Parameter);
00085
00086     // We want to be notified with the OutputFrame is loaded so we can get to the content.
00087     _frameLoadedToken = rootPage->OutputFrameLoaded += ref new Windows::Foundation::EventHandler<Platform::Object^>(this, &ScenarioInput1::rootPage_OutputFrameLoaded);
00088 }
00089
00090 void ScenarioInput1::OnNavigatedFrom(NavigationEventArgs^ e)
00091 {
00092     rootPage->OutputFrameLoaded -= _frameLoadedToken;
00093 }
00094
00095 #pragma endregion
00096
00097 #pragma region Use this code if you need access to elements in the output frame - otherwise delete
00098 void ScenarioInput1::rootPage_OutputFrameLoaded(Object^ sender, Object^ e)
00099 {
00100     // Get a pointer to the content within the OutputFrame.
00101     Page^ outputFrame = dynamic_cast<Page^>(rootPage->OutputFrame->Content);
00102
00103     // Go find the elements that we need for this scenario
00104     // ex: flipView1 = dynamic_cast<FlipView^>(outputFrame->FindName("FlipView1"));
00105 }
00106
00107 #pragma endregion
00108
00109 #pragma region Sample click handlers - modify if you need them, otherwise delete
00110 void ScenarioInput1::Launch_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if ((Message->Text != nullptr) && (Target->Text != nullptr))
00113   {
00114     create_task(CredentialPicker::PickAsync(Message->Text, Target->Text))
00115       .then([this](CredentialPickerResults^ credPickerResult)
00116     {
00117       auto domainName = credPickerResult->CredentialDomainName;
00118       auto userName = credPickerResult->CredentialUserName;
00119       auto password = credPickerResult->CredentialPassword;
00120       auto savedByApi = credPickerResult->CredentialSaved;
00121       auto saveOption = credPickerResult->CredentialSaveOption;
00122       SetResult(credPickerResult);
00123     });
00124   }
00125 }
00126
00127 #pragma endregion
Generated on Sat Nov 23 2024 16:07:59 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX marble maze game/C++/SampleOverlay.cpp Source File

  • DirectX marble maze game

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 Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::UI::ViewManagement;
00015 using namespace Windows::Graphics::Display;
00016 using namespace D2D1;
00017
00018 SampleOverlay::SampleOverlay() :
00019     m_drawOverlay(true)
00020 {
00021 }
00022
00023 void SampleOverlay::Initialize(
00024     _In_ ID2D1Device*         d2dDevice,
00025     _In_ ID2D1DeviceContext*  d2dContext,
00026     _In_ IWICImagingFactory*  wicFactory,
00027     _In_ IDWriteFactory*      dwriteFactory,
00028     _In_ Platform::String^    caption
00029     )
00030 {
00031     m_wicFactory = wicFactory;
00032     m_dwriteFactory = dwriteFactory;
00033     m_sampleName = caption;
00034     m_d2dDevice = d2dDevice;
00035     m_d2dContext = d2dContext;
00036     m_padding = 3.0f;
00037     m_textVerticalOffset = 5.0f;
00038     m_logoSize = D2D1::SizeF(0.0f, 0.0f);
00039     m_overlayWidth = 0.0f;
00040
00041     ComPtr<ID2D1Factory> factory;
00042     d2dDevice->GetFactory(&factory);
00043
00044     DX::ThrowIfFailed(
00045         factory.As(&m_d2dFactory)
00046         );
00047
00048     ResetDirectXResources();
00049 }
00050
00051 void SampleOverlay::ResetDirectXResources()
00052 {
00053     DX::ThrowIfFailed(
00054         m_d2dContext->CreateSolidColorBrush(ColorF(ColorF::White), &m_whiteBrush)
00055         );
00056
00057     ComPtr<IWICBitmapDecoder> wicBitmapDecoder;
00058     DX::ThrowIfFailed(
00059         m_wicFactory->CreateDecoderFromFilename(
00060             L"windowsbig-sdk.png",
00061             nullptr,
00062             GENERIC_READ,
00063             WICDecodeMetadataCacheOnDemand,
00064             &wicBitmapDecoder
00065             )
00066         );
00067
00068     ComPtr<IWICBitmapFrameDecode> wicBitmapFrame;
00069     DX::ThrowIfFailed(
00070         wicBitmapDecoder->GetFrame(0, &wicBitmapFrame)
00071         );
00072
00073     ComPtr<IWICFormatConverter> wicFormatConverter;
00074     DX::ThrowIfFailed(
00075         m_wicFactory->CreateFormatConverter(&wicFormatConverter)
00076         );
00077
00078     DX::ThrowIfFailed(
00079         wicFormatConverter->Initialize(
00080             wicBitmapFrame.Get(),
00081             GUID_WICPixelFormat32bppPBGRA,
00082             WICBitmapDitherTypeNone,
00083             nullptr,
00084             0.0,
00085             WICBitmapPaletteTypeCustom  // the BGRA format has no palette so this value is ignored
00086             )
00087         );
00088
00089     double dpiX = 96.0f;
00090     double dpiY = 96.0f;
00091     DX::ThrowIfFailed(
00092         wicFormatConverter->GetResolution(&dpiX, &dpiY)
00093         );
00094
00095     DX::ThrowIfFailed(
00096         m_d2dContext->CreateBitmapFromWicBitmap(
00097             wicFormatConverter.Get(),
00098             BitmapProperties(
00099                 PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00100                 static_cast<float>(dpiX),
00101                 static_cast<float>(dpiY)
00102                 ),
00103             &m_logoBitmap
00104             )
00105         );
00106
00107     m_logoSize = m_logoBitmap->GetSize();
00108
00109     ComPtr<IDWriteTextFormat> nameTextFormat;
00110     DX::ThrowIfFailed(
00111         m_dwriteFactory->CreateTextFormat(
00112             L"Segoe UI",
00113             nullptr,
00114             DWRITE_FONT_WEIGHT_LIGHT,
00115             DWRITE_FONT_STYLE_NORMAL,
00116             DWRITE_FONT_STRETCH_NORMAL,
00117             36.0f,
00118             L"en-US",
00119             &nameTextFormat
00120             )
00121         );
00122
00123     DX::ThrowIfFailed(
00124         nameTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)
00125         );
00126
00127     DX::ThrowIfFailed(
00128         nameTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)
00129         );
00130
00131     DX::ThrowIfFailed(
00132         m_dwriteFactory->CreateTextLayout(
00133             m_sampleName->Data(),
00134             m_sampleName->Length(),
00135             nameTextFormat.Get(),
00136             4096.0f,
00137             4096.0f,
00138             &m_textLayout
00139             )
00140         );
00141
00142     DWRITE_TEXT_METRICS metrics = {0};
00143     DX::ThrowIfFailed(
00144         m_textLayout->GetMetrics(&metrics)
00145         );
00146
00147     m_overlayWidth = m_padding * 3.0f + m_logoSize.width + metrics.width;
00148
00149     DX::ThrowIfFailed(
00150         m_d2dFactory->CreateDrawingStateBlock(&m_stateBlock)
00151         );
00152
00153     UpdateForWindowSizeChange();
00154 }
00155
00156 void SampleOverlay::UpdateForWindowSizeChange()
00157 {
00158     if (CoreWindow::GetForCurrentThread()->Bounds.Width < m_overlayWidth)
00159     {
00160         m_drawOverlay = false;
00161     }
00162     else
00163     {
00164         m_drawOverlay = true;
00165     }
00166 }
00167
00168 void SampleOverlay::Render()
00169 {
00170     if (m_drawOverlay)
00171     {
00172         m_d2dContext->SaveDrawingState(m_stateBlock.Get());
00173
00174         m_d2dContext->BeginDraw();
00175         m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00176         m_d2dContext->DrawBitmap(
00177             m_logoBitmap.Get(),
00178             D2D1::RectF(m_padding, 0.0f, m_logoSize.width + m_padding, m_logoSize.height)
00179             );
00180
00181         m_d2dContext->DrawTextLayout(
00182             Point2F(m_logoSize.width + 2.0f * m_padding, m_textVerticalOffset),
00183             m_textLayout.Get(),
00184             m_whiteBrush.Get()
00185             );
00186
00187         // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00188         // is lost. It will be handled during the next call to Present.
00189         HRESULT hr = m_d2dContext->EndDraw();
00190         if (hr != D2DERR_RECREATE_TARGET)
00191         {
00192             DX::ThrowIfFailed(hr);
00193         }
00194
00195         m_d2dContext->RestoreDrawingState(m_stateBlock.Get());
00196     }
00197 }
00198
00199 float SampleOverlay::GetTitleHeightInDips()
00200 {
00201     return m_logoSize.height;
00202 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Store device app for camera/C++/Wrapper/WinRTComponent.h Source File

  • Windows Store device app for camera
  • Wrapper

WinRTComponent.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
00009 #pragma once
00010
00011 using namespace Windows::Foundation;
00012
00013 namespace Wrapper
00014 {
00015     public value struct DspSettings
00016     {
00017         unsigned int percentOfScreen;
00018         BOOL isEnabled;
00019     };
00020
00021     public ref class WinRTComponent sealed
00022     {
00023     public:
00024         WinRTComponent ();
00025
00026         bool Initialize(Object^ o);
00027
00028         void UpdateDsp(int percentOfScreen);
00029         void Enable();
00030         void Disable();
00031         DspSettings GetDspSetting();
00032
00033     private:
00034         ~WinRTComponent ();
00035         Microsoft::WRL::ComPtr<IMft0> m_spImpl;
00036     };
00037 }
00038 // WinRTComponent.h
Generated on Sat Nov 23 2024 16:08:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

CoreWindowEvents Member List

This is the complete list of members for CoreWindowEvents, including all inherited members.
CreateDeviceIndependentResources() override | CoreWindowEvents | [virtual]
CreateDeviceResources() override | CoreWindowEvents | [virtual]
EventPrint(_In_ Platform::String^eventText) | CoreWindowEvents | [private]
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | CoreWindowEvents | [virtual]
Load(_In_ Platform::String^entryPoint) | CoreWindowEvents | [virtual]
m_blackBrush | CoreWindowEvents | [private]
m_eventName | CoreWindowEvents | [private]
m_eventTextFormat | CoreWindowEvents | [private]
m_sampleOverlay | CoreWindowEvents | [private]
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | CoreWindowEvents |
OnCharacterReceived(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::CharacterReceivedEventArgs^args) | CoreWindowEvents |
OnDisplayContentsInvalidated(_In_ Platform::Object^sender) | CoreWindowEvents |
OnKeyDown(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::KeyEventArgs^args) | CoreWindowEvents |
OnKeyUp(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::KeyEventArgs^args) | CoreWindowEvents |
OnLogicalDpiChanged(_In_ Platform::Object^sender) | CoreWindowEvents |
OnPointerMoved(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | CoreWindowEvents |
OnPointerPressed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | CoreWindowEvents |
OnPointerReleased(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | CoreWindowEvents |
OnWindowActivated(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowActivatedEventArgs^args) | CoreWindowEvents |
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | CoreWindowEvents |
PrintPointerInfo(_In_ Platform::String^eventText, _In_ Windows::UI::Core::PointerEventArgs^args) | CoreWindowEvents | [private]
Render() override | CoreWindowEvents | [virtual]
Run() | CoreWindowEvents | [virtual]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | CoreWindowEvents | [virtual]
Uninitialize() | CoreWindowEvents | [virtual]
Generated on Sat Nov 23 2024 16:09:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Transcoding media/C++/common/LayoutAwarePage.cpp Source File

  • Transcoding media
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:33 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Geolocation/C++/backgroundtask/LocationBackgroundTask.h Source File

  • Geolocation
  • backgroundtask

LocationBackgroundTask.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 namespace BackgroundTask
00016 {
00017     public ref class LocationBackgroundTask sealed : public Windows::ApplicationModel::Background::IBackgroundTask
00018     {
00019     public:
00020         LocationBackgroundTask();
00021
00022         virtual void Run(Windows::ApplicationModel::Background::IBackgroundTaskInstance^ taskInstance);
00023
00024     private:
00025         void OnCanceled(Windows::ApplicationModel::Background::IBackgroundTaskInstance^ taskInstance, Windows::ApplicationModel::Background::BackgroundTaskCancellationReason reason);
00026         ~LocationBackgroundTask();
00027
00028         Concurrency::cancellation_token_source geopositionTaskTokenSource;
00029     };
00030 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Toast notifications/C#,C++/ScenarioInput6.xaml.cpp Source File

  • Toast notifications
  • C#,C++

ScenarioInput6.xaml.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 //
00009 // Scenario1Input.xaml.cpp
00010 // Implementation of the Scenario1Input class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioInput6.xaml.h"
00015
00016 using namespace ToastsSampleCPP;
00017
00018 using namespace NotificationsExtensions::ToastContent;
00019 using namespace Platform;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Graphics::Display;
00023 using namespace Windows::UI::Notifications;
00024 using namespace Windows::UI::ViewManagement;
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 ScenarioInput6::ScenarioInput6()
00034 {
00035   InitializeComponent();
00036
00037   Scenario6Looping->Click += ref new RoutedEventHandler([this] (Object^ sender, RoutedEventArgs^ e) {
00038     Scenario6DisplayLongToast(true);
00039   });
00040   Scenario6NoLooping->Click += ref new RoutedEventHandler([this] (Object^ sender, RoutedEventArgs^ e) {
00041     Scenario6DisplayLongToast(false);
00042   });
00043
00044
00045   Scenario6LoopingString->Click += ref new RoutedEventHandler([this] (Object^ sender, RoutedEventArgs^ e) {
00046     Scenario6DisplayLongToastWithStringManipulation(true);
00047   });
00048   Scenario6NoLoopingString->Click += ref new RoutedEventHandler([this] (Object^ sender, RoutedEventArgs^ e) {
00049     Scenario6DisplayLongToastWithStringManipulation(false);
00050   });
00051 }
00052
00053 ScenarioInput6::~ScenarioInput6()
00054 {
00055 }
00056
00057 #pragma region Template-Related Code - Do not remove
00058 void ScenarioInput6::OnNavigatedTo(NavigationEventArgs^ e)
00059 {
00060   // Get a pointer to our main page.
00061   rootPage = dynamic_cast<MainPage^>(e->Parameter);
00062
00063 }
00064
00065 void ScenarioInput6::OnNavigatedFrom(NavigationEventArgs^ e)
00066 {
00067
00068 }
00069
00070 #pragma endregion
00071
00072 void ScenarioInput6::OutputText(String^ text) {
00073   if (outputText == nullptr)
00074   {
00075     // Get a pointer to the content within the OutputFrame.
00076     Page^ outputFrame = dynamic_cast<Page^>(rootPage->OutputFrame->Content);
00077
00078     // Go find the elements that we need for this scenario
00079     outputText = dynamic_cast<TextBlock^>(outputFrame->FindName("Scenario6OutputText"));
00080   }
00081
00082   outputText->Text = text;
00083 }
00084
00085 void ScenarioInput6::Scenario6DisplayLongToast(bool loopAudio)
00086 {
00087   IToastText02^ toastContent = ToastContentFactory::CreateToastText02();
00088   toastContent->TextHeading->Text = "Long Duration Toast";
00089   toastContent->Duration = ToastDuration::Long;
00090
00091   if (loopAudio)
00092   {
00093     toastContent->Audio->Content = ToastAudioContent::LoopingAlarm;
00094     toastContent->Audio->Loop = true;
00095     // Long-duration Toasts can optionally loop audio using the 'loop' attribute
00096     toastContent->TextBodyWrap->Text = "Looping audio";
00097   }
00098   else
00099   {
00100     toastContent->Audio->Content = ToastAudioContent::IM;
00101   }
00102
00103   OutputText(toastContent->GetContent());
00104
00105   // Create a toast, then create a ToastNotifier object to show
00106   // the toast
00107   auto toast = toastContent->CreateNotification();
00108   ToastNotificationManager::CreateToastNotifier()->Show(toast);
00109 }
00110
00111 void ScenarioInput6::Scenario6DisplayLongToastWithStringManipulation(bool loopAudio)
00112 {
00113   String^ toastXmlString = nullptr;
00114   if (loopAudio)
00115   {
00116     toastXmlString = "<toast duration='long'>"
00117       + "<visual version='1'>"
00118       + "<binding template='ToastText02'>"
00119       + "<text id='1'>Long Duration Toast</text>"
00120       + "<text id='2'>Looping audio</text>"
00121       + "</binding>"
00122       + "</visual>"
00123       + "<audio loop='true' src='ms-winsoundevent:Notification.Looping.Alarm'/>"
00124       + "</toast>";
00125   }
00126   else
00127   {
00128     toastXmlString = "<toast duration='long'>"
00129       + "<visual version='1'>"
00130       + "<binding template='ToastText02'>"
00131       + "<text id='1'>Long Toast</text>"
00132       + "</binding>"
00133       + "</visual>"
00134       + "<audio loop='true' src='ms-winsoundevent:Notification.IM'/>"
00135       + "</toast>";
00136   }
00137
00138   auto toastDOM = ref new Windows::Data::Xml::Dom::XmlDocument();
00139   toastDOM->LoadXml(toastXmlString);
00140
00141   OutputText(toastDOM->GetXml());
00142
00143   // Create a toast, then create a ToastNotifier object to show
00144   // the toast
00145   auto toast = ref new ToastNotification(toastDOM);
00146
00147   // If you have other applications in your package, you can specify the AppId of
00148   // the app to create a ToastNotifier for that application
00149   ToastNotificationManager::CreateToastNotifier()->Show(toast);
00150 }
00151
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Hilo::ExceptionPolicyFactory Member List

This is the complete list of members for Hilo::ExceptionPolicyFactory, including all inherited members.
GetCurrentPolicy() | Hilo::ExceptionPolicyFactory | [static]
m_policy | Hilo::ExceptionPolicyFactory | [static]
Generated on Sat Nov 23 2024 16:09:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D magazine app/C++/Image.cpp Source File

  • Direct2D magazine app

Image.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
00010 using namespace Microsoft::WRL;
00011 using namespace Windows::Data::Xml::Dom;
00012
00013 ::Image::Image() :
00014     Resource(),
00015     m_bitmap(),
00016     m_file(nullptr)
00017 {
00018 }
00019
00020 bool ::Image::Initialize(
00021     _In_ Document^ document,
00022     _In_ XmlElement^ xmlElement
00023     )
00024 {
00025     if (!Element::Initialize(document, xmlElement))
00026     {
00027         return false;
00028     }
00029
00030     Platform::String^ value = xmlElement->GetAttribute("file");
00031
00032     if (value != nullptr)
00033     {
00034         // Initiate asynchronous loading of image data from the image file
00035         m_file = new ImageFile();
00036         m_file->LoadAsync(document->GetLocation(), value);
00037     }
00038
00039     return true;
00040 }
00041
00042 bool ::Image::DrawBitmap(
00043     _In_ Renderer^ renderer,
00044     D2D1::Matrix3x2F const& transform,
00045     D2D1_RECT_F const& destinationBounds,
00046     D2D1_RECT_F const& bitmapBounds
00047     )
00048 {
00049     ComPtr<ID2D1DeviceContext> d2dDeviceContext;
00050     ComPtr<IWICImagingFactory2> wicFactory;
00051
00052     // Obtain Direct2D device context and WIC imaging factory
00053     renderer->GetD2DDeviceContext(&d2dDeviceContext);
00054     renderer->GetWICImagingFactory(&wicFactory);
00055
00056     if (m_bitmap == nullptr)
00057     {
00058         if (!m_file->Ready())
00059         {
00060             // The image file is still be loaded, requesting redraw upon return.
00061             return true;
00062         }
00063
00064         // Use Windows Imaging Component to decode an image file into a
00065         // WIC bitmap and then make a copy as a Direct2D bitmap in video
00066         // memory.
00067         ComPtr<IWICBitmapDecoder> decoder;
00068         ComPtr<IWICBitmapFrameDecode> frame;
00069         ComPtr<IWICFormatConverter> wicBitmap;
00070
00071         DX::ThrowIfFailed(
00072             wicFactory->CreateDecoderFromStream(
00073                 m_file.Get(),
00074                 nullptr,
00075                 WICDecodeMetadataCacheOnDemand,
00076                 &decoder
00077                 )
00078             );
00079
00080         DX::ThrowIfFailed(
00081             decoder->GetFrame(0, &frame)
00082             );
00083
00084         DX::ThrowIfFailed(
00085             wicFactory->CreateFormatConverter(&wicBitmap)
00086             );
00087
00088         DX::ThrowIfFailed(
00089             wicBitmap->Initialize(
00090                 frame.Get(),
00091                 GUID_WICPixelFormat32bppPBGRA,
00092                 WICBitmapDitherTypeNone,
00093                 nullptr,
00094                 0,
00095                 WICBitmapPaletteTypeCustom
00096                 )
00097             );
00098
00099         DX::ThrowIfFailed(
00100             d2dDeviceContext->CreateBitmapFromWicBitmap(
00101                 wicBitmap.Get(),
00102                 D2D1::BitmapProperties(
00103                     D2D1::PixelFormat(),
00104                     96.0,
00105                     96.0
00106                     ),
00107                 &m_bitmap
00108                 )
00109             );
00110     }
00111
00112     d2dDeviceContext->SetTransform(transform);
00113
00114     d2dDeviceContext->DrawBitmap(
00115         m_bitmap.Get(),
00116         &destinationBounds,
00117         1.0f,
00118         D2D1_INTERPOLATION_MODE_HIGH_QUALITY_CUBIC,
00119         &bitmapBounds
00120         );
00121
00122     return false;
00123 }
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Background task/C++/BackgroundTask/MainPage.xaml.cpp Source File

  • Background task
  • BackgroundTask

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160 }
00161
00162 /// <summary>
00163 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00164 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00165 /// and output sections into the respective UserControl on the main page.
00166 /// </summary>
00167 /// <param name="scenarioName"></param>
00168 void MainPage::LoadScenario(String^ scenarioName)
00169 {
00170     autoSizeInputSectionWhenSnapped = true;
00171
00172     // Load the ScenarioX.xaml file into the Frame.
00173     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00174     HiddenFrame->Navigate(scenarioType, this);
00175
00176     // Get the top element, the Page, so we can look up the elements
00177     // that represent the input and output sections of the ScenarioX file.
00178     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00179
00180     // Get each element.
00181     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00182     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00183
00184     if (input == nullptr)
00185     {
00186         // Malformed input section.
00187         NotifyUser("Cannot load scenario input section for " + scenarioName +
00188             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00189         return;
00190     }
00191
00192     if (output == nullptr)
00193     {
00194         // Malformed output section.
00195         NotifyUser("Cannot load scenario output section for " + scenarioName +
00196             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00197         return;
00198     }
00199
00200     // Find the LayoutRoot which parents the input and output sections in the main page.
00201     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00202
00203     if (panel != nullptr)
00204     {
00205         unsigned int index = 0;
00206         UIElementCollection^ collection = panel->Children;
00207
00208         // Get rid of the content that is currently in the intput and output sections.
00209         collection->IndexOf(input, &index);
00210         collection->RemoveAt(index);
00211
00212         collection->IndexOf(output, &index);
00213         collection->RemoveAt(index);
00214
00215         // Populate the input and output sections with the newly loaded content.
00216         InputSection->Content = input;
00217         OutputSection->Content = output;
00218
00219         ScenarioLoaded(this, nullptr);
00220     }
00221     else
00222     {
00223         // Malformed Scenario file.
00224         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00225             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00226     }
00227 }
00228
00229 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00230 {
00231     if (Scenarios->SelectedItem != nullptr)
00232     {
00233         NotifyUser("", NotifyType::StatusMessage);
00234
00235         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00236         InvalidateSize();
00237     }
00238 }
00239
00240 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00241 {
00242     switch (type)
00243     {
00244     case NotifyType::StatusMessage:
00245         // Use the status message style.
00246         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00247         break;
00248     case NotifyType::ErrorMessage:
00249         // Use the error message style.
00250         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00251         break;
00252     default:
00253         break;
00254     }
00255     StatusBlock->Text = strMessage;
00256
00257     // Collapsed the StatusBlock if it has no text to conserve real estate.
00258     if (StatusBlock->Text != "")
00259     {
00260         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00261     }
00262     else
00263     {
00264         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00265     }
00266 }
00267
00268 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00271     Windows::System::Launcher::LaunchUriAsync(uri);
00272 }
00273
00274
00275 /// <summary>
00276 /// Populates the page with content passed during navigation.  Any saved state is also
00277 /// provided when recreating a page from a prior session.
00278 /// </summary>
00279 /// <param name="navigationParameter">The parameter value passed to
00280 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00281 /// </param>
00282 /// <param name="pageState">A map of state preserved by this page during an earlier
00283 /// session.  This will be null the first time a page is visited.</param>
00284 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00285 {
00286     (void) navigationParameter; // Unused parameter
00287
00288     PopulateScenarios();
00289
00290     // Starting scenario is the first or based upon a previous state.
00291     ListBoxItem^ startingScenario = nullptr;
00292     int startingScenarioIndex = -1;
00293
00294     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00295     {
00296         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00297     }
00298
00299     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00300
00301     InvalidateViewState();
00302 }
00303
00304 /// <summary>
00305 /// Preserves state associated with this page in case the application is suspended or the
00306 /// page is discarded from the navigation cache.  Values must conform to the serialization
00307 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00308 /// </summary>
00309 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00310 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00311 {
00312     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00313     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00314 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Removable storage/C++/S3_GetFromStorage.xaml.h Source File

  • Removable storage

S3_GetFromStorage.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 // S3_GetFromStorage.xaml.h
00013 // Declaration of the S3_GetFromStorage class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "S3_GetFromStorage.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace RemovableStorageCPP
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 S3_GetFromStorage sealed
00031         {
00032         public:
00033             S3_GetFromStorage();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037
00038         private:
00039             void GetImage_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040             void ShowDeviceSelectorAsync();
00041             void DeviceList_Tapped(Platform::Object^ sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^ e);
00042             void GetFirstImageFromStorageAsync(Windows::Devices::Enumeration::DeviceInformation^ deviceInfoElement);
00043             void DisplayImageAsync(Windows::Storage::StorageFile^ imageFile);
00044
00045             MainPage^ rootPage;
00046             // Contains the device information used for populating the device selection list
00047             Windows::Devices::Enumeration::DeviceInformationCollection^ _deviceInfoCollection;
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:08:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application resources and localization/C++/Scenario9.xaml.cpp Source File

  • Application resources and localization

Scenario9.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 "Scenario9.xaml.h"
00018 using namespace SDKSample::ApplicationResources;
00019 using namespace Platform;
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Controls;
00022 using namespace Windows::UI::Xaml::Navigation;
00023 using namespace Windows::ApplicationModel::Resources;
00024 using namespace Windows::ApplicationModel::Resources::Core;
00025
00026
00027 Scenario9::Scenario9()
00028 {
00029     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 void Scenario9::OnNavigatedTo(NavigationEventArgs^ e)
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     rootPage = MainPage::Current;
00042   Scenario9TextBlock->Text = "";
00043 }
00044
00045 void SDKSample::ApplicationResources::Scenario9::Scenario9Button_Show_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00046 {
00047     Button^ b = safe_cast<Button^>(sender);
00048     if (b != nullptr)
00049     {
00050     auto selectedLanguage = Scenario9ComboBox->SelectedValue;
00051     if (selectedLanguage != nullptr)
00052     {
00053       auto context = ref new ResourceContext();
00054       context->QualifierValues->Insert("language", selectedLanguage->ToString());
00055
00056       auto resourceStringMap = ResourceManager::Current->MainResourceMap->GetSubtree("Resources");
00057       auto resourceCandidate = resourceStringMap->GetValue("string1", context);
00058       if (resourceCandidate)
00059       {
00060         Scenario9TextBlock->Text = resourceCandidate->ValueAsString;
00061       }
00062     }
00063     }
00064 }
00065
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Custom driver access/C++/app_cpp/App.xaml.cpp Source File

  • Custom driver access
  • app_cpp

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Proximity/C++/ProximityDeviceEvents.xaml.cpp Source File

  • Proximity

ProximityDeviceEvents.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 // ProximityDeviceEvents.xaml.cpp
00013 // Implementation of the ProximityDeviceEvents class
00014 //
00015
00016
00017 #include "pch.h"
00018 #include "ProximityDeviceEvents.xaml.h"
00019
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Controls;
00022 using namespace Windows::UI::Xaml::Data;
00023 using namespace Windows::UI::Core;
00024 using namespace Windows::UI::ViewManagement;
00025 using namespace Windows::System;
00026 using namespace Windows::Foundation;
00027 using namespace Windows::Foundation::Collections;
00028 using namespace Windows::Networking::Proximity;
00029 using namespace Windows::Storage::Streams;
00030 using namespace Platform;
00031 using namespace ProximityCPP;
00032 using namespace Windows::UI::Xaml::Navigation;
00033
00034 ProximityDeviceEvents::ProximityDeviceEvents()
00035 {
00036     InitializeComponent();
00037     m_proximityDevice = ProximityDevice::GetDefault();
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 void ProximityDeviceEvents::OnNavigatedTo(NavigationEventArgs^ e)
00046 {
00047     // A pointer back to the main page.  This is needed if you want to call methods in ProximityDeviceEvents such
00048     // as NotifyUser()
00049     m_rootPage = MainPage::Current;
00050     if (m_proximityDevice != nullptr)
00051     {
00052         // Also register for device arrived and departed events to know when a proximate device is in range.
00053         m_arrivedToken = m_proximityDevice->DeviceArrived += ref new  DeviceArrivedEventHandler(this, &ProximityDeviceEvents::DeviceArrived, CallbackContext::Same);
00054         m_departedToken = m_proximityDevice->DeviceDeparted += ref new  DeviceDepartedEventHandler(this, &ProximityDeviceEvents::DeviceDeparted, CallbackContext::Same);
00055     }
00056     else
00057     {
00058         m_rootPage->NotifyUser("No proximity device found", NotifyType::ErrorMessage);
00059     }
00060 }
00061
00062 void ProximityDeviceEvents::OnNavigatingFrom(NavigatingCancelEventArgs^ e)
00063 {
00064     if (m_proximityDevice != nullptr)
00065     {
00066         m_proximityDevice->DeviceArrived -= m_arrivedToken;
00067         m_proximityDevice->DeviceDeparted -= m_departedToken;
00068     }
00069 }
00070 void ProximityDeviceEvents::DeviceArrived(ProximityDevice^ device)
00071 {
00072     m_rootPage->LogInfo("Proximate device arrived", ProximityDeviceEventsOutputText);
00073 }
00074
00075 void ProximityDeviceEvents::DeviceDeparted(ProximityDevice^ device)
00076 {
00077     m_rootPage->LogInfo("Proximate device departed", ProximityDeviceEventsOutputText);
00078 }
Generated on Sat Nov 23 2024 16:08:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Secondary tiles/C#,C++/common/LayoutAwarePage.cpp Source File

  • Secondary tiles
  • C#,C++
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013
00014 using namespace SecondaryTiles::Common;
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::UI::ViewManagement;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Interop;
00024
00025 /// <summary>
00026 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00027 /// </summary>
00028 LayoutAwarePage::LayoutAwarePage()
00029 {
00030     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled) return;
00031
00032     // Create an empty default view model
00033     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00034
00035     // Map application view state to visual state for this page when it is part of the visual tree
00036     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::StartLayoutUpdates);
00037     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::StopLayoutUpdates);
00038 }
00039
00040 static TypeName _thisType = { LayoutAwarePage::typeid->FullName, TypeKind::Custom };
00041 static TypeName _observableMapType = { IObservableMap<Platform::String^, Object^>::typeid->FullName, TypeKind::Metadata };
00042 static Windows::UI::Xaml::DependencyProperty^ _defaultViewModelProperty =
00043     DependencyProperty::Register("DefaultViewModel", _observableMapType, _thisType, nullptr);
00044
00045 /// <summary>
00046 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00047 /// </summary>
00048 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00049 {
00050     return _defaultViewModelProperty;
00051 }
00052
00053 /// <summary>
00054 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00055 /// used as a trivial view model.
00056 /// </summary>
00057 IObservableMap<Platform::String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00058 {
00059     return safe_cast<Windows::Foundation::Collections::IObservableMap<Platform::String^, Object^>^>(GetValue(DefaultViewModelProperty));
00060 }
00061
00062 /// <summary>
00063 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00064 /// used as a trivial view model.
00065 /// </summary>
00066 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<Platform::String^, Object^>^ value)
00067 {
00068     SetValue(DefaultViewModelProperty, value);
00069 }
00070
00071 /// <summary>
00072 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00073 /// until it reaches the top of the navigation stack.
00074 /// </summary>
00075 /// <param name="sender">Instance that triggered the event.</param>
00076 /// <param name="e">Event data describing the conditions that led to the event.</param>
00077 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00078 {
00079     // Use the navigation frame to return to the topmost page
00080     if (Frame != nullptr)
00081     {
00082         while (Frame->CanGoBack) Frame->GoBack();
00083     }
00084 }
00085
00086 /// <summary>
00087 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00088 /// to go back one step on the navigation stack.
00089 /// </summary>
00090 /// <param name="sender">Instance that triggered the event.</param>
00091 /// <param name="e">Event data describing the conditions that led to the event.</param>
00092 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00093 {
00094     // Use the navigation frame to return to the previous page
00095     if (Frame != nullptr && Frame->CanGoBack) Frame->GoBack();
00096 }
00097
00098 /// <summary>
00099 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00100 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00101 /// visual state management changes that correspond to application view state changes.
00102 /// </summary>
00103 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00104 /// corresponding to view states.</param>
00105 /// <param name="e">Event data that describes how the request was made.</param>
00106 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00107 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00108 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00109 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00110 /// events.</remarks>
00111 /// <seealso cref="DetermineVisualState"/>
00112 /// <seealso cref="InvalidateVisualState"/>
00113 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00114 {
00115     auto control = safe_cast<Control^>(sender);
00116     if (_layoutAwareControls == nullptr) {
00117         // Start listening to view state changes when there are controls interested in updates
00118         _layoutAwareControls = ref new Vector<Control^>();
00119         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00120     }
00121     _layoutAwareControls->Append(control);
00122
00123     // Set the initial visual state of the control
00124     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00125 }
00126
00127 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00128 {
00129     InvalidateVisualState();
00130 }
00131
00132 /// <summary>
00133 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00134 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00135 /// management changes that correspond to application view state changes.
00136 /// </summary>
00137 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00138 /// corresponding to view states.</param>
00139 /// <param name="e">Event data that describes how the request was made.</param>
00140 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00141 /// when layout updates are requested.</remarks>
00142 /// <seealso cref="StartLayoutUpdates"/>
00143 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00144 {
00145     auto control = safe_cast<Control^>(sender);
00146     unsigned int index;
00147     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00148     {
00149         _layoutAwareControls->RemoveAt(index);
00150         if (_layoutAwareControls->Size == 0)
00151         {
00152             // Stop listening to view state changes when no controls are interested in updates
00153             Window::Current->SizeChanged -= _windowSizeEventToken;
00154             _layoutAwareControls = nullptr;
00155         }
00156     }
00157 }
00158
00159 /// <summary>
00160 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00161 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00162 /// override this method to control the mapping scheme used.
00163 /// </summary>
00164 /// <param name="viewState">View state for which a visual state is desired.</param>
00165 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00166 /// <seealso cref="InvalidateVisualState"/>
00167 Platform::String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00168 {
00169     switch (viewState)
00170     {
00171     case ApplicationViewState::Filled: return "Filled";
00172     case ApplicationViewState::Snapped: return "Snapped";
00173     case ApplicationViewState::FullScreenPortrait: return "FullScreenPortrait";
00174     default: case ApplicationViewState::FullScreenLandscape: return "FullScreenLandscape";
00175     }
00176 }
00177
00178 /// <summary>
00179 /// Updates all controls that are listening for visual state changes with the correct visual
00180 /// state.
00181 /// </summary>
00182 /// <remarks>
00183 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00184 /// signal that a different value may be returned even though the view state has not changed.
00185 /// </remarks>
00186 void LayoutAwarePage::InvalidateVisualState()
00187 {
00188     if (_layoutAwareControls != nullptr)
00189     {
00190         String^ visualState = DetermineVisualState(ApplicationView::Value);
00191         auto controlIterator = _layoutAwareControls->First();
00192         while (controlIterator->HasCurrent)
00193         {
00194             auto control = controlIterator->Current;
00195             VisualStateManager::GoToState(control, visualState, false);
00196             controlIterator->MoveNext();
00197         }
00198     }
00199 }
Generated on Sat Nov 23 2024 16:07:32 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Context menu/C++/Scenario2.xaml.h Source File

  • Context menu

Scenario2.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.xaml.h
00013 // Declaration of the Scenario2 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario2.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace ContextMenu
00025     {
00026         /// <summary>
00027         /// An empty page that can be used on its own or navigated to within a Frame.
00028         /// </summary>
00029         public ref class Scenario2 sealed
00030         {
00031         public:
00032             Scenario2();
00033
00034         private:
00035             MainPage^ rootPage;
00036
00037             Windows::Foundation::Rect Scenario2::GetTextboxSelectionRect(Windows::UI::Xaml::Controls::TextBox^ textbox);
00038             void ReadOnlyTextBox_ContextMenuOpening(Platform::Object^ sender, Windows::UI::Xaml::Controls::ContextMenuEventArgs^ e);
00039         };
00040     }
00041 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite hit testing/C++/DWriteHitTesting.cpp Source File

  • DirectWrite hit testing

DWriteHitTesting.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 "DWriteHitTesting.h"
00010
00011 using namespace Microsoft::WRL;
00012 using namespace Platform;
00013 using namespace Windows::ApplicationModel;
00014 using namespace Windows::ApplicationModel::Core;
00015 using namespace Windows::ApplicationModel::Activation;
00016 using namespace Windows::UI::Core;
00017 using namespace Windows::System;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::Graphics::Display;
00021 using namespace Windows::Storage;
00022
00023 DWriteHitTesting::DWriteHitTesting()
00024 {
00025 }
00026
00027 void DWriteHitTesting::CreateDeviceIndependentResources()
00028 {
00029     DirectXBase::CreateDeviceIndependentResources();
00030
00031     m_text = "Touch Me To Change My Underline!";
00032
00033     // Create a DirectWrite text format object.
00034     DX::ThrowIfFailed(
00035         m_dwriteFactory->CreateTextFormat(
00036             L"Segoe UI",
00037             nullptr,
00038             DWRITE_FONT_WEIGHT_LIGHT,
00039             DWRITE_FONT_STYLE_NORMAL,
00040             DWRITE_FONT_STRETCH_NORMAL,
00041             64.0f,
00042             L"en-US", // locale
00043             &m_textFormat
00044             )
00045         );
00046
00047     // Center the text horizontally.
00048     DX::ThrowIfFailed(
00049         m_textFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER)
00050         );
00051
00052     // Center the text vertically.
00053     DX::ThrowIfFailed(
00054         m_textFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER)
00055         );
00056
00057     // Boolean array to keep track of which characters are underlined
00058     m_underlineArray = ref new Platform::Array<bool>(m_text->Length());
00059
00060     // Initialize the array to all false in order to represent the initial un-underlined text
00061     for (unsigned int i = 0; i < m_text->Length(); i++)
00062     {
00063         m_underlineArray[i] = false;
00064     }
00065 }
00066
00067 void DWriteHitTesting::CreateDeviceResources()
00068 {
00069     DirectXBase::CreateDeviceResources();
00070
00071     m_sampleOverlay = ref new SampleOverlay();
00072
00073     m_sampleOverlay->Initialize(
00074         m_d2dDevice.Get(),
00075         m_d2dContext.Get(),
00076         m_wicFactory.Get(),
00077         m_dwriteFactory.Get(),
00078         "DirectWrite hit testing sample"
00079         );
00080
00081     DX::ThrowIfFailed(
00082         m_d2dContext->CreateSolidColorBrush(
00083             D2D1::ColorF(D2D1::ColorF::Black),
00084             &m_blackBrush
00085             )
00086         );
00087 }
00088
00089 void DWriteHitTesting::CreateWindowSizeDependentResources()
00090 {
00091     DirectXBase::CreateWindowSizeDependentResources();
00092
00093     D2D1_SIZE_F size = m_d2dContext->GetSize();
00094
00095     // Create a DirectWrite Text Layout object
00096     DX::ThrowIfFailed(
00097         m_dwriteFactory->CreateTextLayout(
00098             m_text->Data(),                     // Text to be displayed
00099             m_text->Length(),                   // Length of the text
00100             m_textFormat.Get(),                 // DirectWrite Text Format object
00101             size.width,                         // Width of the Text Layout
00102             size.height,                        // Height of the Text Layout
00103             &m_textLayout
00104             )
00105         );
00106
00107     SetUnderlineOnRedraw();
00108 }
00109
00110 void DWriteHitTesting::Render()
00111 {
00112     m_d2dContext->BeginDraw();
00113
00114     m_d2dContext->Clear(D2D1::ColorF(D2D1::ColorF::CornflowerBlue));
00115     m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00116
00117     m_d2dContext->DrawTextLayout(
00118         D2D1::Point2F(0.0f, 0.0f),
00119         m_textLayout.Get(),
00120         m_blackBrush.Get()
00121         );
00122
00123     // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00124     // is lost. It will be handled during the next call to Present.
00125     HRESULT hr = m_d2dContext->EndDraw();
00126     if (hr != D2DERR_RECREATE_TARGET)
00127     {
00128         DX::ThrowIfFailed(hr);
00129     }
00130
00131     m_sampleOverlay->Render();
00132 }
00133
00134 void DWriteHitTesting::Initialize(
00135     _In_ CoreApplicationView^ applicationView
00136     )
00137 {
00138     applicationView->Activated +=
00139         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &DWriteHitTesting::OnActivated);
00140
00141     CoreApplication::Suspending +=
00142         ref new EventHandler<SuspendingEventArgs^>(this, &DWriteHitTesting::OnSuspending);
00143
00144     CoreApplication::Resuming +=
00145         ref new EventHandler<Platform::Object^>(this, &DWriteHitTesting::OnResuming);
00146 }
00147
00148 void DWriteHitTesting::SetWindow(
00149     _In_ CoreWindow^ window
00150     )
00151 {
00152     window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
00153
00154     window->SizeChanged +=
00155         ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &DWriteHitTesting::OnWindowSizeChanged);
00156
00157     window->PointerPressed +=
00158         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &DWriteHitTesting::OnPointerPressed);
00159
00160     DisplayProperties::LogicalDpiChanged +=
00161         ref new DisplayPropertiesEventHandler(this, &DWriteHitTesting::OnLogicalDpiChanged);
00162
00163     DisplayProperties::DisplayContentsInvalidated +=
00164         ref new DisplayPropertiesEventHandler(this, &DWriteHitTesting::OnDisplayContentsInvalidated);
00165
00166     DirectXBase::Initialize(window, DisplayProperties::LogicalDpi);
00167 }
00168
00169 void DWriteHitTesting::Load(
00170     _In_ Platform::String^ entryPoint
00171     )
00172 {
00173     // Retrieve any stored variables from the LocalSettings collection.
00174     IPropertySet^ settingsValues = ApplicationData::Current->LocalSettings->Values;
00175
00176     if (settingsValues->HasKey("m_underlineArray"))
00177     {
00178         safe_cast<IPropertyValue^>(settingsValues->Lookup("m_underlineArray"))->GetBooleanArray(&m_underlineArray);
00179         SetUnderlineOnRedraw();
00180     }
00181 }
00182
00183 void DWriteHitTesting::Run()
00184 {
00185     Render();
00186     Present();
00187
00188     m_window->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessUntilQuit);
00189 }
00190
00191 void DWriteHitTesting::Uninitialize()
00192 {
00193 }
00194
00195 void DWriteHitTesting::OnWindowSizeChanged(
00196     _In_ CoreWindow^ sender,
00197     _In_ WindowSizeChangedEventArgs^ args
00198     )
00199 {
00200     UpdateForWindowSizeChange();
00201     m_sampleOverlay->UpdateForWindowSizeChange();
00202     Render();
00203     Present();
00204 }
00205
00206 void DWriteHitTesting::OnPointerPressed(
00207     _In_ CoreWindow^ sender,
00208     _In_ PointerEventArgs^ args
00209     )
00210
00211 {
00212     DWRITE_HIT_TEST_METRICS hitTestMetrics;
00213     BOOL isTrailingHit;
00214     BOOL isInside;
00215
00216     Windows::UI::Input::PointerPoint^ point = args->CurrentPoint;
00217
00218     DX::ThrowIfFailed(
00219         m_textLayout->HitTestPoint(
00220             point->Position.X,
00221             point->Position.Y,
00222             &isTrailingHit,
00223             &isInside,
00224             &hitTestMetrics
00225             )
00226         );
00227
00228     if (isInside)
00229     {
00230         BOOL underline;
00231
00232         DX::ThrowIfFailed(
00233             m_textLayout->GetUnderline(hitTestMetrics.textPosition, &underline)
00234             );
00235
00236         DWRITE_TEXT_RANGE textRange = {hitTestMetrics.textPosition, 1};
00237
00238         DX::ThrowIfFailed(
00239             m_textLayout->SetUnderline(!underline, textRange)
00240             );
00241
00242         m_underlineArray[hitTestMetrics.textPosition] = !underline;
00243     }
00244
00245     Render();
00246     Present();
00247 }
00248
00249 // This function is used to keep track of which elements are underlined - in order to redraw
00250 // the underline if the text layout needs to be recreated
00251
00252 void DWriteHitTesting::SetUnderlineOnRedraw()
00253 {
00254     for (unsigned int i = 0; i < m_text->Length(); i++)
00255     {
00256         DWRITE_TEXT_RANGE textRange = {i, 1};
00257         DX::ThrowIfFailed(
00258             m_textLayout->SetUnderline(m_underlineArray[i], textRange)
00259             );
00260     }
00261 }
00262
00263 void DWriteHitTesting::OnLogicalDpiChanged(
00264     _In_ Platform::Object^ sender
00265     )
00266 {
00267     SetDpi(DisplayProperties::LogicalDpi);
00268     Render();
00269     Present();
00270 }
00271
00272 void DWriteHitTesting::OnDisplayContentsInvalidated(
00273     _In_ Platform::Object^ sender
00274     )
00275 {
00276     // Ensure the D3D Device is available for rendering.
00277     ValidateDevice();
00278
00279     Render();
00280     Present();
00281 }
00282
00283 void DWriteHitTesting::OnActivated(
00284     _In_ CoreApplicationView^ applicationView,
00285     _In_ IActivatedEventArgs^ args
00286     )
00287 {
00288     m_window->Activate();
00289 }
00290
00291 void DWriteHitTesting::OnSuspending(
00292     _In_ Platform::Object^ sender,
00293     _In_ SuspendingEventArgs^ args
00294     )
00295 {
00296     IPropertySet^ settingsValues = ApplicationData::Current->LocalSettings->Values;
00297
00298     if (settingsValues->HasKey("m_underlineArray"))
00299     {
00300         settingsValues->Remove("m_underlineArray");
00301     }
00302     settingsValues->Insert("m_underlineArray", PropertyValue::CreateBooleanArray(m_underlineArray));
00303 }
00304
00305 void DWriteHitTesting::OnResuming(
00306     _In_ Platform::Object^ sender,
00307     _In_ Platform::Object^ args
00308     )
00309 {
00310 }
00311
00312 IFrameworkView^ DirectXAppSource::CreateView()
00313 {
00314     return ref new DWriteHitTesting();
00315 }
00316
00317 [Platform::MTAThread]
00318 int main(Platform::Array<Platform::String^>^)
00319 {
00320     auto directXAppSource = ref new DirectXAppSource();
00321     CoreApplication::Run(directXAppSource);
00322     return 0;
00323 }
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/WorldMesh.cpp Source File

  • XAML DirectX 3D shooting game

WorldMesh.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 "WorldMesh.h"
00010 #include "DirectXSample.h"
00011 #include "ConstantBuffers.h"
00012
00013 using namespace Microsoft::WRL;
00014 using namespace DirectX;
00015
00016 WorldCeilingMesh::WorldCeilingMesh(_In_ ID3D11Device *device)
00017 {
00018     PNTVertex cellVertices[] =
00019     {
00020         // CEILING
00021         {XMFLOAT3(-4.0f,  3.0f, -6.0f), XMFLOAT3(0.0f, -1.0f, 0.0f), XMFLOAT2(-0.15f, 0.0f)},
00022         {XMFLOAT3( 4.0f,  3.0f, -6.0f), XMFLOAT3(0.0f, -1.0f, 0.0f), XMFLOAT2( 1.25f, 0.0f)},
00023         {XMFLOAT3(-4.0f,  3.0f,  6.0f), XMFLOAT3(0.0f, -1.0f, 0.0f), XMFLOAT2(-0.15f, 2.1f)},
00024         {XMFLOAT3( 4.0f,  3.0f,  6.0f), XMFLOAT3(0.0f, -1.0f, 0.0f), XMFLOAT2( 1.25f, 2.1f)},
00025     };
00026
00027     WORD cellIndices[] = {
00028         0, 1, 2,
00029         1, 3, 2,
00030     };
00031
00032     m_vertexCount = 4;
00033     m_indexCount = 6;
00034
00035     D3D11_BUFFER_DESC bd = {0};
00036     D3D11_SUBRESOURCE_DATA initData = {0};
00037
00038     bd.Usage = D3D11_USAGE_DEFAULT;
00039     bd.ByteWidth = sizeof(PNTVertex) * m_vertexCount;
00040     bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
00041     bd.CPUAccessFlags = 0;
00042     initData.pSysMem = cellVertices;
00043     DX::ThrowIfFailed(
00044         device->CreateBuffer(&bd, &initData, &m_vertexBuffer)
00045         );
00046
00047     bd.Usage = D3D11_USAGE_DEFAULT;
00048     bd.ByteWidth = sizeof(WORD) * m_indexCount;
00049     bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
00050     bd.CPUAccessFlags = 0;
00051     initData.pSysMem = cellIndices;
00052     DX::ThrowIfFailed(
00053         device->CreateBuffer(&bd, &initData, &m_indexBuffer)
00054         );
00055 }
00056
00057 WorldFloorMesh::WorldFloorMesh(_In_ ID3D11Device *device)
00058 {
00059     PNTVertex cellVertices[] =
00060     {
00061         // FLOOR
00062         {XMFLOAT3(-4.0f, -3.0f,  6.0f), XMFLOAT3(0.0f, 1.0f, 0.0f), XMFLOAT2(0.0f, 0.0f)},
00063         {XMFLOAT3( 4.0f, -3.0f,  6.0f), XMFLOAT3(0.0f, 1.0f, 0.0f), XMFLOAT2(1.0f, 0.0f)},
00064         {XMFLOAT3(-4.0f, -3.0f, -6.0f), XMFLOAT3(0.0f, 1.0f, 0.0f), XMFLOAT2(0.0f, 1.5f)},
00065         {XMFLOAT3( 4.0f, -3.0f, -6.0f), XMFLOAT3(0.0f, 1.0f, 0.0f), XMFLOAT2(1.0f, 1.5f)},
00066     };
00067
00068     WORD cellIndices[] = {
00069         0, 1, 2,
00070         1, 3, 2,
00071     };
00072
00073     m_vertexCount = 4;
00074     m_indexCount = 6;
00075
00076     D3D11_BUFFER_DESC bd = {0};
00077     D3D11_SUBRESOURCE_DATA initData = {0};
00078
00079     bd.Usage = D3D11_USAGE_DEFAULT;
00080     bd.ByteWidth = sizeof(PNTVertex) * m_vertexCount;
00081     bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
00082     bd.CPUAccessFlags = 0;
00083     initData.pSysMem = cellVertices;
00084     DX::ThrowIfFailed(
00085         device->CreateBuffer(&bd, &initData, &m_vertexBuffer)
00086         );
00087
00088     bd.Usage = D3D11_USAGE_DEFAULT;
00089     bd.ByteWidth = sizeof(WORD) * m_indexCount;
00090     bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
00091     bd.CPUAccessFlags = 0;
00092     initData.pSysMem = cellIndices;
00093     DX::ThrowIfFailed(
00094         device->CreateBuffer(&bd, &initData, &m_indexBuffer)
00095         );
00096 }
00097
00098 WorldWallsMesh::WorldWallsMesh(_In_ ID3D11Device *device)
00099 {
00100     PNTVertex cellVertices[] =
00101     {
00102         // WALL
00103         {XMFLOAT3(-4.0f,  3.0f,  6.0f), XMFLOAT3(0.0f, 0.0f, -1.0f), XMFLOAT2(0.0f, 0.0f)},
00104         {XMFLOAT3( 4.0f,  3.0f,  6.0f), XMFLOAT3(0.0f, 0.0f, -1.0f), XMFLOAT2(2.0f, 0.0f)},
00105         {XMFLOAT3(-4.0f, -3.0f,  6.0f), XMFLOAT3(0.0f, 0.0f, -1.0f), XMFLOAT2(0.0f, 1.5f)},
00106         {XMFLOAT3( 4.0f, -3.0f,  6.0f), XMFLOAT3(0.0f, 0.0f, -1.0f), XMFLOAT2(2.0f, 1.5f)},
00107         // WALL
00108         {XMFLOAT3(4.0f,  3.0f,  6.0f), XMFLOAT3(-1.0f, 0.0f, 0.0f), XMFLOAT2(0.0f, 0.0f)},
00109         {XMFLOAT3(4.0f,  3.0f, -6.0f), XMFLOAT3(-1.0f, 0.0f, 0.0f), XMFLOAT2(3.0f, 0.0f)},
00110         {XMFLOAT3(4.0f, -3.0f,  6.0f), XMFLOAT3(-1.0f, 0.0f, 0.0f), XMFLOAT2(0.0f, 1.5f)},
00111         {XMFLOAT3(4.0f, -3.0f, -6.0f), XMFLOAT3(-1.0f, 0.0f, 0.0f), XMFLOAT2(3.0f, 1.5f)},
00112         // WALL
00113         {XMFLOAT3( 4.0f,  3.0f, -6.0f), XMFLOAT3(0.0f, 0.0f, 1.0f), XMFLOAT2(0.0f, 0.0f)},
00114         {XMFLOAT3(-4.0f,  3.0f, -6.0f), XMFLOAT3(0.0f, 0.0f, 1.0f), XMFLOAT2(2.0f, 0.0f)},
00115         {XMFLOAT3( 4.0f, -3.0f, -6.0f), XMFLOAT3(0.0f, 0.0f, 1.0f), XMFLOAT2(0.0f, 1.5f)},
00116         {XMFLOAT3(-4.0f, -3.0f, -6.0f), XMFLOAT3(0.0f, 0.0f, 1.0f), XMFLOAT2(2.0f, 1.5f)},
00117         // WALL
00118         {XMFLOAT3(-4.0f,  3.0f, -6.0f), XMFLOAT3(1.0f, 0.0f, 0.0f), XMFLOAT2(0.0f, 0.0f)},
00119         {XMFLOAT3(-4.0f,  3.0f,  6.0f), XMFLOAT3(1.0f, 0.0f, 0.0f), XMFLOAT2(3.0f, 0.0f)},
00120         {XMFLOAT3(-4.0f, -3.0f, -6.0f), XMFLOAT3(1.0f, 0.0f, 0.0f), XMFLOAT2(0.0f, 1.5f)},
00121         {XMFLOAT3(-4.0f, -3.0f,  6.0f), XMFLOAT3(1.0f, 0.0f, 0.0f), XMFLOAT2(3.0f, 1.5f)},
00122     };
00123
00124     WORD cellIndices[] = {
00125          0,  1,  2,
00126          1,  3,  2,
00127          4,  5,  6,
00128          5,  7,  6,
00129          8,  9, 10,
00130          9, 11, 10,
00131         12, 13, 14,
00132         13, 15, 14,
00133     };
00134
00135     m_vertexCount = 16;
00136     m_indexCount = 24;
00137
00138     D3D11_BUFFER_DESC bd = {0};
00139     D3D11_SUBRESOURCE_DATA initData = {0};
00140
00141     bd.Usage = D3D11_USAGE_DEFAULT;
00142     bd.ByteWidth = sizeof(PNTVertex) * m_vertexCount;
00143     bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
00144     bd.CPUAccessFlags = 0;
00145     initData.pSysMem = cellVertices;
00146     DX::ThrowIfFailed(
00147         device->CreateBuffer(&bd, &initData, &m_vertexBuffer)
00148         );
00149
00150     bd.Usage = D3D11_USAGE_DEFAULT;
00151     bd.ByteWidth = sizeof(WORD) * m_indexCount;
00152     bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
00153     bd.CPUAccessFlags = 0;
00154     initData.pSysMem = cellIndices;
00155     DX::ThrowIfFailed(
00156         device->CreateBuffer(&bd, &initData, &m_indexBuffer)
00157         );
00158 }
00159
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C#,C++/MediaExtensions/Invert/VideoBufferLock.h Source File

  • Media extensions
  • C#,C++
  • MediaExtensions
  • Invert

VideoBufferLock.h

Go to the documentation of this file.
00001 #pragma once
00002 #include <mfapi.h>
00003 #include <mftransform.h>
00004 #include <mfidl.h>
00005 #include <assert.h>
00006 #include <wrl\client.h>
00007
00008 using namespace Microsoft::WRL;
00009
00010 class VideoBufferLock
00011 {
00012 public:
00013     VideoBufferLock() : _bLockedBuffer(FALSE), _bLocked2D(FALSE), _bLocked2D2(FALSE), _pData(NULL), _lPitch(0) {}
00014
00015     HRESULT Lock(__in IMFMediaBuffer *pBuffer, __in MF2DBuffer_LockFlags flags, __in UINT uiMinSize, __in LONG lDefaultStride)
00016     {
00017         HRESULT hr = S_OK;
00018         DWORD dwBufferCount = 0;
00019         DWORD maxSize = 0;
00020         BYTE *pbBufferStart = NULL;
00021         DWORD dwBufferLength = 0;
00022
00023         assert(pBuffer);
00024
00025         // if the lock is already locked, assert
00026         assert(!(_bLocked2D || _bLocked2D2 || _bLockedBuffer));
00027         _pInputBuffer = pBuffer;
00028
00029         hr = _pInputBuffer.As(&_pInputBuffer2D2);
00030         if (SUCCEEDED(hr))
00031         {
00032             hr = _pInputBuffer2D2->Lock2DSize( flags, &_pData, &_lPitch, &pbBufferStart, &dwBufferLength );
00033             if (SUCCEEDED(hr))
00034             {
00035                 if (dwBufferLength < uiMinSize || abs(_lPitch) < abs(lDefaultStride))
00036                 {
00037                     _pInputBuffer2D2->Unlock2D();
00038                     hr = MF_E_BUFFERTOOSMALL;
00039                     goto done;
00040                 }
00041                 _bLocked2D2 = TRUE;
00042             }
00043         }
00044
00045         if(!_bLocked2D2)
00046         {
00047             hr = _pInputBuffer.As(&_pInputBuffer2D);
00048             if (SUCCEEDED(hr))
00049             {
00050                 hr = _pInputBuffer2D->Lock2D(&_pData, &_lPitch);
00051                 if (SUCCEEDED(hr))
00052                 {
00053                     if (abs(_lPitch) < abs(lDefaultStride))
00054                     {
00055                         _pInputBuffer2D->Unlock2D();
00056                         hr = MF_E_BUFFERTOOSMALL;
00057                         goto done;
00058                     }
00059                     _bLocked2D = TRUE;
00060                 }
00061             }
00062         }
00063
00064         if (!(_bLocked2D2 || _bLocked2D))
00065         {
00066             hr = _pInputBuffer->Lock(&_pData, &maxSize, NULL);
00067
00068             if (SUCCEEDED(hr))
00069             {
00070                 if (maxSize < uiMinSize)
00071                 {
00072                     _pInputBuffer->Unlock();
00073                     hr = MF_E_BUFFERTOOSMALL;
00074                     goto done;
00075                 }
00076
00077                 _bLockedBuffer = TRUE;
00078                 _lPitch = lDefaultStride;
00079             }
00080         }
00081
00082     done:
00083         return hr;
00084     }
00085
00086     ~VideoBufferLock() { Unlock(); }
00087
00088     HRESULT Unlock()
00089     {
00090         HRESULT hr = S_OK;
00091
00092         if(_bLockedBuffer && _pInputBuffer)
00093         {
00094             hr = _pInputBuffer->Unlock();
00095             _bLockedBuffer = FALSE;
00096             _pInputBuffer = nullptr;
00097         }
00098         if(_bLocked2D && _pInputBuffer2D)
00099         {
00100             hr = _pInputBuffer2D->Unlock2D();
00101             _bLocked2D = FALSE;
00102             _pInputBuffer2D = nullptr;
00103         }
00104         if(_bLocked2D2 && _pInputBuffer2D2)
00105         {
00106             hr = _pInputBuffer2D2->Unlock2D();
00107             _bLocked2D2 = FALSE;
00108             _pInputBuffer2D2 = nullptr;
00109         }
00110         return hr;
00111     }
00112
00113     BYTE *GetData(){ return _pData; }
00114     LONG GetStride(){ return _lPitch; }
00115
00116 private:
00117     ComPtr<IMFMediaBuffer> _pInputBuffer;
00118     BOOL _bLockedBuffer;
00119
00120     ComPtr<IMF2DBuffer> _pInputBuffer2D;
00121     BOOL _bLocked2D;
00122
00123     ComPtr<IMF2DBuffer2> _pInputBuffer2D2;
00124     BOOL _bLocked2D2;
00125
00126     BYTE *_pData;
00127     LONG _lPitch;
00128 };
Generated on Sat Nov 23 2024 16:08:21 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::PortableDeviceCPP::sealed Member List

This is the complete list of members for SDKSample::PortableDeviceCPP::sealed, including all inherited members.
_deviceEventCookie | SDKSample::PortableDeviceCPP::sealed | [private]
_deviceEventSource | SDKSample::PortableDeviceCPP::sealed | [private]
_deviceInfoCollection | SDKSample::PortableDeviceCPP::sealed | [private]
CreateAndThenDeleteFolderOnDeviceAsync() | SDKSample::PortableDeviceCPP::sealed | [private]
DeviceList_Tapped(Platform::Object^sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^e) | SDKSample::PortableDeviceCPP::sealed | [private]
DeviceList_Tapped(Platform::Object^sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^e) | SDKSample::PortableDeviceCPP::sealed | [private]
DeviceList_Tapped(Platform::Object^sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^e) | SDKSample::PortableDeviceCPP::sealed | [private]
DeviceList_Tapped(Platform::Object^sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^e) | SDKSample::PortableDeviceCPP::sealed | [private]
DeviceList_Tapped(Platform::Object^sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^e) | SDKSample::PortableDeviceCPP::sealed | [private]
DeviceList_Tapped(Platform::Object^sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^e) | SDKSample::PortableDeviceCPP::sealed | [private]
DisplayDeviceProperties(Windows::Devices::Enumeration::DeviceInformation^deviceInfoElement) | SDKSample::PortableDeviceCPP::sealed | [private]
DisplayDeviceStatusAsync(Windows::Devices::Enumeration::DeviceInformation^deviceInfoElement) | SDKSample::PortableDeviceCPP::sealed | [private]
DisplayDeviceStatusServiceProperties(_In_ IPortableDeviceService *service) | SDKSample::PortableDeviceCPP::sealed | [private]
EnumerateObjects(Windows::Devices::Enumeration::DeviceInformation^deviceInfoElement) | SDKSample::PortableDeviceCPP::sealed | [private]
FillInPropertiesForFolder(Platform::String^parentId) | SDKSample::PortableDeviceCPP::sealed | [private]
FillInPropertiesForImage(Windows::Storage::StorageFile^file, Platform::String^parentId, ULONGLONG size) | SDKSample::PortableDeviceCPP::sealed | [private]
FindAndTransferFirstImageFileFromDevice(_In_ IPortableDevice *device) | SDKSample::PortableDeviceCPP::sealed | [private]
GetContentFromDeviceAsync(Windows::Devices::Enumeration::DeviceInformation^deviceInfoElement) | SDKSample::PortableDeviceCPP::sealed | [private]
IsRegisteredForDeviceEvents() | SDKSample::PortableDeviceCPP::sealed | [inline, private]
OnDeviceEventReceived(Platform::String^senderDeviceId, Platform::String^eventData) | SDKSample::PortableDeviceCPP::sealed | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::PortableDeviceCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::PortableDeviceCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::PortableDeviceCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::PortableDeviceCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::PortableDeviceCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::PortableDeviceCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::PortableDeviceCPP::sealed | [protected, virtual]
RegisterForDeviceEvents(Windows::Devices::Enumeration::DeviceInformation^deviceInfo) | SDKSample::PortableDeviceCPP::sealed | [private]
rootPage | SDKSample::PortableDeviceCPP::sealed | [private]
Run_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::PortableDeviceCPP::sealed | [private]
Run_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::PortableDeviceCPP::sealed | [private]
Run_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::PortableDeviceCPP::sealed | [private]
Run_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::PortableDeviceCPP::sealed | [private]
Run_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::PortableDeviceCPP::sealed | [private]
Run_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::PortableDeviceCPP::sealed | [private]
S1_DeviceProperties() | SDKSample::PortableDeviceCPP::sealed |
S2_Enumeration() | SDKSample::PortableDeviceCPP::sealed |
S3_SendToDevice() | SDKSample::PortableDeviceCPP::sealed |
S4_GetFromDevice() | SDKSample::PortableDeviceCPP::sealed |
S5_Events() | SDKSample::PortableDeviceCPP::sealed |
S6_DeviceStatus() | SDKSample::PortableDeviceCPP::sealed |
SendContentToDeviceAsync(Windows::Devices::Enumeration::DeviceInformation^deviceInfoElement) | SDKSample::PortableDeviceCPP::sealed | [private]
ShowDeviceSelectorAsync() | SDKSample::PortableDeviceCPP::sealed | [private]
ShowDeviceSelectorAsync() | SDKSample::PortableDeviceCPP::sealed | [private]
ShowDeviceSelectorAsync() | SDKSample::PortableDeviceCPP::sealed | [private]
ShowDeviceSelectorAsync() | SDKSample::PortableDeviceCPP::sealed | [private]
ShowDeviceSelectorAsync() | SDKSample::PortableDeviceCPP::sealed | [private]
ShowDeviceSelectorAsync() | SDKSample::PortableDeviceCPP::sealed | [private]
TransferFileFromDeviceToAppLocalFolderAsync(_In_ IPortableDevice *device, Platform::String^sourceObjectId, Platform::String^desiredFilename) | SDKSample::PortableDeviceCPP::sealed | [private]
TransferFileToDeviceAsync(Windows::Storage::StorageFile^file, _In_ IPortableDevice *device) | SDKSample::PortableDeviceCPP::sealed | [private]
Trigger_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::PortableDeviceCPP::sealed | [private]
UnregisterForDeviceEvents() | SDKSample::PortableDeviceCPP::sealed | [private]
Generated on Sat Nov 23 2024 16:09:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX marble maze game/C++/Physics.h Source File

  • DirectX marble maze game

Physics.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 DISABLE_RAYCAST_REVERB
00011
00012 const float Gravity = 981.0f;                               // Strength of gravity (x100 for this simulation scale)
00013 const float WallFriction = 0.05f;                           // Friction coefficient to apply to the walls.
00014 const float MaxVelocity = 250.0f;                           // Upper bounds on marble velocity
00015 const float MinVelocity = 0.1f;                             // Only used if you #define ENABLE_VELOCITY_CLAMP_TO_ZERO
00016 const float MinAudibleCollisionSpeed = 10.0f;               // Minimum velocity a collision must have before reporting.
00017 const float WallRestitutionCoefficient = 0.5f;              // How elastic the walls/floor are, from 0.0f to 1.0f
00018 const float Damping = 1.0f;                                 // Only used if you #define ENABLE_VELOCITY_DAMPING
00019 const float MaxPhysicsTimestep = 1.0f / 8.0f;               // Maximum time delta per physics update
00020 const float PhysicsTimestep = 1.0f / 60.0f;                 // Time for single physics iteration
00021
00022
00023 // Contains information regarding any contacts that occurred during the physics simulation. Used for audio feedback.
00024 struct CollisionInfo
00025 {
00026     BOOL        isRollingOnFloor;       // TRUE if the ball is currently rolling along the floor.
00027     BOOL        elasticCollision;       // TRUE if an elastic collision occurred (check maxCollisionSpeed for intensity)
00028     float       maxRollingSpeed;        // The absolute speed the ball was rolling along the surface
00029     float       maxCollisionSpeed;      // The strength of the collision
00030 };
00031
00032 // Performs simple rigid-body collision of the ball against the mesh.
00033 class Physics
00034 {
00035     Collision*  m_collision;
00036     XMFLOAT3    m_previousPosition;
00037     XMFLOAT3    m_position;
00038     XMFLOAT3    m_velocity;
00039     XMFLOAT3    m_velDueToAccel;
00040     XMFLOAT3    m_acceleration;
00041     XMFLOAT3    m_gravity;
00042     float       m_radius;
00043     XMFLOAT3    m_maxRollingSpeed;
00044     XMFLOAT3    m_maxCollisionSpeed;
00045     float       m_currentRoomSize;
00046     float       m_wallDistances[8];
00047     float       m_accumulatedTime;
00048
00049 public:
00050     Physics();
00051
00052     // Quick & dirty reset-teleport to a specific location in the mesh.
00053     void DebugReset()
00054     {
00055         ZeroMemory(&m_velocity, sizeof(XMFLOAT3));
00056         ZeroMemory(&m_velDueToAccel, sizeof(XMFLOAT3));
00057         ZeroMemory(&m_acceleration, sizeof(XMFLOAT3));
00058
00059         SetPosition(XMFLOAT3(286.39178f, -191.74507f, -42.355251f));
00060     }
00061
00062     // Calculates collision data for use by the audio sim (ricochet sounds, rolling along ground sounds)
00063     CollisionInfo GetCollisionInfo() const
00064     {
00065         CollisionInfo ci;
00066         float maxRoll = m_maxRollingSpeed.x;
00067         float maxColl = m_maxCollisionSpeed.x;
00068         ci.maxRollingSpeed = maxRoll;
00069         ci.maxCollisionSpeed = maxColl;
00070         ci.isRollingOnFloor = maxRoll > MinVelocity;
00071         ci.elasticCollision = maxColl > MinAudibleCollisionSpeed;
00072         return ci;
00073     }
00074
00075     // Gets the current instance of the collision handling object associated with the physics simulator.
00076     Collision* GetCollisionEngine()
00077     {
00078         return m_collision;
00079     }
00080
00081     // Gets the size of the room from the current position.
00082     float GetRoomSize()
00083     {
00084         return m_currentRoomSize;
00085     }
00086
00087     // Gets the dimensions of the room (N, S, E, W, NE, NW, SE, SW) from the current position.
00088     int GetRoomDimensions(float *wallDistances, int size)
00089     {
00090         int returnedCount = min(ARRAYSIZE(m_wallDistances), size);
00091         memcpy(wallDistances, m_wallDistances, returnedCount*sizeof(float));
00092         return returnedCount;
00093     }
00094
00095     // Sets the collision engine instance.
00096     void SetCollision(Collision *collision)
00097     {
00098         m_collision = collision;
00099     }
00100
00101     // Sets the radius of the marble.
00102     void SetRadius(float radius)
00103     {
00104         m_radius = radius;
00105     }
00106
00107     // Gets the radius of the marble.
00108     float GetRadius() const
00109     {
00110         return m_radius;
00111     }
00112
00113     // Sets the unit normal associated with gravity, in mesh-local space.
00114     void SetGravity(const XMFLOAT3& gravityUnitNormal)
00115     {
00116         const XMVECTOR gravityMagnitude = XMVectorReplicate(Gravity);
00117         XMStoreFloat3(&m_gravity, XMLoadFloat3(&gravityUnitNormal) * gravityMagnitude);
00118     }
00119
00120     // Sets the current position of the marble.
00121     void SetPosition(const XMFLOAT3& position)
00122     {
00123         m_position = position;
00124         m_previousPosition = position;
00125     }
00126
00127     // Gets the current position of the marble.
00128     const XMFLOAT3& GetPosition() const
00129     {
00130         return m_position;
00131     }
00132
00133     // Gets the previous position (from last frame) for the marble.
00134     const XMFLOAT3& GetPreviousPosition()
00135     {
00136         return m_previousPosition;
00137     }
00138
00139     // Sets the current velocity of the marble.
00140     void SetVelocity(const XMFLOAT3& velocity)
00141     {
00142         m_velocity = velocity;
00143         m_velDueToAccel = XMFLOAT3(0.0f, 0.0f, 0.0f);
00144     }
00145
00146     // Gets the current velocity of the marble.
00147     const XMFLOAT3& GetVelocity() const
00148     {
00149         return m_velocity;
00150     }
00151
00152     // Gets the current acceleration operating on the marble (including resultant forces)
00153     const XMFLOAT3& GetAcceleration() const
00154     {
00155         return m_acceleration;
00156     }
00157
00158     // Returns TRUE if the marble is moving at all. You may want to consider using GetCollisionInfo instead, as
00159     // that will tell you if it's rolling on or colliding with a surface.
00160     BOOL IsMoving() const
00161     {
00162         return !XMVector3InBounds(XMLoadFloat3(&m_velocity), XMVectorReplicate(FLT_EPSILON));
00163     }
00164
00165     // Updates the physics simulation for the provided timestep.
00166     void UpdatePhysicsSimulation(float deltaT);
00167
00168 private:
00169     void ApplyForces();
00170     void IntegrateSimulation(float deltaT);
00171     BOOL FindInitialCollisions(float deltaT);
00172     void HandleCollisions(float deltaT);
00173     void Physics::CalculateCurrentRoomSize();
00174 };
00175
00176 // Compute the intersection of a ray (Origin, Direction) with a triangle
00177 // (V0, V1, V2).  Return TRUE if there is an intersection and also set *pDist
00178 // to the distance along the ray to the intersection.
00179 //
00180 // The algorithm is based on Moller, Tomas and Trumbore, "Fast, Minimum Storage
00181 // Ray-Triangle Intersection", Journal of Graphics Tools, vol. 2, no. 1,
00182 // pp 21-28, 1997.
00183 inline BOOL IntersectRayTriangle(
00184     FXMVECTOR origin,
00185     FXMVECTOR direction,
00186     FXMVECTOR V0,
00187     CXMVECTOR V1,
00188     CXMVECTOR V2,
00189     float* dist
00190     )
00191 {
00192
00193     static const XMVECTOR epsilon = XMVectorSet(1e-20f, 1e-20f, 1e-20f, 1e-20f);
00194
00195     XMVECTOR zero = XMVectorZero();
00196
00197     XMVECTOR e1 = V1 - V0;
00198     XMVECTOR e2 = V2 - V0;
00199
00200     // p = direction ^ e2;
00201     XMVECTOR p = XMVector3Cross(direction, e2);
00202
00203     // det = e1 * p;
00204     XMVECTOR det = XMVector3Dot(e1, p);
00205
00206     XMVECTOR u, v, t;
00207
00208     if (XMVector3GreaterOrEqual(det, epsilon))
00209     {
00210         // Determinate is positive (front side of the triangle).
00211         XMVECTOR s = origin - V0;
00212
00213         // u = s * p;
00214         u = XMVector3Dot(s, p);
00215
00216         XMVECTOR noIntersection = XMVectorLess(u, zero);
00217         noIntersection = XMVectorOrInt(noIntersection, XMVectorGreater(u, det));
00218
00219         // q = s ^ e1;
00220         XMVECTOR q = XMVector3Cross(s, e1);
00221
00222         // v = direction * q;
00223         v = XMVector3Dot(direction, q);
00224
00225         noIntersection = XMVectorOrInt(noIntersection, XMVectorLess(v, zero));
00226         noIntersection = XMVectorOrInt(noIntersection, XMVectorGreater(u + v, det));
00227
00228         // t = e2 * q;
00229         t = XMVector3Dot(e2, q);
00230
00231         noIntersection = XMVectorOrInt(noIntersection, XMVectorLess(t, zero));
00232
00233         if (XMVector4EqualInt(noIntersection, XMVectorTrueInt()))
00234         {
00235             return FALSE;
00236         }
00237     }
00238     else if (XMVector3LessOrEqual(det, -epsilon))
00239     {
00240         // Determinate is negative (back side of the triangle).
00241         XMVECTOR s = origin - V0;
00242
00243         // u = s * p;
00244         u = XMVector3Dot(s, p);
00245
00246         XMVECTOR noIntersection = XMVectorGreater(u, zero);
00247         noIntersection = XMVectorOrInt(noIntersection, XMVectorLess(u, det));
00248
00249         // q = s ^ e1;
00250         XMVECTOR q = XMVector3Cross(s, e1);
00251
00252         // v = direction * q;
00253         v = XMVector3Dot(direction, q);
00254
00255         noIntersection = XMVectorOrInt(noIntersection, XMVectorGreater(v, zero));
00256         noIntersection = XMVectorOrInt(noIntersection, XMVectorLess(u + v, det));
00257
00258         // t = e2 * q;
00259         t = XMVector3Dot(e2, q);
00260
00261         noIntersection = XMVectorOrInt(noIntersection, XMVectorGreater(t, zero));
00262
00263         if (XMVector4EqualInt(noIntersection, XMVectorTrueInt()))
00264         {
00265             return FALSE;
00266         }
00267     }
00268     else
00269     {
00270         // Parallel ray.
00271         return FALSE;
00272     }
00273
00274     XMVECTOR inv_det = XMVectorReciprocal(det);
00275
00276     t *= inv_det;
00277
00278     // u * inv_det and v * inv_det are the barycentric cooridinates of the intersection.
00279
00280     // Store the x-component to dist
00281     XMStoreFloat(dist, t);
00282
00283     return TRUE;
00284 };
Generated on Sat Nov 23 2024 16:08:15 for Win8-Examples by doxygen 1.7.1


Win8-Examples: HomeGroup app/C++/common/LayoutAwarePage.h Source File

  • HomeGroup app
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

ContactPicker::Common::LayoutAwarePage Member List

This is the complete list of members for ContactPicker::Common::LayoutAwarePage, including all inherited members.
__pad0__ | ContactPicker::Common::LayoutAwarePage |
_defaultViewModel | ContactPicker::Common::LayoutAwarePage | [private]
_layoutAwareControls | ContactPicker::Common::LayoutAwarePage | [private]
_windowSizeEventToken | ContactPicker::Common::LayoutAwarePage | [private]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | ContactPicker::Common::LayoutAwarePage | [virtual]
GoBack(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | ContactPicker::Common::LayoutAwarePage | [virtual]
InvalidateVisualState() | ContactPicker::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | ContactPicker::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | ContactPicker::Common::LayoutAwarePage |
WindowSizeChanged(Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | ContactPicker::Common::LayoutAwarePage | [private]
Generated on Sat Nov 23 2024 16:09:36 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Geolocation/C++/Scenario3_BackgroundTask.xaml.h Source File

  • Geolocation

Scenario3_BackgroundTask.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_BackgroundTask.xaml.h
00013 // Declaration of the Scenario3 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario3_BackgroundTask.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace GeolocationCPP
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             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00038
00039         private:
00040             MainPage^ rootPage;
00041             Platform::String^ sampleBackgroundTaskName;
00042             Platform::String^ sampleBackgroundTaskEntryPoint;
00043             Windows::ApplicationModel::Background::BackgroundTaskRegistration^ geolocTask;
00044             Windows::Foundation::EventRegistrationToken taskCompletedToken;
00045             concurrency::cancellation_token_source geopositionTaskTokenSource;
00046
00047             void RegisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void UnregisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00049             void GetGeopositionAsync();
00050             void OnCompleted(Windows::ApplicationModel::Background::BackgroundTaskRegistration^ sender, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^ e);
00051         };
00052     }
00053 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XInput audio controller playback/C++/pch.cpp Source File

  • XInput audio controller playback

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX marble maze game/C++/DirectXBase.cpp Source File

  • DirectX marble maze game

DirectXBase.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 "DirectXBase.h"
00010
00011 using namespace Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::Graphics::Display;
00015 using namespace D2D1;
00016
00017 // Constructor.
00018 DirectXBase::DirectXBase() :
00019     m_windowSizeChangeInProgress(false),
00020     m_dpi(-1.0f)
00021 {
00022 }
00023
00024 // Initialize the DirectX resources required to run.
00025 void DirectXBase::Initialize(CoreWindow^ window, float dpi)
00026 {
00027     m_window = window;
00028
00029     CreateDeviceIndependentResources();
00030     CreateDeviceResources();
00031     SetDpi(dpi);
00032 }
00033
00034 // Recreate all device resources and set them back to the current state.
00035 void DirectXBase::HandleDeviceLost()
00036 {
00037     // Reset these member variables to ensure that SetDpi recreates all resources.
00038     float dpi = m_dpi;
00039     m_dpi = -1.0f;
00040     m_windowBounds.Width = 0;
00041     m_windowBounds.Height = 0;
00042     m_swapChain = nullptr;
00043
00044     CreateDeviceResources();
00045     SetDpi(dpi);
00046 }
00047
00048 // These are the resources required independent of the device.
00049 void DirectXBase::CreateDeviceIndependentResources()
00050 {
00051     D2D1_FACTORY_OPTIONS options;
00052     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00053
00054 #if defined(_DEBUG)
00055     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00056     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00057 #endif
00058
00059     DX::ThrowIfFailed(
00060         D2D1CreateFactory(
00061             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00062             __uuidof(ID2D1Factory1),
00063             &options,
00064             &m_d2dFactory
00065             )
00066         );
00067
00068     DX::ThrowIfFailed(
00069         DWriteCreateFactory(
00070             DWRITE_FACTORY_TYPE_SHARED,
00071             __uuidof(IDWriteFactory),
00072             &m_dwriteFactory
00073             )
00074         );
00075
00076     DX::ThrowIfFailed(
00077         CoCreateInstance(
00078             CLSID_WICImagingFactory,
00079             nullptr,
00080             CLSCTX_INPROC_SERVER,
00081             IID_PPV_ARGS(&m_wicFactory)
00082             )
00083         );
00084 }
00085
00086 // These are the resources that depend on the device.
00087 void DirectXBase::CreateDeviceResources()
00088 {
00089     // This flag adds support for surfaces with a different color channel ordering
00090     // than the API default. It is required for compatibility with Direct2D.
00091     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00092     ComPtr<IDXGIDevice> dxgiDevice;
00093
00094 #if defined(_DEBUG)
00095     // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00096     creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00097 #endif
00098
00099     // This array defines the set of DirectX hardware feature levels this app will support.
00100     // Note the ordering should be preserved.
00101     // Don't forget to declare your application's minimum required feature level in its
00102     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00103     D3D_FEATURE_LEVEL featureLevels[] =
00104     {
00105         D3D_FEATURE_LEVEL_11_1,
00106         D3D_FEATURE_LEVEL_11_0,
00107         D3D_FEATURE_LEVEL_10_1,
00108         D3D_FEATURE_LEVEL_10_0,
00109         D3D_FEATURE_LEVEL_9_3,
00110         D3D_FEATURE_LEVEL_9_2,
00111         D3D_FEATURE_LEVEL_9_1
00112     };
00113
00114     // Create the Direct3D 11 API device object and a corresponding context.
00115     ComPtr<ID3D11Device> device;
00116     ComPtr<ID3D11DeviceContext> context;
00117     DX::ThrowIfFailed(
00118         D3D11CreateDevice(
00119             nullptr,                    // Specify nullptr to use the default adapter.
00120             D3D_DRIVER_TYPE_HARDWARE,
00121             0,
00122             creationFlags,              // Set debug and Direct2D compatibility flags.
00123             featureLevels,              // List of feature levels this app can support.
00124             ARRAYSIZE(featureLevels),
00125             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Metro style apps.
00126             &device,                    // Returns the Direct3D device created.
00127             &m_featureLevel,            // Returns feature level of device created.
00128             &context                    // Returns the device immediate context.
00129             )
00130         );
00131
00132     // Get the Direct3D 11.1 API device and context interfaces.
00133     DX::ThrowIfFailed(
00134         device.As(&m_d3dDevice)
00135         );
00136
00137     DX::ThrowIfFailed(
00138         context.As(&m_d3dContext)
00139         );
00140
00141     // Get the underlying DXGI device of the Direct3D device.
00142     DX::ThrowIfFailed(
00143         m_d3dDevice.As(&dxgiDevice)
00144         );
00145
00146     // Create the Direct2D device object and a corresponding context.
00147     DX::ThrowIfFailed(
00148         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00149         );
00150
00151     DX::ThrowIfFailed(
00152         m_d2dDevice->CreateDeviceContext(
00153             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00154             &m_d2dContext
00155             )
00156         );
00157 }
00158
00159 // Helps track the DPI in the helper class.
00160 // This is called in the dpiChanged event handler in the view class.
00161 void DirectXBase::SetDpi(float dpi)
00162 {
00163     if (dpi != m_dpi)
00164     {
00165         // Save the DPI of this display in our class.
00166         m_dpi = dpi;
00167
00168         // Update Direct2D's stored DPI.
00169         m_d2dContext->SetDpi(m_dpi, m_dpi);
00170
00171         // Often a DPI change implies a window size change. In some cases Windows will issue
00172         // both a size changed event and a DPI changed event. In this case, the resulting bounds
00173         // will not change, and the window resize code will only be executed once.
00174         UpdateForWindowSizeChange();
00175     }
00176 }
00177
00178 // This routine is called in the event handler for the view SizeChanged event.
00179 void DirectXBase::UpdateForWindowSizeChange()
00180 {
00181     // Only handle window size changed if there is no pending DPI change.
00182     if (m_dpi != DisplayProperties::LogicalDpi)
00183     {
00184         return;
00185     }
00186
00187     if (m_window->Bounds.Width  != m_windowBounds.Width ||
00188         m_window->Bounds.Height != m_windowBounds.Height)
00189     {
00190         m_d2dContext->SetTarget(nullptr);
00191         m_d2dTargetBitmap = nullptr;
00192         m_d3dRenderTargetView = nullptr;
00193         m_d3dDepthStencilView = nullptr;
00194         m_windowSizeChangeInProgress = true;
00195         CreateWindowSizeDependentResources();
00196     }
00197 }
00198
00199 // Allocate all memory resources that change on a window SizeChanged event.
00200 void DirectXBase::CreateWindowSizeDependentResources()
00201 {
00202     // Store the window bounds so the next time we get a SizeChanged event we can
00203     // avoid rebuilding everything if the size is identical.
00204     m_windowBounds = m_window->Bounds;
00205
00206     if (m_swapChain != nullptr)
00207     {
00208         // If the swap chain already exists, resize it.
00209         HRESULT hr = m_swapChain->ResizeBuffers(2, 0, 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0);
00210
00211         if (hr == DXGI_ERROR_DEVICE_REMOVED)
00212         {
00213             // If the device was removed for any reason, a new device and swapchain will need to be created.
00214             HandleDeviceLost();
00215
00216             // Everything is set up now. Do not continue execution of this method.
00217             return;
00218         }
00219         else
00220         {
00221             DX::ThrowIfFailed(hr);
00222         }
00223     }
00224     else
00225     {
00226         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00227         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00228         swapChainDesc.Width = 0;                                     // Use automatic sizing.
00229         swapChainDesc.Height = 0;
00230         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;           // This is the most common swap chain format.
00231         swapChainDesc.Stereo = false;
00232         swapChainDesc.SampleDesc.Count = 1;                          // Don't use multi-sampling.
00233         swapChainDesc.SampleDesc.Quality = 0;
00234         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00235         swapChainDesc.BufferCount = 2;                               // Use double-buffering to minimize latency.
00236         swapChainDesc.Scaling = DXGI_SCALING_NONE;
00237         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Metro style apps must use this SwapEffect.
00238         swapChainDesc.Flags = 0;
00239
00240         ComPtr<IDXGIDevice1> dxgiDevice;
00241         DX::ThrowIfFailed(
00242             m_d3dDevice.As(&dxgiDevice)
00243             );
00244
00245         ComPtr<IDXGIAdapter> dxgiAdapter;
00246         DX::ThrowIfFailed(
00247             dxgiDevice->GetAdapter(&dxgiAdapter)
00248             );
00249
00250         ComPtr<IDXGIFactory2> dxgiFactory;
00251         DX::ThrowIfFailed(
00252             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00253             );
00254
00255         CoreWindow^ window = m_window.Get();
00256         DX::ThrowIfFailed(
00257             dxgiFactory->CreateSwapChainForCoreWindow(
00258                 m_d3dDevice.Get(),
00259                 reinterpret_cast<IUnknown*>(window),
00260                 &swapChainDesc,
00261                 nullptr,
00262                 &m_swapChain
00263                 )
00264             );
00265
00266         // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
00267         // ensures that the application will only render after each VSync, minimizing power consumption.
00268         DX::ThrowIfFailed(
00269             dxgiDevice->SetMaximumFrameLatency(1)
00270             );
00271     }
00272
00273     // Create a Direct3D render target view of the swap chain back buffer.
00274     ComPtr<ID3D11Texture2D> backBuffer;
00275     DX::ThrowIfFailed(
00276         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00277         );
00278
00279     DX::ThrowIfFailed(
00280         m_d3dDevice->CreateRenderTargetView(
00281             backBuffer.Get(),
00282             nullptr,
00283             &m_d3dRenderTargetView
00284             )
00285         );
00286
00287     // Cache the rendertarget dimensions in our helper class for convenient use.
00288     D3D11_TEXTURE2D_DESC backBufferDesc = {0};
00289     backBuffer->GetDesc(&backBufferDesc);
00290     m_renderTargetSize.Width  = static_cast<float>(backBufferDesc.Width);
00291     m_renderTargetSize.Height = static_cast<float>(backBufferDesc.Height);
00292
00293     // Create a depth stencil view for use with 3D rendering if needed.
00294     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00295         DXGI_FORMAT_D24_UNORM_S8_UINT,
00296         backBufferDesc.Width,
00297         backBufferDesc.Height,
00298         1,
00299         1,
00300         D3D11_BIND_DEPTH_STENCIL
00301         );
00302
00303     ComPtr<ID3D11Texture2D> depthStencil;
00304     DX::ThrowIfFailed(
00305         m_d3dDevice->CreateTexture2D(
00306             &depthStencilDesc,
00307             nullptr,
00308             &depthStencil
00309             )
00310         );
00311
00312     auto viewDesc = CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D);
00313     DX::ThrowIfFailed(
00314         m_d3dDevice->CreateDepthStencilView(
00315             depthStencil.Get(),
00316             &viewDesc,
00317             &m_d3dDepthStencilView
00318             )
00319         );
00320
00321     // Set the 3D rendering viewport to target the entire window.
00322     CD3D11_VIEWPORT viewport(
00323         0.0f,
00324         0.0f,
00325         static_cast<float>(backBufferDesc.Width),
00326         static_cast<float>(backBufferDesc.Height)
00327         );
00328
00329     m_d3dContext->RSSetViewports(1, &viewport);
00330
00331     // Create a Direct2D target bitmap associated with the
00332     // swap chain back buffer and set it as the current target.
00333     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00334         BitmapProperties1(
00335             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00336             PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00337             m_dpi,
00338             m_dpi
00339             );
00340
00341     ComPtr<IDXGISurface> dxgiBackBuffer;
00342     DX::ThrowIfFailed(
00343         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00344         );
00345
00346     DX::ThrowIfFailed(
00347         m_d2dContext->CreateBitmapFromDxgiSurface(
00348             dxgiBackBuffer.Get(),
00349             &bitmapProperties,
00350             &m_d2dTargetBitmap
00351             )
00352         );
00353
00354     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00355
00356     // Grayscale text anti-aliasing is recommended for all Metro style apps.
00357     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00358 }
00359
00360 // Method to deliver the final image to the display.
00361 void DirectXBase::Present()
00362 {
00363     // The application may optionally specify "dirty" or "scroll" rects to improve efficiency
00364     // in certain scenarios.  In this sample, however, we do not utilize those features.
00365     DXGI_PRESENT_PARAMETERS parameters = {0};
00366     parameters.DirtyRectsCount = 0;
00367     parameters.pDirtyRects = nullptr;
00368     parameters.pScrollRect = nullptr;
00369     parameters.pScrollOffset = nullptr;
00370
00371     // The first argument instructs DXGI to block until VSync, putting the application
00372     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00373     // frames that will never be displayed to the screen.
00374     HRESULT hr = m_swapChain->Present1(1, 0, &parameters);
00375
00376     // Discard the contents of the render target.
00377     // This is a valid operation only when the existing contents will be entirely
00378     // overwritten. If dirty or scroll rects are used, this call should be removed.
00379     m_d3dContext->DiscardView(m_d3dRenderTargetView.Get());
00380
00381     // Discard the contents of the depth stencil.
00382     m_d3dContext->DiscardView(m_d3dDepthStencilView.Get());
00383
00384     // If the device was removed either by a disconnect or a driver upgrade, we
00385     // must recreate all device resources.
00386     if (hr == DXGI_ERROR_DEVICE_REMOVED)
00387     {
00388         HandleDeviceLost();
00389     }
00390     else
00391     {
00392         DX::ThrowIfFailed(hr);
00393     }
00394
00395     if (m_windowSizeChangeInProgress)
00396     {
00397         // A window size change has been initiated and the app has just completed presenting
00398         // the first frame with the new size. Notify the resize manager so we can short
00399         // circuit any resize animation and prevent unnecessary delays.
00400         CoreWindowResizeManager::GetForCurrentView()->NotifyLayoutCompleted();
00401         m_windowSizeChangeInProgress = false;
00402     }
00403 }
00404
00405 void DirectXBase::ValidateDevice()
00406 {
00407     // The D3D Device is no longer valid if the default adapter changes or if
00408     // the device has been removed.
00409
00410     // First, get the information for the adapter related to the current device.
00411
00412     ComPtr<IDXGIDevice1> dxgiDevice;
00413     ComPtr<IDXGIAdapter> deviceAdapter;
00414     DXGI_ADAPTER_DESC deviceDesc;
00415     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00416     DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter));
00417     DX::ThrowIfFailed(deviceAdapter->GetDesc(&deviceDesc));
00418
00419     // Next, get the information for the default adapter.
00420
00421     ComPtr<IDXGIFactory2> dxgiFactory;
00422     ComPtr<IDXGIAdapter1> currentAdapter;
00423     DXGI_ADAPTER_DESC currentDesc;
00424     DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)));
00425     DX::ThrowIfFailed(dxgiFactory->EnumAdapters1(0, &currentAdapter));
00426     DX::ThrowIfFailed(currentAdapter->GetDesc(&currentDesc));
00427
00428     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00429     // a new D3D device must be created.
00430
00431     if ((deviceDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart) ||
00432         (deviceDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart) ||
00433         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00434     {
00435         // Release references to resources related to the old device.
00436         dxgiDevice = nullptr;
00437         deviceAdapter = nullptr;
00438
00439         // Create a new device and swap chain.
00440         HandleDeviceLost();
00441     }
00442 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Network information/C++/LanId.xaml.cpp Source File

  • Network information

LanId.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 // LanId.xaml.cpp
00012 // Implementation of the LanId class
00013
00014 #include "pch.h"
00015 #include "LanId.xaml.h"
00016
00017 using namespace SDKSample::NetworkInformationApi;
00018
00019 using namespace Windows::UI::Xaml;
00020 using namespace Windows::UI::Xaml::Controls;
00021 using namespace Windows::UI::Xaml::Navigation;
00022
00023 #define MAX_GUID_STRING_SIZE 39
00024
00025 LanId::LanId()
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 LanId::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 // Display Lan Identifier Data
00043 void LanId::DisplayLanIdentifierData(LanIdentifier^ lanIdentifier)
00044 {
00045     try
00046     {
00047         if (lanIdentifier == nullptr)
00048         {
00049             lanIdInfo += L"Lan Identifier not defined";
00050             return;
00051         }
00052
00053         // Display InfrastructureId
00054         if (lanIdentifier->InfrastructureId != nullptr)
00055         {
00056             lanIdInfo += L"Infrastructure Type: " + lanIdentifier->InfrastructureId->Type.ToString() + "\n";
00057             lanIdInfo += L"InfraStructure Value : ";
00058             auto lanIdVals = lanIdentifier->InfrastructureId->Value;
00059             if (lanIdVals->Size != 0)
00060             {
00061                 std::for_each(begin(lanIdVals), end(lanIdVals), [this](int lanIdVal)
00062                 {
00063                     lanIdInfo += lanIdVal.ToString() + " ";
00064                 });
00065             }
00066         }
00067
00068         // Display PortId
00069         if (lanIdentifier->PortId != nullptr)
00070         {
00071             lanIdInfo += L"\nPortId Type: " + lanIdentifier->PortId->Type.ToString() + "\n";
00072             lanIdInfo += L"PortId Value : ";
00073             auto portIdVals = lanIdentifier->PortId->Value;
00074             if (portIdVals->Size != 0)
00075             {
00076                 std::for_each(begin(portIdVals), end(portIdVals), [this](int portIdVal)
00077                 {
00078                     lanIdInfo += portIdVal.ToString() + " ";
00079                 });
00080             }
00081         }
00082
00083         // Display NetworkAdapter Id
00084         WCHAR networkAdapterId[MAX_GUID_STRING_SIZE];
00085         if (StringFromGUID2(lanIdentifier->NetworkAdapterId, networkAdapterId, ARRAYSIZE(networkAdapterId)))
00086         {
00087             String^ strAdaptertId = ref new String(networkAdapterId);
00088             lanIdInfo += L"\nNetwork Adapter Id: " + strAdaptertId + L"\n";
00089         }
00090     }
00091     catch (Exception^ ex)
00092     {
00093         rootPage->NotifyUser("An unexpected exception occured: " + ex->Message, NotifyType::ErrorMessage);
00094     }
00095 }
00096
00097 // Display Lan Identifiers
00098 void SDKSample::NetworkInformationApi::LanId::LanId_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00099 {
00100     try
00101     {
00102         lanIdInfo = "";
00103         auto lanIdentifiers = NetworkInformation::GetLanIdentifiers();
00104         if (lanIdentifiers->Size != 0)
00105         {
00106             lanIdInfo += L"Number of Lan Identifiers retrieved : " + lanIdentifiers->Size.ToString() + "\n";
00107             lanIdInfo += L"===========================================\n";
00108
00109             std::for_each(begin(lanIdentifiers), end(lanIdentifiers), [this](LanIdentifier^ lanIdentifier)
00110             {
00111                 // Display Lan Identifiers information
00112                 DisplayLanIdentifierData(lanIdentifier);
00113                 lanIdInfo += "---------------------------------------------------\n";
00114             });
00115
00116             rootPage->NotifyUser(lanIdInfo, NotifyType::StatusMessage);
00117         }
00118         else
00119         {
00120             rootPage->NotifyUser(L"No Lan Identifier Data found", NotifyType::StatusMessage);
00121         }
00122     }
00123     catch (Exception^ ex)
00124     {
00125         rootPage->NotifyUser("An unexpected exception occured: " + ex->Message, NotifyType::ErrorMessage);
00126     }
00127 }
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Folder enumeration/C++/common/LayoutAwarePage.cpp Source File

  • Folder enumeration
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:31 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Contact Picker app/C++/Constants.h Source File

  • Contact Picker app

Constants.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 namespace ContactPicker
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     public enum class NotifyType
00024     {
00025         StatusMessage,
00026         ErrorMessage
00027     };
00028
00029     partial ref class MainPage
00030     {
00031     public:
00032         static property Platform::String^ FEATURE_NAME
00033         {
00034             Platform::String^ get()
00035             {
00036                 return ref new Platform::String(L"Contact Picker Sample");
00037             }
00038         }
00039
00040         static property Platform::Array<Scenario>^ scenarios
00041         {
00042             Platform::Array<Scenario>^ get()
00043             {
00044                 return scenariosInner;
00045             }
00046         }
00047
00048     internal:
00049         bool EnsureUnsnapped();
00050
00051     private:
00052         static Platform::Array<Scenario>^ scenariosInner;
00053     };
00054
00055     partial ref class MainPagePicker
00056     {
00057     public:
00058         static property Platform::String^ FEATURE_NAME
00059         {
00060             Platform::String^ get()
00061             {
00062                 return ref new Platform::String(L"Contact Picker Sample");
00063             }
00064         }
00065
00066         static property Platform::Array<Scenario>^ scenarios
00067         {
00068             Platform::Array<Scenario>^ get()
00069             {
00070                 return scenariosInner;
00071             }
00072         }
00073
00074         void Activate(Windows::ApplicationModel::Activation::ContactPickerActivatedEventArgs^ e);
00075
00076     private:
00077         static Platform::Array<Scenario>^ scenariosInner;
00078     };
00079 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Accelerometer sensor/C++/App.xaml.h Source File

  • Accelerometer sensor

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML scrolling, panning, and zooming/C++/Constants.cpp Source File

  • XAML scrolling, panning, and zooming

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully qualified name for the class that implements the scenario" }
00021     { "Basic panning", "SDKSample.ScrollViewerCPP.Scenario1" },
00022     { "Panning with snap-points ", "SDKSample.ScrollViewerCPP.Scenario2" },
00023     { "Zooming", "SDKSample.ScrollViewerCPP.Scenario3" }
00024 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Certificate enrollment/C++/HttpRequest.h Source File

  • Certificate enrollment

HttpRequest.h

Go to the documentation of this file.
00001 //-----------------------------------------------------------------------
00002 //
00003 //  Copyright (C) Microsoft Corporation.  All rights reserved.
00004 //
00005 //
00006 // THIS CODE AND INFORMATION ARE PROVIDED AS-IS WITHOUT WARRANTY OF ANY
00007 // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
00008 // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00009 // PARTICULAR PURPOSE.
00010 //-----------------------------------------------------------------------
00011 #pragma once
00012 #include "pch.h"
00013
00014 inline void CheckHResult(HRESULT hResult)
00015 {
00016     if (hResult == E_ABORT)
00017     {
00018         concurrency::cancel_current_task();
00019     }
00020     else if (FAILED(hResult))
00021     {
00022         throw Platform::Exception::CreateException(hResult);
00023     }
00024 }
00025
00026 namespace Web
00027 {
00028
00029 namespace Details
00030 {
00031
00032 // Implementation of IXMLHTTPRequest2Callback used when partial buffers are needed from the response.
00033 // When only the complete response is needed, use HttpRequestStringCallback instead.
00034 class HttpRequestBuffersCallback
00035     : public Microsoft::WRL::RuntimeClass<
00036         Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::ClassicCom>,
00037         IXMLHTTPRequest2Callback,
00038         Microsoft::WRL::FtmBase>
00039 {
00040 public:
00041     HttpRequestBuffersCallback(IXMLHTTPRequest2* httpRequest,
00042         concurrency::cancellation_token ct = concurrency::cancellation_token::none()) :
00043         request(httpRequest), cancellationToken(ct), responseReceived(false), dataHResult(S_OK), statusCode(200)
00044     {
00045         // Register a callback function that aborts the HTTP operation when
00046         // the cancellation token is canceled.
00047         if (cancellationToken != concurrency::cancellation_token::none())
00048         {
00049             registrationToken = cancellationToken.register_callback([this]()
00050             {
00051                 if (request != nullptr)
00052                 {
00053                     request->Abort();
00054                 }
00055             });
00056         }
00057
00058         dataEvent = concurrency::task_completion_event<void>();
00059     }
00060
00061     // Called when the HTTP request is being redirected to a new URL.
00062     IFACEMETHODIMP OnRedirect(IXMLHTTPRequest2*, PCWSTR)
00063     {
00064         return S_OK;
00065     }
00066
00067     // Called when HTTP headers have been received and processed.
00068     IFACEMETHODIMP OnHeadersAvailable(IXMLHTTPRequest2*, DWORD statusCode, PCWSTR reasonPhrase)
00069     {
00070         HRESULT hr = S_OK;
00071
00072         // We must not propagate exceptions back to IXHR2.
00073         try
00074         {
00075             this->statusCode = statusCode;
00076             this->reasonPhrase = reasonPhrase;
00077
00078             concurrency::critical_section::scoped_lock lock(dataEventLock);
00079             dataEvent.set();
00080         }
00081         catch (std::bad_alloc&)
00082         {
00083             hr = E_OUTOFMEMORY;
00084         }
00085         return hr;
00086     }
00087
00088     // Called when a portion of the entity body has been received.
00089     IFACEMETHODIMP OnDataAvailable(IXMLHTTPRequest2*, ISequentialStream* stream)
00090     {
00091         HRESULT hr = S_OK;
00092
00093         // We must not propagate exceptions back to IXHR2.
00094         try
00095         {
00096             // Store a reference on the stream so it can be accessed by the task.
00097             dataStream = stream;
00098
00099             // The work must be done as fast as possible, and must not block this thread,
00100             // for example, waiting on another event object.  Here we simply set an event
00101             // that can be processed by another thread.
00102             concurrency::critical_section::scoped_lock lock(dataEventLock);
00103             dataEvent.set();
00104         }
00105         catch (std::bad_alloc&)
00106         {
00107             hr = E_OUTOFMEMORY;
00108         }
00109         return hr;
00110     }
00111
00112     // Called when the entire entity response has been received.
00113     IFACEMETHODIMP OnResponseReceived(IXMLHTTPRequest2* xhr, ISequentialStream* responseStream)
00114     {
00115         responseReceived = true;
00116         return OnDataAvailable(xhr, responseStream);
00117     }
00118
00119     // Called when an error occurs during the HTTP request.
00120     IFACEMETHODIMP OnError(IXMLHTTPRequest2*, HRESULT hrError)
00121     {
00122         HRESULT hr = S_OK;
00123
00124         // We must not propagate exceptions back to IXHR2.
00125         try
00126         {
00127             concurrency::critical_section::scoped_lock lock(dataEventLock);
00128             dataHResult = hrError;
00129             dataEvent.set();
00130         }
00131         catch (std::bad_alloc&)
00132         {
00133             hr = E_OUTOFMEMORY;
00134         }
00135
00136         return hr;
00137     }
00138
00139     // Create a task that completes when data is available, in an exception-safe way.
00140     concurrency::task<void> CreateDataTask();
00141
00142     HRESULT GetError() const
00143     {
00144         return dataHResult;
00145     }
00146
00147     int GetStatusCode() const
00148     {
00149         return statusCode;
00150     }
00151
00152     std::wstring const& GetReasonPhrase() const
00153     {
00154         return reasonPhrase;
00155     }
00156
00157     bool IsResponseReceived() const
00158     {
00159         return responseReceived;
00160     }
00161
00162     // Copy bytes from the sequential stream into the buffer provided until
00163     // we reach the end of one or the other.
00164     unsigned int ReadData(
00165         _Out_writes_(outputBufferSize) byte* outputBuffer,
00166         unsigned int outputBufferSize);
00167
00168 private:
00169     ~HttpRequestBuffersCallback()
00170     {
00171         // Unregister the callback.
00172         if (cancellationToken != concurrency::cancellation_token::none())
00173         {
00174             cancellationToken.deregister_callback(registrationToken);
00175         }
00176     }
00177
00178     // Signals that the download operation was canceled.
00179     concurrency::cancellation_token cancellationToken;
00180
00181     // Used to unregister the cancellation token callback.
00182     concurrency::cancellation_token_registration registrationToken;
00183
00184     // The IXMLHTTPRequest2 that processes the HTTP request.
00185     Microsoft::WRL::ComPtr<IXMLHTTPRequest2> request;
00186
00187     // Task completion event that is set when data is available or error is triggered.
00188     concurrency::task_completion_event<void> dataEvent;
00189     concurrency::critical_section dataEventLock;
00190
00191     // We cannot store the error obtained from IXHR2 in the dataEvent since any value there is first-writer-wins,
00192     // whereas we want a subsequent error to override an initial success.
00193     HRESULT dataHResult;
00194
00195     // Referenced pointer to the data stream.
00196     Microsoft::WRL::ComPtr<ISequentialStream> dataStream;
00197
00198     // HTTP status code and reason returned by the server.
00199     int statusCode;
00200     std::wstring reasonPhrase;
00201
00202     // Whether the response has been completely received.
00203     bool responseReceived;
00204 };
00205
00206 };
00207
00208 // Utility class for performing asynchronous HTTP requests.
00209 // This class only supports one outstanding request at a time.
00210 class HttpRequest
00211 {
00212 public:
00213     HttpRequest();
00214
00215     int GetStatusCode() const
00216     {
00217         return statusCode;
00218     }
00219
00220     std::wstring const& GetReasonPhrase() const
00221     {
00222         return reasonPhrase;
00223     }
00224
00225     // Whether the response has been completely received, if using ReadAsync().
00226     bool IsResponseComplete() const
00227     {
00228         return responseComplete;
00229     }
00230
00231     // Start an HTTP GET on the specified URI.  The returned task completes once the entire response
00232     // has been received, and the task produces the HTTP response text.  The status code and reason
00233     // can be read with GetStatusCode() and GetReasonPhrase().
00234     concurrency::task<std::wstring> GetAsync(
00235         Windows::Foundation::Uri^ uri,
00236         concurrency::cancellation_token cancellationToken = concurrency::cancellation_token::none());
00237
00238     // Start an HTTP POST on the specified URI, using a string body.  The returned task produces the
00239     // HTTP response text.  The status code and reason can be read with GetStatusCode() and GetReasonPhrase().
00240     concurrency::task<std::wstring> PostAsync(
00241         Windows::Foundation::Uri^ uri,
00242         PCWSTR contentType,
00243         IStream* postStream,
00244         uint64 postStreamSizeToSend,
00245         concurrency::cancellation_token cancellationToken = concurrency::cancellation_token::none());
00246
00247   // Start an HTTP POST on the specified URI, using a string body.  The returned task produces the
00248     // HTTP response text.  The status code and reason can be read with GetStatusCode() and GetReasonPhrase().
00249   concurrency::task<std::wstring> HttpRequest::PostAsync(
00250     Windows::Foundation::Uri^ uri,
00251     PCWSTR contentType,
00252     const std::wstring& str,
00253     concurrency::cancellation_token cancellationToken = concurrency::cancellation_token::none());
00254
00255     // Start an HTTP POST on the specified URI, using a stream body.  The returned task produces the
00256     // HTTP response text.  The status code and reason can be read with GetStatusCode() and GetReasonPhrase().
00257     concurrency::task<std::wstring> PostAsync(
00258         Windows::Foundation::Uri^ uri,
00259         const std::wstring& str,
00260         concurrency::cancellation_token cancellationToken = concurrency::cancellation_token::none());
00261
00262     // Send a request but don't return the response.  Instead, let the caller read it with ReadAsync().
00263     concurrency::task<void> SendAsync(
00264         const std::wstring& httpMethod,
00265         Windows::Foundation::Uri^ uri,
00266         concurrency::cancellation_token cancellationToken = concurrency::cancellation_token::none());
00267
00268     // Read a chunk of data from the HTTP response, up to a specified length or until we reach the end
00269     // of the response, and store the value in the provided buffer.  This is useful for large content,
00270     // enabling the streaming of the result.
00271     concurrency::task<void> ReadAsync(
00272         Windows::Storage::Streams::IBuffer^ readBuffer,
00273         unsigned int offsetInBuffer,
00274         unsigned int requestedBytesToRead);
00275
00276     static void CreateMemoryStream(IStream **stream);
00277
00278 private:
00279     // Start a download of the specified URI using the specified method.  The returned task produces the
00280     // HTTP response text.  The status code and reason can be read with GetStatusCode() and GetReasonPhrase().
00281     concurrency::task<std::wstring> DownloadAsync(
00282         PCWSTR httpMethod,
00283         PCWSTR uri,
00284         concurrency::cancellation_token cancellationToken,
00285         PCWSTR contentType,
00286         IStream* postStream,
00287         uint64 postStreamBytesToSend);
00288
00289     // Referenced pointer to the callback, if using SendAsync/ReadAsync.
00290     Microsoft::WRL::ComPtr<Details::HttpRequestBuffersCallback> buffersCallback;
00291
00292     int statusCode;
00293     std::wstring reasonPhrase;
00294
00295     // Whether the response has been completely received, if using ReadAsync().
00296     bool responseComplete;
00297 };
00298
00299 };
Generated on Sat Nov 23 2024 16:07:58 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D sprite/C++/AutoThrottle.h Source File

  • Direct3D sprite

AutoThrottle.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 enum class FrameWorkload
00011 {
00012     Increase,
00013     Decrease,
00014     Maintain
00015 };
00016
00017 ref class AutoThrottle
00018 {
00019 internal:
00020     AutoThrottle(float targetFrameTime);
00021     FrameWorkload Update(float frameTime);
00022
00023 private:
00024     unsigned int m_missedFrameHistory;
00025     float m_targetFrameTime;
00026 };
Generated on Sat Nov 23 2024 16:08:11 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Compression/C++/common/suspensionmanager.cpp Source File

  • Compression
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/TileUpdateScheduler.cpp Source File

  • Hilo C++
  • Hilo

TileUpdateScheduler.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 #include "TileUpdateScheduler.h"
00009 #include "ThumbnailGenerator.h"
00010 #include "Repository.h"
00011 #include "RandomPhotoSelector.h"
00012 #include "WideFiveImageTile.h"
00013 #include "TaskExceptionsExtensions.h"
00014 #include "ExceptionPolicyFactory.h"
00015
00016 using namespace concurrency;
00017 using namespace Hilo;
00018 using namespace std;
00019 using namespace Platform;
00020 using namespace Platform::Collections;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Storage;
00023 using namespace Windows::UI::Notifications;
00024
00025 // See http://go.microsoft.com/fwlink/?LinkId=267275 for info about Hilo's implementation of tiles.
00026
00027 // Specifies the name of the local app folder that holds the thumbnail images.
00028 String^ ThumbnailsFolderName = "thumbnails";
00029
00030 // Specifies the number of photos in a batch.  A batch is applied to a single
00031 // tile update.
00032 const unsigned int BatchSize = 5;
00033 // Specifies the number of batches. The Windows Runtime rotates through
00034 // multiple batches.
00035 const unsigned int SetSize = 3;
00036
00037 TileUpdateScheduler::TileUpdateScheduler()
00038 {
00039 }
00040
00041 // Select random pictures from the Pictures library and copy them
00042 // to a local app folder and then update the tile.
00043 task<void> TileUpdateScheduler::ScheduleUpdateAsync(std::shared_ptr<Repository> repository, std::shared_ptr<ExceptionPolicy> policy)
00044 {
00045     // The storage folder that holds the thumbnails.
00046     auto thumbnailStorageFolder = make_shared<StorageFolder^>(nullptr);
00047
00048     return create_task(
00049         // Create a folder to hold the thumbnails.
00050         // The ReplaceExisting option specifies to replace the contents of any existing folder with a new, empty folder.
00051         ApplicationData::Current->LocalFolder->CreateFolderAsync(
00052             ThumbnailsFolderName,
00053             CreationCollisionOption::ReplaceExisting)).then([repository, thumbnailStorageFolder](StorageFolder^ createdFolder)
00054     {
00055         assert(IsBackgroundThread());
00056         (*thumbnailStorageFolder) = createdFolder;
00057
00058         // Collect a multiple of the batch and set size of the most recent photos from the library.
00059         // Later a random set is selected from this collection for thumbnail image generation.
00060         return repository->GetPhotoStorageFilesAsync("", 2 * BatchSize * SetSize);
00061     }, task_continuation_context::use_arbitrary()).then([](IVectorView<StorageFile^>^ files) -> task<IVector<StorageFile^>^>
00062     {
00063         assert(IsBackgroundThread());
00064         // If we received fewer than the number in one batch,
00065         // return the empty collection.
00066         if (files->Size < BatchSize)
00067         {
00068             return create_task_from_result(static_cast<IVector<StorageFile^>^>(
00069                 ref new Vector<StorageFile^>()));
00070         }
00071         auto copiedFileInfos = ref new Vector<StorageFile^>(begin(files), end(files));
00072         return RandomPhotoSelector::SelectFilesAsync(copiedFileInfos->GetView(), SetSize * BatchSize);
00073     }, task_continuation_context::use_arbitrary()).then([this, thumbnailStorageFolder, policy](IVector<StorageFile^>^ selectedFiles) -> task<Vector<StorageFile^>^>
00074     {
00075         assert(IsBackgroundThread());
00076         // Return the empty collection if the previous step did not
00077         // produce enough photos.
00078         if (selectedFiles->Size == 0)
00079         {
00080             return create_task_from_result(ref new Vector<StorageFile^>());
00081         }
00082         ThumbnailGenerator thumbnailGenerator(policy);
00083         return thumbnailGenerator.Generate(selectedFiles, *thumbnailStorageFolder);
00084     }, task_continuation_context::use_arbitrary()).then([this](Vector<StorageFile^>^ files)
00085     {
00086         assert(IsBackgroundThread());
00087         // Update the tile.
00088         UpdateTile(files);
00089     }, concurrency::task_continuation_context::use_arbitrary()).then(ObserveException<void>(policy));
00090 }
00091
00092 void TileUpdateScheduler::UpdateTile(IVector<StorageFile^>^ files)
00093 {
00094     // Create a tile updater.
00095     TileUpdater^ tileUpdater = TileUpdateManager::CreateTileUpdaterForApplication();
00096     tileUpdater->Clear();
00097
00098     unsigned int imagesCount = files->Size;
00099     unsigned int imageBatches = imagesCount / BatchSize;
00100
00101     tileUpdater->EnableNotificationQueue(imageBatches > 0);
00102
00103     for(unsigned int batch = 0; batch < imageBatches; batch++)
00104     {
00105         vector<wstring> imageList;
00106
00107         // Add the selected images to the wide tile template.
00108         for(unsigned int image = 0; image < BatchSize; image++)
00109         {
00110             StorageFile^ file = files->GetAt(image + (batch * BatchSize));
00111             wstringstream imageSource;
00112             imageSource << L"ms-appdata:///local/"
00113                 << ThumbnailsFolderName->Data()
00114                 << L"/"
00115                 << file->Name->Data();
00116             imageList.push_back(imageSource.str());
00117         }
00118
00119         WideFiveImageTile wideTile;
00120         wideTile.SetImageFilePaths(imageList);
00121
00122         // Create the notification and update the tile.
00123         auto notification = wideTile.GetTileNotification();
00124         tileUpdater->Update(notification);
00125     }
00126 }
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::ToastContent::ToastImageAndText02 Member List

This is the complete list of members for NotificationsExtensions::ToastContent::ToastImageAndText02, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
Audio | NotificationsExtensions::ToastContent::ToastNotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
CreateNotification() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline]
Duration | NotificationsExtensions::ToastContent::ToastNotificationBase |
GetContent() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline, virtual]
GetContent() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline, virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Image | NotificationsExtensions::ToastContent::ToastImageAndText02 |
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
Launch | NotificationsExtensions::ToastContent::ToastNotificationBase |
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextBodyWrap | NotificationsExtensions::ToastContent::ToastImageAndText02 |
TextFields | NotificationsExtensions::NotificationBase |
TextHeading | NotificationsExtensions::ToastContent::ToastImageAndText02 |
ToastImageAndText02() | NotificationsExtensions::ToastContent::ToastImageAndText02 | [inline]
ToastImageAndText02() | NotificationsExtensions::ToastContent::ToastImageAndText02 | [inline]
ToastNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline]
ToastNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKTemplate::Common::LayoutAwarePage::ObservableDictionary< K, V >::ObservableDictionaryChangedEventArgs Member List

This is the complete list of members for SDKTemplate::Common::LayoutAwarePage::ObservableDictionary< K, V >::ObservableDictionaryChangedEventArgs, including all inherited members.
CollectionChange | SDKTemplate::Common::LayoutAwarePage::ObservableDictionary< K, V >::ObservableDictionaryChangedEventArgs |
Key | SDKTemplate::Common::LayoutAwarePage::ObservableDictionary< K, V >::ObservableDictionaryChangedEventArgs |
ObservableDictionaryChangedEventArgs(CollectionChange change, K key) | SDKTemplate::Common::LayoutAwarePage::ObservableDictionary< K, V >::ObservableDictionaryChangedEventArgs | [inline]
ObservableDictionaryChangedEventArgs(CollectionChange change, K key) | SDKTemplate::Common::LayoutAwarePage::ObservableDictionary< K, V >::ObservableDictionaryChangedEventArgs | [inline]
Generated on Sat Nov 23 2024 16:09:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D printing images and effects/C++/DirectXBase.cpp Source File

  • Direct2D printing images and effects

DirectXBase.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 "DirectXBase.h"
00010
00011 using namespace Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::Graphics::Display;
00015 using namespace D2D1;
00016
00017 // Constructor.
00018 DirectXBase::DirectXBase() :
00019     m_windowSizeChangeInProgress(false),
00020     m_dpi(-1.0f)
00021 {
00022 }
00023
00024 // Initialize the DirectX resources required to run.
00025 void DirectXBase::Initialize(CoreWindow^ window, float dpi)
00026 {
00027     m_window = window;
00028
00029     CreateDeviceIndependentResources();
00030     CreateDeviceResources();
00031     SetDpi(dpi);
00032 }
00033
00034 // Recreate all device resources and set them back to the current state.
00035 void DirectXBase::HandleDeviceLost()
00036 {
00037     // Reset these member variables to ensure that SetDpi recreates all resources.
00038     float dpi = m_dpi;
00039     m_dpi = -1.0f;
00040     m_windowBounds.Width = 0;
00041     m_windowBounds.Height = 0;
00042     m_swapChain = nullptr;
00043
00044     CreateDeviceResources();
00045     SetDpi(dpi);
00046 }
00047
00048 // These are the resources required independent of the device.
00049 void DirectXBase::CreateDeviceIndependentResources()
00050 {
00051     D2D1_FACTORY_OPTIONS options;
00052     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00053
00054 #if defined(_DEBUG)
00055     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00056     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00057 #endif
00058
00059     DX::ThrowIfFailed(
00060         D2D1CreateFactory(
00061             D2D1_FACTORY_TYPE_MULTI_THREADED,
00062             __uuidof(ID2D1Factory1),
00063             &options,
00064             &m_d2dFactory
00065             )
00066         );
00067
00068     DX::ThrowIfFailed(
00069         DWriteCreateFactory(
00070             DWRITE_FACTORY_TYPE_SHARED,
00071             __uuidof(IDWriteFactory),
00072             &m_dwriteFactory
00073             )
00074         );
00075
00076     DX::ThrowIfFailed(
00077         CoCreateInstance(
00078             CLSID_WICImagingFactory,
00079             nullptr,
00080             CLSCTX_INPROC_SERVER,
00081             IID_PPV_ARGS(&m_wicFactory)
00082             )
00083         );
00084 }
00085
00086 // These are the resources that depend on the device.
00087 void DirectXBase::CreateDeviceResources()
00088 {
00089     // This flag adds support for surfaces with a different color channel ordering
00090     // than the API default. It is required for compatibility with Direct2D.
00091     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00092     ComPtr<IDXGIDevice> dxgiDevice;
00093
00094 #if defined(_DEBUG)
00095     // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00096     creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00097 #endif
00098
00099     // This array defines the set of DirectX hardware feature levels this app will support.
00100     // Note the ordering should be preserved.
00101     // Don't forget to declare your application's minimum required feature level in its
00102     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00103     D3D_FEATURE_LEVEL featureLevels[] =
00104     {
00105         D3D_FEATURE_LEVEL_11_1,
00106         D3D_FEATURE_LEVEL_11_0,
00107         D3D_FEATURE_LEVEL_10_1,
00108         D3D_FEATURE_LEVEL_10_0,
00109         D3D_FEATURE_LEVEL_9_3,
00110         D3D_FEATURE_LEVEL_9_2,
00111         D3D_FEATURE_LEVEL_9_1
00112     };
00113
00114     // Create the Direct3D 11 API device object and a corresponding context.
00115     ComPtr<ID3D11Device> device;
00116     ComPtr<ID3D11DeviceContext> context;
00117     DX::ThrowIfFailed(
00118         D3D11CreateDevice(
00119             nullptr,                    // Specify nullptr to use the default adapter.
00120             D3D_DRIVER_TYPE_HARDWARE,
00121             0,
00122             creationFlags,              // Set debug and Direct2D compatibility flags.
00123             featureLevels,              // List of feature levels this app can support.
00124             ARRAYSIZE(featureLevels),
00125             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Metro style apps.
00126             &device,                    // Returns the Direct3D device created.
00127             &m_featureLevel,            // Returns feature level of device created.
00128             &context                    // Returns the device immediate context.
00129             )
00130         );
00131
00132     // Get the Direct3D 11.1 API device and context interfaces.
00133     DX::ThrowIfFailed(
00134         device.As(&m_d3dDevice)
00135         );
00136
00137     DX::ThrowIfFailed(
00138         context.As(&m_d3dContext)
00139         );
00140
00141     // Get the underlying DXGI device of the Direct3D device.
00142     DX::ThrowIfFailed(
00143         m_d3dDevice.As(&dxgiDevice)
00144         );
00145
00146     // Create the Direct2D device object and a corresponding context.
00147     DX::ThrowIfFailed(
00148         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00149         );
00150
00151     DX::ThrowIfFailed(
00152         m_d2dDevice->CreateDeviceContext(
00153             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00154             &m_d2dContext
00155             )
00156         );
00157 }
00158
00159 // Helps track the DPI in the helper class.
00160 // This is called in the dpiChanged event handler in the view class.
00161 void DirectXBase::SetDpi(float dpi)
00162 {
00163     if (dpi != m_dpi)
00164     {
00165         // Save the DPI of this display in our class.
00166         m_dpi = dpi;
00167
00168         // Update Direct2D's stored DPI.
00169         m_d2dContext->SetDpi(m_dpi, m_dpi);
00170
00171         // Often a DPI change implies a window size change. In some cases Windows will issue
00172         // both a size changed event and a DPI changed event. In this case, the resulting bounds
00173         // will not change, and the window resize code will only be executed once.
00174         UpdateForWindowSizeChange();
00175     }
00176 }
00177
00178 // This routine is called in the event handler for the view SizeChanged event.
00179 void DirectXBase::UpdateForWindowSizeChange()
00180 {
00181     // Only handle window size changed if there is no pending DPI change.
00182     if (m_dpi != DisplayProperties::LogicalDpi)
00183     {
00184         return;
00185     }
00186
00187     if (m_window->Bounds.Width  != m_windowBounds.Width ||
00188         m_window->Bounds.Height != m_windowBounds.Height)
00189     {
00190         m_d2dContext->SetTarget(nullptr);
00191         m_d2dTargetBitmap = nullptr;
00192         m_d3dRenderTargetView = nullptr;
00193         m_d3dDepthStencilView = nullptr;
00194         m_windowSizeChangeInProgress = true;
00195         CreateWindowSizeDependentResources();
00196     }
00197 }
00198
00199 // Allocate all memory resources that change on a window SizeChanged event.
00200 void DirectXBase::CreateWindowSizeDependentResources()
00201 {
00202     // Store the window bounds so the next time we get a SizeChanged event we can
00203     // avoid rebuilding everything if the size is identical.
00204     m_windowBounds = m_window->Bounds;
00205
00206     if (m_swapChain != nullptr)
00207     {
00208         // If the swap chain already exists, resize it.
00209         HRESULT hr = m_swapChain->ResizeBuffers(2, 0, 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0);
00210
00211         if (hr == DXGI_ERROR_DEVICE_REMOVED)
00212         {
00213             // If the device was removed for any reason, a new device and swapchain will need to be created.
00214             HandleDeviceLost();
00215
00216             // Everything is set up now. Do not continue execution of this method.
00217             return;
00218         }
00219         else
00220         {
00221             DX::ThrowIfFailed(hr);
00222         }
00223     }
00224     else
00225     {
00226         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00227         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00228         swapChainDesc.Width = 0;                                     // Use automatic sizing.
00229         swapChainDesc.Height = 0;
00230         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;           // This is the most common swap chain format.
00231         swapChainDesc.Stereo = false;
00232         swapChainDesc.SampleDesc.Count = 1;                          // Don't use multi-sampling.
00233         swapChainDesc.SampleDesc.Quality = 0;
00234         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00235         swapChainDesc.BufferCount = 2;                               // Use double-buffering to minimize latency.
00236         swapChainDesc.Scaling = DXGI_SCALING_NONE;
00237         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Metro style apps must use this SwapEffect.
00238         swapChainDesc.Flags = 0;
00239
00240         ComPtr<IDXGIDevice1> dxgiDevice;
00241         DX::ThrowIfFailed(
00242             m_d3dDevice.As(&dxgiDevice)
00243             );
00244
00245         ComPtr<IDXGIAdapter> dxgiAdapter;
00246         DX::ThrowIfFailed(
00247             dxgiDevice->GetAdapter(&dxgiAdapter)
00248             );
00249
00250         ComPtr<IDXGIFactory2> dxgiFactory;
00251         DX::ThrowIfFailed(
00252             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00253             );
00254
00255         CoreWindow^ window = m_window.Get();
00256         DX::ThrowIfFailed(
00257             dxgiFactory->CreateSwapChainForCoreWindow(
00258                 m_d3dDevice.Get(),
00259                 reinterpret_cast<IUnknown*>(window),
00260                 &swapChainDesc,
00261                 nullptr,
00262                 &m_swapChain
00263                 )
00264             );
00265
00266         // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
00267         // ensures that the application will only render after each VSync, minimizing power consumption.
00268         DX::ThrowIfFailed(
00269             dxgiDevice->SetMaximumFrameLatency(1)
00270             );
00271     }
00272
00273     // Create a Direct3D render target view of the swap chain back buffer.
00274     ComPtr<ID3D11Texture2D> backBuffer;
00275     DX::ThrowIfFailed(
00276         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00277         );
00278
00279     DX::ThrowIfFailed(
00280         m_d3dDevice->CreateRenderTargetView(
00281             backBuffer.Get(),
00282             nullptr,
00283             &m_d3dRenderTargetView
00284             )
00285         );
00286
00287     // Cache the rendertarget dimensions in our helper class for convenient use.
00288     D3D11_TEXTURE2D_DESC backBufferDesc = {0};
00289     backBuffer->GetDesc(&backBufferDesc);
00290     m_renderTargetSize.Width  = static_cast<float>(backBufferDesc.Width);
00291     m_renderTargetSize.Height = static_cast<float>(backBufferDesc.Height);
00292
00293     // Create a depth stencil view for use with 3D rendering if needed.
00294     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00295         DXGI_FORMAT_D24_UNORM_S8_UINT,
00296         backBufferDesc.Width,
00297         backBufferDesc.Height,
00298         1,
00299         1,
00300         D3D11_BIND_DEPTH_STENCIL
00301         );
00302
00303     ComPtr<ID3D11Texture2D> depthStencil;
00304     DX::ThrowIfFailed(
00305         m_d3dDevice->CreateTexture2D(
00306             &depthStencilDesc,
00307             nullptr,
00308             &depthStencil
00309             )
00310         );
00311
00312     auto viewDesc = CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D);
00313     DX::ThrowIfFailed(
00314         m_d3dDevice->CreateDepthStencilView(
00315             depthStencil.Get(),
00316             &viewDesc,
00317             &m_d3dDepthStencilView
00318             )
00319         );
00320
00321     // Set the 3D rendering viewport to target the entire window.
00322     CD3D11_VIEWPORT viewport(
00323         0.0f,
00324         0.0f,
00325         static_cast<float>(backBufferDesc.Width),
00326         static_cast<float>(backBufferDesc.Height)
00327         );
00328
00329     m_d3dContext->RSSetViewports(1, &viewport);
00330
00331     // Create a Direct2D target bitmap associated with the
00332     // swap chain back buffer and set it as the current target.
00333     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00334         BitmapProperties1(
00335             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00336             PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00337             m_dpi,
00338             m_dpi
00339             );
00340
00341     ComPtr<IDXGISurface> dxgiBackBuffer;
00342     DX::ThrowIfFailed(
00343         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00344         );
00345
00346     DX::ThrowIfFailed(
00347         m_d2dContext->CreateBitmapFromDxgiSurface(
00348             dxgiBackBuffer.Get(),
00349             &bitmapProperties,
00350             &m_d2dTargetBitmap
00351             )
00352         );
00353
00354     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00355
00356     // Grayscale text anti-aliasing is recommended for all Metro style apps.
00357     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00358 }
00359
00360 // Method to deliver the final image to the display.
00361 void DirectXBase::Present()
00362 {
00363     // The application may optionally specify "dirty" or "scroll" rects to improve efficiency
00364     // in certain scenarios.  In this sample, however, we do not utilize those features.
00365     DXGI_PRESENT_PARAMETERS parameters = {0};
00366     parameters.DirtyRectsCount = 0;
00367     parameters.pDirtyRects = nullptr;
00368     parameters.pScrollRect = nullptr;
00369     parameters.pScrollOffset = nullptr;
00370
00371     // The first argument instructs DXGI to block until VSync, putting the application
00372     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00373     // frames that will never be displayed to the screen.
00374     HRESULT hr = m_swapChain->Present1(1, 0, &parameters);
00375
00376     // Discard the contents of the render target.
00377     // This is a valid operation only when the existing contents will be entirely
00378     // overwritten. If dirty or scroll rects are used, this call should be removed.
00379     m_d3dContext->DiscardView(m_d3dRenderTargetView.Get());
00380
00381     // Discard the contents of the depth stencil.
00382     m_d3dContext->DiscardView(m_d3dDepthStencilView.Get());
00383
00384     // If the device was removed either by a disconnect or a driver upgrade, we
00385     // must recreate all device resources.
00386     if (hr == DXGI_ERROR_DEVICE_REMOVED)
00387     {
00388         HandleDeviceLost();
00389     }
00390     else
00391     {
00392         DX::ThrowIfFailed(hr);
00393     }
00394
00395     if (m_windowSizeChangeInProgress)
00396     {
00397         // A window size change has been initiated and the app has just completed presenting
00398         // the first frame with the new size. Notify the resize manager so we can short
00399         // circuit any resize animation and prevent unnecessary delays.
00400         CoreWindowResizeManager::GetForCurrentView()->NotifyLayoutCompleted();
00401         m_windowSizeChangeInProgress = false;
00402     }
00403 }
00404
00405 void DirectXBase::ValidateDevice()
00406 {
00407     // The D3D Device is no longer valid if the default adapter changes or if
00408     // the device has been removed.
00409
00410     // First, get the information for the adapter related to the current device.
00411
00412     ComPtr<IDXGIDevice1> dxgiDevice;
00413     ComPtr<IDXGIAdapter> deviceAdapter;
00414     DXGI_ADAPTER_DESC deviceDesc;
00415     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00416     DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter));
00417     DX::ThrowIfFailed(deviceAdapter->GetDesc(&deviceDesc));
00418
00419     // Next, get the information for the default adapter.
00420
00421     ComPtr<IDXGIFactory2> dxgiFactory;
00422     ComPtr<IDXGIAdapter1> currentAdapter;
00423     DXGI_ADAPTER_DESC currentDesc;
00424     DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)));
00425     DX::ThrowIfFailed(dxgiFactory->EnumAdapters1(0, &currentAdapter));
00426     DX::ThrowIfFailed(currentAdapter->GetDesc(&currentDesc));
00427
00428     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00429     // a new D3D device must be created.
00430
00431     if ((deviceDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart) ||
00432         (deviceDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart) ||
00433         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00434     {
00435         // Release references to resources related to the old device.
00436         dxgiDevice = nullptr;
00437         deviceAdapter = nullptr;
00438
00439         // Create a new device and swap chain.
00440         HandleDeviceLost();
00441     }
00442 }
Generated on Sat Nov 23 2024 16:08:02 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/MoveLookController.cpp Source File

  • XAML DirectX 3D shooting game

MoveLookController.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 "MoveLookController.h"
00010 #include "DirectXSample.h"
00011
00012 using namespace Windows::UI::Core;
00013 using namespace Windows::UI::Input;
00014 using namespace Windows::UI;
00015 using namespace Windows::Foundation;
00016 using namespace Microsoft::WRL;
00017 using namespace DirectX;
00018 using namespace Windows::Devices::Input;
00019 using namespace Windows::System;
00020
00021 #define ROTATION_GAIN 0.008f        // Sensitivity adjustment for look controller.
00022 #define MOVEMENT_GAIN 2.f           // Sensitivity adjustment for move controller.
00023
00024 //----------------------------------------------------------------------
00025
00026 MoveLookController::MoveLookController():
00027     m_autoFire(true),
00028     m_isControllerConnected(false)
00029 {
00030 }
00031
00032 //----------------------------------------------------------------------
00033 // Set up the Controls supported by this controller.
00034
00035 void MoveLookController::Initialize(
00036     _In_ CoreWindow^ window
00037     )
00038 {
00039     window->PointerPressed +=
00040         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &MoveLookController::OnPointerPressed);
00041
00042     window->PointerMoved +=
00043         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &MoveLookController::OnPointerMoved);
00044
00045     window->PointerReleased +=
00046         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &MoveLookController::OnPointerReleased);
00047
00048     window->PointerExited +=
00049         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &MoveLookController::OnPointerExited);
00050
00051     window->KeyDown +=
00052         ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &MoveLookController::OnKeyDown);
00053
00054     window->KeyUp +=
00055         ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &MoveLookController::OnKeyUp);
00056
00057     // There is a separate handler for mouse only relative mouse movement events.
00058     MouseDevice::GetForCurrentView()->MouseMoved +=
00059         ref new TypedEventHandler<MouseDevice^, MouseEventArgs^>(this, &MoveLookController::OnMouseMoved);
00060
00061     ResetState();
00062     m_state = MoveLookControllerState::None;
00063
00064     m_pitch = 0.0f;
00065     m_yaw   = 0.0f;
00066 }
00067
00068 //----------------------------------------------------------------------
00069
00070 bool MoveLookController::IsPauseRequested()
00071 {
00072     switch (m_state)
00073     {
00074     case MoveLookControllerState::Active:
00075         UpdateGameController();
00076         if (m_pausePressed)
00077         {
00078 #ifdef MOVELOOKCONTROLLER_TRACE
00079             DebugTrace(L"IsPauseRequested == true\n");
00080 #endif
00081             m_pausePressed = false;
00082             return true;
00083         }
00084         else
00085         {
00086             return false;
00087         }
00088     }
00089     return false;
00090 }
00091
00092 //----------------------------------------------------------------------
00093
00094 bool MoveLookController::IsFiring()
00095 {
00096     if (m_state == MoveLookControllerState::Active)
00097     {
00098         if (m_autoFire)
00099         {
00100             return (m_fireInUse || (m_mouseInUse && m_mouseLeftInUse) || m_xinputTriggerInUse);
00101         }
00102         else
00103         {
00104             if (m_firePressed)
00105             {
00106                 m_firePressed = false;
00107                 return true;
00108             }
00109         }
00110     }
00111     return false;
00112 }
00113
00114 //----------------------------------------------------------------------
00115
00116 bool MoveLookController::IsPressComplete()
00117 {
00118     switch (m_state)
00119     {
00120     case MoveLookControllerState::WaitForInput:
00121         UpdateGameController();
00122         if (m_buttonPressed)
00123         {
00124 #ifdef MOVELOOKCONTROLLER_TRACE
00125             DebugTrace(L"IsPressComplete == true\n");
00126 #endif
00127             m_buttonPressed = false;
00128             return true;
00129         }
00130         else
00131         {
00132             return false;
00133         }
00134         break;
00135     }
00136
00137     return false;
00138 }
00139
00140 //----------------------------------------------------------------------
00141
00142 void MoveLookController::OnPointerPressed(
00143     _In_ CoreWindow^ /* sender */,
00144     _In_ PointerEventArgs^ args
00145     )
00146 {
00147     PointerPoint^ point = args->CurrentPoint;
00148     uint32 pointerID = point->PointerId;
00149     Point pointerPosition = point->Position;
00150     PointerPointProperties^ pointProperties = point->Properties;
00151     auto pointerDevice = point->PointerDevice;
00152     auto pointerDeviceType = pointerDevice->PointerDeviceType;
00153
00154     XMFLOAT2 position = XMFLOAT2(pointerPosition.X, pointerPosition.Y);
00155
00156 #ifdef MOVELOOKCONTROLLER_TRACE
00157     DebugTrace(L"%-7s (%d) at (%4.0f, %4.0f)", L"Pressed", pointerID, position.x, position.y);
00158 #endif
00159
00160     switch (m_state)
00161     {
00162     case MoveLookControllerState::WaitForInput:
00163         if (position.x > m_buttonUpperLeft.x &&
00164             position.x < m_buttonLowerRight.x &&
00165             position.y > m_buttonUpperLeft.y &&
00166             position.y < m_buttonLowerRight.y)
00167         {
00168             // Wait until button released before setting variable.
00169             m_buttonPointerID = pointerID;
00170             m_buttonInUse = true;
00171 #ifdef MOVELOOKCONTROLLER_TRACE
00172             DebugTrace(L"\tWaitForInput(%d) - BUTTON in USE", pointerID);
00173 #endif
00174         }
00175         break;
00176
00177     case MoveLookControllerState::Active:
00178         switch (pointerDeviceType)
00179         {
00180         case Windows::Devices::Input::PointerDeviceType::Touch:
00181             if (position.x > m_moveUpperLeft.x &&
00182                 position.x < m_moveLowerRight.x &&
00183                 position.y > m_moveUpperLeft.y &&
00184                 position.y < m_moveLowerRight.y)
00185             {
00186                 // This pointer is in the move control.
00187                 if (!m_moveInUse)
00188                 {
00189                     // There is not an active pointer in this control yet.
00190                     // Process a DPad touch down event.
00191                     m_moveFirstDown = position;                 // Save location of initial contact.
00192                     m_movePointerID = pointerID;                // Store the pointer using this control.
00193                     m_moveInUse = true;
00194                 }
00195             }
00196             else if (position.x > m_fireUpperLeft.x &&
00197                 position.x < m_fireLowerRight.x &&
00198                 position.y > m_fireUpperLeft.y &&
00199                 position.y < m_fireLowerRight.y)
00200             {
00201                 // This pointer is in the fire control.
00202                 if (!m_fireInUse)
00203                 {
00204                     m_fireLastPoint = position;
00205                     m_firePointerID = pointerID;
00206                     m_fireInUse = true;
00207                     if (!m_autoFire)
00208                     {
00209                         m_firePressed = true;
00210                     }
00211                 }
00212             }
00213             else
00214             {
00215                 if (!m_lookInUse)
00216                 {
00217                     // There is not an active pointer in this control yet.
00218                     m_lookLastPoint = position;                   // Save point for later move.
00219                     m_lookPointerID = pointerID;                  // Store the pointer using this control.
00220                     m_lookLastDelta.x = m_lookLastDelta.y = 0;    // These are for smoothing.
00221                     m_lookInUse = true;
00222                 }
00223             }
00224             break;
00225
00226         default:
00227             bool rightButton = pointProperties->IsRightButtonPressed;
00228             bool leftButton = pointProperties->IsLeftButtonPressed;
00229
00230             if (!m_autoFire && (!m_mouseLeftInUse && leftButton))
00231             {
00232                 m_firePressed = true;
00233             }
00234
00235             if (!m_mouseInUse)
00236             {
00237                 m_mouseInUse = true;
00238                 m_mouseLastPoint = position;
00239                 m_mousePointerID = pointerID;
00240                 m_mouseLeftInUse = leftButton;
00241                 m_mouseRightInUse = rightButton;
00242                 m_lookLastDelta.x = m_lookLastDelta.y = 0;          // These are for smoothing.
00243             }
00244             else
00245             {
00246 #ifdef MOVELOOKCONTROLLER_TRACE
00247                 DebugTrace(L"\tWARNING: OnPointerPressed()  Mouse aleady in use (%d-%s%s) and new event id: %d %s%s",
00248                     m_mousePointerID,
00249                     m_mouseLeftInUse ? "L" : "",
00250                     m_mouseRightInUse ? "R" : "",
00251                     pointerID,
00252                     leftButton ? "L" : "",
00253                     rightButton ? "R" : ""
00254                     );
00255 #endif
00256             }
00257             break;
00258         }
00259 #ifdef MOVELOOKCONTROLLER_TRACE
00260         DebugTrace(
00261             L"\t%s%s%s %s%s%s",
00262             m_moveInUse ? L"Move " : L"",
00263             m_lookInUse ? L"Look " : L"",
00264             m_fireInUse ? L"Fire " : L"",
00265             m_mouseInUse ? L"Mouse:" : L"",
00266             m_mouseLeftInUse ? L"L" : L"-",
00267             m_mouseRightInUse ? L"R" : L"-"
00268             );
00269 #endif
00270         break;
00271     }
00272 #ifdef MOVELOOKCONTROLLER_TRACE
00273     DebugTrace(L"\n");
00274 #endif
00275     return;
00276 }
00277
00278 //----------------------------------------------------------------------
00279
00280 void MoveLookController::OnPointerMoved(
00281     _In_ CoreWindow^ /* sender */,
00282     _In_ PointerEventArgs^ args
00283     )
00284 {
00285     PointerPoint^ point = args->CurrentPoint;
00286     uint32 pointerID = point->PointerId;
00287     Point pointerPosition = point->Position;
00288     PointerPointProperties^ pointProperties = point->Properties;
00289     auto pointerDevice = point->PointerDevice;
00290
00291     XMFLOAT2 position = XMFLOAT2(pointerPosition.X, pointerPosition.Y);     // convert to allow math
00292
00293 #ifdef MOVELOOKCONTROLLER_TRACE
00294     DebugTrace(L"%-7s (%d) at (%4.0f, %4.0f)", L"Moved", pointerID, position.x, position.y);
00295 #endif
00296
00297     switch (m_state)
00298     {
00299     case MoveLookControllerState::Active:
00300         // Decide which control this pointer is operating.
00301         if (pointerID == m_movePointerID)
00302         {
00303             m_movePointerPosition = position;       // Save the current position.
00304         }
00305         else if (pointerID == m_lookPointerID)
00306         {
00307             // Look control.
00308             XMFLOAT2 pointerDelta;
00309             pointerDelta.x = position.x - m_lookLastPoint.x;        // How far did pointer move?
00310             pointerDelta.y = position.y - m_lookLastPoint.y;
00311
00312             XMFLOAT2 rotationDelta;
00313             rotationDelta.x = pointerDelta.x * ROTATION_GAIN;       // Scale for control sensitivity.
00314             rotationDelta.y = pointerDelta.y * ROTATION_GAIN;
00315             m_lookLastPoint = position;                             // Save for next time through.
00316
00317 #ifdef MOVELOOKCONTROLLER_TRACE
00318             DebugTrace(L"\tDelta (%4.0f, %4.0f)", pointerDelta.x, pointerDelta.y);
00319 #endif
00320
00321             // Update our orientation based on the command.
00322             m_pitch -= rotationDelta.y;
00323             m_yaw   += rotationDelta.x;
00324
00325             // Limit pitch to straight up or straight down.
00326             float limit = XM_PI / 2.0f - 0.01f;
00327             m_pitch = __max(-limit, m_pitch);
00328             m_pitch = __min(+limit, m_pitch);
00329
00330             // Keep longitude in sane range by wrapping.
00331             if (m_yaw >  XM_PI)
00332             {
00333                 m_yaw -= XM_PI * 2.0f;
00334             }
00335             else if (m_yaw < -XM_PI)
00336             {
00337                 m_yaw += XM_PI * 2.0f;
00338             }
00339         }
00340         else if (pointerID == m_firePointerID)
00341         {
00342             m_fireLastPoint = position;
00343         }
00344         else if (pointerID == m_mousePointerID)
00345         {
00346             m_mouseLeftInUse  = pointProperties->IsLeftButtonPressed;
00347             m_mouseRightInUse = pointProperties->IsRightButtonPressed;
00348             m_mouseLastPoint = position;                            // Save for next time through.
00349         }
00350
00351         // Mouse movement is handled via a separate relative mouse movement handler (OnMouseMoved).
00352
00353         break;
00354     }
00355 #ifdef MOVELOOKCONTROLLER_TRACE
00356     DebugTrace(L"\n");
00357 #endif
00358 }
00359
00360 //----------------------------------------------------------------------
00361
00362 void MoveLookController::OnMouseMoved(
00363     _In_ MouseDevice^ /* mouseDevice */,
00364     _In_ MouseEventArgs^ args
00365     )
00366 {
00367     // Handle Mouse Input via dedicated relative movement handler.
00368
00369     switch (m_state)
00370     {
00371     case MoveLookControllerState::Active:
00372         XMFLOAT2 mouseDelta;
00373         mouseDelta.x = static_cast<float>(args->MouseDelta.X);
00374         mouseDelta.y = static_cast<float>(args->MouseDelta.Y);
00375
00376         XMFLOAT2 rotationDelta;
00377         rotationDelta.x  = mouseDelta.x * ROTATION_GAIN;   // Scale for control sensitivity.
00378         rotationDelta.y  = mouseDelta.y * ROTATION_GAIN;
00379
00380         // Update our orientation based on the command.
00381         m_pitch -= rotationDelta.y;
00382         m_yaw   += rotationDelta.x;
00383
00384         // Limit pitch to straight up or straight down.
00385         float limit = XM_PI / 2.0f - 0.01f;
00386         m_pitch = __max(-limit, m_pitch);
00387         m_pitch = __min(+limit, m_pitch);
00388
00389         // Keep longitude in sane range by wrapping.
00390         if (m_yaw >  XM_PI)
00391         {
00392             m_yaw -= XM_PI * 2.0f;
00393         }
00394         else if (m_yaw < -XM_PI)
00395         {
00396             m_yaw += XM_PI * 2.0f;
00397         }
00398         break;
00399     }
00400 }
00401
00402 //----------------------------------------------------------------------
00403
00404 void MoveLookController::OnPointerReleased(
00405     _In_ CoreWindow^ /* sender */,
00406     _In_ PointerEventArgs^ args
00407     )
00408 {
00409     PointerPoint^ point = args->CurrentPoint;
00410     uint32 pointerID = point->PointerId;
00411     Point pointerPosition = point->Position;
00412     PointerPointProperties^ pointProperties = point->Properties;
00413
00414     XMFLOAT2 position = XMFLOAT2(pointerPosition.X, pointerPosition.Y);
00415
00416 #ifdef MOVELOOKCONTROLLER_TRACE
00417     DebugTrace(L"%-7s (%d) at (%4.0f, %4.0f)\n", L"Release", pointerID, position.x, position.y);
00418 #endif
00419
00420     switch (m_state)
00421     {
00422     case MoveLookControllerState::WaitForInput:
00423         if (m_buttonInUse && (pointerID == m_buttonPointerID))
00424         {
00425             m_buttonInUse = false;
00426             m_buttonPressed = true;
00427 #ifdef MOVELOOKCONTROLLER_TRACE
00428             DebugTrace(L"\tWaitForInput: ButtonPressed = true\n");
00429 #endif
00430         }
00431         break;
00432
00433     case MoveLookControllerState::Active:
00434         if (pointerID == m_movePointerID)
00435         {
00436             m_velocity = XMFLOAT3(0, 0, 0);      // Stop on release.
00437             m_moveInUse = false;
00438             m_movePointerID = 0;
00439         }
00440         else if (pointerID == m_lookPointerID)
00441         {
00442             m_lookInUse = false;
00443             m_lookPointerID = 0;
00444         }
00445         else if (pointerID == m_firePointerID)
00446         {
00447             m_fireInUse = false;
00448             m_firePointerID = 0;
00449         }
00450         else if (pointerID == m_mousePointerID)
00451         {
00452             bool rightButton = pointProperties->IsRightButtonPressed;
00453             bool leftButton = pointProperties->IsLeftButtonPressed;
00454
00455             m_mouseInUse = false;
00456
00457             // Don't clear the mouse Pointer ID so that Move events still result in Look changes.
00458             m_mouseLeftInUse = leftButton;
00459             m_mouseRightInUse = rightButton;
00460         }
00461         break;
00462     }
00463 }
00464
00465 //----------------------------------------------------------------------
00466
00467 void MoveLookController::OnPointerExited(
00468     _In_ CoreWindow^ /* sender */,
00469     _In_ PointerEventArgs^ args
00470     )
00471 {
00472     PointerPoint^ point = args->CurrentPoint;
00473     uint32 pointerID = point->PointerId;
00474     Point pointerPosition = point->Position;
00475     PointerPointProperties^ pointProperties = point->Properties;
00476
00477     XMFLOAT2 position  = XMFLOAT2(pointerPosition.X, pointerPosition.Y);
00478
00479 #ifdef MOVELOOKCONTROLLER_TRACE
00480     DebugTrace(L"%-7s (%d) at (%4.0f, %4.0f)\n", L"Exit", pointerID, position.x, position.y);
00481 #endif
00482
00483     switch (m_state)
00484     {
00485     case MoveLookControllerState::WaitForInput:
00486         if (m_buttonInUse && (pointerID == m_buttonPointerID))
00487         {
00488             m_buttonInUse = false;
00489             m_buttonPressed = false;
00490 #ifdef MOVELOOKCONTROLLER_TRACE
00491             DebugTrace(L"\tWaitForPress: ButtonPressed = false -- Got Exit Event\n");
00492 #endif
00493         }
00494         break;
00495
00496     case MoveLookControllerState::Active:
00497         if (pointerID == m_movePointerID)
00498         {
00499             m_velocity = XMFLOAT3(0, 0, 0);      // Stop on release.
00500             m_moveInUse = false;
00501             m_movePointerID = 0;
00502         }
00503         else if (pointerID == m_lookPointerID)
00504         {
00505             m_lookInUse = false;
00506             m_lookPointerID = 0;
00507         }
00508         else if (pointerID == m_firePointerID)
00509         {
00510             m_fireInUse = false;
00511             m_firePointerID = 0;
00512         }
00513         else if (pointerID == m_mousePointerID)
00514         {
00515             m_mouseInUse = false;
00516             m_mousePointerID = 0;
00517             m_mouseLeftInUse = false;
00518             m_mouseRightInUse = false;
00519         }
00520         break;
00521     }
00522 }
00523
00524 //----------------------------------------------------------------------
00525
00526 void MoveLookController::OnKeyDown(
00527     _In_ CoreWindow^ /* sender */,
00528     _In_ KeyEventArgs^ args
00529     )
00530 {
00531     Windows::System::VirtualKey Key;
00532     Key = args->VirtualKey;
00533
00534     // Figure out the command from the keyboard.
00535     if (Key == VirtualKey::W)
00536         m_forward = true;
00537     if (Key == VirtualKey::S)
00538         m_back = true;
00539     if (Key == VirtualKey::A)
00540         m_left = true;
00541     if (Key == VirtualKey::D)
00542         m_right = true;
00543     if (Key == VirtualKey::Space)
00544         m_up = true;
00545     if (Key == VirtualKey::X)
00546         m_down = true;
00547     if (Key == VirtualKey::P)
00548         m_pause = true;
00549 }
00550
00551 //----------------------------------------------------------------------
00552
00553 void MoveLookController::OnKeyUp(
00554     _In_ CoreWindow^ /* sender */,
00555     _In_ KeyEventArgs^ args
00556     )
00557 {
00558     Windows::System::VirtualKey Key;
00559     Key = args->VirtualKey;
00560
00561     // Figure out the command from the keyboard.
00562     if (Key == VirtualKey::W)
00563         m_forward = false;
00564     if (Key == VirtualKey::S)
00565         m_back = false;
00566     if (Key == VirtualKey::A)
00567         m_left = false;
00568     if (Key == VirtualKey::D)
00569         m_right = false;
00570     if (Key == VirtualKey::Space)
00571         m_up = false;
00572     if (Key == VirtualKey::X)
00573         m_down = false;
00574     if (Key == VirtualKey::P)
00575     {
00576         if (m_pause)
00577         {
00578             // Trigger pause only once on button release.
00579             m_pausePressed = true;
00580             m_pause = false;
00581         }
00582     }
00583 }
00584
00585 //----------------------------------------------------------------------
00586
00587 void MoveLookController::ResetState()
00588 {
00589     // Reset the state of the controller.
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
00606     m_xinputStartButtonInUse = false;
00607     m_xinputTriggerInUse = false;
00608
00609     m_moveCommand = XMFLOAT3(0.0f, 0.0f, 0.0f);
00610     m_forward = false;
00611     m_back = false;
00612     m_left = false;
00613     m_right = false;
00614     m_up = false;
00615     m_down = false;
00616     m_pause = false;
00617 }
00618
00619 //----------------------------------------------------------------------
00620
00621 void MoveLookController::SetMoveRect (
00622     _In_ XMFLOAT2 upperLeft,
00623     _In_ XMFLOAT2 lowerRight
00624     )
00625 {
00626 #ifdef MOVELOOKCONTROLLER_TRACE
00627     DebugTrace(L"MoveRect (%d, %d) to (%d, %d)", upperLeft.x, upperLeft.y, lowerRight.x, lowerRight.y);
00628 #endif
00629     m_moveUpperLeft  = upperLeft;
00630     m_moveLowerRight = lowerRight;
00631 }
00632
00633 //----------------------------------------------------------------------
00634
00635 void MoveLookController::SetFireRect (
00636     _In_ XMFLOAT2 upperLeft,
00637     _In_ XMFLOAT2 lowerRight
00638     )
00639 {
00640 #ifdef MOVELOOKCONTROLLER_TRACE
00641     DebugTrace(L"FireRect (%d, %d) to (%d, %d)", upperLeft.x, upperLeft.y, lowerRight.x, lowerRight.y);
00642 #endif
00643     m_fireUpperLeft  = upperLeft;
00644     m_fireLowerRight = lowerRight;
00645 }
00646
00647 //----------------------------------------------------------------------
00648
00649 void MoveLookController::WaitForPress(
00650     _In_ XMFLOAT2 upperLeft,
00651     _In_ XMFLOAT2 lowerRight
00652     )
00653 {
00654 #ifdef MOVELOOKCONTROLLER_TRACE
00655     DebugTrace(L"WaitForPress (%.1f, %.1f) to (%.1f, %.1f)\n", upperLeft.x, upperLeft.y, lowerRight.x, lowerRight.y);
00656 #endif
00657
00658     ResetState();
00659     m_state = MoveLookControllerState::WaitForInput;
00660     m_buttonUpperLeft  = upperLeft;
00661     m_buttonLowerRight = lowerRight;
00662
00663     // Turn on mouse cursor.
00664     CoreWindow::GetForCurrentThread()->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
00665 }
00666
00667 //----------------------------------------------------------------------
00668
00669 void MoveLookController::WaitForPress()
00670 {
00671 #ifdef MOVELOOKCONTROLLER_TRACE
00672     DebugTrace(L"WaitForPress (null rect)\n");
00673 #endif
00674
00675     ResetState();
00676     m_state = MoveLookControllerState::WaitForInput;
00677     m_buttonUpperLeft.x = 0.0f;
00678     m_buttonUpperLeft.y = 0.0f;
00679     m_buttonLowerRight.x = 0.0f;
00680     m_buttonLowerRight.y = 0.0f;
00681
00682     // Turn on mouse cursor.
00683     CoreWindow::GetForCurrentThread()->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
00684 }
00685
00686 //----------------------------------------------------------------------
00687
00688 XMFLOAT3 MoveLookController::Velocity()
00689 {
00690     return m_velocity;
00691 }
00692
00693 //----------------------------------------------------------------------
00694
00695 XMFLOAT3 MoveLookController::LookDirection()
00696 {
00697     XMFLOAT3 lookDirection;
00698
00699     float r = cosf(m_pitch);              // In the plane.
00700     lookDirection.y = sinf(m_pitch);      // Vertical.
00701     lookDirection.z = r * cosf(m_yaw);    // Fwd-back.
00702     lookDirection.x = r * sinf(m_yaw);    // Left-right.
00703
00704     return lookDirection;
00705 }
00706
00707 //----------------------------------------------------------------------
00708
00709 float MoveLookController::Pitch()
00710 {
00711     return m_pitch;
00712 }
00713
00714 //----------------------------------------------------------------------
00715
00716 void MoveLookController::Pitch(_In_ float pitch)
00717 {
00718     m_pitch = pitch;
00719 }
00720
00721 //----------------------------------------------------------------------
00722
00723 float MoveLookController::Yaw()
00724 {
00725     return m_yaw;
00726 }
00727
00728 //----------------------------------------------------------------------
00729
00730 void MoveLookController::Yaw(_In_ float yaw)
00731 {
00732     m_yaw = yaw;
00733 }
00734
00735 //----------------------------------------------------------------------
00736
00737 void MoveLookController::Active(_In_ bool active)
00738 {
00739     ResetState();
00740 #ifdef MOVELOOKCONTROLLER_TRACE
00741     DebugTrace(L"Active = %s\n", active ? L"true" : L"false");
00742 #endif
00743
00744     if (active)
00745     {
00746         m_state = MoveLookControllerState::Active;
00747         // Turn mouse cursor off (hidden).
00748         CoreWindow::GetForCurrentThread()->PointerCursor = nullptr;
00749     }
00750     else
00751     {
00752         m_state = MoveLookControllerState::None;
00753         // Turn mouse cursor on.
00754         auto window = CoreWindow::GetForCurrentThread();
00755         if (window)
00756         {
00757             // Protect case where there isn't a window associated with the current thread.
00758             // This happens on initialization.
00759             window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
00760         }
00761     }
00762 }
00763
00764 //----------------------------------------------------------------------
00765
00766 bool MoveLookController::Active()
00767 {
00768     if (m_state == MoveLookControllerState::Active)
00769     {
00770         return true;
00771     }
00772     else
00773     {
00774         return false;
00775     }
00776 }
00777
00778 //----------------------------------------------------------------------
00779
00780 void MoveLookController::AutoFire(_In_ bool autoFire)
00781 {
00782     m_autoFire = autoFire;
00783 }
00784
00785 //----------------------------------------------------------------------
00786
00787 bool MoveLookController::AutoFire()
00788 {
00789     return m_autoFire;
00790 }
00791
00792 //----------------------------------------------------------------------
00793
00794 void MoveLookController::Update()
00795 {
00796     UpdateGameController();
00797
00798     if (m_moveInUse)
00799     {
00800         // Move control.
00801         XMFLOAT2 pointerDelta;
00802
00803         pointerDelta.x = m_movePointerPosition.x - m_moveFirstDown.x;
00804         pointerDelta.y = m_movePointerPosition.y - m_moveFirstDown.y;
00805
00806         // Figure out the command from the virtual joystick.
00807         XMFLOAT3 commandDirection = XMFLOAT3(0.0f, 0.0f, 0.0f);
00808         if (fabsf(pointerDelta.x) > 16.0f)         // Leave 32 pixel-wide dead spot for being still.
00809             m_moveCommand.x -= pointerDelta.x/fabsf(pointerDelta.x);
00810
00811         if (fabsf(pointerDelta.y) > 16.0f)
00812             m_moveCommand.y -= pointerDelta.y/fabsf(pointerDelta.y);
00813     }
00814
00815     // Poll our state bits set by the keyboard input events.
00816     if (m_forward)
00817     {
00818         m_moveCommand.y += 1.0f;
00819     }
00820     if (m_back)
00821     {
00822         m_moveCommand.y -= 1.0f;
00823     }
00824     if (m_left)
00825     {
00826         m_moveCommand.x += 1.0f;
00827     }
00828     if (m_right)
00829     {
00830         m_moveCommand.x -= 1.0f;
00831     }
00832     if (m_up)
00833     {
00834         m_moveCommand.z += 1.0f;
00835     }
00836     if (m_down)
00837     {
00838         m_moveCommand.z -= 1.0f;
00839     }
00840
00841     // Make sure that 45deg cases are not faster.
00842     if (fabsf(m_moveCommand.x) > 0.1f ||
00843         fabsf(m_moveCommand.y) > 0.1f ||
00844         fabsf(m_moveCommand.z) > 0.1f)
00845     {
00846         XMStoreFloat3(&m_moveCommand, XMVector3Normalize(XMLoadFloat3(&m_moveCommand)));
00847     }
00848
00849     // Rotate command to align with our direction (world coordinates).
00850     XMFLOAT3 wCommand;
00851     wCommand.x =  m_moveCommand.x * cosf(m_yaw) - m_moveCommand.y * sinf(m_yaw);
00852     wCommand.y =  m_moveCommand.x * sinf(m_yaw) + m_moveCommand.y * cosf(m_yaw);
00853     wCommand.z =  m_moveCommand.z;
00854
00855     // Scale for sensitivity adjustment.
00856     // Our velocity is based on the command. Y is up.
00857     m_velocity.x = -wCommand.x * MOVEMENT_GAIN;
00858     m_velocity.z =  wCommand.y * MOVEMENT_GAIN;
00859     m_velocity.y =  wCommand.z * MOVEMENT_GAIN;
00860
00861     // Clear movement input accumulator for use during next frame.
00862     m_moveCommand = XMFLOAT3(0.0f, 0.0f, 0.0f);
00863 }
00864
00865 //----------------------------------------------------------------------
00866
00867 void MoveLookController::UpdateGameController()
00868 {
00869     if (!m_isControllerConnected)
00870     {
00871         // Check for controller connection by trying to get the capabilties.
00872         DWORD capsResult = XInputGetCapabilities(0, XINPUT_FLAG_GAMEPAD, &m_xinputCaps);
00873         if (capsResult != ERROR_SUCCESS)
00874         {
00875             return;
00876         }
00877         // Device is connected.
00878         m_isControllerConnected = true;
00879         m_xinputStartButtonInUse = false;
00880         m_xinputTriggerInUse = false;
00881     }
00882
00883     DWORD stateResult = XInputGetState(0, &m_xinputState);
00884     if (stateResult != ERROR_SUCCESS)
00885     {
00886         // Device is no longer connected.
00887         m_isControllerConnected = false;
00888     }
00889
00890     switch (m_state)
00891     {
00892     case MoveLookControllerState::WaitForInput:
00893         if (m_xinputState.Gamepad.wButtons & XINPUT_GAMEPAD_START)
00894         {
00895             m_xinputStartButtonInUse = true;
00896         }
00897         else if (m_xinputStartButtonInUse)
00898         {
00899             // Trigger once only on button release.
00900             m_xinputStartButtonInUse = false;
00901             m_buttonPressed = true;
00902         }
00903         break;
00904
00905     case MoveLookControllerState::Active:
00906         if (m_xinputState.Gamepad.wButtons & XINPUT_GAMEPAD_START)
00907         {
00908             m_xinputStartButtonInUse = true;
00909         }
00910         else if (m_xinputStartButtonInUse)
00911         {
00912             // Trigger once only on button release.
00913             m_xinputStartButtonInUse = false;
00914             m_pausePressed = true;
00915         }
00916         // Use the Left Thumb joystick on the Xbox controller to control
00917         // the eye point position control.
00918         // The controller input goes from -32767 to 32767.  We will normalize
00919         // this from -1 to 1 and keep a dead spot in the middle to avoid drift.
00920
00921         if (m_xinputState.Gamepad.sThumbLX > XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE ||
00922             m_xinputState.Gamepad.sThumbLX < -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE)
00923         {
00924             float x = (float)m_xinputState.Gamepad.sThumbLX/32767.0f;
00925             m_moveCommand.x -= x / fabsf(x);
00926         }
00927
00928         if (m_xinputState.Gamepad.sThumbLY > XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE ||
00929             m_xinputState.Gamepad.sThumbLY < -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE)
00930         {
00931             float y = (float)m_xinputState.Gamepad.sThumbLY/32767.0f;
00932             m_moveCommand.y += y / fabsf(y);
00933         }
00934
00935         // Use the Right Thumb Joystick on the Xbox controller to control
00936         // the look at control.
00937         // The controller input goes from -32767 to 32767.  We will normalize
00938         // this from -1 to 1 and keep a dead spot in the middle to avoid drift.
00939         XMFLOAT2 pointerDelta;
00940         if (m_xinputState.Gamepad.sThumbRX > XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE ||
00941             m_xinputState.Gamepad.sThumbRX < -XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE)
00942         {
00943             pointerDelta.x = (float)m_xinputState.Gamepad.sThumbRX/32767.0f;
00944             pointerDelta.x = pointerDelta.x * pointerDelta.x * pointerDelta.x;
00945         }
00946         else
00947         {
00948             pointerDelta.x = 0.0f;
00949         }
00950         if (m_xinputState.Gamepad.sThumbRY > XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE ||
00951             m_xinputState.Gamepad.sThumbRY < -XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE)
00952         {
00953             pointerDelta.y = (float)m_xinputState.Gamepad.sThumbRY/32767.0f;
00954             pointerDelta.y = pointerDelta.y * pointerDelta.y * pointerDelta.y;
00955         }
00956         else
00957         {
00958             pointerDelta.y = 0.0f;
00959         }
00960
00961         XMFLOAT2 rotationDelta;
00962         rotationDelta.x = pointerDelta.x *  0.08f;       // Scale for control sensitivity.
00963         rotationDelta.y = pointerDelta.y *  0.08f;
00964
00965         // Update our orientation based on the command.
00966         m_pitch += rotationDelta.y;
00967         m_yaw   += rotationDelta.x;
00968
00969         // Limit pitch to straight up or straight down.
00970         m_pitch = __max(-XM_PI / 2.0f, m_pitch);
00971         m_pitch = __min(+XM_PI / 2.0f, m_pitch);
00972
00973         // Check the state of the Right Trigger button.  This is used to indicate fire control.
00974
00975         if (m_xinputState.Gamepad.bRightTrigger > XINPUT_GAMEPAD_TRIGGER_THRESHOLD)
00976         {
00977             if (!m_autoFire && !m_xinputTriggerInUse)
00978             {
00979                 m_firePressed = true;
00980             }
00981             m_xinputTriggerInUse = true;
00982         }
00983         else
00984         {
00985             m_xinputTriggerInUse = false;
00986         }
00987         break;
00988     }
00989 }
00990
00991 //----------------------------------------------------------------------
00992
00993 #ifdef MOVELOOKCONTROLLER_TRACE
00994 void MoveLookController::DebugTrace(const wchar_t *format, ...)
00995 {
00996     // Generate the message string.
00997     va_list args;
00998     va_start(args, format);
00999     wchar_t message[1024];
01000     vswprintf_s(message, 1024, format, args);
01001     OutputDebugStringW(message);
01002 }
01003 #endif
01004
01005 //----------------------------------------------------------------------
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/pch.h Source File

  • XAML DirectX 3D shooting game

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 <d3d11_1.h>
00012 #include <d2d1_1.h>
00013 #include <d2d1effects.h>
00014 #include <dwrite_1.h>
00015 #include <wincodec.h>
00016 #include <DirectXMath.h>
00017
00018 #include <xaudio2.h>
00019 #include <xaudio2fx.h>
00020
00021 #include <mmreg.h>
00022 #include <mfidl.h>
00023 #include <mfapi.h>
00024 #include <mfreadwrite.h>
00025
00026 #include <XInput.h>
00027
00028 #include <stdio.h>
00029 #include <vector>
00030 #include <memory>
00031
00032 #include <ppltasks.h>
00033 #include <agile.h>
00034
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D sprite/C++/BasicTimer.h Source File

  • Direct3D sprite

BasicTimer.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 timer class used to drive the render loop of the actively-animated
00011 // DirectX SDK samples. Uses the QueryPerformanceCounter function to retrieve
00012 // high-resolution timing information.
00013 ref class BasicTimer
00014 {
00015 private:
00016     LARGE_INTEGER m_frequency;
00017     LARGE_INTEGER m_currentTime;
00018     LARGE_INTEGER m_startTime;
00019     LARGE_INTEGER m_lastTime;
00020     float m_total;
00021     float m_delta;
00022
00023 internal:
00024     BasicTimer();
00025     void Reset();
00026     void Update();
00027     property float Total
00028     {
00029         float get();
00030     }
00031     property float Delta
00032     {
00033         float get();
00034     }
00035 };
Generated on Sat Nov 23 2024 16:08:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Association launching/C++/LaunchFileOutput.xaml.cpp Source File

  • Association launching

LaunchFileOutput.xaml.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 //
00009 // LaunchFileOutput.xaml.cpp
00010 // Implementation of the LaunchFileOutput class
00011 //
00012
00013 #include "pch.h"
00014 #include "LaunchFileOutput.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace AssociationLaunching;
00018
00019 using namespace Platform;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Graphics::Display;
00023 using namespace Windows::UI::ViewManagement;
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 LaunchFileOutput::LaunchFileOutput()
00033 {
00034     InitializeComponent();
00035 }
00036
00037 LaunchFileOutput::~LaunchFileOutput()
00038 {
00039 }
00040
00041 #pragma region Template-Related Code - Do not remove
00042 void LaunchFileOutput::OnNavigatedTo(NavigationEventArgs^ e)
00043 {
00044     // Get a pointer to our main page.
00045     rootPage = dynamic_cast<MainPage^>(e->Parameter);
00046 }
00047
00048 void LaunchFileOutput::OnNavigatedFrom(NavigationEventArgs^ e)
00049 {
00050 }
00051
00052 #pragma endregion
Generated on Sat Nov 23 2024 16:07:57 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Thread pool/C++/App.xaml.h Source File

  • Thread pool

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SimpleCommunication::Scenario Member List

This is the complete list of members for SimpleCommunication::Scenario, including all inherited members.
ClassName | SimpleCommunication::Scenario
Title | SimpleCommunication::Scenario
Generated on Sat Nov 23 2024 16:09:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Sharing content source app/C++/common/suspensionmanager.h Source File

  • Sharing content source app
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

D2DBasicAnimation Member List

This is the complete list of members for D2DBasicAnimation, including all inherited members.
__pad0__ | D2DBasicAnimation |
ComputeTriangleLocation(float startPoint, float endPoint, float duration, float elapsedTime) | D2DBasicAnimation | [private]
CreateDeviceIndependentResources() override | D2DBasicAnimation | [virtual]
CreateDeviceResources() override | D2DBasicAnimation | [virtual]
CreateSpiralPathAndTriangle() | D2DBasicAnimation | [private]
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | D2DBasicAnimation | [virtual]
Load(_In_ Platform::String^entryPoint) | D2DBasicAnimation | [virtual]
m_blackBrush | D2DBasicAnimation | [private]
m_elapsedTime | D2DBasicAnimation | [private]
m_objectGeometry | D2DBasicAnimation | [private]
m_pathGeometry | D2DBasicAnimation | [private]
m_pathLength | D2DBasicAnimation | [private]
m_sampleOverlay | D2DBasicAnimation | [private]
m_textFormat | D2DBasicAnimation | [private]
m_whiteBrush | D2DBasicAnimation | [private]
m_windowClosed | D2DBasicAnimation | [private]
m_windowVisible | D2DBasicAnimation | [private]
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | D2DBasicAnimation | [private]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | D2DBasicAnimation | [private]
OnResuming(_In_ Platform::Object^sender, _In_ Platform::Object^args) | D2DBasicAnimation | [private]
OnSuspending(_In_ Platform::Object^sender, _In_ Windows::ApplicationModel::SuspendingEventArgs^args) | D2DBasicAnimation | [private]
OnVisibilityChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::VisibilityChangedEventArgs^args) | D2DBasicAnimation | [private]
OnWindowClosed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::CoreWindowEventArgs^args) | D2DBasicAnimation | [private]
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | D2DBasicAnimation | [private]
Render() override | D2DBasicAnimation | [virtual]
Run() | D2DBasicAnimation | [virtual]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | D2DBasicAnimation | [virtual]
Uninitialize() | D2DBasicAnimation | [virtual]
Generated on Sat Nov 23 2024 16:09:10 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Clipboard app/C++/Others.xaml.cpp Source File

  • Clipboard app

Others.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 // Others.xaml.cpp
00013 // Implementation of the Others class
00014 //
00015
00016 #include "pch.h"
00017 #include "Others.xaml.h"
00018
00019 using namespace Clipboard;
00020
00021 using namespace Platform;
00022 using namespace Windows::Foundation;
00023 using namespace Windows::Foundation::Collections;
00024 using namespace Windows::UI::Core;
00025
00026 using namespace Windows::UI::Xaml;
00027 using namespace Windows::UI::Xaml::Controls;
00028 using namespace Windows::UI::Xaml::Navigation;
00029
00030 using namespace Windows::ApplicationModel;
00031 using namespace Windows::ApplicationModel::DataTransfer;
00032
00033 bool Others::registerContentChanged = false;
00034 bool Others::needToPrintClipboardFormat = false;
00035 bool Others::windowVisible = false;
00036
00037 EventRegistrationToken Others::contentChangedToken;
00038 EventRegistrationToken Others::visibilityChangedToken;
00039
00040 Others::Others()
00041 {
00042     InitializeComponent();
00043 }
00044
00045 void Others::OnNavigatedTo(NavigationEventArgs^ e)
00046 {
00047     rootPage = MainPage::Current;
00048     windowVisible = true;
00049     RegisterClipboardContentChanged->IsChecked = registerContentChanged;
00050
00051     if (needToPrintClipboardFormat)
00052     {
00053         HandleClipboardChanged();
00054     }
00055 }
00056
00057 void Others::OnNavigatedFrom(NavigationEventArgs^ e)
00058 {
00059     windowVisible = false;
00060 }
00061
00062 void Others::ClearOutput()
00063 {
00064     rootPage->NotifyUser("", NotifyType::StatusMessage);
00065     OutputText->Text = "";
00066     DisplayFormatOutputText->Text = "";
00067 }
00068
00069 void Others::DisplayFormats(DataPackageView^ dataPackageView)
00070 {
00071     if ((dataPackageView != nullptr) && (dataPackageView->AvailableFormats->Size > 0))
00072     {
00073         OutputText->Text = "";
00074         DisplayFormatOutputText->Text = "Clipboard contains following data formats:\n";
00075         auto iterator = dataPackageView->AvailableFormats->First();
00076         while (iterator->HasCurrent)
00077         {
00078             DisplayFormatOutputText->Text += " * " + iterator->Current + "\n";
00079             iterator->MoveNext();
00080         }
00081     }
00082     else
00083     {
00084         OutputText->Text = "The clipboard is empty";
00085     }
00086
00087     needToPrintClipboardFormat = false;
00088 }
00089
00090 void Others::HandleClipboardChanged()
00091 {
00092     if (windowVisible)
00093     {
00094         rootPage->NotifyUserBackgroundThread("Clipboard content has changed!", NotifyType::StatusMessage);
00095         DisplayFormats(DataTransfer::Clipboard::GetContent());
00096     }
00097     else
00098     {
00099         // Background applications can't access clipboard
00100         // Deferring processing of update notification until the application returns to foreground
00101         needToPrintClipboardFormat = true;
00102     }
00103 }
00104
00105 void Others::OnVisibilityChanged(Object^ sender, VisibilityChangedEventArgs^ e)
00106 {
00107     windowVisible = e->Visible;
00108     if (windowVisible && needToPrintClipboardFormat)
00109     {
00110         HandleClipboardChanged();
00111     }
00112 }
00113
00114 void Others::OnClipboardChanged(Platform::Object^ sender, Object^ e)
00115 {
00116     HandleClipboardChanged();
00117 }
00118
00119 #pragma region Others handlers
00120
00121 void Others::ShowFormatButton_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00122 {
00123     DisplayFormats(DataTransfer::Clipboard::GetContent());
00124 }
00125
00126 void Others::EmptyClipboardButton_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00127 {
00128     DisplayFormatOutputText->Text = "";
00129     try
00130     {
00131         DataTransfer::Clipboard::Clear();
00132         OutputText->Text = "Clipboard has been emptied.";
00133     }
00134     catch (Exception^ ex)
00135     {
00136         // Emptying Clipboard can potentially fail - for example, if another application is holding Clipboard open
00137         rootPage->NotifyUserBackgroundThread("Error emptying the clipboard - " + ex->Message, NotifyType::ErrorMessage);
00138     }
00139 }
00140
00141 void Others::ClearOutputButton_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00142 {
00143     ClearOutput();
00144 }
00145
00146 void Others::RegisterClipboardContentChanged_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00147 {
00148     if (registerContentChanged != RegisterClipboardContentChanged->IsChecked->Value)
00149     {
00150         ClearOutput();
00151         registerContentChanged = RegisterClipboardContentChanged->IsChecked->Value;
00152         if (registerContentChanged)
00153         {
00154             contentChangedToken = DataTransfer::Clipboard::ContentChanged += ref new EventHandler<Object^>(this, &Others::OnClipboardChanged);
00155             visibilityChangedToken = Window::Current->VisibilityChanged += ref new WindowVisibilityChangedEventHandler(this, &Others::OnVisibilityChanged);
00156             OutputText->Text = "Successfully registered for clipboard update notification.";
00157         }
00158         else
00159         {
00160             DataTransfer::Clipboard::ContentChanged -= contentChangedToken;
00161             Window::Current->VisibilityChanged -= visibilityChangedToken;
00162             OutputText->Text = "Successfully un-registered for clipboard update notification.";
00163         }
00164     }
00165 }
00166
00167 #pragma endregion
Generated on Sat Nov 23 2024 16:07:59 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::WASAPIAudio::MFSampleGenerator Member List

This is the complete list of members for SDKSample::WASAPIAudio::MFSampleGenerator, including all inherited members.
AddSamplesToQueue(IMFSample *MFSample) | SDKSample::WASAPIAudio::MFSampleGenerator | [private]
ConfigureStreams() | SDKSample::WASAPIAudio::MFSampleGenerator | [private]
CreateAudioType(IMFMediaType **MediaType) | SDKSample::WASAPIAudio::MFSampleGenerator | [private]
dwStreamFlags | SDKSample::WASAPIAudio::MFSampleGenerator |
dwStreamIndex | SDKSample::WASAPIAudio::MFSampleGenerator |
FillSampleBuffer(UINT32 BytesToRead, BYTE *Data, UINT32 *cbWritten) | SDKSample::WASAPIAudio::MFSampleGenerator |
Flush() | SDKSample::WASAPIAudio::MFSampleGenerator |
Initialize(IRandomAccessStream^stream, UINT32 FramesPerPeriod, WAVEFORMATEX *wfx) | SDKSample::WASAPIAudio::MFSampleGenerator |
IsEOF() | SDKSample::WASAPIAudio::MFSampleGenerator | [inline]
IsPreRollFilled() | SDKSample::WASAPIAudio::MFSampleGenerator | [private]
llTimestamp | SDKSample::WASAPIAudio::MFSampleGenerator |
m_AudioMT | SDKSample::WASAPIAudio::MFSampleGenerator | [private]
m_BytesPerPeriod | SDKSample::WASAPIAudio::MFSampleGenerator | [private]
m_ContentStream | SDKSample::WASAPIAudio::MFSampleGenerator | [private]
m_IsInitialized | SDKSample::WASAPIAudio::MFSampleGenerator | [private]
m_MFSourceReader | SDKSample::WASAPIAudio::MFSampleGenerator | [private]
m_MixFormat | SDKSample::WASAPIAudio::MFSampleGenerator | [private]
m_ReaderState | SDKSample::WASAPIAudio::MFSampleGenerator | [private]
m_Ref | SDKSample::WASAPIAudio::MFSampleGenerator | [private]
m_SampleQueue | SDKSample::WASAPIAudio::MFSampleGenerator | [private]
m_SampleQueueTail | SDKSample::WASAPIAudio::MFSampleGenerator | [private]
MFSampleGenerator() | SDKSample::WASAPIAudio::MFSampleGenerator |
pSample | SDKSample::WASAPIAudio::MFSampleGenerator |
ReaderState enum name | SDKSample::WASAPIAudio::MFSampleGenerator |
ReaderStateEOS enum value | SDKSample::WASAPIAudio::MFSampleGenerator |
ReaderStatePlaying enum value | SDKSample::WASAPIAudio::MFSampleGenerator |
ReaderStatePreRoll enum value | SDKSample::WASAPIAudio::MFSampleGenerator |
ReaderStateStopped enum value | SDKSample::WASAPIAudio::MFSampleGenerator |
Shutdown() | SDKSample::WASAPIAudio::MFSampleGenerator |
StartSource() | SDKSample::WASAPIAudio::MFSampleGenerator |
STDMETHODIMP_(ULONG) AddRef() | SDKSample::WASAPIAudio::MFSampleGenerator | [inline]
STDMETHODIMP_(ULONG) Release() | SDKSample::WASAPIAudio::MFSampleGenerator | [inline]
STDMETHODIMP_(HRESULT) QueryInterface(const IID &riid | SDKSample::WASAPIAudio::MFSampleGenerator |
STDMETHODIMP_(HRESULT) OnFlush(_In_ DWORD dwStreamIndex) | SDKSample::WASAPIAudio::MFSampleGenerator |
STDMETHODIMP_(HRESULT) OnReadSample(_In_ HRESULT hrStatus | SDKSample::WASAPIAudio::MFSampleGenerator |
StopSource() | SDKSample::WASAPIAudio::MFSampleGenerator |
~MFSampleGenerator() | SDKSample::WASAPIAudio::MFSampleGenerator | [private]
Generated on Sat Nov 23 2024 16:09:53 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media Server client/C++/common/suspensionmanager.cpp Source File

  • Media Server client
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:36 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/Common/BooleanNegationConverter.h Source File

  • Hilo C++
  • Hilo
  • Common

BooleanNegationConverter.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
00009 namespace Hilo
00010 {
00011   namespace Common
00012   {
00013     /// <summary>
00014     /// Value converter that translates true to false and vice versa.
00015     /// </summary>
00016     [Windows::Foundation::Metadata::WebHostHidden]
00017     public ref class BooleanNegationConverter sealed : Windows::UI::Xaml::Data::IValueConverter
00018     {
00019     public:
00020       virtual Platform::Object^ Convert(Platform::Object^ value, Windows::UI::Xaml::Interop::TypeName targetType, Platform::Object^ parameter, Platform::String^ language);
00021       virtual Platform::Object^ ConvertBack(Platform::Object^ value, Windows::UI::Xaml::Interop::TypeName targetType, Platform::Object^ parameter, Platform::String^ language);
00022     };
00023   }
00024 }
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D tutorial/C++/Lesson5.Components/BasicLoader.h Source File

  • Direct3D tutorial
  • Lesson5.Components

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 Sat Nov 23 2024 16:08:08 for Win8-Examples by doxygen 1.7.1


Win8-Examples: UI contrast and settings/C++/Accessibility.xaml.h Source File

  • UI contrast and settings

Accessibility.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 // Accessibility.xaml.h
00013 // Declaration of the Accessibility class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Accessibility.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace HighContrast
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 Accessibility sealed
00031         {
00032         public:
00033             Accessibility();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void AccessibilityGetSettings_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

BasicTimer Member List

This is the complete list of members for BasicTimer, including all inherited members.
__pad0__ | BasicTimer | [private]
m_currentTime | BasicTimer | [private]
m_delta | BasicTimer | [private]
m_frequency | BasicTimer | [private]
m_lastTime | BasicTimer | [private]
m_startTime | BasicTimer | [private]
m_total | BasicTimer | [private]
Reset() | BasicTimer | [private]
Reset() | BasicTimer | [private]
Reset() | BasicTimer | [private]
Reset() | BasicTimer | [private]
Reset() | BasicTimer | [private]
Reset() | BasicTimer | [private]
Reset() | BasicTimer | [private]
Reset() | BasicTimer | [private]
Reset() | BasicTimer | [private]
Reset() | BasicTimer | [private]
Reset() | BasicTimer | [private]
Reset() | BasicTimer | [private]
Reset() | BasicTimer | [private]
Reset() | BasicTimer | [private]
Reset() | BasicTimer | [private]
Reset() | BasicTimer | [private]
Reset() | BasicTimer | [private]
Reset() | BasicTimer | [private]
Reset() | BasicTimer | [private]
Reset() | BasicTimer | [private]
Update() | BasicTimer | [private]
Update() | BasicTimer | [private]
Update() | BasicTimer | [private]
Update() | BasicTimer | [private]
Update() | BasicTimer | [private]
Update() | BasicTimer | [private]
Update() | BasicTimer | [private]
Update() | BasicTimer | [private]
Update() | BasicTimer | [private]
Update() | BasicTimer | [private]
Update() | BasicTimer | [private]
Update() | BasicTimer | [private]
Update() | BasicTimer | [private]
Update() | BasicTimer | [private]
Update() | BasicTimer | [private]
Update() | BasicTimer | [private]
Update() | BasicTimer | [private]
Update() | BasicTimer | [private]
Update() | BasicTimer | [private]
Update() | BasicTimer | [private]
Generated on Sat Nov 23 2024 16:09:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/Level6.cpp Source File

  • DirectX 3D shooting game

Level6.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 "Level6.h"
00010
00011 //----------------------------------------------------------------------
00012
00013 Level6::Level6()
00014 {
00015     m_timeLimit = 20.0f;
00016     m_objective = "Hit as many moving targets as possible while avoiding the obstacles before time runs out.";
00017 }
00018
00019 //----------------------------------------------------------------------
00020
00021 bool Level6::Update(
00022     float time,
00023     float elapsedTime,
00024     float timeRemaining,
00025     std::vector<GameObject^> objects
00026     )
00027 {
00028     for (auto object = objects.begin(); object != objects.end(); object++)
00029     {
00030         if ((*object)->Active() && (*object)->Target())
00031         {
00032             if ((*object)->Hit() && ((*object)->HitTime() < (time - 2.0f)))
00033             {
00034                 (*object)->Hit(false);
00035             }
00036         }
00037     }
00038     return ((timeRemaining - elapsedTime) <= 0.0f);
00039 }
00040
00041 //----------------------------------------------------------------------
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML vector-based drawing/C++/common/suspensionmanager.cpp Source File

  • XAML vector-based drawing
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/MediaReader.h Source File

  • DirectX 3D shooting game

MediaReader.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 // MediaReader:
00011 // This is a helper class for the SoundEffect class.  It reads small audio files
00012 // synchronously from the package installed folder and returns sound data as a
00013 // byte array.
00014
00015 ref class MediaReader
00016 {
00017 internal:
00018     MediaReader();
00019
00020     Platform::Array<byte>^          LoadMedia(_In_ Platform::String^ filename);
00021     WAVEFORMATEX*                   GetOutputWaveFormatEx();
00022
00023 protected private:
00024     Windows::Storage::StorageFolder^ m_installedLocation;
00025     Platform::String^               m_installedLocationPath;
00026     WAVEFORMATEX                    m_waveFormat;
00027 };
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DatagramSocketSample::Common::LayoutAwarePage Member List

This is the complete list of members for DatagramSocketSample::Common::LayoutAwarePage, including all inherited members.
__pad0__ | DatagramSocketSample::Common::LayoutAwarePage |
_defaultViewModel | DatagramSocketSample::Common::LayoutAwarePage | [private]
_layoutAwareControls | DatagramSocketSample::Common::LayoutAwarePage | [private]
_windowSizeEventToken | DatagramSocketSample::Common::LayoutAwarePage | [private]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | DatagramSocketSample::Common::LayoutAwarePage | [virtual]
GoBack(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | DatagramSocketSample::Common::LayoutAwarePage | [virtual]
InvalidateVisualState() | DatagramSocketSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | DatagramSocketSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | DatagramSocketSample::Common::LayoutAwarePage |
WindowSizeChanged(Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | DatagramSocketSample::Common::LayoutAwarePage | [private]
Generated on Sat Nov 23 2024 16:09:37 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Snap/C++/common/suspensionmanager.h Source File

  • Snap
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Certificate enrollment/C++/common/LayoutAwarePage.cpp Source File

  • Certificate enrollment
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:30 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Folder enumeration/C++/common/LayoutAwarePage.h Source File

  • Folder enumeration
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-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 |
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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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 *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 *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 *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 *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 *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 *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 *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 *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 *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 *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 *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 *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 *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 *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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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_ Platform::String^filename) | BasicLoader | [private]
GetExtension(_In_ Platform::String^filename) | BasicLoader | [private]
GetExtension(_In_ Platform::String^filename) | BasicLoader | [private]
GetExtension(_In_ Platform::String^filename) | BasicLoader | [private]
GetExtension(_In_ Platform::String^filename) | BasicLoader | [private]
GetExtension(_In_ Platform::String^filename) | BasicLoader | [private]
GetExtension(_In_ Platform::String^filename) | BasicLoader | [private]
GetExtension(_In_ Platform::String^filename) | BasicLoader | [private]
GetExtension(_In_ Platform::String^filename) | BasicLoader | [private]
GetExtension(_In_ Platform::String^filename) | BasicLoader | [private]
GetExtension(_In_ Platform::String^filename) | BasicLoader | [private]
GetExtension(_In_ Platform::String^filename) | BasicLoader | [private]
GetExtension(_In_ Platform::String^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_ Platform::String^filename, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ uint32 *vertexCount, _Out_opt_ uint32 *indexCount) | BasicLoader |
LoadMesh(_In_ Platform::String^filename, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ uint32 *vertexCount, _Out_opt_ uint32 *indexCount) | BasicLoader |
LoadMesh(_In_ Platform::String^filename, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ uint32 *vertexCount, _Out_opt_ uint32 *indexCount) | BasicLoader |
LoadMesh(_In_ Platform::String^filename, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ uint32 *vertexCount, _Out_opt_ uint32 *indexCount) | BasicLoader |
LoadMesh(_In_ Platform::String^filename, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ uint32 *vertexCount, _Out_opt_ uint32 *indexCount) | BasicLoader |
LoadMesh(_In_ Platform::String^filename, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ uint32 *vertexCount, _Out_opt_ uint32 *indexCount) | BasicLoader |
LoadMesh(_In_ Platform::String^filename, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ uint32 *vertexCount, _Out_opt_ uint32 *indexCount) | BasicLoader |
LoadMesh(_In_ Platform::String^filename, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ uint32 *vertexCount, _Out_opt_ uint32 *indexCount) | BasicLoader |
LoadMesh(_In_ Platform::String^filename, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ uint32 *vertexCount, _Out_opt_ uint32 *indexCount) | BasicLoader |
LoadMesh(_In_ Platform::String^filename, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ uint32 *vertexCount, _Out_opt_ uint32 *indexCount) | BasicLoader |
LoadMesh(_In_ Platform::String^filename, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ uint32 *vertexCount, _Out_opt_ uint32 *indexCount) | BasicLoader |
LoadMesh(_In_ Platform::String^filename, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ uint32 *vertexCount, _Out_opt_ uint32 *indexCount) | BasicLoader |
LoadMesh(_In_ Platform::String^filename, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ uint32 *vertexCount, _Out_opt_ uint32 *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_ 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_ 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_ 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_ 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_ 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_ 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_ 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 |
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_ 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_ 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_ 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_ 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_ 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_ 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_ 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_ 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_ 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_ 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_ 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_ 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_ 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_ 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_ 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_ 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_ 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_ 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_ 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_ 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_ 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_ 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_ 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_ 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_ 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_ 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_ 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_ 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_ Platform::String^filename, _Out_opt_ ID3D11Texture2D **texture, _Out_opt_ ID3D11ShaderResourceView **textureView) | BasicLoader |
LoadTexture(_In_ Platform::String^filename, _Out_opt_ ID3D11Texture2D **texture, _Out_opt_ ID3D11ShaderResourceView **textureView) | BasicLoader |
LoadTexture(_In_ Platform::String^filename, _Out_opt_ ID3D11Texture2D **texture, _Out_opt_ ID3D11ShaderResourceView **textureView) | BasicLoader |
LoadTexture(_In_ Platform::String^filename, _Out_opt_ ID3D11Texture2D **texture, _Out_opt_ ID3D11ShaderResourceView **textureView) | BasicLoader |
LoadTexture(_In_ Platform::String^filename, _Out_opt_ ID3D11Texture2D **texture, _Out_opt_ ID3D11ShaderResourceView **textureView) | BasicLoader |
LoadTexture(_In_ Platform::String^filename, _Out_opt_ ID3D11Texture2D **texture, _Out_opt_ ID3D11ShaderResourceView **textureView) | BasicLoader |
LoadTexture(_In_ Platform::String^filename, _Out_opt_ ID3D11Texture2D **texture, _Out_opt_ ID3D11ShaderResourceView **textureView) | BasicLoader |
LoadTexture(_In_ Platform::String^filename, _Out_opt_ ID3D11Texture2D **texture, _Out_opt_ ID3D11ShaderResourceView **textureView) | BasicLoader |
LoadTexture(_In_ Platform::String^filename, _Out_opt_ ID3D11Texture2D **texture, _Out_opt_ ID3D11ShaderResourceView **textureView) | BasicLoader |
LoadTexture(_In_ Platform::String^filename, _Out_opt_ ID3D11Texture2D **texture, _Out_opt_ ID3D11ShaderResourceView **textureView) | BasicLoader |
LoadTexture(_In_ Platform::String^filename, _Out_opt_ ID3D11Texture2D **texture, _Out_opt_ ID3D11ShaderResourceView **textureView) | BasicLoader |
LoadTexture(_In_ Platform::String^filename, _Out_opt_ ID3D11Texture2D **texture, _Out_opt_ ID3D11ShaderResourceView **textureView) | BasicLoader |
LoadTexture(_In_ Platform::String^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_ 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_ 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_ 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_ 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_ 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_ 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_ 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 |
m_basicReaderWriter | BasicLoader | [private]
m_d3dDevice | BasicLoader | [private]
m_wicFactory | BasicLoader | [private]
SetDebugName(_In_ DeviceChildType *object, _In_ Platform::String^name) | BasicLoader | [inline, private]
SetDebugName(_In_ DeviceChildType *object, _In_ Platform::String^name) | BasicLoader | [inline, private]
SetDebugName(_In_ DeviceChildType *object, _In_ Platform::String^name) | BasicLoader | [inline, private]
SetDebugName(_In_ DeviceChildType *object, _In_ Platform::String^name) | BasicLoader | [inline, private]
SetDebugName(_In_ DeviceChildType *object, _In_ Platform::String^name) | BasicLoader | [inline, private]
SetDebugName(_In_ DeviceChildType *object, _In_ Platform::String^name) | BasicLoader | [inline, private]
SetDebugName(_In_ DeviceChildType *object, _In_ Platform::String^name) | BasicLoader | [inline, private]
SetDebugName(_In_ DeviceChildType *object, _In_ Platform::String^name) | BasicLoader | [inline, private]
SetDebugName(_In_ DeviceChildType *object, _In_ Platform::String^name) | BasicLoader | [inline, private]
SetDebugName(_In_ DeviceChildType *object, _In_ Platform::String^name) | BasicLoader | [inline, private]
SetDebugName(_In_ DeviceChildType *object, _In_ Platform::String^name) | BasicLoader | [inline, private]
SetDebugName(_In_ DeviceChildType *object, _In_ Platform::String^name) | BasicLoader | [inline, private]
SetDebugName(_In_ DeviceChildType *object, _In_ Platform::String^name) | BasicLoader | [inline, private]
SetDebugName(_In_ DeviceChildType *object, _In_ Platform::String^name) | BasicLoader | [inline, private]
SetDebugName(_In_ DeviceChildType *object, _In_ Platform::String^name) | BasicLoader | [inline, private]
wicFactory | BasicLoader |
Generated on Sat Nov 23 2024 16:09:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Account picture name/C++/common/LayoutAwarePage.cpp Source File

  • Account picture name
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013
00014 using namespace AccountPictureName::Common;
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::UI::ViewManagement;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Interop;
00024
00025 /// <summary>
00026 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00027 /// </summary>
00028 LayoutAwarePage::LayoutAwarePage()
00029 {
00030     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled) return;
00031
00032     // Create an empty default view model
00033     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00034
00035     // Map application view state to visual state for this page when it is part of the visual tree
00036     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::StartLayoutUpdates);
00037     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::StopLayoutUpdates);
00038 }
00039
00040 static TypeName _thisType = { LayoutAwarePage::typeid->FullName, TypeKind::Custom };
00041 static TypeName _observableMapType = { IObservableMap<Platform::String^, Object^>::typeid->FullName, TypeKind::Metadata };
00042 static Windows::UI::Xaml::DependencyProperty^ _defaultViewModelProperty =
00043     DependencyProperty::Register("DefaultViewModel", _observableMapType, _thisType, nullptr);
00044
00045 /// <summary>
00046 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00047 /// </summary>
00048 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00049 {
00050     return _defaultViewModelProperty;
00051 }
00052
00053 /// <summary>
00054 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00055 /// used as a trivial view model.
00056 /// </summary>
00057 IObservableMap<Platform::String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00058 {
00059     return safe_cast<Windows::Foundation::Collections::IObservableMap<Platform::String^, Object^>^>(GetValue(DefaultViewModelProperty));
00060 }
00061
00062 /// <summary>
00063 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00064 /// used as a trivial view model.
00065 /// </summary>
00066 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<Platform::String^, Object^>^ value)
00067 {
00068     SetValue(DefaultViewModelProperty, value);
00069 }
00070
00071 /// <summary>
00072 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00073 /// until it reaches the top of the navigation stack.
00074 /// </summary>
00075 /// <param name="sender">Instance that triggered the event.</param>
00076 /// <param name="e">Event data describing the conditions that led to the event.</param>
00077 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00078 {
00079     // Use the navigation frame to return to the topmost page
00080     if (Frame != nullptr)
00081     {
00082         while (Frame->CanGoBack) Frame->GoBack();
00083     }
00084 }
00085
00086 /// <summary>
00087 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00088 /// to go back one step on the navigation stack.
00089 /// </summary>
00090 /// <param name="sender">Instance that triggered the event.</param>
00091 /// <param name="e">Event data describing the conditions that led to the event.</param>
00092 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00093 {
00094     // Use the navigation frame to return to the previous page
00095     if (Frame != nullptr && Frame->CanGoBack) Frame->GoBack();
00096 }
00097
00098 /// <summary>
00099 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00100 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00101 /// visual state management changes that correspond to application view state changes.
00102 /// </summary>
00103 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00104 /// corresponding to view states.</param>
00105 /// <param name="e">Event data that describes how the request was made.</param>
00106 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00107 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00108 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00109 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00110 /// events.</remarks>
00111 /// <seealso cref="DetermineVisualState"/>
00112 /// <seealso cref="InvalidateVisualState"/>
00113 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00114 {
00115     auto control = safe_cast<Control^>(sender);
00116     if (_layoutAwareControls == nullptr) {
00117         // Start listening to view state changes when there are controls interested in updates
00118         _layoutAwareControls = ref new Vector<Control^>();
00119         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00120     }
00121     _layoutAwareControls->Append(control);
00122
00123     // Set the initial visual state of the control
00124     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00125 }
00126
00127 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00128 {
00129     InvalidateVisualState();
00130 }
00131
00132 /// <summary>
00133 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00134 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00135 /// management changes that correspond to application view state changes.
00136 /// </summary>
00137 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00138 /// corresponding to view states.</param>
00139 /// <param name="e">Event data that describes how the request was made.</param>
00140 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00141 /// when layout updates are requested.</remarks>
00142 /// <seealso cref="StartLayoutUpdates"/>
00143 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00144 {
00145     auto control = safe_cast<Control^>(sender);
00146     unsigned int index;
00147     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00148     {
00149         _layoutAwareControls->RemoveAt(index);
00150         if (_layoutAwareControls->Size == 0)
00151         {
00152             // Stop listening to view state changes when no controls are interested in updates
00153             Window::Current->SizeChanged -= _windowSizeEventToken;
00154             _layoutAwareControls = nullptr;
00155         }
00156     }
00157 }
00158
00159 /// <summary>
00160 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00161 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00162 /// override this method to control the mapping scheme used.
00163 /// </summary>
00164 /// <param name="viewState">View state for which a visual state is desired.</param>
00165 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00166 /// <seealso cref="InvalidateVisualState"/>
00167 Platform::String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00168 {
00169     switch (viewState)
00170     {
00171     case ApplicationViewState::Filled: return "Filled";
00172     case ApplicationViewState::Snapped: return "Snapped";
00173     case ApplicationViewState::FullScreenPortrait: return "FullScreenPortrait";
00174     default: case ApplicationViewState::FullScreenLandscape: return "FullScreenLandscape";
00175     }
00176 }
00177
00178 /// <summary>
00179 /// Updates all controls that are listening for visual state changes with the correct visual
00180 /// state.
00181 /// </summary>
00182 /// <remarks>
00183 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00184 /// signal that a different value may be returned even though the view state has not changed.
00185 /// </remarks>
00186 void LayoutAwarePage::InvalidateVisualState()
00187 {
00188     if (_layoutAwareControls != nullptr)
00189     {
00190         String^ visualState = DetermineVisualState(ApplicationView::Value);
00191         auto controlIterator = _layoutAwareControls->First();
00192         while (controlIterator->HasCurrent)
00193         {
00194             auto control = controlIterator->Current;
00195             VisualStateManager::GoToState(control, visualState, false);
00196             controlIterator->MoveNext();
00197         }
00198     }
00199 }
Generated on Sat Nov 23 2024 16:07:30 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Store device app for camera/C#,C++/DeviceAppPage.xaml.cs Source File

  • Windows Store device app for camera
  • C#,C++

DeviceAppPage.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 System;
00009 using System.Threading.Tasks;
00010 using Windows.Foundation;
00011 using Windows.UI.Xaml;
00012 using Windows.UI.Xaml.Controls;
00013 using Windows.UI.Xaml.Data;
00014 using Windows.ApplicationModel.Activation;
00015 using Windows.Media.Devices;
00016 using System.Runtime.InteropServices;
00017 using Wrapper;
00018
00019 namespace SDKTemplate
00020 {
00021     partial class DeviceAppPage
00022     {
00023         VideoDeviceController videoDevController = null;
00024         Wrapper.WinRTComponent lcWrapper = null;
00025
00026         public DeviceAppPage()
00027         {
00028             InitializeComponent();
00029         }
00030
00031         public void Initialize(CameraSettingsActivatedEventArgs args)
00032         {
00033             videoDevController = (VideoDeviceController)args.VideoDeviceController;
00034
00035             if (args.VideoDeviceExtension != null)
00036             {
00037                 lcWrapper = new WinRTComponent();
00038                 lcWrapper.Initialize(args.VideoDeviceExtension);
00039             }
00040
00041             bool bAuto = false;
00042             double value = 0.0;
00043
00044             if (videoDevController.Brightness.Capabilities.Step != 0)
00045             {
00046                 slBrt.Minimum = videoDevController.Brightness.Capabilities.Min;
00047                 slBrt.Maximum = videoDevController.Brightness.Capabilities.Max;
00048                 slBrt.StepFrequency = videoDevController.Brightness.Capabilities.Step;
00049                 videoDevController.Brightness.TryGetValue(out value);
00050                 slBrt.Value = value;
00051             }
00052             else
00053             {
00054                 slBrt.IsEnabled = false;
00055             }
00056             if (videoDevController.Brightness.Capabilities.AutoModeSupported)
00057             {
00058                 videoDevController.Brightness.TryGetAuto(out bAuto);
00059                 tsBrtAuto.IsOn = bAuto;
00060             }
00061             else
00062             {
00063                 tsBrtAuto.IsOn = false;
00064                 tsBrtAuto.IsEnabled = false;
00065             }
00066
00067             if (videoDevController.Contrast.Capabilities.Step != 0)
00068             {
00069                 slCrt.Minimum = videoDevController.Contrast.Capabilities.Min;
00070                 slCrt.Maximum = videoDevController.Contrast.Capabilities.Max;
00071                 slCrt.StepFrequency = videoDevController.Contrast.Capabilities.Step;
00072                 videoDevController.Contrast.TryGetValue(out value);
00073                 slCrt.Value = value;
00074             }
00075             else
00076             {
00077                 slCrt.IsEnabled = false;
00078             }
00079             if (videoDevController.Contrast.Capabilities.AutoModeSupported)
00080             {
00081                 videoDevController.Contrast.TryGetAuto(out bAuto);
00082                 tsCrtAuto.IsOn = bAuto;
00083             }
00084             else
00085             {
00086                 tsCrtAuto.IsOn = false;
00087                 tsCrtAuto.IsEnabled = false;
00088             }
00089
00090             if (videoDevController.Focus.Capabilities.Step != 0)
00091             {
00092                 slFocus.Minimum = videoDevController.Focus.Capabilities.Min;
00093                 slFocus.Maximum = videoDevController.Focus.Capabilities.Max;
00094                 slFocus.StepFrequency = videoDevController.Focus.Capabilities.Step;
00095                 videoDevController.Focus.TryGetValue(out value);
00096                 slFocus.Value = value;
00097             }
00098             else
00099             {
00100                 slFocus.IsEnabled = false;
00101             }
00102             if (videoDevController.Focus.Capabilities.AutoModeSupported)
00103             {
00104                 videoDevController.Focus.TryGetAuto(out bAuto);
00105                 tsFocusAuto.IsOn = bAuto;
00106             }
00107             else
00108             {
00109                 tsFocusAuto.IsOn = false;
00110                 tsFocusAuto.IsEnabled = false;
00111             }
00112
00113             if (videoDevController.Exposure.Capabilities.Step != 0)
00114             {
00115                 slExp.Minimum = videoDevController.Exposure.Capabilities.Min;
00116                 slExp.Maximum = videoDevController.Exposure.Capabilities.Max;
00117                 slExp.StepFrequency = videoDevController.Exposure.Capabilities.Step;
00118                 videoDevController.Exposure.TryGetValue(out value);
00119                 slExp.Value = value;
00120             }
00121             else
00122             {
00123                 slExp.IsEnabled = false;
00124             }
00125             if (videoDevController.Exposure.Capabilities.AutoModeSupported)
00126             {
00127                 videoDevController.Exposure.TryGetAuto(out bAuto);
00128                 tsExpAuto.IsOn = bAuto;
00129             }
00130             else
00131             {
00132                 tsExpAuto.IsOn = false;
00133                 tsExpAuto.IsEnabled = false;
00134             }
00135
00136             if (lcWrapper != null)
00137             {
00138                 slEffect.Minimum = 0;
00139                 slEffect.Maximum = 100;
00140                 slEffect.StepFrequency = 1;
00141
00142                 DspSettings dspSettings = lcWrapper.GetDspSetting();
00143                 slEffect.Value = dspSettings.percentOfScreen;
00144
00145                 if (dspSettings.isEnabled == 1)
00146                 {
00147                     tsEffectEnabled.IsOn = true;
00148                 }
00149                 else
00150                 {
00151                     tsEffectEnabled.IsOn = false;
00152                     slEffect.IsEnabled = false;
00153                 }
00154             }
00155             else
00156             {
00157                 tsEffectEnabled.IsEnabled = false;
00158                 slEffect.IsEnabled = false;
00159             }
00160         }
00161
00162         protected void OnBrtAutoToggleChanged(object sender, RoutedEventArgs e)
00163         {
00164             videoDevController.Brightness.TrySetAuto(tsBrtAuto.IsOn);
00165             slBrt.IsEnabled = !tsBrtAuto.IsOn;
00166         }
00167
00168         protected void OnBrtSliderValueChanged(object sender, RoutedEventArgs e)
00169         {
00170             videoDevController.Brightness.TrySetValue(slBrt.Value);
00171         }
00172
00173         protected void OnCrtAutoToggleChanged(object sender, RoutedEventArgs e)
00174         {
00175             videoDevController.Contrast.TrySetAuto(tsCrtAuto.IsOn);
00176             slCrt.IsEnabled = !tsCrtAuto.IsOn;
00177         }
00178
00179         protected void OnCrtSliderValueChanged(object sender, RoutedEventArgs e)
00180         {
00181             videoDevController.Contrast.TrySetValue(slCrt.Value);
00182         }
00183
00184         protected void OnFocusAutoToggleChanged(object sender, RoutedEventArgs e)
00185         {
00186             videoDevController.Focus.TrySetAuto(tsFocusAuto.IsOn);
00187             slFocus.IsEnabled = !tsFocusAuto.IsOn;
00188         }
00189
00190         protected void OnFocusSliderValueChanged(object sender, RoutedEventArgs e)
00191         {
00192             videoDevController.Focus.TrySetValue(slFocus.Value);
00193         }
00194
00195         protected void OnExpAutoToggleChanged(object sender, RoutedEventArgs e)
00196         {
00197             videoDevController.Exposure.TrySetAuto(tsExpAuto.IsOn);
00198             slExp.IsEnabled = !tsExpAuto.IsOn;
00199         }
00200
00201         protected void OnExpSliderValueChanged(object sender, RoutedEventArgs e)
00202         {
00203             videoDevController.Exposure.TrySetValue(slExp.Value);
00204         }
00205
00206         protected void OnEffectEnabledToggleChanged(object sender, RoutedEventArgs e)
00207         {
00208             if (tsEffectEnabled.IsOn)
00209             {
00210                 lcWrapper.Enable();
00211             }
00212             else
00213             {
00214                 lcWrapper.Disable();
00215             }
00216             slEffect.IsEnabled = tsEffectEnabled.IsOn;
00217         }
00218
00219         protected void OnEffectSliderValueChanged(object sender, RoutedEventArgs e)
00220         {
00221             lcWrapper.UpdateDsp(Convert.ToInt32(slEffect.Value));
00222         }
00223     }
00224 }
Generated on Sat Nov 23 2024 16:08:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application resources and localization/C++/Scenario5.xaml.cpp Source File

  • Application resources and localization

Scenario5.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 // Scenario5.xaml.cpp
00013 // Implementation of the Scenario5 class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario5.xaml.h"
00018
00019 using namespace SDKSample::ApplicationResources;
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 Scenario5::Scenario5()
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 Scenario5::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   this->Scenario5TextBlock->Text = "";
00042 }
00043
00044
00045 void Scenario5::Scenario5Button_Show_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00046 {
00047     Button^ b = safe_cast<Button^>(sender);
00048     if (b != nullptr)
00049     {
00050         auto resourceLoader = ref new ResourceLoader("Errors");
00051         this->Scenario5TextBlock->Text = resourceLoader->GetString("InvalidOperation");
00052     }
00053 }
00054
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/Level1.h Source File

  • XAML DirectX 3D shooting game

Level1.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 // Level1:
00011 // This class defines the first level of the game.  There are nine active targets.
00012 // Each of the targets is stationary and can be hit in any order.
00013
00014 #include "Level.h"
00015
00016 ref class Level1: public Level
00017 {
00018 internal:
00019     Level1();
00020     virtual void Initialize(std::vector<GameObject^> objects) override;
00021 };
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Compass sensor/C++/App.xaml.h Source File

  • Compass sensor

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Hilo::IPhoto Member List

This is the complete list of members for Hilo::IPhoto, including all inherited members.
OpenReadAsync() Hilo::IPhoto
Generated on Sat Nov 23 2024 16:09:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text editing/C++/Scenario1.xaml.cpp Source File

  • XAML text editing

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::TextEditing;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 Scenario1::Scenario1()
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 Scenario1::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 SDKSample::TextEditing::Scenario1::Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00043 {
00044     Button^ b = safe_cast<Button^>(sender);
00045     if (b != nullptr)
00046     {
00047         rootPage->NotifyUser("You clicked the " + b->Name + " button", NotifyType::StatusMessage);
00048     }
00049 }
00050
00051 void SDKSample::TextEditing::Scenario1::Other_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00052 {
00053     Button^ b = safe_cast<Button^>(sender);
00054     if (b != nullptr)
00055     {
00056         rootPage->NotifyUser("You clicked the " + b->Name + " button", NotifyType::StatusMessage);
00057     }
00058 }
Generated on Sat Nov 23 2024 16:07:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML user and custom controls/C++/Scenario1.xaml.cpp Source File

  • XAML user and custom controls

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::UserAndCustomControls;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 Scenario1::Scenario1()
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 Scenario1::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 SDKSample::UserAndCustomControls::Scenario1::Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00043 {
00044     Button^ b = safe_cast<Button^>(sender);
00045     if (b != nullptr)
00046     {
00047         rootPage->NotifyUser("You clicked the " + b->Name + " button", NotifyType::StatusMessage);
00048     }
00049 }
00050
00051 void SDKSample::UserAndCustomControls::Scenario1::Other_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00052 {
00053     Button^ b = safe_cast<Button^>(sender);
00054     if (b != nullptr)
00055     {
00056         rootPage->NotifyUser("You clicked the " + b->Name + " button", NotifyType::StatusMessage);
00057     }
00058 }
Generated on Sat Nov 23 2024 16:07:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/ScenarioOutput2.xaml.h Source File

  • Media extensions

ScenarioOutput2.xaml.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 //
00009 // Scenario2Output.xaml.h
00010 // Declaration of the Scenario2Output class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioOutput2.g.h"
00017 #include "MainPage.g.h"
00018
00019 namespace MediaExtensionsCPP
00020 {
00021     [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class ScenarioOutput2 sealed
00023     {
00024     public:
00025         ScenarioOutput2();
00026
00027     protected:
00028         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030
00031     private:
00032         ~ScenarioOutput2();
00033         MainPage^ rootPage;
00034         Windows::Foundation::EventRegistrationToken _mediaFailedToken;
00035     };
00036 }
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D stereoscopic 3D/C++/BasicLoader.cpp Source File

  • Direct3D stereoscopic 3D

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 Sat Nov 23 2024 16:08:07 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playback Manager msAudioCategory/C++/StreamTypeAlert.xaml.cpp Source File

  • Playback Manager msAudioCategory

StreamTypeAlert.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 // StreamTypeAlert.xaml.cpp
00013 // Implementation of the StreamTypeAlert class
00014 //
00015
00016 #include "pch.h"
00017 #include "StreamTypeAlert.xaml.h"
00018
00019 using namespace SDKSample::PlaybackManager;
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::UI::Xaml::Media;
00025
00026 StreamTypeAlert::StreamTypeAlert()
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 StreamTypeAlert::OnNavigatedTo(NavigationEventArgs^ e)
00037 {
00038     // Get a pointer to our main page.
00039     rootPage = MainPage::Current;
00040 }
00041
00042
00043 void StreamTypeAlert::Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00044 {
00045   Playback->SetAudioCategory(AudioCategory::Alerts);
00046     Playback->SelectFile();
00047 }
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: SMS background task/C++/SmsBackgroundTaskSample/App.xaml.cpp Source File

  • SMS background task
  • SmsBackgroundTaskSample

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:28 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

AudioEngineCallbacks Member List

This is the complete list of members for AudioEngineCallbacks, including all inherited members.
AudioEngineCallbacks() | AudioEngineCallbacks | [inline]
Initialize(Audio *audio) | AudioEngineCallbacks |
m_audio | AudioEngineCallbacks | [private]
OnCriticalError(HRESULT Error) | AudioEngineCallbacks |
OnProcessingPassEnd() | AudioEngineCallbacks | [inline]
OnProcessingPassStart() | AudioEngineCallbacks | [inline]
Generated on Sat Nov 23 2024 16:09:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Device app for printers SDK/C++/DeviceAppForPrinters/Constants.h Source File

  • Device app for printers SDK
  • DeviceAppForPrinters

Constants.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 namespace DeviceAppForPrinters
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"Device App For Printers");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044
00045
00046 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Lock screen apps/C#,C++/MainPage.xaml.cpp Source File

  • Lock screen apps
  • C#,C++

MainPage.xaml.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 //
00009 // MainPage.xaml.cpp
00010 // Implementation of the MainPage.xaml class.
00011 //
00012
00013 #include "pch.h"
00014 #include "MainPage.xaml.h"
00015 #include "App.xaml.h"
00016
00017 using namespace Windows::UI::Xaml;
00018 using namespace Windows::UI::Xaml::Controls;
00019 using namespace Windows::UI::Xaml::Data;
00020 using namespace Windows::System;
00021 using namespace Windows::Foundation;
00022 using namespace Platform;
00023 using namespace LockScreenAppsCPP;
00024 using namespace CppSamplesUtils;
00025 using namespace Windows::UI::Xaml::Navigation;
00026 using namespace Windows::UI::Xaml::Interop;
00027 using namespace Windows::Graphics::Display;
00028 using namespace Windows::UI::ViewManagement;
00029
00030 MainPage::MainPage()
00031 {
00032     InitializeComponent();
00033
00034     SetFeatureName("Lock Screen Apps");
00035
00036     _scenariosFrame = ScenarioList;
00037     _inputFrame = ScenarioInput;
00038     _outputFrame = ScenarioOutput;
00039
00040     _pageLoadedHandlerToken = Loaded += ref new RoutedEventHandler(this, &MainPage::Page_Loaded);
00041     _logicalDpiChangedToken = DisplayProperties::LogicalDpiChanged += ref new DisplayPropertiesEventHandler(this, &MainPage::DisplayProperties_LogicalDpiChanged);
00042     _resizeHandlerToken = Window::Current->SizeChanged += ref new Windows::UI::Xaml::WindowSizeChangedEventHandler(this, &MainPage::Page_SizeChanged);
00043 }
00044
00045 MainPage::~MainPage()
00046 {
00047 }
00048
00049 void MainPage::Page_Loaded(Object^ sender, RoutedEventArgs^ e)
00050 {
00051     // Load the ScenarioList page into the proper frame
00052     TypeName pageType = { "LockScreenAppsCPP.ScenarioList", TypeKind::Custom };
00053     ScenarioList->Navigate(pageType, this);
00054
00055     // Figure out what resolution and orientation we are in and respond appropriately.
00056     CheckResolutionAndViewState();
00057 }
00058
00059 void MainPage::SetFeatureName(String^ strFeature)
00060 {
00061     FeatureName->Text = strFeature;
00062 }
00063
00064 void MainPage::DisplayProperties_LogicalDpiChanged(Object^ sender)
00065 {
00066     CheckResolutionAndViewState();
00067 }
00068
00069 void MainPage::CheckResolutionAndViewState()
00070 {
00071     ApplicationViewState state = ApplicationView::Value;
00072     String^ stateString = ConvertViewState(state);
00073
00074     ResolutionScale scale = DisplayProperties::ResolutionScale;
00075     String^ scaleString = ConvertResolution(scale);
00076
00077     VisualStateManager::GoToState(this, stateString + scaleString, false);
00078 }
00079
00080 String^ MainPage::ConvertViewState(ApplicationViewState state)
00081 {
00082     switch(state)
00083     {
00084     case ApplicationViewState::Filled:
00085         return "Filled";
00086     case ApplicationViewState::FullScreenLandscape:
00087         return "FullScreenLandscape";
00088     case ApplicationViewState::FullScreenPortrait:
00089         return "FullScreenPortrait";
00090     case ApplicationViewState::Snapped:
00091         return "Snapped";
00092     }
00093     return "";
00094 }
00095
00096 String^ MainPage::ConvertResolution(ResolutionScale scale)
00097 {
00098     switch(scale)
00099     {
00100     case ResolutionScale::Scale100Percent:
00101         return "Scale100Percent";
00102     case ResolutionScale::Scale140Percent:
00103         return "Scale140Percent";
00104     case ResolutionScale::Scale180Percent:
00105         return "Scale180Percent";
00106     }
00107     return "";
00108 }
00109
00110 void MainPage::DoNavigation(TypeName inPageType, Windows::UI::Xaml::Controls::Frame^ inFrame, TypeName outPageType, Windows::UI::Xaml::Controls::Frame^ outFrame)
00111 {
00112     inFrame->Navigate(inPageType, this);
00113     outFrame->Navigate(outPageType, this);
00114
00115     // Raise OutputFrameLoaded so downstream pages know that the output frame content has been loaded
00116     OutputFrameLoaded(this, nullptr);
00117     // Raise InputFrameLoaded so downstream pages know that the input frame content has been loaded
00118     InputFrameLoaded(this, nullptr);
00119 }
00120
00121 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00122 {
00123     switch (type)
00124     {
00125     case NotifyType::StatusMessage:
00126         StatusBlock->Style = dynamic_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00127         break;
00128     case NotifyType::ErrorMessage:
00129         StatusBlock->Style = dynamic_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00130         break;
00131     default:
00132         break;
00133     }
00134     StatusBlock->Text = strMessage;
00135 }
00136
00137 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00138 {
00139     auto _hyperlinkButton = (HyperlinkButton^)sender;
00140     auto uri = ref new Windows::Foundation::Uri((String^)_hyperlinkButton->Tag);
00141
00142     Windows::System::Launcher::LaunchUriAsync(uri);
00143 }
00144
00145 void MainPage::Page_SizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ args)
00146 {
00147     switch (Windows::UI::ViewManagement::ApplicationView::Value)
00148     {
00149     case ApplicationViewState::Filled:
00150         VisualStateManager::GoToState(this, "Filled", false);
00151         break;
00152     case ApplicationViewState::FullScreenLandscape:
00153         VisualStateManager::GoToState(this, "FullScreenLandscape", false);
00154         break;
00155     case ApplicationViewState::Snapped:
00156         VisualStateManager::GoToState(this, "Snapped", false);
00157         break;
00158     case ApplicationViewState::FullScreenPortrait:
00159         VisualStateManager::GoToState(this, "FullScreenPortrait", false);
00160         break;
00161     }
00162 }
Generated on Sat Nov 23 2024 16:07:42 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Toast notifications/C#,C++/pch.cpp Source File

  • Toast notifications
  • C#,C++

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 //
00009 // pch.cpp
00010 // Include the standard header and generate the precompiled header.
00011 //
00012
00013 #include "pch.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite paragraph text/C++/pch.h Source File

  • DirectWrite paragraph text

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 <d3d11_1.h>
00012 #include <d2d1_1.h>
00013 #include <d2d1_1helper.h>
00014 #include <d2d1effects.h>
00015 #include <dwrite_1.h>
00016 #include <wincodec.h>
00017 #include <math.h>
00018 #include <agile.h>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: StreamSocket/C++/pch.h Source File

  • StreamSocket

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include "Sample-Utils\CppSamplesUtils.h"
00019 #include <ppltasks.h>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D 3D transform effect/C++/PersistentState.cpp Source File

  • Direct2D 3D transform effect

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 Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Extended Linguistic Services (ELS)/C++/elsutil.h Source File

  • Extended Linguistic Services (ELS)
  • C++

elsutil.h

Go to the documentation of this file.
00001 #pragma once
00002 #include <windows.h>
00003 #include <elscore.h>
00004 #include <elssrvc.h>
00005
00006 #include <string>
00007 #include <sstream>
00008
00009 namespace SDKSample
00010 {
00011     namespace ELS
00012     {
00013
00014     namespace Private
00015     {
00016       inline MAPPING_SERVICE_INFO* GetSingleELSServiceWithNoOptions(const GUID& serviceGUID)
00017       {
00018         MAPPING_ENUM_OPTIONS EnumOptions = {};
00019         EnumOptions.Size = sizeof(EnumOptions);
00020         EnumOptions.pGuid = const_cast<GUID*>(&serviceGUID);
00021
00022         DWORD dwServicesCount = 0;
00023         MAPPING_SERVICE_INFO* pService;
00024         HRESULT hr = MappingGetServices(&EnumOptions, &pService, &dwServicesCount);
00025         if (FAILED(hr))
00026         {
00027           pService = nullptr;
00028         }
00029
00030         return pService;
00031       }
00032     } //namespace Private
00033
00034     inline std::wstring RecognizeTextLanguages(_In_ PCWSTR text)
00035     {
00036       auto pService = Private::GetSingleELSServiceWithNoOptions(ELS_GUID_LANGUAGE_DETECTION);
00037       std::wstring ret;
00038       if (nullptr != pService)
00039       {
00040         MAPPING_PROPERTY_BAG bag = {};
00041         bag.Size = sizeof(bag);
00042
00043         HRESULT hr = MappingRecognizeText(pService, text, static_cast<DWORD>(wcslen(text)), 0, nullptr, &bag);
00044         if (SUCCEEDED(hr))
00045         {
00046           for (auto pos = reinterpret_cast<wchar_t*>(bag.prgResultRanges[0].pData); *pos; pos += (wcslen(pos) + 1))
00047           {
00048             ret += pos;
00049             ret += L"\n";
00050           }
00051           MappingFreePropertyBag(&bag);
00052         }
00053         MappingFreeServices(pService);
00054       }
00055
00056       return ret;
00057     }
00058
00059 inline std::wstring RecognizeTextScripts(_In_ PCWSTR text)
00060 {
00061   auto pService = Private::GetSingleELSServiceWithNoOptions(ELS_GUID_SCRIPT_DETECTION);
00062   std::wstring ret;
00063   if (nullptr != pService)
00064   {
00065     MAPPING_PROPERTY_BAG bag = {};
00066     bag.Size = sizeof(bag);
00067
00068     HRESULT hr = MappingRecognizeText(pService, text, static_cast<DWORD>(wcslen(text)), 0, nullptr, &bag);
00069     if (SUCCEEDED(hr))
00070     {
00071       std::wstringstream output(std::wstringstream::out);
00072       for (DWORD rangeIndex = 0; rangeIndex < bag.dwRangesCount; ++rangeIndex)
00073       {
00074         output << L"Range from " << bag.prgResultRanges[rangeIndex].dwStartIndex << L" to " << bag.prgResultRanges[rangeIndex].dwEndIndex << L": ";
00075         output << reinterpret_cast<wchar_t*>(bag.prgResultRanges[rangeIndex].pData) << L" script\n";
00076       }
00077
00078       ret = output.str();
00079       MappingFreePropertyBag(&bag);
00080     }
00081     MappingFreeServices(pService);
00082   }
00083
00084   return ret;
00085 }
00086
00087 inline std::wstring TransliterateFromCyrillicToLatin(_In_ PCWSTR text)
00088 {
00089   auto pService = Private::GetSingleELSServiceWithNoOptions(ELS_GUID_TRANSLITERATION_CYRILLIC_TO_LATIN);
00090   std::wstring ret;
00091   if (nullptr != pService)
00092   {
00093     MAPPING_PROPERTY_BAG bag = {};
00094     bag.Size = sizeof(bag);
00095     HRESULT hr = MappingRecognizeText(pService, text, static_cast<DWORD>(wcslen(text) + 1), 0, nullptr, &bag); // wcslen(text) + 1 to account for a null terminator also
00096     if (SUCCEEDED(hr))
00097     {
00098       ret = reinterpret_cast<wchar_t*>(bag.prgResultRanges[0].pData);
00099       MappingFreePropertyBag(&bag);
00100     }
00101     MappingFreeServices(pService);
00102   }
00103
00104   return ret;
00105 }
00106
00107 } //namespace ELS
00108 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::TextEditing::sealed Member List

This is the complete list of members for SDKSample::TextEditing::sealed, including all inherited members.
BoldButtonClick(Object^sender, RoutedEventArgs^e) | SDKSample::TextEditing::sealed | [private]
ClearAllHighlightedWords() | SDKSample::TextEditing::sealed | [private]
ColorButtonClick(Object^sender, RoutedEventArgs^e) | SDKSample::TextEditing::sealed | [private]
Default_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::TextEditing::sealed | [private]
Default_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::TextEditing::sealed | [private]
Default_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::TextEditing::sealed | [private]
Default_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::TextEditing::sealed | [private]
Default_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::TextEditing::sealed | [private]
DoSomething_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::TextEditing::sealed | [private]
FindAndHighlightText(String^textToFind) | SDKSample::TextEditing::sealed | [private]
FindBoxGotFocus(Object^sender, RoutedEventArgs^e) | SDKSample::TextEditing::sealed | [private]
FindBoxLostFocus(Object^sender, RoutedEventArgs^e) | SDKSample::TextEditing::sealed | [private]
FindBoxTextChanged(Object^sender, Windows::UI::Xaml::Controls::TextChangedEventArgs^e) | SDKSample::TextEditing::sealed | [private]
FontColorButtonClick(Object^sender, RoutedEventArgs^e) | SDKSample::TextEditing::sealed | [private]
FontColorButtonLostFocus(Object^sender, RoutedEventArgs^e) | SDKSample::TextEditing::sealed | [private]
Go_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::TextEditing::sealed | [private]
ItalicButtonClick(Object^sender, RoutedEventArgs^e) | SDKSample::TextEditing::sealed | [private]
LoadContentAsync() | SDKSample::TextEditing::sealed | [private]
m_highlightedWords | SDKSample::TextEditing::sealed | [private]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::TextEditing::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::TextEditing::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::TextEditing::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::TextEditing::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::TextEditing::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::TextEditing::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::TextEditing::sealed | [protected, virtual]
Other_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::TextEditing::sealed | [private]
Other_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::TextEditing::sealed | [private]
Other_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::TextEditing::sealed | [private]
Other_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::TextEditing::sealed | [private]
Other_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::TextEditing::sealed | [private]
rootPage | SDKSample::TextEditing::sealed | [private]
Scenario1() | SDKSample::TextEditing::sealed |
Scenario2() | SDKSample::TextEditing::sealed |
Scenario3() | SDKSample::TextEditing::sealed |
Scenario4() | SDKSample::TextEditing::sealed |
Scenario5() | SDKSample::TextEditing::sealed |
Scenario6() | SDKSample::TextEditing::sealed |
Scenario7() | SDKSample::TextEditing::sealed |
Generated on Sat Nov 23 2024 16:09:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Custom driver access/C++/app_cpp/pch.h Source File

  • Custom driver access
  • app_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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
00023 #include "DeviceList.h"
00024
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text display/C++/Scenario2.xaml.h Source File

  • XAML text display

Scenario2.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.xaml.h
00013 // Declaration of the Scenario2 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario2.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace TextDisplay
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 sealed
00031         {
00032         public:
00033             Scenario2();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void DoSomething_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::Tiles::sealed Member List

This is the complete list of members for SDKSample::Tiles::sealed, including all inherited members.
ClearBadge_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Tiles::sealed | [private]
ClearTile_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Tiles::sealed | [private]
ClearTile_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Tiles::sealed | [private]
ClearTile_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Tiles::sealed | [private]
ClearTile_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Tiles::sealed | [private]
DisableNotificationQueue_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Tiles::sealed | [private]
EnableNotificationQueue() | SDKSample::Tiles::sealed |
EnableNotificationQueue_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Tiles::sealed | [private]
Globalization() | SDKSample::Tiles::sealed |
ImageProtocols() | SDKSample::Tiles::sealed |
imageRelativePath | SDKSample::Tiles::sealed | [private]
NotificationExpiration() | SDKSample::Tiles::sealed |
NumberOrGlyph_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | SDKSample::Tiles::sealed | [private]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Tiles::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Tiles::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Tiles::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Tiles::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Tiles::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Tiles::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Tiles::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Tiles::sealed | [protected, virtual]
PickImage_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Tiles::sealed | [private]
ProtocolList_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | SDKSample::Tiles::sealed | [private]
rootPage | SDKSample::Tiles::sealed | [private]
SendBadge() | SDKSample::Tiles::sealed |
SendLocalImageTile() | SDKSample::Tiles::sealed |
SendTextTile() | SDKSample::Tiles::sealed |
SendTileNotification_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Tiles::sealed | [private]
SendTileNotificationImage_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Tiles::sealed | [private]
SendTileNotificationText_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Tiles::sealed | [private]
SendTileNotificationWithQueryStrings_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Tiles::sealed | [private]
SendWebImageTile() | SDKSample::Tiles::sealed |
UpdateBadge_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Tiles::sealed | [private]
UpdateBadgeWithGlyph(int glyphIndex) | SDKSample::Tiles::sealed | [private]
UpdateBadgeWithGlyphWithStringManipulation() | SDKSample::Tiles::sealed | [private]
UpdateBadgeWithNumber(int number) | SDKSample::Tiles::sealed | [private]
UpdateBadgeWithNumberWithStringManipulation(int number) | SDKSample::Tiles::sealed | [private]
UpdateTile_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Tiles::sealed | [private]
UpdateTileExpiring_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Tiles::sealed | [private]
UpdateTileWithImage_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Tiles::sealed | [private]
UpdateTileWithImageWithStringManipulation_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Tiles::sealed | [private]
UpdateTileWithText_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Tiles::sealed | [private]
UpdateTileWithTextWithStringManipulation_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Tiles::sealed | [private]
UpdateTileWithWebImage_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Tiles::sealed | [private]
UpdateTileWithWebImageWithStringManipulation_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Tiles::sealed | [private]
ViewCurrentResources_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Tiles::sealed | [private]
Generated on Sat Nov 23 2024 16:09:53 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Calendar details and math/C++/common/LayoutAwarePage.h Source File

  • Calendar details and math
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DirectX::Blob Member List

This is the complete list of members for DirectX::Blob, including all inherited members.
_buffer | DirectX::Blob | [private]
_size | DirectX::Blob | [private]
Blob() | DirectX::Blob | [inline]
Blob(const Blob &) | DirectX::Blob | [private]
GetBufferPointer() const | DirectX::Blob | [inline]
GetBufferSize() const | DirectX::Blob | [inline]
Initialize(_In_ size_t size) | DirectX::Blob |
operator=(const Blob &) | DirectX::Blob | [private]
Release() | DirectX::Blob |
~Blob() | DirectX::Blob | [inline]
Generated on Sat Nov 23 2024 16:09:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D tutorial/C++/Lesson5.Components/BasicTimer.h Source File

  • Direct3D tutorial
  • Lesson5.Components

BasicTimer.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 timer class used to drive the render loop of the actively-animated
00011 // DirectX SDK samples. Uses the QueryPerformanceCounter function to retrieve
00012 // high-resolution timing information.
00013 ref class BasicTimer
00014 {
00015 private:
00016     LARGE_INTEGER m_frequency;
00017     LARGE_INTEGER m_currentTime;
00018     LARGE_INTEGER m_startTime;
00019     LARGE_INTEGER m_lastTime;
00020     float m_total;
00021     float m_delta;
00022
00023 internal:
00024     BasicTimer();
00025     void Reset();
00026     void Update();
00027     property float Total
00028     {
00029         float get();
00030     }
00031     property float Delta
00032     {
00033         float get();
00034     }
00035 };
Generated on Sat Nov 23 2024 16:08:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D interpolation modes/C++/D2DInterpolationModes.h Source File

  • Direct2D interpolation modes

D2DInterpolationModes.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 #include "DirectXBase.h"
00009 #include "SampleOverlay.h"
00010 #include "BasicTimer.h"
00011 #include <deque>
00012
00013 #define _USE_MATH_DEFINES
00014 #include <math.h>
00015
00016 ref class D2DInterpolationModes : public DirectXBase, public Windows::ApplicationModel::Core::IFrameworkView
00017 {
00018 internal:
00019     D2DInterpolationModes();
00020
00021     void UpdateEffectMatrices();
00022
00023     void D2DInterpolationModes::MenuItemSelected(Windows::UI::Popups::IUICommand^ command);
00024
00025     // DirectX Base Methods.
00026     virtual void CreateDeviceResources() override;
00027     virtual void CreateWindowSizeDependentResources() override;
00028     virtual void Render() override;
00029
00030 public:
00031     // IFrameworkView Methods.
00032     virtual void Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00033     virtual void SetWindow(_In_ Windows::UI::Core::CoreWindow^ window);
00034     virtual void Load(_In_ Platform::String^ entryPoint);
00035     virtual void Run();
00036     virtual void Uninitialize();
00037
00038 private:
00039     // Event Handlers.
00040     void OnLogicalDpiChanged(
00041         _In_ Platform::Object^ sender
00042         );
00043
00044     void OnDisplayContentsInvalidated(
00045         _In_ Platform::Object^ sender
00046         );
00047
00048     void OnWindowSizeChanged(
00049         _In_ Windows::UI::Core::CoreWindow^ sender,
00050         _In_ Windows::UI::Core::WindowSizeChangedEventArgs^ args
00051         );
00052
00053     void OnVisibilityChanged(
00054         _In_ Windows::UI::Core::CoreWindow^ sender,
00055         _In_ Windows::UI::Core::VisibilityChangedEventArgs^ args
00056         );
00057
00058     void OnWindowClosed(
00059         _In_ Windows::UI::Core::CoreWindow^ window,
00060         _In_ Windows::UI::Core::CoreWindowEventArgs^ args
00061         );
00062
00063     void OnActivated(
00064         _In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView,
00065         _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^ args
00066         );
00067
00068     void OnSuspending(
00069         _In_ Platform::Object^ sender,
00070         _In_ Windows::ApplicationModel::SuspendingEventArgs^ args
00071         );
00072
00073     void OnResuming(
00074         _In_ Platform::Object^ sender,
00075         _In_ Platform::Object^ args
00076         );
00077
00078     void OnPointerPressed(
00079         _In_ Windows::UI::Core::CoreWindow^ window,
00080         _In_ Windows::UI::Core::PointerEventArgs^ args
00081         );
00082
00083     void OnPointerReleased(
00084         _In_ Windows::UI::Core::CoreWindow^ window,
00085         _In_ Windows::UI::Core::PointerEventArgs^ args
00086         );
00087
00088     void OnPointerMoved(
00089         _In_ Windows::UI::Core::CoreWindow^ window,
00090         _In_ Windows::UI::Core::PointerEventArgs^ args
00091         );
00092
00093     void OnPointerWheelChanged(
00094         _In_ Windows::UI::Core::CoreWindow^ window,
00095         _In_ Windows::UI::Core::PointerEventArgs^ args
00096         );
00097
00098     void OnManipulationUpdated(
00099         _In_ Windows::UI::Input::GestureRecognizer^ recognizer,
00100         _In_ Windows::UI::Input::ManipulationUpdatedEventArgs^ args
00101         );
00102
00103     // Declare event handlers for responding to touch gestures.
00104     void HandleManipulationUpdated(
00105         Windows::Foundation::Point position,
00106         Windows::Foundation::Point positionDelta,
00107         float zoomDelta
00108         );
00109
00110     void HandlePointerPressed(
00111         Windows::UI::Input::PointerPoint^ point
00112         );
00113
00114     void AddMenuItem(
00115         Windows::UI::Popups::PopupMenu^ popupMenu,
00116         Platform::String^ caption
00117         );
00118
00119     inline const float Clamp(float v, float low, float high)
00120     {
00121         return (v < low) ? low : (v > high) ? high : v;
00122     }
00123
00124     Platform::Agile<Windows::UI::Input::GestureRecognizer> m_gestureRecognizer;
00125
00126     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> m_whiteBrush;
00127
00128     Platform::String^                            m_modeTextLeft;
00129     Platform::String^                            m_modeTextRight;
00130     Microsoft::WRL::ComPtr<IDWriteTextFormat>    m_modeTextFormat;
00131     Microsoft::WRL::ComPtr<IDWriteTextFormat>    m_renderTimeFormat;
00132
00133     float                                        m_totalZoom;
00134     float                                        m_imageRotate;
00135     D2D1_POINT_2F                                m_viewPosition;
00136     D2D1_SIZE_U                                  m_imageSize;
00137     D2D1_SIZE_F                                  m_imageSizeDips;
00138     bool                                         m_isSnapped;
00139
00140     SampleOverlay^                               m_sampleOverlay;
00141
00142     Microsoft::WRL::ComPtr<ID2D1Effect>          m_bitmapSourceEffect;
00143     Microsoft::WRL::ComPtr<ID2D1Effect>          m_2DAffineTransformEffectLeft;
00144     Microsoft::WRL::ComPtr<ID2D1Effect>          m_2DAffineTransformEffectRight;
00145
00146     // Used by the context menu to avoid code duplication.
00147     Microsoft::WRL::ComPtr<ID2D1Effect>          m_selectedEffect;
00148
00149     // Measure time it takes to render each frame.
00150     BasicTimer^                                  m_renderTimer;
00151     float                                        m_renderDuration;
00152
00153     bool                                         m_isWindowClosed;
00154     bool                                         m_isWindowVisible;
00155 };
00156
00157 ref class DirectXAppSource : Windows::ApplicationModel::Core::IFrameworkViewSource
00158 {
00159 public:
00160     virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00161 };
Generated on Sat Nov 23 2024 16:08:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Configure keys for media/C++/common/suspensionmanager.h Source File

  • Configure keys for media
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Background task/C++/BackgroundTask/App.xaml.h Source File

  • Background task
  • BackgroundTask

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/ConstantBuffers.h Source File

  • XAML DirectX 3D shooting game

ConstantBuffers.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 struct PNTVertex
00011 {
00012     DirectX::XMFLOAT3 position;
00013     DirectX::XMFLOAT3 normal;
00014     DirectX::XMFLOAT2 textureCoordinate;
00015 };
00016
00017 static D3D11_INPUT_ELEMENT_DESC PNTVertexLayout[] =
00018 {
00019     {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0,  0, D3D11_INPUT_PER_VERTEX_DATA, 0},
00020     {"NORMAL",   0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0},
00021     {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT,    0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0},
00022 };
00023
00024 struct ConstantBufferNeverChanges
00025 {
00026     DirectX::XMFLOAT4 lightPosition[4];
00027     DirectX::XMFLOAT4 lightColor;
00028 };
00029
00030 struct ConstantBufferChangeOnResize
00031 {
00032     DirectX::XMFLOAT4X4 projection;
00033 };
00034
00035 struct ConstantBufferChangesEveryFrame
00036 {
00037     DirectX::XMFLOAT4X4 view;
00038 };
00039
00040 struct ConstantBufferChangesEveryPrim
00041 {
00042     DirectX::XMFLOAT4X4 worldMatrix;
00043     DirectX::XMFLOAT4 meshColor;
00044     DirectX::XMFLOAT4 diffuseColor;
00045     DirectX::XMFLOAT4 specularColor;
00046     float specularPower;
00047 };
00048
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Audio Session (WASAPI)/C++/Scenario3.xaml.cpp Source File

  • Windows Audio Session (WASAPI)
  • C++

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 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 Scenario3::Scenario3() :
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_Oscilliscope = safe_cast<Windows::UI::Xaml::Shapes::Polyline^>(static_cast<IFrameworkElement^>(this)->FindName("Oscilliscope"));
00050 }
00051
00052 Scenario3::~Scenario3()
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 Scenario3::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 Scenario3::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 Scenario3::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 Scenario3::UpdateMediaControlUI( DeviceState deviceState )
00118 {
00119     switch( deviceState )
00120     {
00121     case DeviceState::DeviceStateCapturing:
00122         btnStartCapture->IsEnabled = false;
00123         btnStopCapture->IsEnabled = true;
00124         break;
00125
00126     case DeviceState::DeviceStateStopped:
00127         btnStartCapture->IsEnabled = true;
00128         btnStopCapture->IsEnabled = false;
00129         break;
00130
00131     case DeviceState::DeviceStateInitialized:
00132     case DeviceState::DeviceStateStarting:
00133     case DeviceState::DeviceStateStopping:
00134     case DeviceState::DeviceStateFlushing:
00135     case DeviceState::DeviceStateInError:
00136         btnStartCapture->IsEnabled = false;
00137         btnStopCapture->IsEnabled = false;
00138         break;
00139     }
00140 }
00141 #pragma endregion
00142
00143 #pragma region UI Event Handlers
00144 void Scenario3::btnStartCapture_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00145 {
00146     ShowStatusMessage( "", NotifyType::StatusMessage );
00147     InitializeCapture( sender, e );
00148 }
00149
00150 void Scenario3::btnStopCapture_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00151 {
00152     StopCapture( sender, e );
00153 }
00154 #pragma endregion
00155
00156 // Event callback from WASAPI capture for changes in device state
00157 void Scenario3::OnDeviceStateChange( Object^ sender, DeviceStateChangedEventArgs^ e )
00158 {
00159     String^ strMessage = "";
00160
00161     // Get the current time for messages
00162     auto t = Windows::Globalization::DateTimeFormatting::DateTimeFormatter::LongTime;
00163     Windows::Globalization::Calendar^ calendar = ref new Windows::Globalization::Calendar();
00164     calendar->SetToNow();
00165
00166     // Update Control Buttons
00167     m_CoreDispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler(
00168         [this, e]()
00169     {
00170         UpdateMediaControlUI( e->State );
00171     }));
00172
00173     // Handle state specific messages
00174     switch( e->State )
00175     {
00176     case DeviceState::DeviceStateInitialized:
00177         m_spCapture->StartCaptureAsync();
00178         break;
00179
00180     case DeviceState::DeviceStateCapturing:
00181         strMessage = "Capture Started @" + t->Format( calendar->GetDateTime() );
00182         ShowStatusMessage( strMessage, NotifyType::StatusMessage );
00183         break;
00184
00185     case DeviceState::DeviceStateDiscontinutity:
00186         {
00187             m_DiscontinuityCount++;
00188
00189             // Should always have a discontinuity when starting the capture, so will disregard it
00190             if (m_DiscontinuityCount > 1)
00191             {
00192                 strMessage = "DISCONTINUITY DETECTED: " + t->Format( calendar->GetDateTime() ) + " (Count = " + (m_DiscontinuityCount - 1) + ")";
00193                 ShowStatusMessage( strMessage, NotifyType::StatusMessage );
00194             }
00195         }
00196         break;
00197
00198     case DeviceState::DeviceStateFlushing:
00199         PlotDataReadyEvent::PlotDataReady -= m_plotDataReadyToken;
00200         m_plotDataReadyToken.Value = 0;
00201
00202         ShowStatusMessage( "Finalizing WAV Header.  This may take a few minutes...", NotifyType::StatusMessage );
00203
00204         m_CoreDispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler(
00205             [this]()
00206         {
00207             m_Oscilliscope->Points->Clear();
00208
00209             Windows::Foundation::Point p;
00210             p.X = OSC_START_X;
00211             p.Y = OSC_START_Y;
00212
00213             m_Oscilliscope->Points->Append( p );
00214
00215             p.X = OSC_X_LENGTH;
00216             p.Y = OSC_START_Y;
00217
00218             m_Oscilliscope->Points->Append( p );
00219         }));
00220         break;
00221
00222     case DeviceState::DeviceStateStopped:
00223         // For the stopped state, completely tear down the audio device
00224         m_spCapture = nullptr;
00225
00226         if (m_deviceStateChangeToken.Value != 0)
00227         {
00228             m_StateChangedEvent->StateChangedEvent -= m_deviceStateChangeToken;
00229             m_StateChangedEvent = nullptr;
00230             m_deviceStateChangeToken.Value = 0;
00231         }
00232
00233         ShowStatusMessage( "Capture Stopped", NotifyType::StatusMessage );
00234         break;
00235
00236     case DeviceState::DeviceStateInError:
00237         HRESULT hr = e->hr;
00238
00239         if (m_deviceStateChangeToken.Value != 0)
00240         {
00241             m_StateChangedEvent->StateChangedEvent -= m_deviceStateChangeToken;
00242             m_StateChangedEvent = nullptr;
00243             m_deviceStateChangeToken.Value = 0;
00244         }
00245
00246         m_spCapture = nullptr;
00247
00248         wchar_t hrVal[11];
00249         swprintf_s( hrVal, 11, L"0x%08x\0", hr );
00250         String^ strHRVal = ref new String( hrVal );
00251
00252         // Specifically handle a couple of known errors
00253         switch( hr )
00254         {
00255         case AUDCLNT_E_RESOURCES_INVALIDATED:
00256             strMessage = "ERROR: Endpoint Lost Access To Resources (" + strHRVal + ")";
00257             ShowStatusMessage( strMessage, NotifyType::ErrorMessage );
00258             break;
00259
00260         case E_ACCESSDENIED:
00261             strMessage = "ERROR: Access Denied (" + strHRVal + ").  Check 'Settings->Permissions' for access to Microphone.";
00262             ShowStatusMessage( strMessage, NotifyType::ErrorMessage );
00263             break;
00264
00265         default:
00266             strMessage = "ERROR: " + strHRVal + " has occurred.";
00267             ShowStatusMessage( strMessage, NotifyType::ErrorMessage );
00268         }
00269     }
00270 }
00271
00272 // Event callback when visualization data is ready to be plotted
00273 void Scenario3::OnPlotDataReady( Object^ sender, PlotDataReadyEventArgs^ e )
00274 {
00275     Platform::Array<int,1>^ Points = e->Points;
00276     UINT32 Size = e->Size;
00277
00278     m_CoreDispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler(
00279         [this, Points, Size]()
00280     {
00281         // The last point value gives the maximum and minimum values in the data
00282         // Get absolute value of the minimum
00283         float y_max = static_cast<float>( abs( Points[Size - 1] ) );
00284
00285         // Scale the incoming point list so that it fills our scope
00286         float x_inc = static_cast<float>( OSC_X_LENGTH ) / static_cast<float>( Size - 2 );
00287
00288         UINT32 existingPoints = m_Oscilliscope->Points->Size;
00289
00290         for (UINT32 i = 0; i < Size - 1; i++)
00291         {
00292             Point p;
00293
00294             // Fixup the x and y coordinates and set it back into the collection
00295             p.X = OSC_START_X + i * x_inc;
00296             p.Y = OSC_START_Y - ( Points[i] * OSC_TOTAL_HEIGHT ) / ( 2.0F * y_max );
00297
00298             if (i < existingPoints)
00299             {
00300                 m_Oscilliscope->Points->SetAt(i, p);
00301             }
00302             else
00303             {
00304                 m_Oscilliscope->Points->Append(p);
00305             }
00306         }
00307     }));
00308 }
00309
00310 //
00311 //  InitializeCapture()
00312 //
00313 void Scenario3::InitializeCapture( Platform::Object^ sender, Object^ e )
00314 {
00315     HRESULT hr = S_OK;
00316
00317     if (m_spCapture)
00318     {
00319         m_spCapture = nullptr;
00320     }
00321
00322     // Create a new WASAPI capture instance
00323     m_spCapture = Make<WASAPICapture>();
00324
00325     if (nullptr == m_spCapture)
00326     {
00327         OnDeviceStateChange( this, ref new DeviceStateChangedEventArgs( DeviceState::DeviceStateInError, E_OUTOFMEMORY ));
00328         return;
00329     }
00330
00331     // Get a pointer to the device event interface
00332     m_StateChangedEvent = m_spCapture->GetDeviceStateEvent();
00333
00334     if (nullptr == m_StateChangedEvent)
00335     {
00336         OnDeviceStateChange( this, ref new DeviceStateChangedEventArgs( DeviceState::DeviceStateInError, E_FAIL ));
00337         return;
00338     }
00339
00340     // Register for events
00341     m_deviceStateChangeToken = m_StateChangedEvent->StateChangedEvent += ref new DeviceStateChangedHandler( this, &Scenario3::OnDeviceStateChange );
00342     m_plotDataReadyToken = PlotDataReadyEvent::PlotDataReady += ref new PlotDataReadyHandler( this, &Scenario3::OnPlotDataReady );
00343
00344     // Reset discontinuity counter
00345     m_DiscontinuityCount = 0;
00346
00347     // Perform the initialization
00348     m_spCapture->InitializeAudioDeviceAsync();
00349 }
00350
00351 //
00352 //  StopCapture()
00353 //
00354 void Scenario3::StopCapture( Platform::Object^ sender, Object^ e )
00355 {
00356     if (m_spCapture)
00357     {
00358         // Set the event to stop playback
00359         m_spCapture->StopCaptureAsync();
00360     }
00361 }
00362
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML ListView and GridView essentials/C++/Constants.cpp Source File

  • XAML ListView and GridView essentials

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully qualified name for the class that implements the scenario" }
00021     { "Instantiating a GridView", "SDKSample.ListViewSimple.Scenario1" },
00022     { "Responding to click events", "SDKSample.ListViewSimple.Scenario2" },
00023     { "Instantiating a ListView", "SDKSample.ListViewSimple.Scenario3" }
00024 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Connecting with WebSockets/C++/App.xaml.cpp Source File

  • Connecting with WebSockets

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX touch input/C++/MoveLookController.h Source File

  • DirectX touch input

MoveLookController.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
00009 #pragma once
00010
00011 #include "BasicMath.h"
00012 #include "math.h"
00013
00014 // A basic Move/Look Controller class such as in an FPS
00015 // horizontal (x-z-plane) movement on left virtual joystick
00016 //          also supports WASD keyboard input
00017 // steering and orientation via left mouse down or touch drag
00018
00019 namespace MoveLookControllerConstants
00020 {
00021     static const float  MoveMaxXCoordinate  = 500.0f;
00022     static const float  MoveMinYCoordinate  = 580.0f;
00023 };
00024
00025 ref class MoveLookController
00026 {
00027 private:
00028     // properties of the controller object
00029     float3 m_position;              // the position of the controller
00030     float m_pitch, m_yaw;           // orientation euler angles in radians
00031
00032     // properties of the Move control
00033     bool m_moveInUse;               // the move control is in use
00034     uint32 m_movePointerID;         // id of the pointer in this control
00035     float2 m_moveFirstDown;         // point where initial contact occurred
00036     float2 m_movePointerPosition;   // point where the move pointer is currently located
00037     float3 m_moveCommand;           // the net command from the move control
00038
00039     // properties of the Look control
00040     bool m_lookInUse;               // the look control is in use
00041     uint32 m_lookPointerID;         // id of the pointer in this control
00042     float2 m_lookLastPoint;         // last point (from last frame)
00043     float2 m_lookLastDelta;         // for smoothing
00044
00045     // properties of the Mouse Look control
00046     bool m_mouseLookInUse;          // the mouse look control is in use
00047     uint32 m_mouseLookPointerID;    // id of the pointer in this control
00048
00049 internal:
00050     // Methods to get input from the UI pointers
00051
00052     void OnPointerPressed(
00053         _In_ Windows::UI::Core::CoreWindow^ sender,
00054         _In_ Windows::UI::Core::PointerEventArgs^ args
00055         );
00056
00057     void OnPointerMoved(
00058         _In_ Windows::UI::Core::CoreWindow^ sender,
00059         _In_ Windows::UI::Core::PointerEventArgs^ args
00060         );
00061
00062     void OnPointerReleased(
00063         _In_ Windows::UI::Core::CoreWindow^ sender,
00064         _In_ Windows::UI::Core::PointerEventArgs^ args
00065         );
00066
00067     void OnKeyDown(
00068         _In_ Windows::UI::Core::CoreWindow^ sender,
00069         _In_ Windows::UI::Core::KeyEventArgs^ args
00070         );
00071
00072     void OnKeyUp(
00073         _In_ Windows::UI::Core::CoreWindow^ sender,
00074         _In_ Windows::UI::Core::KeyEventArgs^ args
00075         );
00076
00077     void OnMouseMoved(
00078         _In_ Windows::Devices::Input::MouseDevice^ mouseDevice,
00079         _In_ Windows::Devices::Input::MouseEventArgs^ args
00080         );
00081
00082     // Set up the Controls supported by this controller.
00083     void Initialize(_In_ Windows::UI::Core::CoreWindow^ window);
00084
00085     // Accessor to set position of controller.
00086     void SetPosition(_In_ float3 pos);
00087
00088     // Accessor to set position of controller.
00089     void SetOrientation(_In_ float pitch, _In_ float yaw);
00090
00091     // Returns the position of the controller object.
00092     float3 GetPosition();
00093
00094     // Returns the point at which the controller is facing.
00095     float3 GetLookPoint();
00096
00097     void Update(Windows::UI::Core::CoreWindow^ window);
00098
00099     void SaveInternalValue(
00100         _In_ Windows::Foundation::Collections::IPropertySet^ state,
00101         _In_ Platform::String^ key,
00102         _In_ Platform::Object^ value
00103         );
00104
00105     void SaveInternalState(_In_ Windows::Foundation::Collections::IPropertySet^ state);
00106     void LoadInternalState(_In_ Windows::Foundation::Collections::IPropertySet^ state);
00107
00108 };  // class MoveLookController
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-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.
__pad0__ | Sphere |
Active(bool active) | GameObject |
Active() | GameObject |
Active(bool active) | GameObject |
Active() | GameObject |
AnimatePosition(_In_opt_ Animate^animate) | GameObject |
AnimatePosition() | GameObject |
AnimatePosition(_In_opt_ Animate^animate) | GameObject |
AnimatePosition() | GameObject |
center | Sphere |
Hit(bool hit) | GameObject |
Hit() | GameObject |
Hit(bool hit) | GameObject |
Hit() | GameObject |
HitMaterial(_In_ Material^material) | GameObject |
HitMaterial() | GameObject |
HitMaterial(_In_ Material^material) | GameObject |
HitMaterial() | GameObject |
HitSound(_In_ SoundEffect^hitSound) | GameObject |
HitSound() | GameObject |
HitSound(_In_ SoundEffect^hitSound) | GameObject |
HitSound() | GameObject |
HitTime(float t) | GameObject |
HitTime() | GameObject |
HitTime(float t) | GameObject |
HitTime() | GameObject |
IsTouching(DirectX::XMFLOAT3 point, float radius, _Out_ DirectX::XMFLOAT3 *contact, _Out_ DirectX::XMFLOAT3 *normal) override | Sphere | [virtual]
IsTouching(DirectX::XMFLOAT3 point, float radius, _Out_ DirectX::XMFLOAT3 *contact, _Out_ DirectX::XMFLOAT3 *normal) override | Sphere | [virtual]
m_radius | Sphere | [private]
Mesh(_In_ MeshObject^mesh) | GameObject |
Mesh(_In_ MeshObject^mesh) | GameObject |
ModelMatrix() | GameObject |
ModelMatrix() | GameObject |
NormalMaterial(_In_ Material^material) | GameObject |
NormalMaterial() | GameObject |
NormalMaterial(_In_ Material^material) | GameObject |
NormalMaterial() | GameObject |
OnGround(bool ground) | GameObject |
OnGround() | GameObject |
OnGround(bool ground) | GameObject |
OnGround() | GameObject |
PlaySound(float impactSpeed, DirectX::XMFLOAT3 eyePoint) | GameObject |
PlaySound(float impactSpeed, DirectX::XMFLOAT3 eyePoint) | GameObject |
Position(DirectX::XMFLOAT3 position) | Sphere |
Position(DirectX::XMVECTOR position) | Sphere |
Position(DirectX::XMFLOAT3 position) | Sphere |
Position(DirectX::XMVECTOR position) | Sphere |
GameObject::Position() | GameObject |
Radius(float radius) | Sphere |
Radius() | Sphere |
Radius() const | Sphere | [inline]
Radius(float radius) | Sphere |
Radius() | Sphere |
Render(_In_ ID3D11DeviceContext *context, _In_ ID3D11Buffer *primitiveConstantBuffer) | GameObject |
Render(_In_ ID3D11DeviceContext *context, _In_ ID3D11Buffer *primitiveConstantBuffer) | GameObject |
Sphere(DirectX::XMFLOAT3 pos, float radius) | Sphere |
Sphere() | Sphere | [inline]
Sphere(const XMFLOAT3 &centerIn, FLOAT radius) | Sphere | [inline, explicit]
Sphere(float x, float y, float z, float radius) | Sphere | [inline, explicit]
Sphere(DirectX::XMFLOAT3 pos, float radius) | Sphere |
Target(bool target) | GameObject |
Target() | GameObject |
Target(bool target) | GameObject |
Target() | GameObject |
TargetId(int targetId) | GameObject |
TargetId() | GameObject |
TargetId(int targetId) | GameObject |
TargetId() | GameObject |
Update() | Sphere | [private]
Update() | Sphere | [private]
VectorPosition() | GameObject |
VectorPosition() | GameObject |
VectorVelocity() | GameObject |
VectorVelocity() | GameObject |
Velocity(DirectX::XMFLOAT3 velocity) | GameObject |
Velocity(DirectX::XMVECTOR velocity) | GameObject |
Velocity() | GameObject |
Velocity(DirectX::XMFLOAT3 velocity) | GameObject |
Velocity(DirectX::XMVECTOR velocity) | GameObject |
Velocity() | GameObject |
Generated on Sat Nov 23 2024 16:09:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML Popup/C++/App.xaml.h Source File

  • XAML Popup

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML images/C++/common/suspensionmanager.h Source File

  • XAML images
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Geolocation/C++/pch.cpp Source File

  • Geolocation

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media capture using capture device/C#,C++/AudioCapture.xaml.cs Source File

  • Media capture using capture device
  • C#,C++

AudioCapture.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.Media.MediaProperties;
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.Media.Capture;
00018 namespace MediaCapture
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 AudioCapture : SDKTemplate.Common.LayoutAwarePage
00024     {
00025         private Windows.Media.Capture.MediaCapture m_mediaCaptureMgr;
00026         private Windows.Storage.StorageFile m_recordStorageFile;
00027         private bool m_bRecording;
00028         private bool m_bSuspended;
00029         private EventHandler<Object> m_soundLevelHandler;
00030
00031         private readonly String AUDIO_FILE_NAME = "audio.mp4";
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         MainPage rootPage = MainPage.Current;
00036
00037         public AudioCapture()
00038         {
00039             this.InitializeComponent();
00040             ScenarioInit();
00041             m_soundLevelHandler = new EventHandler<Object>(MediaControl_SoundLevelChanged);
00042         }
00043
00044         /// <summary>
00045         /// Invoked when this page is about to be displayed in a Frame.
00046         /// </summary>
00047         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00048         /// property is typically used to configure the page.</param>
00049         protected override void OnNavigatedTo(NavigationEventArgs e)
00050         {
00051             Windows.Media.MediaControl.SoundLevelChanged += m_soundLevelHandler;
00052         }
00053
00054         protected override void OnNavigatedFrom(NavigationEventArgs e)
00055         {
00056             Windows.Media.MediaControl.SoundLevelChanged -= m_soundLevelHandler;
00057         }
00058
00059         private void ScenarioInit()
00060         {
00061             btnStartDevice3.IsEnabled = true;
00062             btnStartStopRecord3.IsEnabled = false;
00063             m_bRecording = false;
00064             playbackElement3.Source = null;
00065             m_bSuspended = false;
00066             ShowStatusMessage("");
00067
00068         }
00069
00070         private void ScenarioReset()
00071         {
00072             ScenarioInit();
00073         }
00074
00075         private async void MediaControl_SoundLevelChanged(object sender, Object e)
00076         {
00077             await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
00078             {
00079                 if (Windows.Media.MediaControl.SoundLevel != Windows.Media.SoundLevel.Muted)
00080                 {
00081                     ScenarioReset();
00082                 }
00083                 else
00084                 {
00085                     if (m_bRecording)
00086                     {
00087                         ShowStatusMessage("Stopping Record on invisibility");
00088
00089                         await m_mediaCaptureMgr.StopRecordAsync();
00090                         m_bRecording = false;
00091                         EnableButton(true, "StartStopRecord");
00092                     }
00093                 }
00094             });
00095         }
00096
00097
00098         public async void RecordLimitationExceeded(Windows.Media.Capture.MediaCapture currentCaptureObject)
00099         {
00100             try
00101             {
00102                 if (m_bRecording)
00103                 {
00104                     await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
00105                     {
00106                         try
00107                         {
00108                             ShowStatusMessage("Stopping Record on exceeding max record duration");
00109                             await m_mediaCaptureMgr.StopRecordAsync();
00110                             m_bRecording = false;
00111                             SwitchRecordButtonContent();
00112                             EnableButton(true, "StartStopRecord");
00113                             ShowStatusMessage("Stopped record on exceeding max record duration:" + m_recordStorageFile.Path);
00114                         }
00115                         catch (Exception e)
00116                         {
00117                             ShowExceptionMessage(e);
00118                         }
00119
00120                     });
00121                 }
00122             }
00123             catch (Exception e)
00124             {
00125                 ShowExceptionMessage(e);
00126             }
00127         }
00128
00129         public void Failed(Windows.Media.Capture.MediaCapture currentCaptureObject, MediaCaptureFailedEventArgs currentFailure)
00130         {
00131             try
00132             {
00133                 var ignored = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00134                 {
00135                     try
00136                     {
00137                         ShowStatusMessage("Fatal error" + currentFailure.Message);
00138
00139                     }
00140                     catch (Exception e)
00141                     {
00142                         ShowExceptionMessage(e);
00143                     }
00144                 });
00145             }
00146             catch (Exception e)
00147             {
00148                 ShowExceptionMessage(e);
00149             }
00150         }
00151
00152
00153         internal async void btnStartDevice_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e)
00154         {
00155             try
00156             {
00157                 EnableButton(false, "StartDevice");
00158                 ShowStatusMessage("Starting device");
00159                 m_mediaCaptureMgr = new Windows.Media.Capture.MediaCapture();
00160                 var settings = new Windows.Media.Capture.MediaCaptureInitializationSettings();
00161                 settings.StreamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.Audio;
00162                 await m_mediaCaptureMgr.InitializeAsync();
00163
00164                 EnableButton(true, "StartPreview");
00165                 EnableButton(true, "StartStopRecord");
00166                 EnableButton(true, "TakePhoto");
00167                 ShowStatusMessage("Device initialized successful");
00168                 m_mediaCaptureMgr.RecordLimitationExceeded += new Windows.Media.Capture.RecordLimitationExceededEventHandler(RecordLimitationExceeded); ;
00169                 m_mediaCaptureMgr.Failed += new Windows.Media.Capture.MediaCaptureFailedEventHandler(Failed); ;
00170
00171             }
00172             catch (Exception exception)
00173             {
00174                 ShowExceptionMessage(exception);
00175             }
00176         }
00177
00178         internal async void btnStartStopRecord_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e)
00179         {
00180             try
00181             {
00182                 String fileName;
00183                 EnableButton(false, "StartStopRecord");
00184
00185                 if (!m_bRecording)
00186                 {
00187                     ShowStatusMessage("Starting Record");
00188
00189                     fileName = AUDIO_FILE_NAME;
00190
00191                     m_recordStorageFile = await Windows.Storage.KnownFolders.VideosLibrary.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.GenerateUniqueName);
00192
00193                     ShowStatusMessage("Create record file successful");
00194
00195                     MediaEncodingProfile recordProfile = null;
00196                     recordProfile = MediaEncodingProfile.CreateM4a(Windows.Media.MediaProperties.AudioEncodingQuality.Auto);
00197
00198                     await m_mediaCaptureMgr.StartRecordToStorageFileAsync(recordProfile, this.m_recordStorageFile);
00199
00200                     m_bRecording = true;
00201                     SwitchRecordButtonContent();
00202                     EnableButton(true, "StartStopRecord");
00203
00204                     ShowStatusMessage("Start Record successful");
00205
00206                 }
00207                 else
00208                 {
00209                     ShowStatusMessage("Stopping Record");
00210
00211                     await m_mediaCaptureMgr.StopRecordAsync();
00212
00213                     m_bRecording = false;
00214                     EnableButton(true, "StartStopRecord");
00215                     SwitchRecordButtonContent();
00216
00217                     ShowStatusMessage("Stop record successful");
00218                     if (!m_bSuspended)
00219                     {
00220                         var stream = await m_recordStorageFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
00221
00222                         ShowStatusMessage("Record file opened");
00223                         ShowStatusMessage(this.m_recordStorageFile.Path);
00224                         playbackElement3.AutoPlay = true;
00225                         playbackElement3.SetSource(stream, this.m_recordStorageFile.FileType);
00226                         playbackElement3.Play();
00227
00228                     }
00229
00230                 }
00231             }
00232             catch (Exception exception)
00233             {
00234                 EnableButton(true, "StartStopRecord");
00235                 ShowExceptionMessage(exception);
00236                 m_bRecording = false;
00237             }
00238         }
00239
00240         private void ShowStatusMessage(String text)
00241         {
00242             rootPage.NotifyUser(text, NotifyType.StatusMessage);
00243         }
00244
00245         private void ShowExceptionMessage(Exception ex)
00246         {
00247             rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
00248         }
00249
00250         private void SwitchRecordButtonContent()
00251         {
00252             {
00253                 if (m_bRecording)
00254                 {
00255                     btnStartStopRecord3.Content = "StopRecord";
00256                 }
00257                 else
00258                 {
00259                     btnStartStopRecord3.Content = "StartRecord";
00260                 }
00261             }
00262         }
00263
00264         private void EnableButton(bool enabled, String name)
00265         {
00266             if (name.Equals("StartDevice"))
00267             {
00268                 btnStartDevice3.IsEnabled = enabled;
00269             }
00270
00271             else if (name.Equals("StartStopRecord"))
00272             {
00273                 btnStartStopRecord3.IsEnabled = enabled;
00274             }
00275
00276         }
00277     }
00278 }
Generated on Sat Nov 23 2024 16:08:19 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D sprite/C++/SimpleSprites.cpp Source File

  • Direct3D sprite

SimpleSprites.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 "SimpleSprites.h"
00010 #include "BasicLoader.h"
00011
00012 using namespace Microsoft::WRL;
00013 using namespace Windows::Foundation;
00014 using namespace Windows::Foundation::Collections;
00015 using namespace Windows::UI::Core;
00016
00017 using namespace BasicSprites;
00018
00019 SimpleSprites::SimpleSprites() :
00020     m_numParticlesToDraw(SampleSettings::Performance::InitialParticleCount)
00021 {
00022 }
00023
00024 void SimpleSprites::CreateDeviceIndependentResources()
00025 {
00026     DirectXBase::CreateDeviceIndependentResources();
00027
00028     // Create the performance throttler.
00029
00030     m_autoThrottle = ref new AutoThrottle(SampleSettings::Performance::TargetFrameTime);
00031 }
00032
00033 void SimpleSprites::CreateDeviceResources()
00034 {
00035     DirectXBase::CreateDeviceResources();
00036
00037     // Create the sprite batch.
00038
00039     m_spriteBatch = ref new SpriteBatch();
00040     unsigned int capacity = SampleSettings::Performance::ParticleCountMax + SampleSettings::NumAsteroids + 1;
00041     if (m_featureLevel < D3D_FEATURE_LEVEL_9_3)
00042     {
00043         capacity = min(Parameters::MaximumCapacityCompatible, capacity);
00044     }
00045     m_spriteBatch->Initialize(
00046         m_d3dDevice.Get(),
00047         capacity
00048         );
00049
00050     // Load the sprite textures.
00051
00052     BasicLoader^ loader = ref new BasicLoader(m_d3dDevice.Get(), m_wicFactory.Get());
00053
00054     loader->LoadTexture(
00055         "m31.png",
00056         &m_background,
00057         nullptr
00058         );
00059     m_spriteBatch->AddTexture(m_background.Get());
00060
00061     loader->LoadTexture(
00062         "ida.dds",
00063         &m_asteroid,
00064         nullptr
00065         );
00066     m_spriteBatch->AddTexture(m_asteroid.Get());
00067
00068     loader->LoadTexture(
00069         "particle.dds",
00070         &m_particle,
00071         nullptr
00072         );
00073     m_spriteBatch->AddTexture(m_particle.Get());
00074
00075     // Create the Sample Overlay.
00076
00077     m_sampleOverlay = ref new SampleOverlay();
00078
00079     m_sampleOverlay->Initialize(
00080         m_d2dDevice.Get(),
00081         m_d2dContext.Get(),
00082         m_wicFactory.Get(),
00083         m_dwriteFactory.Get(),
00084         "Direct3D SpriteBatch sample"
00085         );
00086 }
00087
00088 void SimpleSprites::CreateWindowSizeDependentResources()
00089 {
00090     DirectXBase::CreateWindowSizeDependentResources();
00091
00092     // Randomly generate some non-interactive asteroids to fit the screen.
00093
00094     m_asteroidData.clear();
00095     for (int i = 0; i < SampleSettings::NumAsteroids; i++)
00096     {
00097         AsteroidData data;
00098         data.pos.x = RandFloat(0.0f, m_windowBounds.Width);
00099         data.pos.y = RandFloat(0.0f, m_windowBounds.Height);
00100         float tempRot = RandFloat(-PI_F, PI_F);
00101         float tempMag = RandFloat(0.0f, 17.0f);
00102         data.vel.x = tempMag * cosf(tempRot);
00103         data.vel.y = tempMag * sinf(tempRot);
00104         data.rot = RandFloat(-PI_F, PI_F);
00105         data.scale = RandFloat(0.1f, 1.0f);
00106         data.rotVel = RandFloat(-PI_F, PI_F) / (7.0f + 3.0f * data.scale);
00107         m_asteroidData.push_back(data);
00108     }
00109
00110
00111     if (m_particleData.size() == 0)
00112     {
00113         // Initialize the interactive particle buffer to fill the window if it is empty.
00114
00115         for (int i = 0; i < SampleSettings::Performance::ParticleCountMax; i++)
00116         {
00117             ParticleData data;
00118             data.pos.x = RandFloat(0.0f, m_windowBounds.Width);
00119             data.pos.y = RandFloat(0.0f, m_windowBounds.Height);
00120             data.vel = float2(0.0f, 0.0f);
00121             m_particleData.push_back(data);
00122         }
00123     }
00124     else
00125     {
00126         // Otherwise, move the interactive particles to fit within the screen.
00127
00128         for (auto particle = m_particleData.begin(); particle != m_particleData.end(); particle++)
00129         {
00130             if (particle->pos.x > m_windowBounds.Width)
00131             {
00132                 particle->pos.x = m_windowBounds.Width;
00133             }
00134             if (particle->pos.y > m_windowBounds.Height)
00135             {
00136                 particle->pos.y = m_windowBounds.Height;
00137             }
00138         }
00139     }
00140
00141     m_sampleOverlay->UpdateForWindowSizeChange();
00142 }
00143
00144 void SimpleSprites::Update(float timeTotal, float timeDelta)
00145 {
00146     // Update the performance throttler.
00147
00148     auto control = m_autoThrottle->Update(timeDelta);
00149
00150     if (control == FrameWorkload::Increase)
00151     {
00152         m_numParticlesToDraw += SampleSettings::Performance::ParticleCountDelta;
00153     }
00154     if (control == FrameWorkload::Decrease)
00155     {
00156         m_numParticlesToDraw -= SampleSettings::Performance::ParticleCountDelta;
00157     }
00158     if (control != FrameWorkload::Maintain)
00159     {
00160         m_numParticlesToDraw = max(SampleSettings::Performance::ParticleCountMin, min(SampleSettings::Performance::ParticleCountMax, m_numParticlesToDraw));
00161         if (m_featureLevel < D3D_FEATURE_LEVEL_9_3)
00162         {
00163             m_numParticlesToDraw = min(static_cast<int>(Parameters::MaximumCapacityCompatible - SampleSettings::NumAsteroids - 1), m_numParticlesToDraw);
00164         }
00165     }
00166
00167     // Update the non-interactive asteroids.
00168     // Their behavior is to drift across the window with a fixed translational and rotational
00169     // velocity.  Upon crossing a boundary outside the window, their position wraps.
00170
00171     for (auto asteroid = m_asteroidData.begin(); asteroid != m_asteroidData.end(); asteroid++)
00172     {
00173         static const float border = 100.0f;
00174         asteroid->pos = asteroid->pos + asteroid->vel * timeDelta;
00175         if (asteroid->vel.x < 0)
00176         {
00177             if (asteroid->pos.x < -border)
00178             {
00179                 asteroid->pos.x = m_windowBounds.Width + border;
00180             }
00181         }
00182         else
00183         {
00184             if (asteroid->pos.x > m_windowBounds.Width + border)
00185             {
00186                 asteroid->pos.x = -border;
00187             }
00188         }
00189         if (asteroid->vel.y < 0)
00190         {
00191             if (asteroid->pos.y < -border)
00192             {
00193                 asteroid->pos.y = m_windowBounds.Height + border;
00194             }
00195         }
00196         else
00197         {
00198             if (asteroid->pos.y > m_windowBounds.Height + border)
00199             {
00200                 asteroid->pos.y = -border;
00201             }
00202         }
00203
00204         asteroid->rot += asteroid->rotVel * timeDelta;
00205         if (asteroid->rot > PI_F)
00206         {
00207             asteroid->rot -= 2.0f * PI_F;
00208         }
00209         if (asteroid->rot < -PI_F)
00210         {
00211             asteroid->rot += 2.0f * PI_F;
00212         }
00213     }
00214
00215     // Update the interactive particles.
00216     // Their behavior is to be gravitationally attracted to two oscillating gravity
00217     // wells and repelled by any pressed pointer points.  Upon reaching the edge of
00218     // the window, the particles bounce.
00219
00220     // Add two gravity wells that move throughout the window.
00221     float2 wellPositions[] =
00222     {
00223         float2(
00224             (1.0f + 0.8f * cosf(timeTotal / (2.0f * PI_F) + 3.0f)) * m_windowBounds.Width / 2.0f,
00225             (1.0f + 0.8f * sinf(timeTotal / 5.0f)) * m_windowBounds.Height / 2.0f
00226             ),
00227         float2(
00228             (1.0f + 0.8f * cosf(timeTotal / (PI_F * PI_F) + 1.0f)) * m_windowBounds.Width / 2.0f,
00229             (1.0f + 0.8f * sinf(timeTotal / PI_F)) * m_windowBounds.Height / 2.0f
00230             )
00231     };
00232
00233     for (auto particle = m_particleData.begin(); particle != m_particleData.begin() + m_numParticlesToDraw; particle++)
00234     {
00235         if (particle->pos.x < 0)
00236         {
00237             particle->vel.x = abs(particle->vel.x);
00238         }
00239         if (particle->pos.x > m_windowBounds.Width)
00240         {
00241             particle->vel.x = -abs(particle->vel.x);
00242         }
00243         if (particle->pos.y < 0)
00244         {
00245             particle->vel.y = abs(particle->vel.y);
00246         }
00247         if (particle->pos.y > m_windowBounds.Height)
00248         {
00249             particle->vel.y = -abs(particle->vel.y);
00250         }
00251
00252         for (auto repulsor = m_repulsors.begin(); repulsor != m_repulsors.end(); repulsor++)
00253         {
00254             float2 delta = particle->pos - repulsor->second;
00255             float deltaLength = length(delta) + 24.0f; // Offset length to avoid division by zero.
00256             float deltaLengthCubed = deltaLength * deltaLength * deltaLength;
00257             particle->vel = particle->vel + SampleSettings::Physics::Gravity * timeDelta * delta / deltaLengthCubed;
00258         }
00259
00260         for (int i = 0; i < ARRAYSIZE(wellPositions); i++)
00261         {
00262             float gravitySign = 1.0f;
00263             if ((static_cast<int>(timeTotal / 2.0f) + 1) % 10 == 0)
00264             {
00265                 // Every 20 seconds, "explode" the gravity wells for 2 seconds.
00266                 gravitySign = -1.0f;
00267             }
00268             float2 delta = wellPositions[i] - particle->pos;
00269             float deltaLength = length(delta) + 24.0f;
00270             float deltaLengthCubed = deltaLength * deltaLength * deltaLength;
00271             particle->vel = particle->vel + gravitySign * 0.2f * SampleSettings::Physics::Gravity * timeDelta * delta / deltaLengthCubed;
00272         }
00273
00274         particle->vel = particle->vel * (1.0f - SampleSettings::Physics::Damping);
00275
00276         // Add random noise to the velocity to prevent particles from locking together.
00277
00278         particle->vel.x += RandFloat(-0.5f, 0.5f);
00279         particle->vel.y += RandFloat(-0.5f, 0.5f);
00280
00281         particle->pos = particle->pos + particle->vel * timeDelta;
00282     }
00283 }
00284
00285 void SimpleSprites::Render()
00286 {
00287     m_d3dContext->OMSetRenderTargets(
00288         1,
00289         m_d3dRenderTargetView.GetAddressOf(),
00290         nullptr
00291         );
00292
00293     m_d3dContext->ClearRenderTargetView(
00294         m_d3dRenderTargetView.Get(),
00295         reinterpret_cast<float*>(&D2D1::ColorF(D2D1::ColorF::MidnightBlue))
00296         );
00297
00298     m_spriteBatch->Begin();
00299
00300     // Draw the background.
00301
00302     m_spriteBatch->Draw(
00303         m_background.Get(),
00304         float2(0.5f, 0.5f),
00305         PositionUnits::Normalized,
00306         float2(1.0f, 1.0f),
00307         SizeUnits::Normalized
00308         );
00309
00310     // Draw the non-interactive asteroids.
00311
00312     for (auto asteroid = m_asteroidData.begin(); asteroid != m_asteroidData.end(); asteroid++)
00313     {
00314         m_spriteBatch->Draw(
00315             m_asteroid.Get(),
00316             asteroid->pos,
00317             PositionUnits::DIPs,
00318             float2(1.0f, 1.0f) * asteroid->scale,
00319             SizeUnits::Normalized,
00320             float4(0.8f, 0.8f, 1.0f, 1.0f),
00321             asteroid->rot
00322             );
00323     }
00324
00325     // Draw the interactive particles.
00326
00327     for (auto particle = m_particleData.begin(); particle != m_particleData.begin() + m_numParticlesToDraw; particle++)
00328     {
00329         float alpha = length(particle->vel) / 200.0f;
00330         m_spriteBatch->Draw(
00331             m_particle.Get(),
00332             particle->pos,
00333             PositionUnits::DIPs,
00334             float2(32.0f, 32.0f),
00335             SizeUnits::DIPs,
00336             float4(0.1f, 0.02f, 0.0f, alpha),
00337             0.0f,
00338             BlendMode::Additive
00339             );
00340     }
00341
00342     m_spriteBatch->End();
00343
00344     // Render the Sample Overlay.
00345
00346     m_sampleOverlay->Render();
00347 }
00348
00349 float SimpleSprites::RandFloat(float min, float max)
00350 {
00351     return (static_cast<float>(rand() % RAND_MAX) / static_cast<float>(RAND_MAX)) * (max - min) + min;
00352 }
00353
00354 void SimpleSprites::AddRepulsor(_In_ uint32 id, _In_ float2 position)
00355 {
00356     m_repulsors[id] = position;
00357 }
00358
00359 void SimpleSprites::MoveRepulsor(_In_ uint32 id, _In_ float2 position)
00360 {
00361     m_repulsors[id] = position;
00362 }
00363
00364 void SimpleSprites::RemoveRepulsor(_In_ uint32 id)
00365 {
00366     m_repulsors.erase(id);
00367 }
Generated on Sat Nov 23 2024 16:08:12 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

ToastsSampleCPP::sealed Member List

This is the complete list of members for ToastsSampleCPP::sealed, including all inherited members.
_displayHandlerToken | ToastsSampleCPP::sealed | [private]
_frameLoadedToken | ToastsSampleCPP::sealed | [private]
_inputFrame | ToastsSampleCPP::sealed | [private]
_inputFrameLoadedToken | ToastsSampleCPP::sealed | [private]
_layoutHandlerToken | ToastsSampleCPP::sealed | [private]
_logicalDpiChangedToken | ToastsSampleCPP::sealed | [private]
_outputFrame | ToastsSampleCPP::sealed | [private]
_outputFrameLoadedToken | ToastsSampleCPP::sealed | [private]
_pageLoadedHandlerToken | ToastsSampleCPP::sealed | [private]
_scenariosFrame | ToastsSampleCPP::sealed | [private]
_toast | ToastsSampleCPP::sealed | [private]
_toastContext | ToastsSampleCPP::sealed | [private]
App() | ToastsSampleCPP::sealed |
CheckResolutionAndViewState() | ToastsSampleCPP::sealed | [private]
CheckResolutionAndViewState() | ToastsSampleCPP::sealed | [private]
ConvertResolution(ResolutionScale scale) | ToastsSampleCPP::sealed |
ConvertViewState(ApplicationViewState state) | ToastsSampleCPP::sealed |
dispatcher | ToastsSampleCPP::sealed | [private]
DisplayProperties_LogicalDpiChanged(Object^sender) | ToastsSampleCPP::sealed | [private]
DisplayProperties_LogicalDpiChanged(Object^sender) | ToastsSampleCPP::sealed | [private]
DoNavigation(TypeName pageType, Windows::UI::Xaml::Controls::Frame^frame) | ToastsSampleCPP::sealed |
Footer_Click(Object^sender, RoutedEventArgs^e) | ToastsSampleCPP::sealed | [private]
inputFrameNavigated(Object^sender, NavigationEventArgs^e) | ToastsSampleCPP::sealed | [private]
MainPage() | ToastsSampleCPP::sealed |
MainPageAndContext(ToastsSampleCPP::MainPage^mainPage, Platform::String^toastContext) | ToastsSampleCPP::sealed | [inline]
NotifyUser(String^strMessage, NotifyType type) | ToastsSampleCPP::sealed |
OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^args) override | ToastsSampleCPP::sealed | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ToastsSampleCPP::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ToastsSampleCPP::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ToastsSampleCPP::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ToastsSampleCPP::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ToastsSampleCPP::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ToastsSampleCPP::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ToastsSampleCPP::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ToastsSampleCPP::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ToastsSampleCPP::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ToastsSampleCPP::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ToastsSampleCPP::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ToastsSampleCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ToastsSampleCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ToastsSampleCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ToastsSampleCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ToastsSampleCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ToastsSampleCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ToastsSampleCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ToastsSampleCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ToastsSampleCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ToastsSampleCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ToastsSampleCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ToastsSampleCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ToastsSampleCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ToastsSampleCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ToastsSampleCPP::sealed | [protected, virtual]
OnSuspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^pArgs) | ToastsSampleCPP::sealed | [virtual]
OutputFrameLoaded | ToastsSampleCPP::sealed |
outputFrameNavigated(Object^sender, NavigationEventArgs^e) | ToastsSampleCPP::sealed | [private]
OutputText(Platform::String^text) | ToastsSampleCPP::sealed | [private]
OutputText(Platform::String^text) | ToastsSampleCPP::sealed | [private]
OutputText(Platform::String^text) | ToastsSampleCPP::sealed | [private]
OutputText(Platform::String^text) | ToastsSampleCPP::sealed | [private]
OutputText(Platform::String^text) | ToastsSampleCPP::sealed | [private]
OutputText(Platform::String^text) | ToastsSampleCPP::sealed | [private]
outputText | ToastsSampleCPP::sealed | [private]
Page_Loaded(Object^sender, RoutedEventArgs^e) | ToastsSampleCPP::sealed | [private]
Page_Loaded(Object^sender, RoutedEventArgs^e) | ToastsSampleCPP::sealed | [private]
Page_SizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | ToastsSampleCPP::sealed | [private]
Page_SizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | ToastsSampleCPP::sealed | [private]
rootPage | ToastsSampleCPP::sealed | [private]
rootPage_InputFrameLoaded(Object^sender, Object^e) | ToastsSampleCPP::sealed | [private]
rootPage_InputFrameLoaded(Object^sender, Object^e) | ToastsSampleCPP::sealed | [private]
rootPage_InputFrameLoaded(Object^sender, Object^e) | ToastsSampleCPP::sealed | [private]
rootPage_InputFrameLoaded(Object^sender, Object^e) | ToastsSampleCPP::sealed | [private]
rootPage_InputFrameLoaded(Object^sender, Object^e) | ToastsSampleCPP::sealed | [private]
rootPage_InputFrameLoaded(Object^sender, Object^e) | ToastsSampleCPP::sealed | [private]
rootPage_OutputFrameLoaded(Object^sender, Object^e) | ToastsSampleCPP::sealed | [private]
Scenario1DisplayToast(Windows::UI::Notifications::ToastTemplateType templateType) | ToastsSampleCPP::sealed | [private]
Scenario1DisplayToastWithStringManipulation(Windows::UI::Notifications::ToastTemplateType templateType) | ToastsSampleCPP::sealed | [private]
Scenario2DisplayToast(Windows::UI::Notifications::ToastTemplateType templateType) | ToastsSampleCPP::sealed | [private]
Scenario2DisplayToastWithStringManipulation(Windows::UI::Notifications::ToastTemplateType templateType) | ToastsSampleCPP::sealed | [private]
Scenario3DisplayToast(Windows::UI::Notifications::ToastTemplateType templateType) | ToastsSampleCPP::sealed | [private]
Scenario3DisplayToastWithStringManipulation(Windows::UI::Notifications::ToastTemplateType templateType) | ToastsSampleCPP::sealed | [private]
Scenario4DisplayToastWithSound(NotificationsExtensions::ToastContent::ToastAudioContent audioContent, Platform::String^audioSrc) | ToastsSampleCPP::sealed | [private]
Scenario4DisplayToastWithSoundWithStringManipulation(NotificationsExtensions::ToastContent::ToastAudioContent audioContent, Platform::String^audioSrc) | ToastsSampleCPP::sealed | [private]
Scenario5DisplayToastWithCallbacks_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | ToastsSampleCPP::sealed | [private]
Scenario5HideToast_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | ToastsSampleCPP::sealed | [private]
Scenario6DisplayLongToast(bool loopAudio) | ToastsSampleCPP::sealed | [private]
Scenario6DisplayLongToastWithStringManipulation(bool loopAudio) | ToastsSampleCPP::sealed | [private]
ScenarioInput1() | ToastsSampleCPP::sealed |
ScenarioInput2() | ToastsSampleCPP::sealed |
ScenarioInput3() | ToastsSampleCPP::sealed |
ScenarioInput4() | ToastsSampleCPP::sealed |
ScenarioInput5() | ToastsSampleCPP::sealed |
ScenarioInput6() | ToastsSampleCPP::sealed |
ScenarioList() | ToastsSampleCPP::sealed |
ScenarioOutput1() | ToastsSampleCPP::sealed |
ScenarioOutput2() | ToastsSampleCPP::sealed |
ScenarioOutput3() | ToastsSampleCPP::sealed |
ScenarioOutput4() | ToastsSampleCPP::sealed |
ScenarioOutput5() | ToastsSampleCPP::sealed |
ScenarioOutput6() | ToastsSampleCPP::sealed |
Scenarios_SelectionChanged(Object^sender, SelectionChangedEventArgs^e) | ToastsSampleCPP::sealed | [protected]
SetFeatureName(Platform::String^strFeature) | ToastsSampleCPP::sealed | [private]
toast_Dismissed(Windows::UI::Notifications::ToastNotification^sender, Windows::UI::Notifications::ToastDismissedEventArgs^e) | ToastsSampleCPP::sealed | [private]
toast_Failed(Windows::UI::Notifications::ToastNotification^sender, Windows::UI::Notifications::ToastFailedEventArgs^e) | ToastsSampleCPP::sealed | [private]
toastContext | ToastsSampleCPP::sealed | [private]
~MainPage() | ToastsSampleCPP::sealed | [private]
~ScenarioInput1() | ToastsSampleCPP::sealed | [private]
~ScenarioInput2() | ToastsSampleCPP::sealed | [private]
~ScenarioInput3() | ToastsSampleCPP::sealed | [private]
~ScenarioInput4() | ToastsSampleCPP::sealed | [private]
~ScenarioInput5() | ToastsSampleCPP::sealed | [private]
~ScenarioInput6() | ToastsSampleCPP::sealed | [private]
~ScenarioList() | ToastsSampleCPP::sealed | [private]
~ScenarioOutput1() | ToastsSampleCPP::sealed | [private]
~ScenarioOutput2() | ToastsSampleCPP::sealed | [private]
~ScenarioOutput3() | ToastsSampleCPP::sealed | [private]
~ScenarioOutput4() | ToastsSampleCPP::sealed | [private]
~ScenarioOutput5() | ToastsSampleCPP::sealed | [private]
~ScenarioOutput6() | ToastsSampleCPP::sealed | [private]
Generated on Sat Nov 23 2024 16:09:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::ToastContent::ToastImageAndText01 Member List

This is the complete list of members for NotificationsExtensions::ToastContent::ToastImageAndText01, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
Audio | NotificationsExtensions::ToastContent::ToastNotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
CreateNotification() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline]
Duration | NotificationsExtensions::ToastContent::ToastNotificationBase |
GetContent() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline, virtual]
GetContent() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline, virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Image | NotificationsExtensions::ToastContent::ToastImageAndText01 |
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
Launch | NotificationsExtensions::ToastContent::ToastNotificationBase |
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextBodyWrap | NotificationsExtensions::ToastContent::ToastImageAndText01 |
TextFields | NotificationsExtensions::NotificationBase |
ToastImageAndText01() | NotificationsExtensions::ToastContent::ToastImageAndText01 | [inline]
ToastImageAndText01() | NotificationsExtensions::ToastContent::ToastImageAndText01 | [inline]
ToastNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline]
ToastNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: App tiles and badges/C#,C++/SendLocalImageTile.xaml.h Source File

  • App tiles and badges
  • C#,C++

SendLocalImageTile.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 // SendLocalImageTile.xaml.h
00013 // Declaration of the SendLocalImageTile class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "SendLocalImageTile.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace Tiles
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 SendLocalImageTile sealed
00031         {
00032         public:
00033             SendLocalImageTile();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039         void UpdateTileWithImage_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040     void UpdateTileWithImageWithStringManipulation_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         void ClearTile_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00042         };
00043     }
00044 }
Generated on Sat Nov 23 2024 16:07:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Programmatic file search/C++/pch.cpp Source File

  • Programmatic file search

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D interpolation modes/C++/pch.h Source File

  • Direct2D interpolation modes

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 <d3d11_1.h>
00012 #include <dxgi1_2.h>
00013 #include <d2d1_1.h>
00014 #include <d2d1effects.h>
00015 #include <dwrite_1.h>
00016 #include <wincodec.h>
00017 #include <agile.h>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/texconv/Texconv.cpp Source File

  • Direct3D resource loading
  • texconv

Texconv.cpp

Go to the documentation of this file.
00001 //--------------------------------------------------------------------------------------
00002 // File: TexConv.cpp
00003 //
00004 // DirectX 11 Texture Converer
00005 //
00006 // Copyright (c) Microsoft Corporation. All rights reserved.
00007 //--------------------------------------------------------------------------------------
00008
00009 #pragma warning( disable : 4447 )
00010 #include <stdio.h>
00011 #include <stdlib.h>
00012 #include <assert.h>
00013
00014 #include <dxgiformat.h>
00015
00016 #include "directxtex.h"
00017
00018 using namespace DirectX;
00019
00020 enum OPTIONS    // Note: dwOptions below assumes 32 or less options.
00021 {
00022     OPT_WIDTH = 1,
00023     OPT_HEIGHT,
00024     OPT_MIPLEVELS,
00025     OPT_FORMAT,
00026     OPT_FILTER,
00027     OPT_SRGBI,
00028     OPT_SRGBO,
00029     OPT_SRGB,
00030     OPT_PREFIX,
00031     OPT_SUFFIX,
00032     OPT_OUTPUTDIR,
00033     OPT_FILETYPE,
00034     OPT_HFLIP,
00035     OPT_VFLIP,
00036     OPT_DDS_DWORD_ALIGN,
00037     OPT_USE_DX10,
00038     OPT_NOLOGO,
00039     OPT_SEPALPHA
00040 };
00041
00042 struct SConversion
00043 {
00044     WCHAR szSrc [MAX_PATH];
00045     WCHAR szDest[MAX_PATH];
00046
00047     SConversion *pNext;
00048 };
00049
00050 struct SValue
00051 {
00052     LPCWSTR pName;
00053     DWORD dwValue;
00054 };
00055
00056 //////////////////////////////////////////////////////////////////////////////
00057 //////////////////////////////////////////////////////////////////////////////
00058 //////////////////////////////////////////////////////////////////////////////
00059
00060 SValue g_pOptions[] =
00061 {
00062     { L"w",             OPT_WIDTH     },
00063     { L"h",             OPT_HEIGHT    },
00064     { L"m",             OPT_MIPLEVELS },
00065     { L"f",             OPT_FORMAT    },
00066     { L"if",            OPT_FILTER    },
00067     { L"srgbi",         OPT_SRGBI     },
00068     { L"srgbo",         OPT_SRGBO     },
00069     { L"srgb",          OPT_SRGB      },
00070     { L"px",            OPT_PREFIX    },
00071     { L"sx",            OPT_SUFFIX    },
00072     { L"o",             OPT_OUTPUTDIR },
00073     { L"ft",            OPT_FILETYPE  },
00074     { L"hflip",         OPT_HFLIP     },
00075     { L"vflip",         OPT_VFLIP     },
00076     { L"dword",         OPT_DDS_DWORD_ALIGN },
00077     { L"dx10",          OPT_USE_DX10  },
00078     { L"nologo",        OPT_NOLOGO    },
00079     { L"sepalpha",      OPT_SEPALPHA  },
00080     { nullptr,          0             }
00081 };
00082
00083 #define DEFFMT(fmt) { L#fmt , DXGI_FORMAT_ ## fmt }
00084
00085 SValue g_pFormats[] =
00086 {
00087     // List does not include _TYPELESS or depth/stencil formats
00088     DEFFMT(R32G32B32A32_FLOAT),
00089     DEFFMT(R32G32B32A32_UINT),
00090     DEFFMT(R32G32B32A32_SINT),
00091     DEFFMT(R32G32B32_FLOAT),
00092     DEFFMT(R32G32B32_UINT),
00093     DEFFMT(R32G32B32_SINT),
00094     DEFFMT(R16G16B16A16_FLOAT),
00095     DEFFMT(R16G16B16A16_UNORM),
00096     DEFFMT(R16G16B16A16_UINT),
00097     DEFFMT(R16G16B16A16_SNORM),
00098     DEFFMT(R16G16B16A16_SINT),
00099     DEFFMT(R32G32_FLOAT),
00100     DEFFMT(R32G32_UINT),
00101     DEFFMT(R32G32_SINT),
00102     DEFFMT(R10G10B10A2_UNORM),
00103     DEFFMT(R10G10B10A2_UINT),
00104     DEFFMT(R11G11B10_FLOAT),
00105     DEFFMT(R8G8B8A8_UNORM),
00106     DEFFMT(R8G8B8A8_UNORM_SRGB),
00107     DEFFMT(R8G8B8A8_UINT),
00108     DEFFMT(R8G8B8A8_SNORM),
00109     DEFFMT(R8G8B8A8_SINT),
00110     DEFFMT(R16G16_FLOAT),
00111     DEFFMT(R16G16_UNORM),
00112     DEFFMT(R16G16_UINT),
00113     DEFFMT(R16G16_SNORM),
00114     DEFFMT(R16G16_SINT),
00115     DEFFMT(R32_FLOAT),
00116     DEFFMT(R32_UINT),
00117     DEFFMT(R32_SINT),
00118     DEFFMT(R8G8_UNORM),
00119     DEFFMT(R8G8_UINT),
00120     DEFFMT(R8G8_SNORM),
00121     DEFFMT(R8G8_SINT),
00122     DEFFMT(R16_FLOAT),
00123     DEFFMT(R16_UNORM),
00124     DEFFMT(R16_UINT),
00125     DEFFMT(R16_SNORM),
00126     DEFFMT(R16_SINT),
00127     DEFFMT(R8_UNORM),
00128     DEFFMT(R8_UINT),
00129     DEFFMT(R8_SNORM),
00130     DEFFMT(R8_SINT),
00131     DEFFMT(A8_UNORM),
00132     //DEFFMT(R1_UNORM)
00133     DEFFMT(R9G9B9E5_SHAREDEXP),
00134     DEFFMT(R8G8_B8G8_UNORM),
00135     DEFFMT(G8R8_G8B8_UNORM),
00136     DEFFMT(BC1_UNORM),
00137     DEFFMT(BC1_UNORM_SRGB),
00138     DEFFMT(BC2_UNORM),
00139     DEFFMT(BC2_UNORM_SRGB),
00140     DEFFMT(BC3_UNORM),
00141     DEFFMT(BC3_UNORM_SRGB),
00142     DEFFMT(BC4_UNORM),
00143     DEFFMT(BC4_SNORM),
00144     DEFFMT(BC5_UNORM),
00145     DEFFMT(BC5_SNORM),
00146     DEFFMT(B5G6R5_UNORM),
00147     DEFFMT(B5G5R5A1_UNORM),
00148
00149     // DXGI 1.1 formats
00150     DEFFMT(B8G8R8A8_UNORM),
00151     DEFFMT(B8G8R8X8_UNORM),
00152     DEFFMT(R10G10B10_XR_BIAS_A2_UNORM),
00153     DEFFMT(B8G8R8A8_UNORM_SRGB),
00154     DEFFMT(B8G8R8X8_UNORM_SRGB),
00155     DEFFMT(BC6H_UF16),
00156     DEFFMT(BC6H_SF16),
00157     DEFFMT(BC7_UNORM),
00158     DEFFMT(BC7_UNORM_SRGB),
00159
00160     // DXGI 1.2 formats
00161     DEFFMT(B4G4R4A4_UNORM),
00162
00163     { nullptr, DXGI_FORMAT_UNKNOWN }
00164 };
00165
00166 SValue g_pFilters[] =
00167 {
00168     { L"POINT",         TEX_FILTER_POINT                                },
00169     { L"LINEAR",        TEX_FILTER_LINEAR                               },
00170     { L"CUBIC",         TEX_FILTER_CUBIC                                },
00171     { L"FANT",          TEX_FILTER_FANT                                 },
00172     { L"POINT_DITHER",  TEX_FILTER_POINT | TEX_FILTER_DITHER_DIFFUSION  },
00173     { L"LINEAR_DITHER", TEX_FILTER_LINEAR | TEX_FILTER_DITHER_DIFFUSION },
00174     { L"CUBIC_DITHER",  TEX_FILTER_CUBIC | TEX_FILTER_DITHER_DIFFUSION  },
00175     { L"FANT_DITHER",   TEX_FILTER_FANT  | TEX_FILTER_DITHER_DIFFUSION  },
00176     { nullptr,          TEX_FILTER_DEFAULT                              }
00177 };
00178
00179 #define CODEC_DDS 0xFFFF0001
00180 #define CODEC_TGA 0xFFFF0002
00181
00182 SValue g_pSaveFileTypes[] =     // valid formats to write to
00183 {
00184     { L"BMP",           WIC_CODEC_BMP  },
00185     { L"JPG",           WIC_CODEC_JPEG },
00186     { L"JPEG",          WIC_CODEC_JPEG },
00187     { L"PNG",           WIC_CODEC_PNG  },
00188     { L"DDS",           CODEC_DDS      },
00189     { L"TGA",           CODEC_TGA      },
00190     { L"TIF",           WIC_CODEC_TIFF },
00191     { L"TIFF",          WIC_CODEC_TIFF },
00192     { L"WDP",           WIC_CODEC_WMP  },
00193     { L"HDP",           WIC_CODEC_WMP  },
00194     { nullptr,          CODEC_DDS      }
00195 };
00196
00197 //////////////////////////////////////////////////////////////////////////////
00198 //////////////////////////////////////////////////////////////////////////////
00199 //////////////////////////////////////////////////////////////////////////////
00200
00201 #pragma warning( disable : 4616 6211 )
00202
00203 inline static bool ispow2(size_t x)
00204 {
00205     return ((x != 0) && !(x & (x - 1)));
00206 }
00207
00208 #pragma prefast(disable : 26018, "Only used with static internal arrays")
00209
00210 DWORD LookupByName(const WCHAR *pName, const SValue *pArray)
00211 {
00212     while(pArray->pName)
00213     {
00214         if(!_wcsicmp(pName, pArray->pName))
00215             return pArray->dwValue;
00216
00217         pArray++;
00218     }
00219
00220     return 0;
00221 }
00222
00223 const WCHAR* LookupByValue(DWORD pValue, const SValue *pArray)
00224 {
00225     while(pArray->pName)
00226     {
00227         if(pValue == pArray->dwValue)
00228             return pArray->pName;
00229
00230         pArray++;
00231     }
00232
00233     return L"";
00234 }
00235
00236 void PrintFormat(DXGI_FORMAT Format)
00237 {
00238     for(SValue *pFormat = g_pFormats; pFormat->pName; pFormat++)
00239     {
00240         if((DXGI_FORMAT) pFormat->dwValue == Format)
00241         {
00242             wprintf( pFormat->pName );
00243             break;
00244         }
00245     }
00246 }
00247
00248 void PrintInfo( const TexMetadata& info )
00249 {
00250     wprintf( L" (%Iux%Iu", info.width, info.height);
00251
00252     if ( TEX_DIMENSION_TEXTURE3D == info.dimension )
00253         wprintf( L"x%Iu", info.depth);
00254
00255     if ( info.mipLevels > 1 )
00256         wprintf( L",%Iu", info.mipLevels);
00257
00258     wprintf( L" ");
00259     PrintFormat( info.format );
00260
00261     switch ( info.dimension )
00262     {
00263     case TEX_DIMENSION_TEXTURE1D:
00264         wprintf( (info.arraySize > 1) ? L" 1DArray" : L" 1D" );
00265         break;
00266
00267     case TEX_DIMENSION_TEXTURE2D:
00268         if ( info.miscFlags & TEX_MISC_TEXTURECUBE )
00269         {
00270             wprintf( (info.arraySize > 1) ? L" CubeArray" : L" Cube" );
00271         }
00272         else
00273         {
00274             wprintf( (info.arraySize > 1) ? L" 2DArray" : L" 2D" );
00275         }
00276         break;
00277
00278     case TEX_DIMENSION_TEXTURE3D:
00279         wprintf( L" 3D");
00280         break;
00281     }
00282
00283     wprintf( L")");
00284 }
00285
00286
00287 void PrintList(size_t cch, SValue *pValue)
00288 {
00289     while(pValue->pName)
00290     {
00291         size_t cchName = wcslen(pValue->pName);
00292
00293         if(cch + cchName + 2>= 80)
00294         {
00295             wprintf( L"\n      ");
00296             cch = 6;
00297         }
00298
00299         wprintf( L"%s ", pValue->pName );
00300         cch += cchName + 2;
00301         pValue++;
00302     }
00303
00304     wprintf( L"\n");
00305 }
00306
00307
00308 void PrintLogo()
00309 {
00310     wprintf( L"Microsoft (R) DirectX 11 Texture Converter (DirectXTex version)\n");
00311     wprintf( L"Copyright (C) Microsoft Corp. All rights reserved.\n");
00312     wprintf( L"\n");
00313 }
00314
00315
00316 void PrintUsage()
00317 {
00318     PrintLogo();
00319
00320     wprintf( L"Usage: texconv <options> <files>\n");
00321     wprintf( L"\n");
00322     wprintf( L"   -w <n>              width\n");
00323     wprintf( L"   -h <n>              height\n");
00324     wprintf( L"   -d <n>              depth\n");
00325     wprintf( L"   -m <n>              miplevels\n");
00326     wprintf( L"   -f <format>         format\n");
00327     wprintf( L"   -if <filter>        image filtering\n");
00328     wprintf( L"   -srgb{i|o}          sRGB {input, output}\n");
00329     wprintf( L"   -px <string>        name prefix\n");
00330     wprintf( L"   -sx <string>        name suffix\n");
00331     wprintf( L"   -o <directory>      output directory\n");
00332     wprintf( L"   -ft <filetype>      output file type\n");
00333     wprintf( L"   -hflip              horizonal flip of source image\n");
00334     wprintf( L"   -vflip              vertical flip of source image\n");
00335     wprintf( L"   -sepalpha           resize/generate mips alpha channel separately from color channels\n");
00336     wprintf( L"   -dword              Use DWORD instead of BYTE alignment (DDS input only)\n");
00337     wprintf( L"   -dx10               Force use of 'DX10' extended header (DDS output only)\n");
00338     wprintf( L"   -nologo             suppress copyright message\n");
00339
00340     wprintf( L"\n");
00341     wprintf( L"   <format>: ");
00342     PrintList(13, g_pFormats);
00343
00344     wprintf( L"\n");
00345     wprintf( L"   <filter>: ");
00346     PrintList(13, g_pFilters);
00347
00348     wprintf( L"\n");
00349     wprintf( L"   <filetype>: ");
00350     PrintList(15, g_pSaveFileTypes);
00351 }
00352
00353
00354 //--------------------------------------------------------------------------------------
00355 // Entry-point
00356 //--------------------------------------------------------------------------------------
00357 #pragma prefast(disable : 28198, "Command-line tool, frees all memory on exit")
00358
00359 int __cdecl wmain(_In_ int argc, _In_reads_(argc) PWSTR argv[])
00360 {
00361     // Parameters and defaults
00362     HRESULT hr;
00363     INT nReturn;
00364
00365     size_t width = 0;
00366     size_t height = 0;
00367     size_t mipLevels = 0;
00368     DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;
00369     DWORD dwFilter = TEX_FILTER_DEFAULT;
00370     DWORD dwSRGB = 0;
00371     DWORD dwFilterOpts = 0;
00372     DWORD FileType = CODEC_DDS;
00373
00374     WCHAR szPrefix   [MAX_PATH];
00375     WCHAR szSuffix   [MAX_PATH];
00376     WCHAR szOutputDir[MAX_PATH];
00377
00378     szPrefix[0]    = 0;
00379     szSuffix[0]    = 0;
00380     szOutputDir[0] = 0;
00381
00382     // Initialize COM (needed for WIC)
00383     if( FAILED( hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED) ) )
00384     {
00385         wprintf( L"Failed to initialize COM (%08X)\n", hr);
00386         return 1;
00387     }
00388
00389     // Process command line
00390     DWORD dwOptions = 0;
00391     SConversion *pConversion = nullptr;
00392     SConversion **ppConversion = &pConversion;
00393
00394     for(int iArg = 1; iArg < argc; iArg++)
00395     {
00396         PWSTR pArg = argv[iArg];
00397
00398         if(('-' == pArg[0]) || ('/' == pArg[0]))
00399         {
00400             pArg++;
00401             PWSTR pValue;
00402
00403             for(pValue = pArg; *pValue && (':' != *pValue); pValue++);
00404
00405             if(*pValue)
00406                 *pValue++ = 0;
00407
00408             DWORD dwOption = LookupByName(pArg, g_pOptions);
00409
00410             if(!dwOption || (dwOptions & (1 << dwOption)))
00411             {
00412                 PrintUsage();
00413                 return 1;
00414             }
00415
00416             dwOptions |= 1 << dwOption;
00417
00418             if( (OPT_NOLOGO != dwOption) && (OPT_SEPALPHA != dwOption)
00419                 && (OPT_SRGB != dwOption) && (OPT_SRGBI != dwOption) && (OPT_SRGBO != dwOption)
00420                 && (OPT_HFLIP != dwOption) && (OPT_VFLIP != dwOption)
00421                 && (OPT_DDS_DWORD_ALIGN != dwOption) && (OPT_USE_DX10 != dwOption) )
00422             {
00423                 if(!*pValue)
00424                 {
00425                     if((iArg + 1 >= argc))
00426                     {
00427                         PrintUsage();
00428                         return 1;
00429                     }
00430
00431                     iArg++;
00432                     pValue = argv[iArg];
00433                 }
00434             }
00435
00436             switch(dwOption)
00437             {
00438             case OPT_WIDTH:
00439                 if (swscanf_s(pValue, L"%Iu", &width) != 1)
00440                 {
00441                     wprintf( L"Invalid value specified with -w (%s)\n", pValue);
00442                     wprintf( L"\n");
00443                     PrintUsage();
00444                     return 1;
00445                 }
00446                 break;
00447
00448             case OPT_HEIGHT:
00449                 if (swscanf_s(pValue, L"%Iu", &height) != 1)
00450                 {
00451                     wprintf( L"Invalid value specified with -h (%s)\n", pValue);
00452                     printf("\n");
00453                     PrintUsage();
00454                     return 1;
00455                 }
00456                 break;
00457
00458             case OPT_MIPLEVELS:
00459                 if (swscanf_s(pValue, L"%Iu", &mipLevels) != 1)
00460                 {
00461                     wprintf( L"Invalid value specified with -m (%s)\n", pValue);
00462                     wprintf( L"\n");
00463                     PrintUsage();
00464                     return 1;
00465                 }
00466                 break;
00467
00468             case OPT_FORMAT:
00469                 format = (DXGI_FORMAT) LookupByName(pValue, g_pFormats);
00470                 if ( !format )
00471                 {
00472                     wprintf( L"Invalid value specified with -f (%s)\n", pValue);
00473                     wprintf( L"\n");
00474                     PrintUsage();
00475                     return 1;
00476                 }
00477                 break;
00478
00479             case OPT_FILTER:
00480                 dwFilter = LookupByName(pValue, g_pFilters);
00481                 if ( !dwFilter )
00482                 {
00483                     wprintf( L"Invalid value specified with -if (%s)\n", pValue);
00484                     wprintf( L"\n");
00485                     PrintUsage();
00486                     return 1;
00487                 }
00488                 break;
00489
00490             case OPT_SRGBI:
00491                 dwSRGB |= TEX_FILTER_SRGB_IN;
00492                 break;
00493
00494             case OPT_SRGBO:
00495                 dwSRGB |= TEX_FILTER_SRGB_OUT;
00496                 break;
00497
00498             case OPT_SRGB:
00499                 dwSRGB |= TEX_FILTER_SRGB;
00500                 break;
00501
00502             case OPT_SEPALPHA:
00503                 dwFilterOpts |= TEX_FILTER_SEPARATE_ALPHA;
00504                 break;
00505
00506             case OPT_PREFIX:
00507                 wcscpy_s(szPrefix, MAX_PATH, pValue);
00508                 break;
00509
00510             case OPT_SUFFIX:
00511                 wcscpy_s(szSuffix, MAX_PATH, pValue);
00512                 break;
00513
00514             case OPT_OUTPUTDIR:
00515                 wcscpy_s(szOutputDir, MAX_PATH, pValue);
00516                 break;
00517
00518             case OPT_FILETYPE:
00519                 FileType = LookupByName(pValue, g_pSaveFileTypes);
00520                 if ( !FileType )
00521                 {
00522                     wprintf( L"Invalid value specified with -ft (%s)\n", pValue);
00523                     wprintf( L"\n");
00524                     PrintUsage();
00525                     return 1;
00526                 }
00527                 break;
00528             }
00529         }
00530         else
00531         {
00532             SConversion *pConv = new SConversion;
00533             if ( !pConv )
00534                 return 1;
00535
00536             wcscpy_s(pConv->szSrc, MAX_PATH, pArg);
00537
00538             pConv->szDest[0] = 0;
00539             pConv->pNext = nullptr;
00540
00541             *ppConversion = pConv;
00542             ppConversion = &pConv->pNext;
00543         }
00544     }
00545
00546     if(!pConversion)
00547     {
00548         PrintUsage();
00549         return 0;
00550     }
00551
00552     if(~dwOptions & (1 << OPT_NOLOGO))
00553         PrintLogo();
00554
00555     // Work out out filename prefix and suffix
00556     if(szOutputDir[0] && (L'\\' != szOutputDir[wcslen(szOutputDir) - 1]))
00557         wcscat_s( szOutputDir, MAX_PATH, L"\\" );
00558
00559     if(szPrefix[0])
00560         wcscat_s(szOutputDir, MAX_PATH, szPrefix);
00561
00562     wcscpy_s(szPrefix, MAX_PATH, szOutputDir);
00563
00564     const WCHAR* fileTypeName = LookupByValue(FileType, g_pSaveFileTypes);
00565
00566     if (fileTypeName)
00567     {
00568         wcscat_s(szSuffix, MAX_PATH, L".");
00569         wcscat_s(szSuffix, MAX_PATH, fileTypeName);
00570     }
00571     else
00572     {
00573         wcscat_s(szSuffix, MAX_PATH, L".unknown");
00574     }
00575
00576     if (FileType != CODEC_DDS)
00577     {
00578         mipLevels = 1;
00579     }
00580
00581     // Convert images
00582     bool nonpow2warn = false;
00583     SConversion *pConv;
00584
00585     for(pConv = pConversion; pConv; pConv = pConv->pNext)
00586     {
00587         // Load source image
00588         if(pConv != pConversion)
00589             wprintf( L"\n");
00590
00591         wprintf( L"reading %s", pConv->szSrc );
00592         fflush(stdout);
00593
00594         WCHAR ext[_MAX_EXT];
00595         WCHAR fname[_MAX_FNAME];
00596         _wsplitpath_s( pConv->szSrc, nullptr, 0, nullptr, 0, fname, _MAX_FNAME, ext, _MAX_EXT );
00597
00598         TexMetadata info;
00599         ScratchImage *image = new ScratchImage;
00600
00601         if ( !image )
00602         {
00603             wprintf( L" ERROR: Memory allocation failed\n" );
00604             goto LError;
00605         }
00606
00607         if ( _wcsicmp( ext, L".dds" ) == 0 )
00608         {
00609             hr = LoadFromDDSFile( pConv->szSrc,
00610                                   (dwOptions & (1 << OPT_DDS_DWORD_ALIGN)) ? DDS_FLAGS_LEGACY_DWORD : DDS_FLAGS_NONE,
00611                                   &info, *image );
00612             if ( FAILED(hr) )
00613             {
00614                 wprintf( L" FAILED (%x)\n", hr);
00615                 delete image;
00616                 continue;
00617             }
00618         }
00619         else if ( _wcsicmp( ext, L".tga" ) == 0 )
00620         {
00621             hr = LoadFromTGAFile( pConv->szSrc, &info, *image );
00622             if ( FAILED(hr) )
00623             {
00624                 wprintf( L" FAILED (%x)\n", hr);
00625                 delete image;
00626                 continue;
00627             }
00628         }
00629         else
00630         {
00631             // WIC shares the same filter values for mode and dither
00632             static_assert( WIC_FLAGS_DITHER == TEX_FILTER_DITHER, "WIC_FLAGS_* & TEX_FILTER_* should match" );
00633             static_assert( WIC_FLAGS_DITHER_DIFFUSION == TEX_FILTER_DITHER_DIFFUSION, "WIC_FLAGS_* & TEX_FILTER_* should match"  );
00634             static_assert( WIC_FLAGS_FILTER_POINT == TEX_FILTER_POINT, "WIC_FLAGS_* & TEX_FILTER_* should match"  );
00635             static_assert( WIC_FLAGS_FILTER_LINEAR == TEX_FILTER_LINEAR, "WIC_FLAGS_* & TEX_FILTER_* should match"  );
00636             static_assert( WIC_FLAGS_FILTER_CUBIC == TEX_FILTER_CUBIC, "WIC_FLAGS_* & TEX_FILTER_* should match"  );
00637             static_assert( WIC_FLAGS_FILTER_FANT == TEX_FILTER_FANT, "WIC_FLAGS_* & TEX_FILTER_* should match"  );
00638
00639             hr = LoadFromWICFile( pConv->szSrc, dwFilter, &info, *image );
00640             if ( FAILED(hr) )
00641             {
00642                 wprintf( L" FAILED (%x)\n", hr);
00643                 delete image;
00644                 continue;
00645             }
00646         }
00647
00648         PrintInfo( info );
00649
00650         size_t twidth = ( !width ) ? info.width : width;
00651         size_t theight = ( !height ) ? info.height : height;
00652         size_t tMips = ( !mipLevels && info.mipLevels > 1 ) ? info.mipLevels : mipLevels;
00653         DXGI_FORMAT tformat = ( format == DXGI_FORMAT_UNKNOWN ) ? info.format : format;
00654
00655         // Convert texture
00656         wprintf( L" as");
00657         fflush(stdout);
00658
00659         // --- Decompress --------------------------------------------------------------
00660         if ( IsCompressed( info.format ) )
00661         {
00662             const Image* img = image->GetImage(0,0,0);
00663             assert( img );
00664             size_t nimg = image->GetImageCount();
00665
00666             ScratchImage *timage = new ScratchImage;
00667             if ( !timage )
00668             {
00669                 wprintf( L" ERROR: Memory allocation failed\n" );
00670                 delete image;
00671                 goto LError;
00672             }
00673
00674             hr = Decompress( img, nimg, info, DXGI_FORMAT_UNKNOWN /* picks good default */, *timage );
00675             if ( FAILED(hr) )
00676             {
00677                 wprintf( L" FAILED [decompress] (%x)\n", hr);
00678                 delete timage;
00679                 delete image;
00680                 continue;
00681             }
00682
00683             const TexMetadata& tinfo = timage->GetMetadata();
00684
00685             info.format = tinfo.format;
00686
00687             assert( info.width == tinfo.width );
00688             assert( info.height == tinfo.height );
00689             assert( info.depth == tinfo.depth );
00690             assert( info.arraySize == tinfo.arraySize );
00691             assert( info.mipLevels == tinfo.mipLevels );
00692             assert( info.miscFlags == tinfo.miscFlags );
00693             assert( info.dimension == tinfo.dimension );
00694
00695             delete image;
00696             image = timage;
00697         }
00698
00699         // --- Flip/Rotate -------------------------------------------------------------
00700         if ( dwOptions & ( (1 << OPT_HFLIP) | (1 << OPT_VFLIP) ) )
00701         {
00702             ScratchImage *timage = new ScratchImage;
00703             if ( !timage )
00704             {
00705                 wprintf( L" ERROR: Memory allocation failed\n" );
00706                 delete image;
00707                 goto LError;
00708             }
00709
00710             DWORD dwFlags = 0;
00711
00712             if ( dwOptions & (1 << OPT_HFLIP) )
00713                 dwFlags |= TEX_FR_FLIP_HORIZONTAL;
00714
00715             if ( dwOptions & (1 << OPT_VFLIP) )
00716                 dwFlags |= TEX_FR_FLIP_VERTICAL;
00717
00718             assert( dwFlags != 0 );
00719
00720             hr = FlipRotate( image->GetImages(), image->GetImageCount(), image->GetMetadata(), dwFlags, *timage );
00721             if ( FAILED(hr) )
00722             {
00723                 wprintf( L" FAILED [fliprotate] (%x)\n", hr);
00724                 delete timage;
00725                 delete image;
00726                 goto LError;
00727             }
00728
00729             const TexMetadata& tinfo = timage->GetMetadata();
00730
00731             assert( tinfo.width == twidth && tinfo.height == theight );
00732
00733             info.width = tinfo.width;
00734             info.height = tinfo.height;
00735
00736             assert( info.depth == tinfo.depth );
00737             assert( info.arraySize == tinfo.arraySize );
00738             assert( info.mipLevels == tinfo.mipLevels );
00739             assert( info.miscFlags == tinfo.miscFlags );
00740             assert( info.format == tinfo.format );
00741             assert( info.dimension == tinfo.dimension );
00742
00743             delete image;
00744             image = timage;
00745         }
00746
00747         // --- Resize ------------------------------------------------------------------
00748         if ( info.width != twidth || info.height != theight )
00749         {
00750             ScratchImage *timage = new ScratchImage;
00751             if ( !timage )
00752             {
00753                 wprintf( L" ERROR: Memory allocation failed\n" );
00754                 delete image;
00755                 goto LError;
00756             }
00757
00758             hr = Resize( image->GetImages(), image->GetImageCount(), image->GetMetadata(), twidth, theight, dwFilter | dwFilterOpts, *timage );
00759             if ( FAILED(hr) )
00760             {
00761                 wprintf( L" FAILED [resize] (%x)\n", hr);
00762                 delete timage;
00763                 delete image;
00764                 goto LError;
00765             }
00766
00767             const TexMetadata& tinfo = timage->GetMetadata();
00768
00769             assert( tinfo.width == twidth && tinfo.height == theight && tinfo.mipLevels == 1 );
00770             info.width = tinfo.width;
00771             info.height = tinfo.height;
00772             info.mipLevels = 1;
00773
00774             assert( info.depth == tinfo.depth );
00775             assert( info.arraySize == tinfo.arraySize );
00776             assert( info.miscFlags == tinfo.miscFlags );
00777             assert( info.format == tinfo.format );
00778             assert( info.dimension == tinfo.dimension );
00779
00780             delete image;
00781             image = timage;
00782         }
00783
00784         // --- Convert -----------------------------------------------------------------
00785         if ( info.format != tformat && !IsCompressed( tformat ) )
00786         {
00787             ScratchImage *timage = new ScratchImage;
00788             if ( !timage )
00789             {
00790                 wprintf( L" ERROR: Memory allocation failed\n" );
00791                 delete image;
00792                 goto LError;
00793             }
00794
00795             hr = Convert( image->GetImages(), image->GetImageCount(), image->GetMetadata(), tformat, dwFilter | dwSRGB, 05.f, *timage );
00796             if ( FAILED(hr) )
00797             {
00798                 wprintf( L" FAILED [convert] (%x)\n", hr);
00799                 delete timage;
00800                 delete image;
00801                 goto LError;
00802             }
00803
00804             const TexMetadata& tinfo = timage->GetMetadata();
00805
00806             assert( tinfo.format == tformat );
00807             info.format = tinfo.format;
00808
00809             assert( info.width == tinfo.width );
00810             assert( info.height == tinfo.height );
00811             assert( info.depth == tinfo.depth );
00812             assert( info.arraySize == tinfo.arraySize );
00813             assert( info.mipLevels == tinfo.mipLevels );
00814             assert( info.miscFlags == tinfo.miscFlags );
00815             assert( info.dimension == tinfo.dimension );
00816
00817             delete image;
00818             image = timage;
00819         }
00820
00821         // --- Generate mips -----------------------------------------------------------
00822         if ( !ispow2(info.width) || !ispow2(info.height) || !ispow2(info.depth) )
00823         {
00824             if ( info.dimension == TEX_DIMENSION_TEXTURE3D )
00825             {
00826                 if ( !tMips )
00827                 {
00828                     tMips = 1;
00829                 }
00830                 else
00831                 {
00832                     wprintf( L" ERROR: Cannot generate mips for non-power-of-2 volume textures\n" );
00833                     delete image;
00834                     goto LError;
00835                 }
00836             }
00837             else if ( !tMips || info.mipLevels != 1 )
00838             {
00839                 nonpow2warn = true;
00840             }
00841         }
00842
00843         if ( !tMips || info.mipLevels != tMips )
00844         {
00845             ScratchImage *timage = new ScratchImage;
00846             if ( !timage )
00847             {
00848                 wprintf( L" ERROR: Memory allocation failed\n" );
00849                 delete image;
00850                 goto LError;
00851             }
00852
00853             if ( info.dimension == TEX_DIMENSION_TEXTURE3D )
00854             {
00855                 hr = GenerateMipMaps3D( image->GetImages(), image->GetImageCount(), image->GetMetadata(), dwFilter | dwFilterOpts, tMips, *timage );
00856             }
00857             else
00858             {
00859                 hr = GenerateMipMaps( image->GetImages(), image->GetImageCount(), image->GetMetadata(), dwFilter | dwFilterOpts, tMips, *timage );
00860             }
00861             if ( FAILED(hr) )
00862             {
00863                 wprintf( L" FAILED [mipmaps] (%x)\n", hr);
00864                 delete timage;
00865                 delete image;
00866                 goto LError;
00867             }
00868
00869             const TexMetadata& tinfo = timage->GetMetadata();
00870             info.mipLevels = tinfo.mipLevels;
00871
00872             assert( info.width == tinfo.width );
00873             assert( info.height == tinfo.height );
00874             assert( info.depth == tinfo.depth );
00875             assert( info.arraySize == tinfo.arraySize );
00876             assert( info.mipLevels == tinfo.mipLevels );
00877             assert( info.miscFlags == tinfo.miscFlags );
00878             assert( info.dimension == tinfo.dimension );
00879
00880             delete image;
00881             image = timage;
00882         }
00883
00884         // --- Compress ----------------------------------------------------------------
00885         if ( IsCompressed( tformat ) && (FileType == CODEC_DDS) )
00886         {
00887             const Image* img = image->GetImage(0,0,0);
00888             assert( img );
00889             size_t nimg = image->GetImageCount();
00890
00891             ScratchImage *timage = new ScratchImage;
00892             if ( !timage )
00893             {
00894                 wprintf( L" ERROR: Memory allocation failed\n" );
00895                 delete image;
00896                 goto LError;
00897             }
00898
00899             hr = Compress( img, nimg, info, tformat, TEX_COMPRESS_DEFAULT, 0.5f, *timage );
00900             if ( FAILED(hr) )
00901             {
00902                 wprintf( L" FAILED [compress] (%x)\n", hr);
00903                 delete timage;
00904                 delete image;
00905                 continue;
00906             }
00907
00908             const TexMetadata& tinfo = timage->GetMetadata();
00909
00910             info.format = tinfo.format;
00911             assert( info.width == tinfo.width );
00912             assert( info.height == tinfo.height );
00913             assert( info.depth == tinfo.depth );
00914             assert( info.arraySize == tinfo.arraySize );
00915             assert( info.mipLevels == tinfo.mipLevels );
00916             assert( info.miscFlags == tinfo.miscFlags );
00917             assert( info.dimension == tinfo.dimension );
00918
00919             delete image;
00920             image = timage;
00921         }
00922
00923         // --- Save result -------------------------------------------------------------
00924         {
00925             const Image* img = image->GetImage(0,0,0);
00926             assert( img );
00927             size_t nimg = image->GetImageCount();
00928
00929             PrintInfo( info );
00930             wprintf( L"\n");
00931
00932             // Figure out dest filename
00933             WCHAR *pchSlash, *pchDot;
00934
00935             wcscpy_s(pConv->szDest, MAX_PATH, szPrefix);
00936
00937             pchSlash = wcsrchr(pConv->szSrc, L'\\');
00938             if(pchSlash != 0)
00939                 wcscat_s(pConv->szDest, MAX_PATH, pchSlash + 1);
00940             else
00941                 wcscat_s(pConv->szDest, MAX_PATH, pConv->szSrc);
00942
00943             pchSlash = wcsrchr(pConv->szDest, '\\');
00944             pchDot = wcsrchr(pConv->szDest, '.');
00945
00946             if(pchDot > pchSlash)
00947                 *pchDot = 0;
00948
00949             wcscat_s(pConv->szDest, MAX_PATH, szSuffix);
00950
00951             // Write texture
00952             wprintf( L"writing %s", pConv->szDest);
00953             fflush(stdout);
00954
00955             switch( FileType )
00956             {
00957             case CODEC_DDS:
00958                 hr = SaveToDDSFile( img, nimg, info,
00959                                     (dwOptions & (1 << OPT_USE_DX10) ) ? DDS_FLAGS_FORCE_DX10_EXT : DDS_FLAGS_NONE,
00960                                     pConv->szDest );
00961                 break;
00962
00963             case CODEC_TGA:
00964                 hr = SaveToTGAFile( img[0], pConv->szDest );
00965                 break;
00966
00967             default:
00968                 hr = SaveToWICFile( img, nimg, WIC_FLAGS_ALL_FRAMES, GetWICCodec( static_cast<WICCodecs>(FileType) ), pConv->szDest );
00969                 break;
00970             }
00971
00972             if(FAILED(hr))
00973             {
00974                 wprintf( L" FAILED (%x)\n", hr);
00975                 delete image;
00976                 continue;
00977             }
00978             wprintf( L"\n");
00979         }
00980
00981         delete image;
00982     }
00983
00984     if ( nonpow2warn )
00985         wprintf( L"\n WARNING: Not all feature levels support non-power-of-2 textures with mipmaps\n" );
00986
00987     nReturn = 0;
00988
00989     goto LDone;
00990
00991 LError:
00992     nReturn = 1;
00993
00994 LDone:
00995
00996     while(pConversion)
00997     {
00998         pConv = pConversion;
00999         pConversion = pConversion->pNext;
01000         delete pConv;
01001     }
01002
01003     return nReturn;
01004 }
Generated on Sat Nov 23 2024 16:08:12 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/YearGroup.cpp Source File

  • Hilo C++
  • Hilo

YearGroup.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 #include "YearGroup.h"
00009 #include "MonthBlock.h"
00010 #include "ExceptionPolicy.h"
00011 #include "LocalResourceLoader.h"
00012 #include "Repository.h"
00013 #include "CalendarExtensions.h"
00014
00015 using namespace concurrency;
00016 using namespace Hilo;
00017 using namespace Platform;
00018 using namespace Platform::Collections;
00019 using namespace std;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Storage::Search;
00023
00024 YearGroup::YearGroup(DateTime yearDate, IStorageFolderQueryOperations^ folderQuery, shared_ptr<Repository> repository, shared_ptr<ExceptionPolicy> exceptionPolicy) :
00025     m_yearDate(yearDate), m_folderQuery(folderQuery), m_repository(repository), m_exceptionPolicy(exceptionPolicy)
00026 {
00027     m_year = CalendarExtensions::GetNumericYear(yearDate);
00028     m_name = CalendarExtensions::GetLocalizedYear(yearDate);
00029 }
00030
00031 void YearGroup::OnPropertyChanged(String^ propertyName)
00032 {
00033     assert(IsMainThread());
00034     PropertyChanged(this, ref new Windows::UI::Xaml::Data::PropertyChangedEventArgs(propertyName));
00035 }
00036
00037 IObservableVector<IMonthBlock^>^ YearGroup::Items::get()
00038 {
00039     if (nullptr == m_months)
00040     {
00041         m_months = ref new Vector<IMonthBlock^>();
00042         auto yearDate = m_yearDate;
00043         auto nMonths = CalendarExtensions::GetNumberOfMonthsInYear(yearDate);
00044         vector<IMonthBlock^> monthBlocks;
00045         monthBlocks.reserve(nMonths);
00046         for (int month = 1; month <= nMonths; month++)
00047         {
00048             auto monthBlock = ref new MonthBlock(this, month, m_folderQuery, m_repository, m_exceptionPolicy);
00049             monthBlocks.push_back(monthBlock);
00050         }
00051         m_months = ref new Vector<IMonthBlock^>(std::move(monthBlocks));
00052     }
00053     return m_months;
00054 }
00055
00056 String^ YearGroup::Title::get()
00057 {
00058     return m_name;
00059 }
00060
00061 int YearGroup::Year::get()
00062 {
00063     return m_year;
00064 }
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Touch keyboard text input/C++/common/LayoutAwarePage.cpp Source File

  • Input Touch keyboard text input
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:31 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML data binding/C++/Scenario3.xaml.h Source File

  • XAML data binding

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 "Employee.h"
00022
00023 namespace SDKSample
00024 {
00025     namespace DataBinding
00026     {
00027       /// <summary>
00028       /// An empty page that can be used on its own or navigated to within a Frame.
00029       /// </summary>
00030       public ref class Scenario3 sealed
00031       {
00032       public:
00033         Scenario3();
00034       private:
00035         property Employee^ _employee;
00036         MainPage^ rootPage;
00037         void Scenario3Reset(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038         void employeeChanged(Object^ sender, PropertyChangedEventArgs^ e);
00039       };
00040     }
00041 }
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text display/C++/Scenario4.xaml.h Source File

  • XAML text display

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
00022 namespace SDKSample
00023 {
00024     namespace TextDisplay
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 Scenario4 sealed
00031         {
00032         public:
00033             Scenario4();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040             void Other_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         };
00042     }
00043 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Clipboard app/C++/CopyImage.xaml.cpp Source File

  • Clipboard app

CopyImage.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 // CopyImage.xaml.cpp
00013 // Implementation of the CopyImage class
00014 //
00015
00016 #include "pch.h"
00017 #include "CopyImage.xaml.h"
00018
00019 using namespace Clipboard;
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::Graphics::Imaging;
00026 using namespace Windows::UI::ViewManagement;
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 using namespace Windows::UI::Xaml::Media::Imaging;
00035
00036 // App specific namespace references
00037 using namespace concurrency;
00038 using namespace Windows::ApplicationModel;
00039 using namespace Windows::ApplicationModel::DataTransfer;
00040 using namespace Windows::Storage::Streams;
00041 using namespace Windows::Storage;
00042 using namespace Windows::Storage::Pickers;
00043 using namespace Windows::Graphics::Display;
00044 using namespace Windows::Graphics::Imaging;
00045
00046 CopyImage::CopyImage()
00047 {
00048     InitializeComponent();
00049 }
00050
00051 void CopyImage::OnNavigatedTo(NavigationEventArgs^ e)
00052 {
00053     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00054     // as NotifyUser()
00055     rootPage = MainPage::Current;
00056 }
00057
00058 #pragma region CopyImage handlers
00059
00060 void CopyImage::CopyWithDelayedRenderingButton_Click(Object^ sender, RoutedEventArgs^ e)
00061 {
00062     CopyBitmap(true);
00063 }
00064
00065 void CopyImage::CopyButton_Click(Object^ sender, RoutedEventArgs^ e)
00066 {
00067     CopyBitmap(false);
00068 }
00069
00070 void CopyImage::CopyBitmap(bool useDelayedRendering)
00071 {
00072     OutputText->Text = "";
00073     OutputImageHolder->Source = nullptr;
00074
00075     if (rootPage->EnsureUnsnapped())
00076     {
00077         // Select an image using the filepicker.
00078         auto imageFilePicker = ref new FileOpenPicker();
00079         imageFilePicker->ViewMode = PickerViewMode::Thumbnail;
00080         imageFilePicker->SuggestedStartLocation = PickerLocationId::PicturesLibrary;
00081
00082         // Supported image formats for clipboard.
00083         imageFilePicker->FileTypeFilter->Append(".jpg");
00084         imageFilePicker->FileTypeFilter->Append(".png");
00085         imageFilePicker->FileTypeFilter->Append(".bmp");
00086         imageFilePicker->FileTypeFilter->Append(".gif");
00087         imageFilePicker->FileTypeFilter->Append(".tif");
00088
00089         create_task(imageFilePicker->PickSingleFileAsync()).then(
00090             [this, useDelayedRendering](task<StorageFile^> imageTask)
00091             {
00092                 StorageFile^ imageFile = imageTask.get();
00093                 if (imageFile)
00094                 {
00095                     imgStreamRef = RandomAccessStreamReference::CreateFromFile(imageFile);
00096                     auto dataPackage = ref new DataPackage();
00097                     if (useDelayedRendering)
00098                     {
00099                         dataPackage->SetDataProvider(StandardDataFormats::Bitmap, ref new DataProviderHandler(this, &CopyImage::OnDeferredImageRequestedHandler));
00100                     }
00101                     else
00102                     {
00103                         dataPackage->SetBitmap(imgStreamRef);
00104                     }
00105
00106                     try
00107                     {
00108                         // Set the contents in clipboard
00109                         DataTransfer::Clipboard::SetContent(dataPackage);
00110                         if (useDelayedRendering)
00111                         {
00112                             rootPage->NotifyUserBackgroundThread("Image has been copied to clipboard using delayed rendering.", NotifyType::StatusMessage);
00113                         }
00114                         else
00115                         {
00116                             rootPage->NotifyUserBackgroundThread("Image has been copied to clipboard.", NotifyType::StatusMessage);
00117                         }
00118                     }
00119                     catch (Exception^ ex)
00120                     {
00121                         // Copying data to Clipboard can potentially fail - for example, if another application is holding Clipboard open
00122                         rootPage->NotifyUserBackgroundThread("Error copying image to Clipboard: " + ex->Message + ".", NotifyType::ErrorMessage);
00123                     }
00124                 }
00125                 else
00126                 {
00127                     rootPage->NotifyUserBackgroundThread("No Image was selected", NotifyType::ErrorMessage);
00128                 }
00129             });
00130     }
00131 }
00132
00133 void CopyImage::PasteButton_Click(Object^ sender, RoutedEventArgs^ e)
00134 {
00135     OutputText->Text = "";
00136     OutputImageHolder->Source = nullptr;
00137
00138     auto dataPackageView = DataTransfer::Clipboard::GetContent();
00139     if (dataPackageView->Contains(StandardDataFormats::Bitmap))
00140     {
00141         create_task(dataPackageView->GetBitmapAsync()).then(
00142             [this](task<RandomAccessStreamReference^> bitmapTask)
00143             {
00144                 RandomAccessStreamReference^ bitmapStreamRef;
00145
00146                 try
00147                 {
00148                     bitmapStreamRef = bitmapTask.get();
00149                 }
00150                 catch (Exception^ ex)
00151                 {
00152                     rootPage->NotifyUserBackgroundThread("Failed GetBitmapAsync - " + ex->Message, NotifyType::ErrorMessage);
00153                 }
00154
00155                 if (bitmapStreamRef != nullptr)
00156                 {
00157                     create_task(bitmapStreamRef->OpenReadAsync()).then(
00158                         [this](task<IRandomAccessStreamWithContentType^> imageTask)
00159                         {
00160                             IRandomAccessStreamWithContentType^ imageStream;
00161
00162                             try
00163                             {
00164                                 imageStream = imageTask.get();
00165                             }
00166                             catch (Exception^ ex)
00167                             {
00168                                 rootPage->NotifyUserBackgroundThread("Failed OpenReadAsync - " + ex->Message, NotifyType::ErrorMessage);
00169                             }
00170
00171                             if (imageStream != nullptr)
00172                             {
00173                                 auto bitmapImage = ref new BitmapImage();
00174                                 bitmapImage->SetSource(imageStream);
00175
00176                                 // Display the image.
00177                                 OutputImageHolder->Source = bitmapImage;
00178                                 OutputImageHolder->Visibility = Windows::UI::Xaml::Visibility::Visible;
00179                                 rootPage->NotifyUserBackgroundThread("Image in clipboard rendered below:", NotifyType::StatusMessage);
00180                             }
00181                         });
00182                 }
00183             });
00184     }
00185     else
00186     {
00187         rootPage->NotifyUser("Bitmap format is not available in clipboard", NotifyType::StatusMessage);
00188     }
00189 }
00190
00191 void CopyImage::OnDeferredImageRequestedHandler(DataProviderRequest^ request)
00192 {
00193     if (imgStreamRef != nullptr)
00194     {
00195         // Since this method is calling async methods prior to setting the data in DataPackage,
00196         // deferral object must be used
00197         auto deferral = request->GetDeferral();
00198         auto inMemoryStream = ref new InMemoryRandomAccessStream();
00199
00200         // Use a reference-counted pointer to store the requested dimensions across function calls.
00201         std::shared_ptr<Size> newSize(new Size);
00202
00203         create_task(imgStreamRef->OpenReadAsync()).then(
00204             [this](task<IRandomAccessStreamWithContentType^> streamTask) -> IAsyncOperation<BitmapDecoder^>^
00205         {
00206             return BitmapDecoder::CreateAsync(streamTask.get());
00207         }).then( [this, inMemoryStream, newSize](BitmapDecoder^ imageDecoder) -> IAsyncOperation<BitmapEncoder^>^
00208         {
00209             newSize.get()->Height = imageDecoder->OrientedPixelHeight * 0.5f;
00210             newSize.get()->Width = imageDecoder->OrientedPixelWidth * 0.5f;
00211             return BitmapEncoder::CreateForTranscodingAsync(inMemoryStream, imageDecoder);
00212         }).then([this, newSize](BitmapEncoder^ imageEncoder) -> IAsyncAction^
00213         {
00214             imageEncoder->BitmapTransform->ScaledWidth = safe_cast<unsigned int>(newSize.get()->Width);
00215             imageEncoder->BitmapTransform->ScaledHeight = safe_cast<unsigned int>(newSize.get()->Height);
00216             return imageEncoder->FlushAsync();
00217         }).then([this, request, deferral, inMemoryStream](task<void> newTask)
00218         {
00219             // Forces any exceptions from previous operations to get thrown here.
00220             // That way, we can ensure that the deferral completed method always gets called.
00221             try
00222             {
00223                 newTask.get();
00224                 request->SetData(RandomAccessStreamReference::CreateFromStream(inMemoryStream));
00225             }
00226             catch (Exception^ ex)
00227             {
00228                 rootPage->NotifyUserBackgroundThread("Failed delayed rendering - " + ex->Message, NotifyType::ErrorMessage);
00229             }
00230
00231             // End the deferral.
00232             deferral->Complete();
00233         });
00234     }
00235 }
00236
00237 #pragma endregion
Generated on Sat Nov 23 2024 16:07:59 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D custom image effects/C++/ComputeShader/SampleOverlay.h Source File

  • Direct2D custom image effects
  • ComputeShader

SampleOverlay.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 "DirectXSample.h"
00011
00012 // This class is responsible for initializing and rendering the title overlay visible
00013 // at the top of the DirectX SDK samples.
00014 ref class SampleOverlay
00015 {
00016 internal:
00017     SampleOverlay();
00018
00019     void Initialize(
00020         _In_ ID2D1Device*         d2dDevice,
00021         _In_ ID2D1DeviceContext*  d2dContext,
00022         _In_ IWICImagingFactory*  wicFactory,
00023         _In_ IDWriteFactory*      dwriteFactory,
00024         _In_ Platform::String^    caption
00025         );
00026
00027     void ResetDirectXResources();
00028
00029     void UpdateForWindowSizeChange();
00030
00031     void Render();
00032
00033     float GetTitleHeightInDips();
00034
00035 private:
00036
00037     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00038     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00039     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00040     Microsoft::WRL::ComPtr<IDWriteFactory>          m_dwriteFactory;
00041     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_whiteBrush;
00042     Microsoft::WRL::ComPtr<ID2D1DrawingStateBlock>  m_stateBlock;
00043
00044     Microsoft::WRL::ComPtr<IWICImagingFactory>      m_wicFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Bitmap>             m_logoBitmap;
00046     Microsoft::WRL::ComPtr<IDWriteTextLayout>       m_textLayout;
00047
00048     UINT                                            m_idIncrement;
00049     bool                                            m_drawOverlay;
00050     Platform::String^                               m_sampleName;
00051     float                                           m_padding;
00052     float                                           m_textVerticalOffset;
00053     D2D1_SIZE_F                                     m_logoSize;
00054     float                                           m_overlayWidth;
00055 };
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-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 Sat Nov 23 2024 16:09:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

RandomAccessReader Member List

This is the complete list of members for RandomAccessReader, including all inherited members.
__pad0__ | RandomAccessReader |
GetFileSize() | RandomAccessReader |
GetPosition() | RandomAccessReader |
m_file | RandomAccessReader | [private]
Read(_In_ size_t bytesToRead) | RandomAccessReader |
SeekAbsolute(_In_ int64 position) | RandomAccessReader |
SeekRelative(_In_ int64 offset) | RandomAccessReader |
SeekToEnd() | RandomAccessReader |
SeekToStart() | RandomAccessReader |
Generated on Sat Nov 23 2024 16:09:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Programmatic file search/C++/App.xaml.cpp Source File

  • Programmatic file search

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:28 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Touch keyboard text input/C++/Constants.cpp Source File

  • Input Touch keyboard text input

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     { "Spelling & Text Suggestions", "SDKSample.TouchKeyboardTextInput.SpellingTextSuggestions" },
00020     { "Scoped Views", "SDKSample.TouchKeyboardTextInput.ScopedViews" }
00021 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CryptoWinRT/C++/Scenario7.xaml.cpp Source File

  • CryptoWinRT

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 SDKSample::CryptoWinRT;
00020
00021 using namespace Platform;
00022 using namespace Windows::Security::Cryptography;
00023 using namespace Windows::Security::Cryptography::Core;
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 Scenario7::Scenario7()
00030 {
00031     InitializeComponent();
00032     AlgorithmNames->SelectedIndex = 0;
00033     KeySizes->SelectedIndex = 0;
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 Scenario7::OnNavigatedTo(NavigationEventArgs^ e)
00042 {
00043     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00044     // as NotifyUser()
00045     rootPage = MainPage::Current;
00046 }
00047
00048 void SDKSample::CryptoWinRT::Scenario7::RunSample_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00049 {
00050     Scenario7Text->Text = "";
00051
00052     IBuffer^ Data;
00053     String^ algName = AlgorithmNames->SelectionBoxItem->ToString();
00054     unsigned int KeySize;
00055
00056     IBuffer^ Encrypted;
00057     IBuffer^ Decrypted;
00058     IBuffer^ blobOfPublicKey;
00059     IBuffer^ blobOfKeyPair;
00060
00061     switch (AlgorithmNames->SelectedIndex)
00062     {
00063     case 0:
00064         Data = CryptographicBuffer::ConvertStringToBinary("Some cookie to encrypt", BinaryStringEncoding::Utf16LE);
00065         break;
00066
00067     // OAEP Padding depends on key size, message length and hash block length
00068     //
00069     // The maximum plaintext length is KeyLength - 2*HashBlock - 2
00070     //
00071     // OEAP padding supports an optional label with the length is restricted by plaintext/key/hash sizes.
00072     // Here we just use a small label.
00073     case 1:
00074         Data = CryptographicBuffer::GenerateRandom(1024 / 8 - 2 * 20 - 2);
00075         break;
00076     case 2:
00077         Data = CryptographicBuffer::GenerateRandom(1024 / 8 - 2 * (256 / 8) - 2);
00078         break;
00079     case 3:
00080         Data = CryptographicBuffer::GenerateRandom(2048 / 8 - 2 * (384 / 8) - 2);
00081         break;
00082     case 4:
00083         Data = CryptographicBuffer::GenerateRandom(2048 / 8 - 2 * (512 / 8) - 2);
00084         break;
00085     default:
00086         Scenario7Text->Text += "An invalid Algorithm was selected";
00087         return;
00088     }
00089
00090     switch (KeySizes->SelectedIndex)
00091     {
00092     case 0:
00093         KeySize = 512;
00094         break;
00095     case 1:
00096         KeySize = 1024;
00097         break;
00098     case 2:
00099         KeySize = 2048;
00100         break;
00101     case 3:
00102         KeySize = 4096;
00103         break;
00104     default:
00105         Scenario7Text->Text += "An invalid size was selected";
00106         return;
00107     }
00108
00109     // Crate an AsymmetricKeyAlgorithmProvider object for the algorithm specified on input.
00110     AsymmetricKeyAlgorithmProvider^ Algorithm = AsymmetricKeyAlgorithmProvider::OpenAlgorithm(algName);
00111
00112     Scenario7Text->Text += "\n*** Sample Encryption Algorithm\n";
00113     Scenario7Text->Text += "    Algorithm Name: " + Algorithm->AlgorithmName + "\n";
00114     Scenario7Text->Text += "    KeySize = " + KeySize + "\n";
00115
00116     CryptographicKey^ keyPair;
00117     try
00118     {
00119         // Generate a random key.
00120         keyPair = Algorithm->CreateKeyPair(KeySize);
00121
00122         // Encrypt the data.
00123         Encrypted = CryptographicEngine::Encrypt(keyPair, Data, nullptr);
00124     }
00125     catch (InvalidArgumentException^ e)
00126     {
00127         Scenario7Text->Text += "Exception: " + e->Message + "\n";
00128         Scenario7Text->Text += "The given keysize is not supported for the given algorithm\n";
00129         return;
00130     }
00131
00132     Scenario7Text->Text += "    Plain text: " + Data->Length + " bytes\n";
00133     Scenario7Text->Text += "    Encrypted: " + Encrypted->Length + " bytes\n";
00134
00135     // Export the public key.
00136     blobOfPublicKey = keyPair->ExportPublicKey();
00137     blobOfKeyPair = keyPair->Export();
00138
00139     // Import the public key.
00140     CryptographicKey^ keyPublic = Algorithm->ImportPublicKey(blobOfPublicKey);
00141     if (keyPublic->KeySize != keyPair->KeySize)
00142     {
00143         Scenario7Text->Text += "ImportPublicKey failed!  The imported key's size did not match the original's!\n";
00144         return;
00145     }
00146
00147     // Import the key pair.
00148     keyPair = Algorithm->ImportKeyPair(blobOfKeyPair);
00149
00150     // Check the key size of the imported key.
00151     if (keyPublic->KeySize != keyPair->KeySize)
00152     {
00153         Scenario7Text->Text += "ImportKeyPair failed!  The imported key's size did not match the original's!\n";
00154         return;
00155     }
00156
00157     // Decrypt the data.
00158     Decrypted = CryptographicEngine::Decrypt(keyPair, Encrypted, nullptr);
00159
00160     if (!CryptographicBuffer::Compare(Decrypted, Data))
00161     {
00162         Scenario7Text->Text += "Decrypted data does not match original!\n";
00163         return;
00164     }
00165 }
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2Dapp printing/C++/SampleOverlay.h Source File

  • Direct2Dapp printing

SampleOverlay.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 "DirectXSample.h"
00011
00012 // This class is responsible for initializing and rendering the title overlay visible
00013 // at the top of the DirectX SDK samples.
00014 ref class SampleOverlay
00015 {
00016 internal:
00017     SampleOverlay();
00018
00019     void Initialize(
00020         _In_ ID2D1Device*         d2dDevice,
00021         _In_ ID2D1DeviceContext*  d2dContext,
00022         _In_ IWICImagingFactory*  wicFactory,
00023         _In_ IDWriteFactory*      dwriteFactory,
00024         _In_ Platform::String^    caption
00025         );
00026
00027     void ResetDirectXResources();
00028
00029     void UpdateForWindowSizeChange();
00030
00031     void Render();
00032
00033     float GetTitleHeightInDips();
00034
00035 private:
00036
00037     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00038     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00039     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00040     Microsoft::WRL::ComPtr<IDWriteFactory>          m_dwriteFactory;
00041     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_whiteBrush;
00042     Microsoft::WRL::ComPtr<ID2D1DrawingStateBlock>  m_stateBlock;
00043
00044     Microsoft::WRL::ComPtr<IWICImagingFactory>      m_wicFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Bitmap>             m_logoBitmap;
00046     Microsoft::WRL::ComPtr<IDWriteTextLayout>       m_textLayout;
00047
00048     UINT                                            m_idIncrement;
00049     bool                                            m_drawOverlay;
00050     Platform::String^                               m_sampleName;
00051     float                                           m_padding;
00052     float                                           m_textVerticalOffset;
00053     D2D1_SIZE_F                                     m_logoSize;
00054     float                                           m_overlayWidth;
00055 };
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX postcard app/C++/TextFlyout.xaml.h Source File

  • DirectX postcard app

TextFlyout.xaml.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 "TextFlyout.g.h"
00011
00012 namespace Postcard
00013 {
00014     public delegate void TextSubmittedHandler(Platform::String^);
00015
00016     [Windows::Foundation::Metadata::WebHostHidden]
00017     public ref class TextFlyout sealed
00018     {
00019     public:
00020         TextFlyout();
00021         event TextSubmittedHandler^ TextSubmitted;
00022
00023     private:
00024         void TextBoxKeyUp(Platform::Object^ sender, Windows::UI::Xaml::Input::KeyRoutedEventArgs^ e);
00025         void GotFocusHandler(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00026         void LostFocusHandler(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00027     };
00028 }
Generated on Sat Nov 23 2024 16:08:15 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::BadgeContent::BadgeGlyphNotificationContent Member List

This is the complete list of members for NotificationsExtensions::BadgeContent::BadgeGlyphNotificationContent, including all inherited members.
BadgeGlyphNotificationContent() | NotificationsExtensions::BadgeContent::BadgeGlyphNotificationContent | [inline]
BadgeGlyphNotificationContent(GlyphValue glyph) | NotificationsExtensions::BadgeContent::BadgeGlyphNotificationContent | [inline]
BadgeGlyphNotificationContent() | NotificationsExtensions::BadgeContent::BadgeGlyphNotificationContent | [inline]
BadgeGlyphNotificationContent(GlyphValue glyph) | NotificationsExtensions::BadgeContent::BadgeGlyphNotificationContent | [inline]
CreateNotification() | NotificationsExtensions::BadgeContent::BadgeGlyphNotificationContent | [inline]
CreateNotification() | NotificationsExtensions::BadgeContent::BadgeGlyphNotificationContent | [inline]
GetContent() | NotificationsExtensions::BadgeContent::BadgeGlyphNotificationContent | [inline]
GetContent() | NotificationsExtensions::BadgeContent::BadgeGlyphNotificationContent | [inline]
GetXml() | NotificationsExtensions::BadgeContent::BadgeGlyphNotificationContent | [inline]
GetXml() | NotificationsExtensions::BadgeContent::BadgeGlyphNotificationContent | [inline]
Glyph | NotificationsExtensions::BadgeContent::BadgeGlyphNotificationContent |
m_Glyph | NotificationsExtensions::BadgeContent::BadgeGlyphNotificationContent | [private]
ToString() | NotificationsExtensions::BadgeContent::BadgeGlyphNotificationContent | [inline]
ToString() | NotificationsExtensions::BadgeContent::BadgeGlyphNotificationContent | [inline]
Generated on Sat Nov 23 2024 16:09:41 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Splash screen/C++/Scenario1.xaml.h Source File

  • Splash screen

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 SDKSample
00023 {
00024     namespace SplashScreen
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 Scenario1 sealed
00031         {
00032         public:
00033             Scenario1();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         };
00038     }
00039 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Inclinometer sensor/C++/App.xaml.cpp Source File

  • Inclinometer sensor

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application data/C++/common/suspensionmanager.h Source File

  • Application data
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C#,C++/MediaExtensions/Invert/InvertModule.h Source File

  • Media extensions
  • C#,C++
  • MediaExtensions
  • Invert

InvertModule.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include "DirectXVideoTransform.h"
00004 #include <wrl\client.h>
00005 using namespace Microsoft::WRL;
00006
00007 class CInvertModule : public DirectXVideoTransform
00008 {
00009 public:
00010     virtual ~CInvertModule();
00011     virtual void Invalidate();
00012     virtual HRESULT Initialize(ID3D11Device *pDevice, UINT uiWidth, UINT uiHeight);
00013     virtual HRESULT ProcessFrame(ID3D11Device *pDevice, ID3D11Texture2D *pInput, UINT uiInIndex, ID3D11Texture2D *pOutput, UINT uiOutIndex);
00014
00015 private:
00016     UINT m_uiWidth, m_uiHeight;
00017     ComPtr<ID3D11Buffer> m_pScreenQuadVB;
00018     ComPtr<ID3D11SamplerState> m_pSampleStateLinear;
00019     ComPtr<ID3D11InputLayout> m_spQuadLayout;
00020     ComPtr<ID3D11VertexShader> m_pVertexShader;
00021     ComPtr<ID3D11PixelShader> m_pPixelShader;
00022 };
Generated on Sat Nov 23 2024 16:08:21 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Magazine::sealed Member List

This is the complete list of members for Magazine::sealed, including all inherited members.
App() | Magazine::sealed |
DocumentLoaded(_In_ Document^document) | Magazine::sealed | [private]
LoadState(_In_ Windows::Foundation::Collections::IPropertySet^localSettings) | Magazine::sealed |
m_background | Magazine::sealed | [private]
m_content | Magazine::sealed | [private]
m_document | Magazine::sealed | [private]
MainPage() | Magazine::sealed |
OnDeviceLost() | Magazine::sealed | [private]
OnLaunched(_In_ Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^args) override | Magazine::sealed | [virtual]
OnResuming(_In_ Platform::Object^sender, _In_ Platform::Object^args) | Magazine::sealed | [private]
OnSuspending(_In_ Platform::Object^sender, _In_ Windows::ApplicationModel::SuspendingEventArgs^args) | Magazine::sealed | [private]
OnWindowSizeChanged(_In_ Platform::Object^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | Magazine::sealed | [private]
PropertyChanged | Magazine::sealed |
SaveState(_In_ Windows::Foundation::Collections::IPropertySet^localSettings) | Magazine::sealed |
UpdateContent(_In_ Element^content) | Magazine::sealed |
~App() | Magazine::sealed | [private]
Generated on Sat Nov 23 2024 16:09:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::DeviceCaps::sealed Member List

This is the complete list of members for SDKSample::DeviceCaps::sealed, including all inherited members.
Keyboard() | SDKSample::DeviceCaps::sealed |
KeyboardGetSettings_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::DeviceCaps::sealed | [private]
Mouse() | SDKSample::DeviceCaps::sealed |
MouseGetSettings_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::DeviceCaps::sealed | [private]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::DeviceCaps::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::DeviceCaps::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::DeviceCaps::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::DeviceCaps::sealed | [protected, virtual]
Pointer() | SDKSample::DeviceCaps::sealed |
PointerGetSettings_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::DeviceCaps::sealed | [private]
PointerType(Windows::Devices::Input::PointerDevice^pointerDevice) | SDKSample::DeviceCaps::sealed | [private]
rootPage | SDKSample::DeviceCaps::sealed | [private]
Touch() | SDKSample::DeviceCaps::sealed |
TouchGetSettings_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::DeviceCaps::sealed | [private]
Generated on Sat Nov 23 2024 16:09:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX marble maze game/C++/Audio.h Source File

  • DirectX marble maze game

Audio.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 "MediaStreamer.h"
00011 #include "BasicMath.h"
00012
00013 static const int STREAMING_BUFFER_SIZE = 65536;
00014 static const int MAX_BUFFER_COUNT = 3;
00015
00016 enum SoundEvent
00017 {
00018     RollingEvent        = 0,
00019     FallingEvent        = 1,
00020     CollisionEvent      = 2,
00021     CheckpointEvent     = 3,
00022     MenuChangeEvent     = 4,
00023     MenuSelectedEvent   = 5,
00024     LastSoundEvent,
00025 };
00026
00027 // Make sure this matches the number of entries in the SoundEvent enum above
00028 static const int SOUND_EVENTS = LastSoundEvent;
00029
00030 struct SoundEffectData
00031 {
00032     SoundEvent                  m_soundEventType;
00033     IXAudio2SourceVoice*        m_soundEffectSourceVoice;
00034     XAUDIO2_BUFFER              m_audioBuffer;
00035     byte*                       m_soundEffectBufferData;
00036     uint32                      m_soundEffectBufferLength;
00037     uint32                      m_soundEffectSampleRate;
00038     bool                        m_soundEffectStarted;
00039 };
00040
00041 struct StreamingVoiceContext : public IXAudio2VoiceCallback
00042 {
00043     STDMETHOD_(void, OnVoiceProcessingPassStart)(UINT32){}
00044     STDMETHOD_(void, OnVoiceProcessingPassEnd)(){}
00045     STDMETHOD_(void, OnStreamEnd)(){}
00046     STDMETHOD_(void, OnBufferStart)(void*)
00047     {
00048         ResetEvent(hBufferEndEvent);
00049     }
00050     STDMETHOD_(void, OnBufferEnd)(void* pContext)
00051     {
00052         // Trigger the event for the music stream.
00053         if (pContext == 0) {
00054             SetEvent(hBufferEndEvent);
00055         }
00056     }
00057     STDMETHOD_(void, OnLoopEnd)(void*){}
00058     STDMETHOD_(void, OnVoiceError)(void*, HRESULT){}
00059
00060     HANDLE hBufferEndEvent;
00061     StreamingVoiceContext() : hBufferEndEvent(CreateEventEx(NULL, FALSE, FALSE, NULL))
00062     {
00063     }
00064     virtual ~StreamingVoiceContext()
00065     {
00066         CloseHandle(hBufferEndEvent);
00067     }
00068 };
00069
00070 class Audio;
00071 class AudioEngineCallbacks: public IXAudio2EngineCallback
00072 {
00073 private:
00074     Audio* m_audio;
00075
00076 public :
00077     AudioEngineCallbacks(){};
00078     void Initialize(Audio* audio);
00079
00080     // Called by XAudio2 just before an audio processing pass begins.
00081     void _stdcall OnProcessingPassStart(){};
00082
00083     // Called just after an audio processing pass ends.
00084     void  _stdcall OnProcessingPassEnd(){};
00085
00086     // Called when a critical system error causes XAudio2
00087     // to be closed and restarted. The error code is given in Error.
00088     void  _stdcall OnCriticalError(HRESULT Error);
00089 };
00090
00091 class Audio
00092 {
00093 private:
00094     IXAudio2*                   m_musicEngine;
00095     IXAudio2*                   m_soundEffectEngine;
00096     IXAudio2MasteringVoice*     m_musicMasteringVoice;
00097     IXAudio2MasteringVoice*     m_soundEffectMasteringVoice;
00098     IXAudio2SourceVoice*        m_musicSourceVoice;
00099     StreamingVoiceContext       m_voiceContext;
00100     byte                        m_audioBuffers[MAX_BUFFER_COUNT][STREAMING_BUFFER_SIZE];
00101     MediaStreamer               m_musicStreamer;
00102     uint32                      m_currentBuffer;
00103     SoundEffectData             m_soundEffects[SOUND_EVENTS];
00104     XAUDIO2FX_REVERB_PARAMETERS m_reverbParametersLarge;
00105     XAUDIO2FX_REVERB_PARAMETERS m_reverbParametersSmall;
00106     IXAudio2SubmixVoice*        m_soundEffectReverbVoiceSmallRoom;
00107     IXAudio2SubmixVoice*        m_soundEffectReverbVoiceLargeRoom;
00108     IXAudio2SubmixVoice*        m_musicReverbVoiceSmallRoom;
00109     IXAudio2SubmixVoice*        m_musicReverbVoiceLargeRoom;
00110     bool                        m_engineExperiencedCriticalError;
00111     AudioEngineCallbacks        m_musicEngineCallback;
00112     AudioEngineCallbacks        m_soundEffectEngineCallback;
00113
00114     void CreateSourceVoice(SoundEvent);
00115     void CreateReverb(
00116         IXAudio2* engine,
00117         IXAudio2MasteringVoice* masteringVoice,
00118         XAUDIO2FX_REVERB_PARAMETERS* parameters,
00119         IXAudio2SubmixVoice** newSubmix,
00120         bool enableEffect
00121         );
00122
00123 public:
00124     bool m_isAudioStarted;
00125
00126     ~Audio();
00127     void Initialize();
00128     void CreateResources();
00129     void ReleaseResources();
00130     void Start();
00131     void Render();
00132     void SuspendAudio();
00133     void ResumeAudio();
00134
00135     // This flag can be used to tell when the audio system
00136     // is experiencing critial errors.
00137     // XAudio2 gives a critical error when the user unplugs
00138     // the headphones and a new speaker configuration is generated.
00139     void SetEngineExperiencedCriticalError()
00140     {
00141         m_engineExperiencedCriticalError = true;
00142     }
00143
00144     bool HasEngineExperiencedCriticalError()
00145     {
00146         return m_engineExperiencedCriticalError;
00147     }
00148
00149     void PlaySoundEffect(SoundEvent sound);
00150     bool IsSoundEffectStarted(SoundEvent sound);
00151     void StopSoundEffect(SoundEvent sound);
00152     void SetSoundEffectVolume(SoundEvent sound, float volume);
00153     void SetSoundEffectPitch(SoundEvent sound, float pitch);
00154     void SetSoundEffectFilter(SoundEvent sound, float frequency, float oneOverQ);
00155     void SetRoomSize(float roomSize, float* wallDistances);
00156 };
00157
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX swap chain implementation/C++/pch.h Source File

  • DirectX swap chain implementation

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 <d3d11_1.h>
00012 #include <d2d1_1.h>
00013 #include <d2d1effects.h>
00014 #include <dwrite_1.h>
00015 #include <wincodec.h>
00016 #include <agile.h>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D custom image effects/C++/PixelShader/DirectXBase.h Source File

  • Direct2D custom image effects
  • PixelShader

DirectXBase.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 "DirectXSample.h"
00011
00012 // Helper class that initializes DirectX APIs for both 2D and 3D rendering.
00013 // Some of the code in this class may be omitted if only 2D or only 3D rendering is being used.
00014 ref class DirectXBase abstract
00015 {
00016 internal:
00017     DirectXBase();
00018
00019     virtual void Initialize(Windows::UI::Core::CoreWindow^ window, float dpi);
00020     virtual void HandleDeviceLost();
00021     virtual void CreateDeviceIndependentResources();
00022     virtual void CreateDeviceResources();
00023     virtual void SetDpi(float dpi);
00024     virtual void UpdateForWindowSizeChange();
00025     virtual void CreateWindowSizeDependentResources();
00026     virtual void Render() = 0;
00027     virtual void Present();
00028     void ValidateDevice();
00029
00030 protected private:
00031     Platform::Agile<Windows::UI::Core::CoreWindow>  m_window;
00032
00033     // DirectWrite & Windows Imaging Component Objects.
00034     Microsoft::WRL::ComPtr<IDWriteFactory1>         m_dwriteFactory;
00035     Microsoft::WRL::ComPtr<IWICImagingFactory2>     m_wicFactory;
00036
00037     // DirectX Core Objects. Required for 2D and 3D.
00038     Microsoft::WRL::ComPtr<ID3D11Device1>           m_d3dDevice;
00039     Microsoft::WRL::ComPtr<ID3D11DeviceContext1>    m_d3dContext;
00040     Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00041     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00042
00043     // Direct2D Rendering Objects. Required for 2D.
00044     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00046     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00047     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmap;
00048
00049     // Direct3D Rendering Objects. Required for 3D.
00050     Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00051
00052     // Cached renderer properties.
00053     D3D_FEATURE_LEVEL                               m_featureLevel;
00054     Windows::Foundation::Size                       m_renderTargetSize;
00055     Windows::Foundation::Rect                       m_windowBounds;
00056     float                                           m_dpi;
00057     bool                                            m_windowSizeChangeInProgress;
00058 };
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/TaskExtensions.cpp Source File

  • Hilo C++
  • Hilo

TaskExtensions.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 namespace Hilo
00010 {
00011     // The run_async_non_interactive function allows lower priority (noninteractive) work to be scheduled on the main thread.
00012     void run_async_non_interactive(std::function<void ()>&& action)
00013     {
00014         Windows::UI::Core::CoreWindow^ wnd = Windows::ApplicationModel::Core::CoreApplication::MainView->CoreWindow;
00015         assert(wnd != nullptr);
00016
00017         wnd->Dispatcher->RunAsync(
00018             Windows::UI::Core::CoreDispatcherPriority::Low,
00019             ref new Windows::UI::Core::DispatchedHandler([action]()
00020         {
00021             action();
00022         }));
00023     }
00024 }
00025
00026 #ifndef NDEBUG
00027 unsigned int _mainThreadId = 0U;
00028
00029 #ifdef  __cplusplus
00030 extern "C" {
00031 #endif
00032
00033     // The IsMainThread function returns true if the current thread is the app's main thread and false otherwise.
00034     bool IsMainThread()
00035     {
00036         return (_mainThreadId == 0U || _mainThreadId == GetCurrentThreadId());
00037     }
00038
00039     // The IsBackgroundThread function returns false if the current thread is the app's main thread and true otherwise.
00040     bool IsBackgroundThread()
00041     {
00042         return (_mainThreadId == 0U || _mainThreadId != GetCurrentThreadId());
00043     }
00044
00045     // The RecordMainThread function registers the main thread ID for use by the IsMainThread and IsBackgroundThread functions.
00046     void RecordMainThread()
00047     {
00048         _mainThreadId = GetCurrentThreadId();
00049     }
00050
00051 #ifdef  __cplusplus
00052 }
00053 #endif
00054
00055 #endif /* not NDEBUG */
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DatagramSocket/C++/Scenario4.xaml.h Source File

  • DatagramSocket

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
00022 namespace DatagramSocketSample
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 Scenario4 sealed
00029     {
00030     public:
00031         Scenario4();
00032
00033     protected:
00034         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00035     private:
00036         MainPage^ rootPage;
00037         void CloseSockets_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038     };
00039 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX postcard app/C++/BasicLoader.h Source File

  • DirectX postcard app

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 Sat Nov 23 2024 16:08:08 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::TileContent::TileWideBlockAndText02 Member List

This is the complete list of members for NotificationsExtensions::TileContent::TileWideBlockAndText02, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
Branding | NotificationsExtensions::TileContent::TileNotificationBase |
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
RequireSquareContent | NotificationsExtensions::TileContent::TileWideBase |
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SquareContent | NotificationsExtensions::TileContent::TileWideBase |
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextBlock | NotificationsExtensions::TileContent::TileWideBlockAndText02 |
TextBodyWrap | NotificationsExtensions::TileContent::TileWideBlockAndText02 |
TextFields | NotificationsExtensions::NotificationBase |
TextSubBlock | NotificationsExtensions::TileContent::TileWideBlockAndText02 |
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWideBlockAndText02() | NotificationsExtensions::TileContent::TileWideBlockAndText02 | [inline]
TileWideBlockAndText02() | NotificationsExtensions::TileContent::TileWideBlockAndText02 | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:43 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application resources and localization/C++/Scenario1.xaml.h Source File

  • Application resources and localization

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 SDKSample
00023 {
00024     namespace ApplicationResources
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 Scenario1 sealed
00031         {
00032         public:
00033             Scenario1();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039         };
00040     }
00041 }
Generated on Sat Nov 23 2024 16:07:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/BasicReaderWriter.cpp Source File

  • XAML DirectX 3D shooting game

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     m_locationPath = Platform::String::Concat(m_location->Path, "\\");
00023 }
00024
00025 BasicReaderWriter::BasicReaderWriter(
00026     _In_ Windows::Storage::StorageFolder^ folder
00027     )
00028 {
00029     m_location = folder;
00030     Platform::String^ path = m_location->Path;
00031     if (path->Length() == 0)
00032     {
00033         // Applications are not permitted to access certain
00034         // folders, such as the Documents folder, using this
00035         // code path.  In such cases, the Path property for
00036         // the folder will be an empty string.
00037         throw ref new Platform::FailureException();
00038     }
00039     m_locationPath = Platform::String::Concat(path, "\\");
00040 }
00041
00042 Platform::Array<byte>^ BasicReaderWriter::ReadData(
00043     _In_ Platform::String^ filename
00044     )
00045 {
00046     CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {0};
00047     extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
00048     extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
00049     extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN;
00050     extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
00051     extendedParams.lpSecurityAttributes = nullptr;
00052     extendedParams.hTemplateFile = nullptr;
00053
00054     Wrappers::FileHandle file(
00055         CreateFile2(
00056             Platform::String::Concat(m_locationPath, filename)->Data(),
00057             GENERIC_READ,
00058             FILE_SHARE_READ,
00059             OPEN_EXISTING,
00060             &extendedParams
00061             )
00062         );
00063     if (file.Get() == INVALID_HANDLE_VALUE)
00064     {
00065         throw ref new Platform::FailureException();
00066     }
00067
00068     FILE_STANDARD_INFO fileInfo = {0};
00069     if (!GetFileInformationByHandleEx(
00070         file.Get(),
00071         FileStandardInfo,
00072         &fileInfo,
00073         sizeof(fileInfo)
00074         ))
00075     {
00076         throw ref new Platform::FailureException();
00077     }
00078
00079     if (fileInfo.EndOfFile.HighPart != 0)
00080     {
00081         throw ref new Platform::OutOfMemoryException();
00082     }
00083
00084     Platform::Array<byte>^ fileData = ref new Platform::Array<byte>(fileInfo.EndOfFile.LowPart);
00085
00086     if (!ReadFile(
00087         file.Get(),
00088         fileData->Data,
00089         fileData->Length,
00090         nullptr,
00091         nullptr
00092         ))
00093     {
00094         throw ref new Platform::FailureException();
00095     }
00096
00097     return fileData;
00098 }
00099
00100 task<Platform::Array<byte>^> BasicReaderWriter::ReadDataAsync(
00101     _In_ Platform::String^ filename
00102     )
00103 {
00104     return task<StorageFile^>(m_location->GetFileAsync(filename)).then([=](StorageFile^ file)
00105     {
00106         return FileIO::ReadBufferAsync(file);
00107     }).then([=](IBuffer^ buffer)
00108     {
00109         auto fileData = ref new Platform::Array<byte>(buffer->Length);
00110         DataReader::FromBuffer(buffer)->ReadBytes(fileData);
00111         return fileData;
00112     });
00113 }
00114
00115 uint32 BasicReaderWriter::WriteData(
00116     _In_ Platform::String^ filename,
00117     _In_ const Platform::Array<byte>^ fileData
00118     )
00119 {
00120     CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {0};
00121     extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
00122     extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
00123     extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN;
00124     extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
00125     extendedParams.lpSecurityAttributes = nullptr;
00126     extendedParams.hTemplateFile = nullptr;
00127
00128     Wrappers::FileHandle file(
00129         CreateFile2(
00130             Platform::String::Concat(m_locationPath, filename)->Data(),
00131             GENERIC_WRITE,
00132             0,
00133             CREATE_ALWAYS,
00134             &extendedParams
00135             )
00136         );
00137     if (file.Get() == INVALID_HANDLE_VALUE)
00138     {
00139         throw ref new Platform::FailureException();
00140     }
00141
00142     DWORD numBytesWritten;
00143     if (
00144         !WriteFile(
00145             file.Get(),
00146             fileData->Data,
00147             fileData->Length,
00148             &numBytesWritten,
00149             nullptr
00150             ) ||
00151         numBytesWritten != fileData->Length
00152         )
00153     {
00154         throw ref new Platform::FailureException();
00155     }
00156
00157     return numBytesWritten;
00158 }
00159
00160 task<void> BasicReaderWriter::WriteDataAsync(
00161     _In_ Platform::String^ filename,
00162     _In_ const Platform::Array<byte>^ fileData
00163     )
00164 {
00165     return task<StorageFile^>(m_location->CreateFileAsync(filename, CreationCollisionOption::ReplaceExisting)).then([=](StorageFile^ file)
00166     {
00167         FileIO::WriteBytesAsync(file, fileData);
00168     });
00169 }
Generated on Sat Nov 23 2024 16:08:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D tutorial/C++/Lesson3.Cubes/Main.cpp Source File

  • Direct3D tutorial
  • Lesson3.Cubes

Main.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 "DirectXSample.h"
00010 #include "BasicMath.h"
00011 #include "BasicReaderWriter.h"
00012
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::UI::Core;
00015 using namespace Windows::Foundation;
00016 using namespace Windows::ApplicationModel::Core;
00017 using namespace Windows::ApplicationModel::Activation;
00018
00019 struct SimpleCubeVertex
00020 {
00021     float3 pos;   // position
00022     float3 color; // color
00023 };
00024
00025 struct ConstantBuffer
00026 {
00027     float4x4 model;
00028     float4x4 view;
00029     float4x4 projection;
00030 };
00031
00032 // This class defines the application as a whole.
00033 ref class Direct3DTutorialFrameworkView : public IFrameworkView
00034 {
00035 private:
00036     Platform::Agile<CoreWindow> m_window;
00037     ComPtr<IDXGISwapChain1> m_swapChain;
00038     ComPtr<ID3D11Device1> m_d3dDevice;
00039     ComPtr<ID3D11DeviceContext1> m_d3dDeviceContext;
00040     ComPtr<ID3D11RenderTargetView> m_renderTargetView;
00041     ComPtr<ID3D11DepthStencilView> m_depthStencilView;
00042     ComPtr<ID3D11Buffer> m_constantBuffer;
00043     ConstantBuffer m_constantBufferData;
00044
00045 public:
00046     // This method is called on application launch.
00047     virtual void Initialize(
00048         _In_ CoreApplicationView^ applicationView
00049         )
00050     {
00051         applicationView->Activated +=
00052             ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &Direct3DTutorialFrameworkView::OnActivated);
00053     }
00054
00055     // This method is called after Initialize.
00056     virtual void SetWindow(
00057         _In_ CoreWindow^ window
00058         )
00059     {
00060         m_window = window;
00061
00062         // Specify the cursor type as the standard arrow cursor.
00063         m_window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
00064
00065         // Allow the application to respond when the window size changes.
00066         m_window->SizeChanged +=
00067             ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(
00068                 this,
00069                 &Direct3DTutorialFrameworkView::OnWindowSizeChanged
00070                 );
00071     }
00072
00073     void OnActivated(
00074         _In_ CoreApplicationView^ applicationView,
00075         _In_ IActivatedEventArgs^ args
00076         )
00077     {
00078         // Activate the application window, making it visible and enabling it to receive events.
00079         CoreWindow::GetForCurrentThread()->Activate();
00080     }
00081
00082     virtual void Load(_In_ Platform::String^ entryPoint)
00083     {
00084     }
00085
00086     // This method is called after Load.
00087     virtual void Run()
00088     {
00089         // First, create the Direct3D device.
00090
00091         // This flag is required in order to enable compatibility with Direct2D.
00092         UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00093
00094 #if defined(_DEBUG)
00095         // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00096         creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00097 #endif
00098
00099         // This array defines the ordering of feature levels that D3D should attempt to create.
00100         D3D_FEATURE_LEVEL featureLevels[] =
00101         {
00102             D3D_FEATURE_LEVEL_11_1,
00103             D3D_FEATURE_LEVEL_11_0,
00104             D3D_FEATURE_LEVEL_10_1,
00105             D3D_FEATURE_LEVEL_10_0,
00106             D3D_FEATURE_LEVEL_9_3,
00107             D3D_FEATURE_LEVEL_9_1
00108         };
00109
00110         ComPtr<ID3D11Device> d3dDevice;
00111         ComPtr<ID3D11DeviceContext> d3dDeviceContext;
00112         DX::ThrowIfFailed(
00113             D3D11CreateDevice(
00114                 nullptr,                    // specify nullptr to use the default adapter
00115                 D3D_DRIVER_TYPE_HARDWARE,
00116                 nullptr,                    // leave as nullptr if hardware is used
00117                 creationFlags,              // optionally set debug and Direct2D compatibility flags
00118                 featureLevels,
00119                 ARRAYSIZE(featureLevels),
00120                 D3D11_SDK_VERSION,          // always set this to D3D11_SDK_VERSION
00121                 &d3dDevice,
00122                 nullptr,
00123                 &d3dDeviceContext
00124                 )
00125             );
00126
00127         // Retrieve the Direct3D 11.1 interfaces.
00128         DX::ThrowIfFailed(
00129             d3dDevice.As(&m_d3dDevice)
00130             );
00131
00132         DX::ThrowIfFailed(
00133             d3dDeviceContext.As(&m_d3dDeviceContext)
00134             );
00135
00136
00137         // After the D3D device is created, create additional application resources.
00138         CreateWindowSizeDependentResources();
00139
00140         // Create a Basic Reader-Writer class to load data from disk.  This class is examined
00141         // in the Resource Loading sample.
00142         BasicReaderWriter^ reader = ref new BasicReaderWriter();
00143
00144         // Load the raw vertex shader bytecode from disk and create a vertex shader with it.
00145         auto vertexShaderBytecode = reader->ReadData("SimpleVertexShader.cso");
00146         ComPtr<ID3D11VertexShader> vertexShader;
00147         DX::ThrowIfFailed(
00148             m_d3dDevice->CreateVertexShader(
00149                 vertexShaderBytecode->Data,
00150                 vertexShaderBytecode->Length,
00151                 nullptr,
00152                 &vertexShader
00153                 )
00154             );
00155
00156         // Create an input layout that matches the layout defined in the vertex shader code.
00157         // For this lesson, this is simply a float3 vector defining the vertex position, and
00158         // a float3 vector defining the vertex color.
00159         const D3D11_INPUT_ELEMENT_DESC basicVertexLayoutDesc[] =
00160         {
00161             { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0,  0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
00162             { "COLOR",    0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
00163         };
00164
00165         ComPtr<ID3D11InputLayout> inputLayout;
00166         DX::ThrowIfFailed(
00167             m_d3dDevice->CreateInputLayout(
00168                 basicVertexLayoutDesc,
00169                 ARRAYSIZE(basicVertexLayoutDesc),
00170                 vertexShaderBytecode->Data,
00171                 vertexShaderBytecode->Length,
00172                 &inputLayout
00173                 )
00174             );
00175
00176         // Load the raw pixel shader bytecode from disk and create a pixel shader with it.
00177         auto pixelShaderBytecode = reader->ReadData("SimplePixelShader.cso");
00178         ComPtr<ID3D11PixelShader> pixelShader;
00179         DX::ThrowIfFailed(
00180             m_d3dDevice->CreatePixelShader(
00181                 pixelShaderBytecode->Data,
00182                 pixelShaderBytecode->Length,
00183                 nullptr,
00184                 &pixelShader
00185                 )
00186             );
00187
00188         // Create vertex and index buffers that define a simple unit cube.
00189
00190         // In the array below, which will be used to initialize the cube vertex buffers,
00191         // each vertex is assigned a color in addition to a position.  This will allow
00192         // the pixel shader to color each face differently, enabling them to be distinguished.
00193         SimpleCubeVertex cubeVertices[] =
00194         {
00195             { float3(-0.5f, 0.5f, -0.5f), float3(0.0f, 1.0f, 0.0f) }, // +Y (top face)
00196             { float3( 0.5f, 0.5f, -0.5f), float3(1.0f, 1.0f, 0.0f) },
00197             { float3( 0.5f, 0.5f,  0.5f), float3(1.0f, 1.0f, 1.0f) },
00198             { float3(-0.5f, 0.5f,  0.5f), float3(0.0f, 1.0f, 1.0f) },
00199
00200             { float3(-0.5f, -0.5f,  0.5f), float3(0.0f, 0.0f, 1.0f) }, // -Y (bottom face)
00201             { float3( 0.5f, -0.5f,  0.5f), float3(1.0f, 0.0f, 1.0f) },
00202             { float3( 0.5f, -0.5f, -0.5f), float3(1.0f, 0.0f, 0.0f) },
00203             { float3(-0.5f, -0.5f, -0.5f), float3(0.0f, 0.0f, 0.0f) },
00204         };
00205
00206         unsigned short cubeIndices[] =
00207         {
00208             0, 1, 2,
00209             0, 2, 3,
00210
00211             4, 5, 6,
00212             4, 6, 7,
00213
00214             3, 2, 5,
00215             3, 5, 4,
00216
00217             2, 1, 6,
00218             2, 6, 5,
00219
00220             1, 7, 6,
00221             1, 0, 7,
00222
00223             0, 3, 4,
00224             0, 4, 7
00225         };
00226
00227         D3D11_BUFFER_DESC vertexBufferDesc = {0};
00228         vertexBufferDesc.ByteWidth = sizeof(SimpleCubeVertex) * ARRAYSIZE(cubeVertices);
00229         vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
00230         vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
00231         vertexBufferDesc.CPUAccessFlags = 0;
00232         vertexBufferDesc.MiscFlags = 0;
00233         vertexBufferDesc.StructureByteStride = 0;
00234
00235         D3D11_SUBRESOURCE_DATA vertexBufferData;
00236         vertexBufferData.pSysMem = cubeVertices;
00237         vertexBufferData.SysMemPitch = 0;
00238         vertexBufferData.SysMemSlicePitch = 0;
00239
00240         ComPtr<ID3D11Buffer> vertexBuffer;
00241         DX::ThrowIfFailed(
00242             m_d3dDevice->CreateBuffer(
00243                 &vertexBufferDesc,
00244                 &vertexBufferData,
00245                 &vertexBuffer
00246                 )
00247             );
00248
00249         D3D11_BUFFER_DESC indexBufferDesc;
00250         indexBufferDesc.ByteWidth = sizeof(unsigned short) * ARRAYSIZE(cubeIndices);
00251         indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
00252         indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
00253         indexBufferDesc.CPUAccessFlags = 0;
00254         indexBufferDesc.MiscFlags = 0;
00255         indexBufferDesc.StructureByteStride = 0;
00256
00257         D3D11_SUBRESOURCE_DATA indexBufferData;
00258         indexBufferData.pSysMem = cubeIndices;
00259         indexBufferData.SysMemPitch = 0;
00260         indexBufferData.SysMemSlicePitch = 0;
00261
00262         ComPtr<ID3D11Buffer> indexBuffer;
00263         DX::ThrowIfFailed(
00264             m_d3dDevice->CreateBuffer(
00265                 &indexBufferDesc,
00266                 &indexBufferData,
00267                 &indexBuffer
00268                 )
00269             );
00270
00271
00272         // Create a constant buffer for passing model, view, and projection matrices
00273         // to the vertex shader.  This will allow us to rotate the cube and apply
00274         // a perspective projection to it.
00275
00276         D3D11_BUFFER_DESC constantBufferDesc = {0};
00277         constantBufferDesc.ByteWidth = sizeof(m_constantBufferData);
00278         constantBufferDesc.Usage = D3D11_USAGE_DEFAULT;
00279         constantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
00280         constantBufferDesc.CPUAccessFlags = 0;
00281         constantBufferDesc.MiscFlags = 0;
00282         constantBufferDesc.StructureByteStride = 0;
00283         DX::ThrowIfFailed(
00284             m_d3dDevice->CreateBuffer(
00285                 &constantBufferDesc,
00286                 nullptr,
00287                 &m_constantBuffer
00288                 )
00289             );
00290
00291         // Specify the view transform corresponding to a camera position of
00292         // X = 0, Y = 1, Z = 2.  See Lesson 5 for a generalized camera class.
00293
00294         m_constantBufferData.view = float4x4(
00295             -1.00000000f, 0.00000000f,  0.00000000f,  0.00000000f,
00296              0.00000000f, 0.89442718f,  0.44721359f,  0.00000000f,
00297              0.00000000f, 0.44721359f, -0.89442718f, -2.23606800f,
00298              0.00000000f, 0.00000000f,  0.00000000f,  1.00000000f
00299             );
00300
00301
00302         // This value will be used to animate the cube by rotating it every frame;
00303         float degree = 0.0f;
00304
00305         // Enter the render loop. Note that Windows Store apps should never exit.
00306         while (true)
00307         {
00308             // Process events incoming to the window.
00309             m_window->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
00310
00311             // Update the constant buffer to rotate the cube model.
00312             m_constantBufferData.model = rotationY(-degree);
00313             degree += 1.0f;
00314
00315             m_d3dDeviceContext->UpdateSubresource(
00316                 m_constantBuffer.Get(),
00317                 0,
00318                 nullptr,
00319                 &m_constantBufferData,
00320                 0,
00321                 0
00322                 );
00323
00324             // Specify the render target and depth stencil we created as the output target.
00325             m_d3dDeviceContext->OMSetRenderTargets(
00326                 1,
00327                 m_renderTargetView.GetAddressOf(),
00328                 m_depthStencilView.Get()
00329                 );
00330
00331             // Clear the render target to a solid color, and reset the depth stencil.
00332             const float clearColor[4] = { 0.071f, 0.04f, 0.561f, 1.0f };
00333             m_d3dDeviceContext->ClearRenderTargetView(
00334                 m_renderTargetView.Get(),
00335                 clearColor
00336                 );
00337
00338             m_d3dDeviceContext->ClearDepthStencilView(
00339                 m_depthStencilView.Get(),
00340                 D3D11_CLEAR_DEPTH,
00341                 1.0f,
00342                 0
00343                 );
00344
00345             m_d3dDeviceContext->IASetInputLayout(inputLayout.Get());
00346
00347             // Set the vertex and index buffers, and specify the way they define geometry.
00348             UINT stride = sizeof(SimpleCubeVertex);
00349             UINT offset = 0;
00350             m_d3dDeviceContext->IASetVertexBuffers(
00351                 0,
00352                 1,
00353                 vertexBuffer.GetAddressOf(),
00354                 &stride,
00355                 &offset
00356                 );
00357
00358             m_d3dDeviceContext->IASetIndexBuffer(
00359                 indexBuffer.Get(),
00360                 DXGI_FORMAT_R16_UINT,
00361                 0
00362                 );
00363
00364             m_d3dDeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
00365
00366             // Set the vertex and pixel shader stage state.
00367             m_d3dDeviceContext->VSSetShader(
00368                 vertexShader.Get(),
00369                 nullptr,
00370                 0
00371                 );
00372
00373             m_d3dDeviceContext->VSSetConstantBuffers(
00374                 0,
00375                 1,
00376                 m_constantBuffer.GetAddressOf()
00377                 );
00378
00379             m_d3dDeviceContext->PSSetShader(
00380                 pixelShader.Get(),
00381                 nullptr,
00382                 0
00383                 );
00384
00385             // Draw the cube.
00386             m_d3dDeviceContext->DrawIndexed(
00387                 ARRAYSIZE(cubeIndices),
00388                 0,
00389                 0
00390                 );
00391
00392             // Present the rendered image to the window.  Because the maximum frame latency is set to 1,
00393             // the render loop will generally be throttled to the screen refresh rate, typically around
00394             // 60Hz, by sleeping the application on Present until the screen is refreshed.
00395             DX::ThrowIfFailed(
00396                 m_swapChain->Present(1, 0)
00397                 );
00398         }
00399     }
00400
00401     // This method is called before the application exits.
00402     virtual void Uninitialize()
00403     {
00404     }
00405
00406 private:
00407
00408     // This method is called whenever the application window size changes.
00409     void OnWindowSizeChanged(
00410         _In_ CoreWindow^ sender,
00411         _In_ WindowSizeChangedEventArgs^ args
00412         )
00413     {
00414         m_renderTargetView = nullptr;
00415         m_depthStencilView = nullptr;
00416         CreateWindowSizeDependentResources();
00417     }
00418
00419     // This method creates all application resources that depend on
00420     // the application window size.  It is called at app initialization,
00421     // and whenever the application window size changes.
00422     void CreateWindowSizeDependentResources()
00423     {
00424         if (m_swapChain != nullptr)
00425         {
00426             // If the swap chain already exists, resize it.
00427             DX::ThrowIfFailed(
00428                 m_swapChain->ResizeBuffers(
00429                     2,
00430                     0,
00431                     0,
00432                     DXGI_FORMAT_B8G8R8A8_UNORM,
00433                     0
00434                     )
00435                 );
00436         }
00437         else
00438         {
00439             // If the swap chain does not exist, create it.
00440             DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00441
00442             swapChainDesc.Stereo = false;
00443             swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00444             swapChainDesc.Scaling = DXGI_SCALING_NONE;
00445             swapChainDesc.Flags = 0;
00446
00447             // Use automatic sizing.
00448             swapChainDesc.Width = 0;
00449             swapChainDesc.Height = 0;
00450
00451             // This is the most common swap chain format.
00452             swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
00453
00454             // Don't use multi-sampling.
00455             swapChainDesc.SampleDesc.Count = 1;
00456             swapChainDesc.SampleDesc.Quality = 0;
00457
00458             // Use two buffers to enable flip effect.
00459             swapChainDesc.BufferCount = 2;
00460
00461             // We recommend using this swap effect for all applications.
00462             swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
00463
00464
00465             // Once the swap chain description is configured, it must be
00466             // created on the same adapter as the existing D3D Device.
00467
00468             // First, retrieve the underlying DXGI Device from the D3D Device.
00469             ComPtr<IDXGIDevice2> dxgiDevice;
00470             DX::ThrowIfFailed(
00471                 m_d3dDevice.As(&dxgiDevice)
00472                 );
00473
00474             // Ensure that DXGI does not queue more than one frame at a time. This both reduces
00475             // latency and ensures that the application will only render after each VSync, minimizing
00476             // power consumption.
00477             DX::ThrowIfFailed(
00478                 dxgiDevice->SetMaximumFrameLatency(1)
00479                 );
00480
00481             // Next, get the parent factory from the DXGI Device.
00482             ComPtr<IDXGIAdapter> dxgiAdapter;
00483             DX::ThrowIfFailed(
00484                 dxgiDevice->GetAdapter(&dxgiAdapter)
00485                 );
00486
00487             ComPtr<IDXGIFactory2> dxgiFactory;
00488             DX::ThrowIfFailed(
00489                 dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00490                 );
00491
00492             // Finally, create the swap chain.
00493             CoreWindow^ window = m_window.Get();
00494             DX::ThrowIfFailed(
00495                 dxgiFactory->CreateSwapChainForCoreWindow(
00496                     m_d3dDevice.Get(),
00497                     reinterpret_cast<IUnknown*>(window),
00498                     &swapChainDesc,
00499                     nullptr, // allow on all displays
00500                     &m_swapChain
00501                     )
00502                 );
00503         }
00504
00505         // Once the swap chain is created, create a render target view.  This will
00506         // allow Direct3D to render graphics to the window.
00507
00508         ComPtr<ID3D11Texture2D> backBuffer;
00509         DX::ThrowIfFailed(
00510             m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00511             );
00512
00513         DX::ThrowIfFailed(
00514             m_d3dDevice->CreateRenderTargetView(
00515                 backBuffer.Get(),
00516                 nullptr,
00517                 &m_renderTargetView
00518                 )
00519             );
00520
00521         // Once the render target view is created, create a depth stencil view.  This
00522         // allows Direct3D to efficiently render objects closer to the camera in front
00523         // of objects further from the camera.
00524
00525         D3D11_TEXTURE2D_DESC backBufferDesc = {0};
00526         backBuffer->GetDesc(&backBufferDesc);
00527
00528         D3D11_TEXTURE2D_DESC depthStencilDesc;
00529         depthStencilDesc.Width = backBufferDesc.Width;
00530         depthStencilDesc.Height = backBufferDesc.Height;
00531         depthStencilDesc.MipLevels = 1;
00532         depthStencilDesc.ArraySize = 1;
00533         depthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
00534         depthStencilDesc.SampleDesc.Count = 1;
00535         depthStencilDesc.SampleDesc.Quality = 0;
00536         depthStencilDesc.Usage = D3D11_USAGE_DEFAULT;
00537         depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
00538         depthStencilDesc.CPUAccessFlags = 0;
00539         depthStencilDesc.MiscFlags = 0;
00540         ComPtr<ID3D11Texture2D> depthStencil;
00541         DX::ThrowIfFailed(
00542             m_d3dDevice->CreateTexture2D(
00543                 &depthStencilDesc,
00544                 nullptr,
00545                 &depthStencil
00546                 )
00547             );
00548
00549         D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
00550         depthStencilViewDesc.Format = depthStencilDesc.Format;
00551         depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
00552         depthStencilViewDesc.Flags = 0;
00553         depthStencilViewDesc.Texture2D.MipSlice = 0;
00554         DX::ThrowIfFailed(
00555             m_d3dDevice->CreateDepthStencilView(
00556                 depthStencil.Get(),
00557                 &depthStencilViewDesc,
00558                 &m_depthStencilView
00559                 )
00560             );
00561
00562         // After the render target and depth stencil views are created, specify that
00563         // the viewport, which describes what portion of the window to draw to, should
00564         // cover the entire window.
00565
00566         D3D11_VIEWPORT viewport;
00567         viewport.TopLeftX = 0.0f;
00568         viewport.TopLeftY = 0.0f;
00569         viewport.Width = static_cast<float>(backBufferDesc.Width);
00570         viewport.Height = static_cast<float>(backBufferDesc.Height);
00571         viewport.MinDepth = D3D11_MIN_DEPTH;
00572         viewport.MaxDepth = D3D11_MAX_DEPTH;
00573
00574         m_d3dDeviceContext->RSSetViewports(1, &viewport);
00575
00576         // Finally, update the constant buffer perspective projection parameters
00577         // to account for the size of the application window.  In this sample,
00578         // the parameters are fixed to a 70-degree field of view, with a depth
00579         // range of 0.01 to 100.  See Lesson 5 for a generalized camera class.
00580
00581         float xScale = 1.42814801f;
00582         float yScale = 1.42814801f;
00583         if (backBufferDesc.Width > backBufferDesc.Height)
00584         {
00585             xScale = yScale *
00586                 static_cast<float>(backBufferDesc.Height) /
00587                 static_cast<float>(backBufferDesc.Width);
00588         }
00589         else
00590         {
00591             yScale = xScale *
00592                 static_cast<float>(backBufferDesc.Width) /
00593                 static_cast<float>(backBufferDesc.Height);
00594         }
00595
00596         m_constantBufferData.projection = float4x4(
00597             xScale, 0.0f,    0.0f,  0.0f,
00598             0.0f,   yScale,  0.0f,  0.0f,
00599             0.0f,   0.0f,   -1.0f, -0.01f,
00600             0.0f,   0.0f,   -1.0f,  0.0f
00601             );
00602     }
00603 };
00604
00605 // This class defines how to create the custom View Provider defined above.
00606 ref class Direct3DTutorialFrameworkViewSource : IFrameworkViewSource
00607 {
00608 public:
00609     virtual IFrameworkView^ CreateView()
00610     {
00611         return ref new Direct3DTutorialFrameworkView();
00612     }
00613 };
00614
00615 [Platform::MTAThread]
00616 int main(Platform::Array<Platform::String^>^)
00617 {
00618     auto frameworkViewSource = ref new Direct3DTutorialFrameworkViewSource();
00619     Windows::ApplicationModel::Core::CoreApplication::Run(frameworkViewSource);
00620     return 0;
00621 }
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Contact Picker app/C++/App.xaml.h Source File

  • Contact Picker app

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace ContactPicker
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028
00029     public:
00030         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00031         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00032
00033     protected:
00034         virtual void OnActivated(Windows::ApplicationModel::Activation::IActivatedEventArgs^ args) override;
00035
00036     private:
00037         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00038         void SetupWindowing(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs);
00039
00040     };
00041 }
00042
00043
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML FlipView control/C++/Scenario4.xaml.cpp Source File

  • XAML FlipView control

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 #include "SampleDataSource.h"
00019
00020 using namespace SDKSample::FlipViewCPP;
00021 using namespace SDKSample::FlipViewData;
00022
00023 using namespace Windows::UI::Xaml;
00024 using namespace Windows::UI::Xaml::Controls;
00025 using namespace Windows::UI::Xaml::Navigation;
00026
00027 Scenario4::Scenario4()
00028 {
00029     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 void Scenario4::OnNavigatedTo(NavigationEventArgs^ e)
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     rootPage = MainPage::Current;
00042
00043   auto sampleData = ref new FlipViewData::SampleDataSource();
00044   FlipView4->ItemsSource = sampleData->Items;
00045   ContextControl->ItemsSource =sampleData->Items;
00046 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: OrientationSensor/C++/Constants.h Source File

  • OrientationSensor

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"Orientation Sensor Raw Data");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044
00045
00046 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Background task/C++/BackgroundTask/TimeTriggeredTask.xaml.cpp Source File

  • Background task
  • BackgroundTask

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 // TimeTriggeredTask.xaml.cpp
00013 // Implementation of the TimeTriggeredTask class
00014 //
00015
00016 #include "pch.h"
00017 #include "TimeTriggeredTask.xaml.h"
00018 #include "Constants.h"
00019
00020 using namespace SDKSample::BackgroundTask;
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     auto iter = BackgroundTaskRegistration::AllTasks->First();
00048     auto hascur = iter->HasCurrent;
00049     while (hascur)
00050     {
00051         auto cur = iter->Current->Value;
00052
00053         if (cur->Name == TimeTriggeredTaskName)
00054         {
00055             AttachProgressAndCompletedHandlers(cur);
00056             break;
00057         }
00058
00059         hascur = iter->MoveNext();
00060     }
00061
00062     UpdateUI();
00063 }
00064
00065 /// <summary>
00066 /// Attach progress and completed handers to a background task.
00067 /// </summary>
00068 /// <param name="task">The task to attach progress and completed handlers to.</param>
00069 void TimeTriggeredTask::AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration^ task)
00070 {
00071     auto progress = [this](BackgroundTaskRegistration^ task, BackgroundTaskProgressEventArgs^ args)
00072     {
00073         auto progress = "Progress: " + args->Progress + "%";
00074         BackgroundTaskSample::TimeTriggeredTaskProgress = progress;
00075         UpdateUI();
00076     };
00077     task->Progress += ref new BackgroundTaskProgressEventHandler(progress);
00078
00079     auto completed = [this](BackgroundTaskRegistration^ task, BackgroundTaskCompletedEventArgs^ args)
00080     {
00081         UpdateUI();
00082     };
00083     task->Completed += ref new BackgroundTaskCompletedEventHandler(completed);
00084 }
00085
00086 void TimeTriggeredTask::RegisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088     //
00089     // Time triggered tasks can only run when the application is on the lock screen.
00090     // Time triggered tasks can be registered even if the application is not on the lockscreen.
00091     //
00092     BackgroundExecutionManager::RequestAccessAsync();
00093
00094     auto task = BackgroundTaskSample::RegisterBackgroundTask(SampleBackgroundTaskEntryPoint,
00095                                                              TimeTriggeredTaskName,
00096                                                              ref new TimeTrigger(15, false),
00097                                                              nullptr);
00098     AttachProgressAndCompletedHandlers(task);
00099     UpdateUI();
00100 }
00101
00102 void TimeTriggeredTask::UnregisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00103 {
00104     BackgroundTaskSample::UnregisterBackgroundTasks(TimeTriggeredTaskName);
00105     UpdateUI();
00106 }
00107
00108 /// <summary>
00109 /// Update the scenario UI.
00110 /// </summary>
00111 void TimeTriggeredTask::UpdateUI()
00112 {
00113     auto uiDelegate = [this]()
00114     {
00115         RegisterButton->IsEnabled = !BackgroundTaskSample::TimeTriggeredTaskRegistered;
00116         UnregisterButton->IsEnabled = BackgroundTaskSample::TimeTriggeredTaskRegistered;
00117         Progress->Text = BackgroundTaskSample::TimeTriggeredTaskProgress;
00118         Status->Text = BackgroundTaskSample::GetBackgroundTaskStatus(TimeTriggeredTaskName);
00119     };
00120     auto handler = ref new Windows::UI::Core::DispatchedHandler(uiDelegate, Platform::CallbackContext::Any);
00121
00122     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, handler);
00123 }
Generated on Sat Nov 23 2024 16:07:58 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Touch keyboard/C++/TouchableTextBlock.xaml.cpp Source File

  • Input Touch keyboard

TouchableTextBlock.xaml.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 //
00009 // TouchableTextBlock.xaml.cpp
00010 // Implementation of the TouchableTextBlock class
00011 //
00012
00013 #include "pch.h"
00014 #include "TouchableTextBlock.xaml.h"
00015
00016 using namespace SDKSample::TouchKeyboard;
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::UI::Xaml::Automation;            // needed for enum SupportedTextSelection in ITextProvider
00029 using namespace Windows::UI::Xaml::Automation::Text;      // needed for TextPatternRangeEndpoint
00030 using namespace Windows::UI::Xaml::Automation::Peers;     // needed for FrameworkElementAutomationPeer class
00031 using namespace Windows::UI::Xaml::Automation::Provider;  // needed for ITextProvider and IValueProvider
00032
00033 namespace SDKSample
00034 {
00035     namespace TouchKeyboard
00036     {
00037       /// <summary>
00038       /// Automation Peer class for TouchableTextBlock.
00039       ///
00040       /// Note: The difference between this and NonTouchableTextBlockAutomationPeer is that this one implements
00041       /// Text Pattern (ITextProvider) and Value Pattern (IValuePattern) interfaces.  So Touch keyboard shows
00042       /// automatically when user taps on the control with Touch or Pen.
00043       /// </summary>
00044       [Windows::Foundation::Metadata::WebHostHidden]
00045       public ref class TouchableTextBlockAutomationPeer sealed : FrameworkElementAutomationPeer, ITextProvider, IValueProvider
00046       {
00047       public:
00048
00049         TouchableTextBlockAutomationPeer(TouchableTextBlock^ owner)
00050           : FrameworkElementAutomationPeer(owner)
00051         {
00052           this->textBlock = owner;
00053           this->accClass = "TouchableTextBlock";
00054         }
00055       protected:
00056         /// <summary>
00057         /// Override GetPatternCore to return the object that supports the specified pattern.  In this case the Value pattern, Text
00058         /// patter and any base class patterns.
00059         /// </summary>
00060         /// <param name="patternInterface"></param>
00061         /// <returns>the object that supports the specified pattern</returns>
00062         virtual Object^ GetPatternCore(PatternInterface patternInterface) override
00063         {
00064           if (patternInterface == PatternInterface::Value)
00065           {
00066             return this;
00067           }
00068           else if (patternInterface == PatternInterface::Text)
00069           {
00070             return this;
00071           }
00072           return FrameworkElementAutomationPeer::GetPatternCore(patternInterface);
00073         }
00074
00075         /// <summary>
00076         /// Override GetClassNameCore and set the name of the class that defines the type associated with this control.
00077         /// </summary>
00078         /// <returns>The name of the control class</returns>
00079         virtual String^ GetClassNameCore() override
00080         {
00081           return this->accClass;
00082         }
00083       public:
00084     #pragma region ITextProvider_Implementation
00085         // Complete implementation of the ITextPattern is beyond the scope of this sample.  The implementation provided
00086         // is specific to this sample's custom control, so it is unlikely that they are directly transferable to other
00087         // custom control.
00088
00089         property ITextRangeProvider^ DocumentRange
00090         {
00091           // A real implementation of this method is beyond the scope of this sample.
00092           // If your custom control has complex text involving both readonly and non-readonly ranges,
00093           // it will need a smarter implementation than just returning a fixed range
00094           virtual ITextRangeProvider^ get() { return ref new TouchableTextBlockRangeProvider(textBlock->ContentText, this); }
00095         }
00096
00097         virtual Array<ITextRangeProvider^>^ GetSelection()
00098         {
00099           return ref new Array<ITextRangeProvider^>(0);
00100         }
00101
00102         virtual Array<ITextRangeProvider^>^ GetVisibleRanges()
00103         {
00104           auto ret = ref new Array<ITextRangeProvider^>(1);
00105           ret[0] = ref new TouchableTextBlockRangeProvider(textBlock->ContentText, this);
00106           return ret;
00107         }
00108
00109         virtual ITextRangeProvider^ RangeFromChild(IRawElementProviderSimple^ childElement)
00110         {
00111           return ref new TouchableTextBlockRangeProvider(textBlock->ContentText, this);
00112         }
00113
00114         virtual ITextRangeProvider^ RangeFromPoint(Point screenLocation)
00115         {
00116           return ref new TouchableTextBlockRangeProvider(textBlock->ContentText, this);
00117         }
00118
00119         property SupportedTextSelection SupportedTextSelection
00120         {
00121           virtual Windows::UI::Xaml::Automation::SupportedTextSelection get() { return Windows::UI::Xaml::Automation::SupportedTextSelection::Single; }
00122         }
00123
00124     #pragma endregion ITextProvider_Implementation
00125
00126     #pragma region IValueProvider_Implementation
00127         // Complete implementation of the IValueProvider is beyond the scope of this sample.  The implementation provided
00128         // is specific to this sample's custom control, so it is unlikely that they are directly transferable to other
00129         // custom control.
00130
00131         /// <summary>
00132         /// The value needs to be false for the Touch keyboard to be launched automatically because Touch keyboard
00133         /// does not appear when the input focus is in a readonly UI control.
00134         /// </summary>
00135         property bool IsReadOnly
00136         {
00137           virtual bool get() { return false; }
00138         }
00139
00140         virtual void SetValue(String^ value)
00141         {
00142           textBlock->ContentText = value;
00143         }
00144
00145         property String^ Value
00146         {
00147           virtual String^ get() { return textBlock->ContentText; }
00148         }
00149
00150     #pragma endregion IValueProvider_Implementation
00151
00152         IRawElementProviderSimple^ GetRawElementProviderSimple()
00153         {
00154           return ProviderFromPeer(this);
00155         }
00156
00157       private:
00158         TouchableTextBlock^ textBlock;
00159         String^ accClass;
00160       };
00161
00162     }
00163
00164 TouchableTextBlockRangeProvider::TouchableTextBlockRangeProvider(String^ text, TouchableTextBlockAutomationPeer^ peer) : _text(text), _peer(peer)
00165 {
00166
00167 }
00168
00169 void TouchableTextBlockRangeProvider::AddToSelection()
00170 {
00171
00172 }
00173
00174 ITextRangeProvider^ TouchableTextBlockRangeProvider::Clone()
00175 {
00176   return ref new TouchableTextBlockRangeProvider(_text, _peer);
00177 }
00178
00179 bool TouchableTextBlockRangeProvider::Compare(ITextRangeProvider^ other)
00180 {
00181   return true;
00182 }
00183
00184 int TouchableTextBlockRangeProvider::CompareEndpoints(TextPatternRangeEndpoint endpoint, ITextRangeProvider^ targetRange, TextPatternRangeEndpoint targetEndpoint)
00185 {
00186   return 0;
00187 }
00188
00189 void TouchableTextBlockRangeProvider::ExpandToEnclosingUnit(TextUnit unit)
00190 {
00191
00192 }
00193
00194 ITextRangeProvider^ TouchableTextBlockRangeProvider::FindAttribute(int attribute, Object^ value, bool backward)
00195 {
00196   return this;
00197 }
00198
00199 ITextRangeProvider^ TouchableTextBlockRangeProvider::FindText(String^ text, bool backward, bool ignoreCase)
00200 {
00201   return this;
00202 }
00203
00204 Object^ TouchableTextBlockRangeProvider::GetAttributeValue(int attribute)
00205 {
00206   return this;
00207 }
00208
00209 void TouchableTextBlockRangeProvider::GetBoundingRectangles(Array<double>^* rectangles)
00210 {
00211   *rectangles = ref new Array<double>(0);
00212 }
00213
00214 Array<IRawElementProviderSimple^>^ TouchableTextBlockRangeProvider::GetChildren()
00215 {
00216   return ref new Array<IRawElementProviderSimple^>(0);
00217 }
00218
00219 IRawElementProviderSimple^ TouchableTextBlockRangeProvider::GetEnclosingElement()
00220 {
00221   return _peer->GetRawElementProviderSimple();
00222 }
00223
00224 String^ TouchableTextBlockRangeProvider::GetText(int maxLength)
00225 {
00226   auto textLength = _text->End() - _text->Begin();
00227   auto retLength = (maxLength < 0) ? textLength : min(maxLength, textLength);
00228   return ref new String(_text->Data(), retLength);
00229 }
00230
00231 int TouchableTextBlockRangeProvider::Move(TextUnit unit, int count)
00232 {
00233   return 0;
00234 }
00235
00236 void TouchableTextBlockRangeProvider::MoveEndpointByRange(TextPatternRangeEndpoint endpoint, ITextRangeProvider^ targetRange, TextPatternRangeEndpoint targetEndpoint)
00237 {
00238
00239 }
00240
00241 int TouchableTextBlockRangeProvider::MoveEndpointByUnit(TextPatternRangeEndpoint endpoint, TextUnit unit, int count)
00242 {
00243   return 0;
00244 }
00245
00246 void TouchableTextBlockRangeProvider::RemoveFromSelection()
00247 {
00248
00249 }
00250
00251 void TouchableTextBlockRangeProvider::ScrollIntoView(bool alignToTop)
00252 {
00253
00254 }
00255
00256 void TouchableTextBlockRangeProvider::Select()
00257 {
00258
00259 }
00260
00261 // The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
00262
00263 /// <summary>
00264 /// Loads the XAML UI contents and set properties required for this custom control.
00265 /// </summary>
00266 TouchableTextBlock::TouchableTextBlock()
00267 {
00268   InitializeComponent();
00269   this->IsTabStop = true;
00270   this->IsTapEnabled = true;
00271   this->contentText = "";
00272 }
00273
00274 /// <summary>
00275 /// Create the Automation peer implementations for custom control (CustomInputBox2) to provide the accessibility support.
00276 /// </summary>
00277 /// <returns>Automation Peer implementation for this control</returns>
00278 AutomationPeer^ TouchableTextBlock::OnCreateAutomationPeer()
00279 {
00280   return ref new TouchableTextBlockAutomationPeer(this);
00281 }
00282
00283 /// <summary>
00284 /// Override the default event handler for GotFocus.
00285 /// When the control got focus, indicate it has focus by highlighting the control by changing the background color to yellow.
00286 /// </summary>
00287 /// <param name="e">State information and event data associated with GotFocus event.</param>
00288 void TouchableTextBlock::OnGotFocus(RoutedEventArgs^ e)
00289 {
00290   this->myBorder->Background = ref new SolidColorBrush(Windows::UI::Colors::Yellow);
00291 }
00292
00293 /// <summary>
00294 /// Override the default event handler for LostFocus.
00295 /// When the control lost focus, indicate it does not have focus by changing the background color to gray.
00296 /// And the content is cleared.
00297 /// </summary>
00298 /// <param name="e">State information and event data associated with LostFocus event.</param>
00299 void TouchableTextBlock::OnLostFocus(RoutedEventArgs^ e)
00300 {
00301   this->myBorder->Background = ref new SolidColorBrush(Windows::UI::Colors::Gray);
00302   contentText = "";
00303   this->myTextBlock->Text = contentText;
00304 }
00305
00306 /// <summary>
00307 /// Override the default event handler for Tapped.
00308 /// Set input focus to the control when tapped on.
00309 /// </summary>
00310 /// <param name="e">State information and event data associated with Tapped event.</param>
00311 void TouchableTextBlock::OnTapped(TappedRoutedEventArgs^ e)
00312 {
00313   this->Focus(Windows::UI::Xaml::FocusState::Pointer);
00314 }
00315
00316 /// <summary>
00317 /// Override the default event handler for KeyDown.
00318 /// Displays the text "A key is pressed" and the approximate time when the key is pressed.
00319 /// </summary>
00320 /// <param name="e">State information and event data associated with KeyDown event.</param>
00321 void TouchableTextBlock::OnKeyDown(KeyRoutedEventArgs^ e)
00322 {
00323   auto currentCalendar = ref new Windows::Globalization::Calendar();
00324   String^ timeOfDay = currentCalendar->HourAsPaddedString(2) + ":" +
00325     currentCalendar->MinuteAsPaddedString(2) + ":" +
00326     currentCalendar->SecondAsPaddedString(2);
00327   contentText = "A key was pressed @ " + timeOfDay + " ";
00328   this->myTextBlock->Text = contentText;
00329 }
00330 }
Generated on Sat Nov 23 2024 16:08:19 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX postcard app/C++/MainPage.xaml.cpp Source File

  • DirectX postcard app

MainPage.xaml.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 "MainPage.xaml.h"
00010 #include "EffectsFlyout.xaml.h"
00011 #include "PaperFlyout.xaml.h"
00012 #include "TextFlyout.xaml.h"
00013 #include "SignatureFlyout.xaml.h"
00014
00015 using namespace Postcard;
00016
00017 using namespace concurrency;
00018 using namespace Platform;
00019 using namespace Platform::Collections;
00020 using namespace Windows::ApplicationModel;
00021 using namespace Windows::ApplicationModel::Activation;
00022 using namespace Windows::ApplicationModel::Core;
00023 using namespace Windows::ApplicationModel::DataTransfer;
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::Pickers;
00029 using namespace Windows::Storage::Streams;
00030 using namespace Windows::System;
00031 using namespace Windows::UI::Core;
00032 using namespace Windows::UI::Popups;
00033 using namespace Windows::UI::ViewManagement;
00034 using namespace Windows::UI::Xaml;
00035 using namespace Windows::UI::Xaml::Controls;
00036 using namespace Windows::UI::Xaml::Controls::Primitives;
00037 using namespace Windows::UI::Xaml::Data;
00038 using namespace Windows::UI::Xaml::Input;
00039 using namespace Windows::UI::Xaml::Media;
00040 using namespace Microsoft::WRL;
00041
00042 MainPage::MainPage()
00043 {
00044     InitializeComponent();
00045
00046     m_renderer = ref new PostcardRenderer();
00047     m_renderer->Initialize(Window::Current->CoreWindow, this->DXSwapChainPanel, DisplayProperties::LogicalDpi);
00048
00049     m_atStartScreen = true;
00050
00051     DisplayProperties::LogicalDpiChanged +=
00052         ref new DisplayPropertiesEventHandler(this, &MainPage::OnLogicalDpiChanged);
00053
00054     Window::Current->CoreWindow->SizeChanged +=
00055         ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &MainPage::OnWindowSizeChanged);
00056
00057     this->PointerPressed +=
00058         ref new PointerEventHandler(this, &MainPage::OnPointerPressed);
00059     this->PointerReleased +=
00060         ref new PointerEventHandler(this, &MainPage::OnPointerReleased);
00061     this->PointerMoved +=
00062         ref new PointerEventHandler(this, &MainPage::OnPointerMoved);
00063
00064     this->ManipulationMode =
00065         ManipulationModes::TranslateX |
00066         ManipulationModes::TranslateY |
00067         ManipulationModes::Scale;
00068
00069     this->ManipulationStarted +=
00070         ref new ManipulationStartedEventHandler(m_renderer, &PostcardRenderer::OnManipulationStarted);
00071     this->ManipulationCompleted +=
00072         ref new ManipulationCompletedEventHandler(m_renderer, &PostcardRenderer::OnManipulationCompleted);
00073     this->ManipulationDelta +=
00074         ref new ManipulationDeltaEventHandler(m_renderer, &PostcardRenderer::OnManipulationDelta);
00075
00076     this->Tapped +=
00077         ref new TappedEventHandler(m_renderer, &PostcardRenderer::OnTapped);
00078
00079     DataTransferManager::GetForCurrentView()->DataRequested +=
00080         ref new TypedEventHandler<DataTransferManager^, DataRequestedEventArgs^>(m_renderer, &PostcardRenderer::OnDataRequested);
00081
00082     m_renderer->Render();
00083     m_renderer->Present();
00084 }
00085
00086 void MainPage::OnLogicalDpiChanged(Object^ /* sender */)
00087 {
00088     m_renderer->SetDpi(DisplayProperties::LogicalDpi);
00089     m_renderer->Render();
00090     m_renderer->Present();
00091 }
00092
00093 void MainPage::OnWindowSizeChanged(CoreWindow^ /* sender */, WindowSizeChangedEventArgs^ args)
00094 {
00095     if (ApplicationView::Value == ApplicationViewState::Snapped)
00096     {
00097         VisualStateManager::GoToState(this, "SnappedState", true);
00098     }
00099     else
00100     {
00101         if (m_atStartScreen)
00102         {
00103             VisualStateManager::GoToState(this, "StartingState", true);
00104         }
00105         else
00106         {
00107             VisualStateManager::GoToState(this, "ClearState", true);
00108         }
00109     }
00110
00111     m_renderer->UpdateForViewStateChanged(ApplicationView::Value);
00112     m_renderer->UpdateForWindowSizeChange();
00113     m_renderer->Render();
00114     m_renderer->Present();
00115 }
00116
00117 void MainPage::OnPointerPressed(Object^ sender, PointerRoutedEventArgs^ args)
00118 {
00119     if (m_atStartScreen && ApplicationView::Value != ApplicationViewState::Snapped)
00120     {
00121         AddImage();
00122     }
00123     else
00124     {
00125         m_renderer->OnPointerPressed(sender, args);
00126     }
00127 }
00128
00129 void MainPage::OnPointerReleased(Object^ sender, PointerRoutedEventArgs^ args)
00130 {
00131     m_renderer->OnPointerReleased(sender, args);
00132 }
00133
00134 void MainPage::OnPointerMoved(Object^ sender, PointerRoutedEventArgs^ args)
00135 {
00136     m_renderer->OnPointerMoved(sender, args);
00137 }
00138
00139 void MainPage::AddImage()
00140 {
00141     FileOpenPicker^ picker = ref new FileOpenPicker();
00142     picker->SuggestedStartLocation = PickerLocationId::PicturesLibrary;
00143     picker->ViewMode = PickerViewMode::Thumbnail;
00144     picker->FileTypeFilter->Append(".png");
00145     picker->FileTypeFilter->Append(".jpg");
00146     picker->FileTypeFilter->Append(".bmp");
00147
00148     create_task(picker->PickSingleFileAsync()).then([=](StorageFile^ file)
00149     {
00150         if (file == nullptr)
00151         {
00152             cancel_current_task();
00153         }
00154         return file->OpenAsync(FileAccessMode::Read);
00155     }).then([=](IRandomAccessStream^ randomAccessStream)
00156     {
00157         m_renderer->SetSampleMode(SampleMode::AddImage);
00158         m_renderer->LoadImage(randomAccessStream);
00159         VisualStateManager::GoToState(this, "ClearState", true);
00160         m_atStartScreen = false;
00161     });
00162 }
00163
00164 void MainPage::AddEffectsClicked(Object^ sender, RoutedEventArgs^ e)
00165 {
00166     GeneralTransform^ t = AddEffectsButtonBorder->TransformToVisual(this);
00167     auto point = t->TransformPoint(Point(0, 0));
00168
00169     EffectsPopup->VerticalOffset = point.Y - EffectsFlyout->Height - 10;
00170     EffectsPopup->HorizontalOffset = point.X;
00171     EffectsPopup->IsOpen = true;
00172
00173     m_renderer->SetSampleMode(SampleMode::AddEffect);
00174 }
00175
00176 void MainPage::EffectIntensitySliderChanged(RangeBaseValueChangedEventArgs^ e)
00177 {
00178     // Check for the renderer's existence, since this event can be fired before
00179     // m_renderer is initialized.
00180     if (m_renderer != nullptr)
00181     {
00182         m_renderer->SetEffectIntensity(static_cast<float>(e->NewValue));
00183     }
00184 }
00185
00186 void MainPage::AddConstructionPaperClicked(Object^ sender, RoutedEventArgs^ e)
00187 {
00188     GeneralTransform^ t = AddConstructionPaperButtonBorder->TransformToVisual(this);
00189     auto point = t->TransformPoint(Point(0, 0));
00190
00191     PaperPopup->VerticalOffset = point.Y - PaperFlyout->Height - 10;
00192     PaperPopup->HorizontalOffset = point.X;
00193     PaperPopup->IsOpen = true;
00194
00195     m_renderer->SetSampleMode(SampleMode::AddConstructionPaper);
00196 }
00197
00198 void MainPage::PaperFlyoutAddPaperClicked()
00199 {
00200     m_renderer->SetSampleMode(SampleMode::AddConstructionPaper);
00201     m_renderer->AddPaper();
00202 }
00203
00204 void MainPage::PaperFlyoutDeletePaperClicked()
00205 {
00206     m_renderer->SetSampleMode(SampleMode::AddConstructionPaper);
00207     m_renderer->RemovePaper();
00208 }
00209
00210 void MainPage::PaperFlyoutMoveClicked()
00211 {
00212     m_renderer->SetSampleMode(SampleMode::AddConstructionPaper);
00213     m_renderer->MovePaper();
00214 }
00215
00216 void MainPage::PaperFlyoutStampClicked()
00217 {
00218     m_renderer->SetSampleMode(SampleMode::AddConstructionPaper);
00219     m_renderer->StampPaper();
00220 }
00221
00222 void MainPage::AddTextClicked(Object^ sender, RoutedEventArgs^ e)
00223 {
00224     GeneralTransform^ t = AddTextButton->TransformToVisual(this);
00225     auto point = t->TransformPoint(Point(0, 0));
00226
00227     TextPopup->VerticalOffset = point.Y - TextFlyout->Height - 10;
00228     TextPopup->HorizontalOffset = point.X;
00229     TextPopup->IsOpen = true;
00230
00231     TextFlyout->Focus(::FocusState::Programmatic);
00232
00233     m_renderer->SetSampleMode(SampleMode::AddText);
00234 }
00235
00236 void MainPage::TextSubmitted(String^ text)
00237 {
00238     m_renderer->SetExtrudedText(text);
00239 }
00240
00241 void MainPage::AddSignatureClicked(Object^ sender, RoutedEventArgs^ e)
00242 {
00243     GeneralTransform^ t = AddSignatureButtonBorder->TransformToVisual(this);
00244     auto point = t->TransformPoint(Point(0, 0));
00245
00246     SignaturePopup->VerticalOffset = point.Y - SignatureFlyout->Height - 10;
00247     SignaturePopup->HorizontalOffset = point.X;
00248     SignaturePopup->IsOpen = true;
00249 }
00250
00251 void MainPage::SignClicked()
00252 {
00253     m_renderer->SetSampleMode(SampleMode::AddSignature);
00254     m_renderer->StartSignature();
00255 }
00256
00257 void MainPage::EraseClicked()
00258 {
00259     m_renderer->ResetSignature();
00260 }
00261
00262 void MainPage::SaveClicked(Object^ sender, RoutedEventArgs^ e)
00263 {
00264     FileSavePicker^ savePicker = ref new FileSavePicker();
00265     auto pngExtensions = ref new Vector<String^>();
00266     pngExtensions->Append(".png");
00267     savePicker->FileTypeChoices->Insert("PNG file", pngExtensions);
00268     auto jpgExtensions = ref new Vector<String^>();
00269     jpgExtensions->Append(".jpg");
00270     savePicker->FileTypeChoices->Insert("JPEG file", jpgExtensions);
00271     auto bmpExtensions = ref new Vector<String^>();
00272     bmpExtensions->Append(".bmp");
00273     savePicker->FileTypeChoices->Insert("BMP file", bmpExtensions);
00274     savePicker->DefaultFileExtension = ".png";
00275     savePicker->SuggestedFileName = "MyPostcard";
00276     savePicker->SuggestedStartLocation = Pickers::PickerLocationId::PicturesLibrary;
00277
00278     std::shared_ptr<GUID> wicFormat = std::make_shared<GUID>(GUID_ContainerFormatPng);
00279
00280     create_task(savePicker->PickSaveFileAsync()).then([=](StorageFile^ file)
00281     {
00282         if (file == nullptr)
00283         {
00284             cancel_current_task();
00285         }
00286
00287         // Select the appropriate format based on the user-selected file extension.
00288         if (file->FileType == ".bmp")
00289         {
00290             *wicFormat = GUID_ContainerFormatBmp;
00291         }
00292         else if (file->FileType == ".jpg")
00293         {
00294             *wicFormat = GUID_ContainerFormatJpeg;
00295         }
00296         return file->OpenAsync(FileAccessMode::ReadWrite);
00297     }).then([=](Streams::IRandomAccessStream^ randomAccessStream)
00298     {
00299         m_renderer->SavePostcard(randomAccessStream, *wicFormat);
00300     });
00301 }
00302
00303 void MainPage::ShareClicked(Object^ sender, RoutedEventArgs^ e)
00304 {
00305     DataTransferManager::ShowShareUI();
00306 }
00307
00308 void MainPage::ResetClicked(Object^ sender, RoutedEventArgs^ e)
00309 {
00310     VisualStateManager::GoToState(this, "StartingState", true);
00311
00312     m_renderer->SetSampleMode(SampleMode::Ready);
00313     m_renderer->ResetPostcard();
00314     m_atStartScreen = true;
00315 }
Generated on Sat Nov 23 2024 16:07:42 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Inclinometer sensor/C++/Scenario1.xaml.h Source File

  • Inclinometer sensor

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 SDKSample
00023 {
00024     namespace InclinometerCPP
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 Scenario1 sealed
00031         {
00032         public:
00033             Scenario1();
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             MainPage^ rootPage;
00041             Windows::Devices::Sensors::Inclinometer^ inclinometer;
00042             Windows::Foundation::EventRegistrationToken visibilityToken;
00043             Windows::Foundation::EventRegistrationToken readingToken;
00044             uint32 desiredReportInterval;
00045
00046             void VisibilityChanged(Platform::Object^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ e);
00047             void ReadingChanged(Windows::Devices::Sensors::Inclinometer^ sender, Windows::Devices::Sensors::InclinometerReadingChangedEventArgs^ 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     }
00052 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Association launching/C++/LaunchUriOutput.xaml.h Source File

  • Association launching

LaunchUriOutput.xaml.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 //
00009 // LaunchUriOutput.xaml.h
00010 // Declaration of the LaunchUriOutput class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "LaunchUriOutput.g.h"
00017 #include "MainPage.xaml.h"
00018
00019 namespace AssociationLaunching
00020 {
00021   [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class LaunchUriOutput sealed
00023     {
00024     public:
00025         LaunchUriOutput();
00026
00027     protected:
00028         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030
00031     private:
00032         ~LaunchUriOutput();
00033         MainPage^ rootPage;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:57 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX touch input/C++/MoveLookController.cpp Source File

  • DirectX touch input

MoveLookController.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
00009 #include "pch.h"
00010 #include <DirectXMath.h>
00011
00012 using namespace Windows::UI::Core;
00013 using namespace Windows::UI::Input;
00014 using namespace Windows::System;
00015 using namespace Windows::Foundation;
00016 using namespace Windows::Foundation::Collections;
00017 using namespace Windows::Devices::Input;
00018
00019 #include "MoveLookController.h"
00020
00021 #define ROTATION_GAIN 0.004f    // sensitivity adjustment for look controller
00022 #define MOVEMENT_GAIN 0.07f     // sensitivity adjustment for move controller
00023 #define DEADSPOT (16.0f)        // dead space in move control (virtual joystick) center
00024
00025 // A basic Move/Look Controller class such as in an FPS
00026 // horizontal (x-z-plane) movement on left virtual joystick
00027 //          also supports WASD keyboard input
00028 // steering and orientation via left mouse down or touch drag
00029
00030 // Methods to get input from the UI pointers
00031 void MoveLookController::OnPointerPressed(
00032     _In_ CoreWindow^ sender,
00033     _In_ PointerEventArgs^ args
00034     )
00035 {
00036     // get the current pointer position
00037     uint32 pointerID = args->CurrentPoint->PointerId;
00038     float2 position = float2(args->CurrentPoint->Position.X, args->CurrentPoint->Position.Y);
00039
00040     auto device = args->CurrentPoint->PointerDevice;
00041     auto deviceType = device->PointerDeviceType;
00042     if (deviceType == PointerDeviceType::Mouse)
00043     {
00044         if (args->CurrentPoint->Properties->IsLeftButtonPressed && !m_mouseLookInUse)
00045         {
00046             // Left mouse button has been pressed, so enable mouse look mode.
00047             m_mouseLookInUse = true;
00048             m_mouseLookPointerID = pointerID;
00049
00050             // Turn mouse cursor off (hidden).  This locks the cursor position.
00051             // In this mode the cursor will never leave the Window allowing the look controller
00052             // to rotate continuously around.
00053             CoreWindow::GetForCurrentThread()->PointerCursor = nullptr;
00054         }
00055         return;
00056     }
00057
00058     if (position.x < MoveLookControllerConstants::MoveMaxXCoordinate &&
00059         position.y > MoveLookControllerConstants::MoveMinYCoordinate)
00060     {
00061         // Pointer is in the move control area.
00062         if (!m_moveInUse)   // if no pointer is in this control yet
00063         {
00064             // process a DPad touch down event
00065             m_moveFirstDown = position;                 // save location of initial contact
00066             m_movePointerPosition = position;
00067             m_movePointerID = pointerID;                // store the id of pointer using this control
00068             m_moveInUse = TRUE;
00069         }
00070     }
00071     else
00072     {
00073         // this pointer must be in the look control
00074         if (!m_lookInUse)   // if no pointer is in this control yet
00075         {
00076             m_lookLastPoint = position;                         // save point for later move
00077             m_lookPointerID = pointerID;                        // store the id of pointer using this control
00078             m_lookLastDelta.x = m_lookLastDelta.y = 0;          // these are for smoothing
00079             m_lookInUse = TRUE;
00080         }
00081     }
00082 }
00083
00084 void MoveLookController::OnPointerMoved(
00085     _In_ CoreWindow^ sender,
00086     _In_ PointerEventArgs^ args
00087     )
00088 {
00089     PointerPoint^ point = args->CurrentPoint;
00090     PointerDevice^ pointerDevice = point->PointerDevice;
00091     PointerDeviceType pointerDeviceType = pointerDevice->PointerDeviceType;
00092     if (pointerDeviceType == PointerDeviceType::Mouse)
00093     {
00094         return;         // mouse moves are handled by OnMouseMoved, not by generic pointer events
00095     }
00096
00097     float2 position = float2(point->Position.X, point->Position.Y);
00098
00099     // decide which control this pointer is operating
00100     uint32 pointerID = point->PointerId;
00101     if (pointerID == m_movePointerID)           // this is the move pointer
00102     {
00103         // Move control
00104         m_movePointerPosition = position;       // save current position
00105
00106     }
00107     else if (pointerID == m_lookPointerID)      // this is the look pointer
00108     {
00109         // Look control
00110
00111         float2 pointerDelta;
00112         pointerDelta = position - m_lookLastPoint;      // how far did pointer move
00113
00114         float2 rotationDelta;
00115         rotationDelta = pointerDelta * ROTATION_GAIN;   // scale for control sensitivity
00116         m_lookLastPoint = position;                     // save for next time through
00117
00118         // update our orientation based on the command
00119         m_pitch -= rotationDelta.y;                     // mouse y increases down, but pitch increases up
00120         m_yaw   -= rotationDelta.x;                     // yaw defined as CCW around y-axis
00121
00122         // limit pitch to straight up or straight down
00123         float limit = PI_F / 2.0f - 0.01f;
00124         m_pitch = __max(-limit, m_pitch);
00125         m_pitch = __min(+limit, m_pitch);
00126
00127         // keep longitude in sane range by wrapping
00128         if (m_yaw >  PI_F)
00129         {
00130             m_yaw -= PI_F * 2.0f;
00131         }
00132         else if (m_yaw < -PI_F)
00133         {
00134             m_yaw += PI_F * 2.0f;
00135         }
00136     }
00137 }
00138
00139 void MoveLookController::OnPointerReleased(
00140     _In_ CoreWindow^ sender,
00141     _In_ PointerEventArgs^ args
00142     )
00143 {
00144     uint32 pointerID = args->CurrentPoint->PointerId;
00145     float2 position = float2(args->CurrentPoint->Position.X, args->CurrentPoint->Position.Y);
00146
00147     if (pointerID == m_movePointerID)       // this was the move pointer
00148     {
00149         m_moveInUse = FALSE;
00150         m_movePointerID = 0;
00151     }
00152     else if (pointerID == m_lookPointerID)  // this was the look pointer
00153     {
00154         m_lookInUse = FALSE;
00155         m_lookPointerID = 0;
00156     }
00157     else if (pointerID == m_mouseLookPointerID)
00158     {
00159         if (!args->CurrentPoint->Properties->IsLeftButtonPressed)
00160         {
00161             // Left mouse button has been released, so leave mouse look mode.
00162             m_mouseLookInUse = false;
00163             m_mouseLookPointerID = 0;
00164
00165             // Turn mouse cursor on.  This unlocks the cursor position.
00166             CoreWindow::GetForCurrentThread()->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
00167         }
00168     }
00169 }
00170
00171 // Handle Mouse Input via dedicated relative movement handler
00172 void MoveLookController::OnMouseMoved(
00173     _In_ MouseDevice^ mouseDevice,
00174     _In_ MouseEventArgs^ args
00175     )
00176 {
00177     if (!m_mouseLookInUse)
00178     {
00179         // Ignore mouse movement events when not in mouse look mode.
00180         return;
00181     }
00182
00183     float2 pointerDelta;
00184     pointerDelta.x = static_cast<float>(args->MouseDelta.X);
00185     pointerDelta.y = static_cast<float>(args->MouseDelta.Y);
00186
00187     float2 rotationDelta;
00188     rotationDelta = pointerDelta * ROTATION_GAIN;       // scale for control sensitivity
00189
00190     // update our orientation based on the command
00191     m_pitch -= rotationDelta.y;                         // mouse y increases down, but pitch increases up
00192     m_yaw   -= rotationDelta.x;                         // yaw defined as CCW around y-axis
00193
00194     // limit pitch to straight up or straight down
00195     float limit = PI_F / 2.0f - 0.01f;
00196     m_pitch = __max(-limit, m_pitch);
00197     m_pitch = __min(+limit, m_pitch);
00198
00199     // keep longitude in sane range by wrapping
00200     if (m_yaw >  PI_F)
00201     {
00202         m_yaw -= PI_F * 2.0f;
00203     }
00204     else if (m_yaw < -PI_F)
00205     {
00206         m_yaw += PI_F * 2.0f;
00207     }
00208 }
00209
00210 // set up the Controls supported by this controller
00211 void MoveLookController::Initialize(_In_ CoreWindow^ window)
00212 {
00213     // opt in to recieve touch/mouse events
00214     window->PointerPressed +=
00215         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &MoveLookController::OnPointerPressed);
00216
00217     window->PointerMoved +=
00218         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &MoveLookController::OnPointerMoved);
00219
00220     window->PointerReleased +=
00221         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &MoveLookController::OnPointerReleased);
00222
00223     // for mouse-only use
00224     // register handler for relative mouse movement events
00225     Windows::Devices::Input::MouseDevice::GetForCurrentView()->MouseMoved +=
00226         ref new TypedEventHandler<MouseDevice^, MouseEventArgs^>(this, &MoveLookController::OnMouseMoved);
00227
00228     // Initialize state of the controller
00229     m_moveInUse = FALSE;                // no pointer is in the Move control
00230     m_movePointerID = 0;
00231
00232     m_lookInUse = FALSE;                // no pointer is in the Look control
00233     m_lookPointerID = 0;
00234
00235     // Need to init this as it is reset every frame
00236     m_moveCommand = float3(0.0f, 0.0f, 0.0f);
00237
00238     SetOrientation(0, 0);               // look straight ahead when starting
00239 }
00240
00241 // accessor to set position of controller
00242 void MoveLookController::SetPosition(_In_ float3 pos)
00243 {
00244     m_position = pos;
00245 }
00246
00247 // accessor to set position of controller
00248 void MoveLookController::SetOrientation(_In_ float pitch, _In_ float yaw)
00249 {
00250     m_pitch = pitch;
00251     m_yaw = yaw;
00252 }
00253
00254 // returns the position of the controller object
00255 float3 MoveLookController::GetPosition()
00256 {
00257     return m_position;
00258 }
00259
00260 // returns the point at which the camera controller is facing
00261 float3 MoveLookController::GetLookPoint()
00262 {
00263     float y = sinf(m_pitch);        // vertical
00264     float r = cosf(m_pitch);        // in the plane
00265     float z = r*cosf(m_yaw);        // fwd-back
00266     float x = r*sinf(m_yaw);        // left-right
00267
00268     return m_position + float3(x, y, z);
00269 }
00270
00271
00272 void MoveLookController::Update(CoreWindow^ window)
00273 {
00274     // check for input from the Move control
00275     if (m_moveInUse)
00276     {
00277         float2 pointerDelta = m_movePointerPosition - m_moveFirstDown;
00278
00279         // figure out the command from the touch-based virtual joystick
00280         if (pointerDelta.x > DEADSPOT)          // leave 32 pixel-wide dead spot for being still
00281         {
00282             m_moveCommand.x =  1.0f;
00283         }
00284         else if (pointerDelta.x < -DEADSPOT)
00285         {
00286             m_moveCommand.x = -1.0f;
00287         }
00288
00289         if (pointerDelta.y > DEADSPOT)          // joystick y is up so change sign
00290         {
00291             m_moveCommand.y = -1.0f;
00292         }
00293         else if (pointerDelta.y < -DEADSPOT)
00294         {
00295             m_moveCommand.y =  1.0f;
00296         }
00297     }
00298
00299     // poll our state set by the keyboard input events
00300     Windows::UI::Core::CoreVirtualKeyStates KeyState;
00301
00302     // Arrow keys
00303     KeyState = window->GetAsyncKeyState(VirtualKey::Up);
00304     if (bool(KeyState & CoreVirtualKeyStates::Down))
00305     {
00306         m_moveCommand.y += 1.0f;
00307     }
00308
00309     KeyState = window->GetAsyncKeyState(VirtualKey::Down);
00310     if (bool(KeyState & CoreVirtualKeyStates::Down))
00311     {
00312         m_moveCommand.y -= 1.0f;
00313     }
00314
00315     KeyState = window->GetAsyncKeyState(VirtualKey::Left);
00316     if (bool(KeyState & CoreVirtualKeyStates::Down))
00317     {
00318         m_moveCommand.x -= 1.0f;
00319     }
00320
00321     KeyState = window->GetAsyncKeyState(VirtualKey::Right);
00322     if (bool(KeyState & CoreVirtualKeyStates::Down))
00323     {
00324         m_moveCommand.x += 1.0f;
00325     }
00326
00327     KeyState = window->GetAsyncKeyState(VirtualKey::PageUp);
00328     if (bool(KeyState & CoreVirtualKeyStates::Down))
00329     {
00330         m_moveCommand.z += 1.0f;
00331     }
00332
00333     KeyState = window->GetAsyncKeyState(VirtualKey::PageDown);
00334     if (bool(KeyState == CoreVirtualKeyStates::Down))
00335     {
00336         m_moveCommand.z -= 1.0f;
00337     }
00338
00339 // WASD controls
00340     KeyState = window->GetAsyncKeyState(VirtualKey::W);
00341     if (bool(KeyState & CoreVirtualKeyStates::Down))
00342     {
00343         m_moveCommand.y += 1.0f;
00344     }
00345
00346     KeyState = window->GetAsyncKeyState(VirtualKey::A);
00347     if (bool(KeyState & CoreVirtualKeyStates::Down))
00348     {
00349         m_moveCommand.x -= 1.0f;
00350     }
00351
00352     KeyState = window->GetAsyncKeyState(VirtualKey::S);
00353     if (bool(KeyState & CoreVirtualKeyStates::Down))
00354     {
00355         m_moveCommand.y -= 1.0f;
00356     }
00357
00358     KeyState = window->GetAsyncKeyState(VirtualKey::D);
00359     if (bool(KeyState & CoreVirtualKeyStates::Down))
00360     {
00361         m_moveCommand.x += 1.0f;
00362     }
00363
00364     KeyState = window->GetAsyncKeyState(VirtualKey::Space);
00365     if (bool(KeyState & CoreVirtualKeyStates::Down))
00366     {
00367         m_moveCommand.z += 1.0f;
00368     }
00369
00370     KeyState = window->GetAsyncKeyState(VirtualKey::X);
00371     if (bool(KeyState == CoreVirtualKeyStates::Down))
00372     {
00373         m_moveCommand.z -= 1.0f;
00374     }
00375
00376
00377     // make sure that 45degree cases are not faster
00378     float3 command = m_moveCommand;
00379     if (fabsf(command.x) > DEADSPOT || fabsf(command.y) > DEADSPOT || fabsf(command.z) > DEADSPOT)
00380     {
00381         command = normalize(command);
00382     }
00383
00384     // rotate command to align with our direction (world coordinates)
00385     float3 wCommand;
00386     wCommand.x = command.x*cosf(m_yaw) - command.y*sinf(m_yaw);
00387     wCommand.y = command.x*sinf(m_yaw) + command.y*cosf(m_yaw);
00388     wCommand.z = command.z;
00389
00390     // scale for sensitivity adjustment
00391     wCommand = wCommand*MOVEMENT_GAIN;
00392
00393     // our velocity is based on the command, y is up
00394     float3 velocity;
00395     velocity.x = -wCommand.x;
00396     velocity.z =  wCommand.y;
00397     velocity.y =  wCommand.z;
00398
00399     // integrate
00400     m_position = m_position + velocity;
00401
00402     // clear movement input accumulator for use during next frame
00403     m_moveCommand = float3(0.0f, 0.0f, 0.0f);
00404 }
00405
00406 void MoveLookController::SaveInternalValue(
00407     _In_ IPropertySet^ state,
00408     _In_ Platform::String^ key,
00409     _In_ Platform::Object^ value
00410     )
00411 {
00412     if (state->HasKey(key))
00413     {
00414         state->Remove(key);
00415     }
00416     state->Insert(key, value);
00417 }
00418
00419 void MoveLookController::SaveInternalState(_In_ IPropertySet^ state)
00420 {
00421     SaveInternalValue(state, "m_position.x", PropertyValue::CreateSingle(m_position.x));
00422     SaveInternalValue(state, "m_position.y", PropertyValue::CreateSingle(m_position.y));
00423     SaveInternalValue(state, "m_position.z", PropertyValue::CreateSingle(m_position.z));
00424     SaveInternalValue(state, "m_pitch", PropertyValue::CreateSingle(m_pitch));
00425     SaveInternalValue(state, "m_yaw", PropertyValue::CreateSingle(m_yaw));
00426 }
00427
00428 void MoveLookController::LoadInternalState(_In_ IPropertySet^ state)
00429 {
00430     if (state->HasKey("m_position.x") &&
00431         state->HasKey("m_position.y") &&
00432         state->HasKey("m_position.z") &&
00433         state->HasKey("m_pitch") &&
00434         state->HasKey("m_yaw"))
00435     {
00436         m_position.x = safe_cast<IPropertyValue^>(state->Lookup("m_position.x"))->GetSingle();
00437         m_position.y = safe_cast<IPropertyValue^>(state->Lookup("m_position.y"))->GetSingle();
00438         m_position.z = safe_cast<IPropertyValue^>(state->Lookup("m_position.z"))->GetSingle();
00439         m_pitch = safe_cast<IPropertyValue^>(state->Lookup("m_pitch"))->GetSingle();
00440         m_yaw = safe_cast<IPropertyValue^>(state->Lookup("m_yaw"))->GetSingle();
00441     }
00442 }
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Raw notifications/C++/MainAppSample/pch.h Source File

  • Raw notifications
  • MainAppSample

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 //
00009 // pch.h
00010 // Header for standard system include files.
00011 //
00012
00013 #pragma once
00014 #include <ppltasks.h>
00015 #include "CppSamplesUtils.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/DebugLoggingExceptionPolicy.h Source File

  • Hilo C++
  • Hilo

DebugLoggingExceptionPolicy.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 "ExceptionPolicy.h"
00009
00010 namespace Hilo
00011 {
00012     class DebugLoggingExceptionPolicy: public ExceptionPolicy
00013     {
00014     public:
00015         virtual void HandleException(Platform::Exception^ exception);
00016     };
00017 }
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::BadgeContent::BadgeNumericNotificationContent Member List

This is the complete list of members for NotificationsExtensions::BadgeContent::BadgeNumericNotificationContent, including all inherited members.
BadgeNumericNotificationContent() | NotificationsExtensions::BadgeContent::BadgeNumericNotificationContent | [inline]
BadgeNumericNotificationContent(uint number) | NotificationsExtensions::BadgeContent::BadgeNumericNotificationContent | [inline]
BadgeNumericNotificationContent() | NotificationsExtensions::BadgeContent::BadgeNumericNotificationContent | [inline]
BadgeNumericNotificationContent(uint number) | NotificationsExtensions::BadgeContent::BadgeNumericNotificationContent | [inline]
CreateNotification() | NotificationsExtensions::BadgeContent::BadgeNumericNotificationContent | [inline]
CreateNotification() | NotificationsExtensions::BadgeContent::BadgeNumericNotificationContent | [inline]
GetContent() | NotificationsExtensions::BadgeContent::BadgeNumericNotificationContent | [inline]
GetContent() | NotificationsExtensions::BadgeContent::BadgeNumericNotificationContent | [inline]
GetXml() | NotificationsExtensions::BadgeContent::BadgeNumericNotificationContent | [inline]
GetXml() | NotificationsExtensions::BadgeContent::BadgeNumericNotificationContent | [inline]
m_Number | NotificationsExtensions::BadgeContent::BadgeNumericNotificationContent | [private]
Number | NotificationsExtensions::BadgeContent::BadgeNumericNotificationContent |
ToString() | NotificationsExtensions::BadgeContent::BadgeNumericNotificationContent | [inline]
ToString() | NotificationsExtensions::BadgeContent::BadgeNumericNotificationContent | [inline]
Generated on Sat Nov 23 2024 16:09:41 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media capture using capture device/C#,C++/BasicCapture.xaml.cs Source File

  • Media capture using capture device
  • C#,C++

BasicCapture.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.Media.MediaProperties;
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Media.Imaging;
00015 using Windows.UI.Xaml.Navigation;
00016 using SDKTemplate;
00017 using System;
00018 using Windows.Media.Capture;
00019
00020 namespace MediaCapture
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 BasicCapture : SDKTemplate.Common.LayoutAwarePage
00026     {
00027         private Windows.Media.Capture.MediaCapture m_mediaCaptureMgr;
00028         private Windows.Storage.StorageFile m_photoStorageFile;
00029         private Windows.Storage.StorageFile m_recordStorageFile;
00030         private bool m_bRecording;
00031         private bool m_bSuspended;
00032         private bool m_bPreviewing;
00033         private EventHandler<Object> m_soundLevelHandler;
00034
00035         private readonly String PHOTO_FILE_NAME = "photo.jpg";
00036         private readonly String VIDEO_FILE_NAME = "video.mp4";
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         MainPage rootPage = MainPage.Current;
00041
00042         public BasicCapture()
00043         {
00044             this.InitializeComponent();
00045             ScenarioInit();
00046             m_soundLevelHandler = new EventHandler<Object>(MediaControl_SoundLevelChanged);
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             Windows.Media.MediaControl.SoundLevelChanged += m_soundLevelHandler;
00057         }
00058
00059         protected override void OnNavigatedFrom(NavigationEventArgs e)
00060         {
00061             Windows.Media.MediaControl.SoundLevelChanged -= m_soundLevelHandler;
00062         }
00063
00064         private void ScenarioInit()
00065         {
00066             btnStartDevice1.IsEnabled = true;
00067             btnStartPreview1.IsEnabled = false;
00068             btnStartStopRecord1.IsEnabled = false;
00069             m_bRecording = false;
00070             m_bPreviewing = false;
00071             btnStartStopRecord1.Content = "StartRecord";
00072             btnTakePhoto1.IsEnabled = false;
00073             previewElement1.Source = null;
00074             playbackElement1.Source = null;
00075             imageElement1.Source = null;
00076             sldBrightness.IsEnabled = false;
00077             sldContrast.IsEnabled = false;
00078             m_bSuspended = false;
00079             previewCanvas1.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
00080
00081             ShowStatusMessage("");
00082
00083         }
00084
00085         private async void MediaControl_SoundLevelChanged(object sender, Object e)
00086         {
00087             await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
00088             {
00089                 try
00090                 {
00091                     if (Windows.Media.MediaControl.SoundLevel != Windows.Media.SoundLevel.Muted)
00092                     {
00093                         ScenarioReset();
00094                     }
00095                     else
00096                     {
00097                         if (m_bRecording)
00098                         {
00099                             ShowStatusMessage("Stopping Record on invisibility");
00100
00101                             await m_mediaCaptureMgr.StopRecordAsync();
00102                             m_bRecording = false;
00103                             EnableButton(true, "StartStopRecord");
00104                         }
00105                         if (m_bPreviewing)
00106                         {
00107                             ShowStatusMessage("Stopping Preview on invisibility");
00108
00109                             await m_mediaCaptureMgr.StopPreviewAsync();
00110                             m_bPreviewing = false;
00111                             EnableButton(true, "StartPreview");
00112                             previewElement1.Source = null;
00113                         }
00114                     }
00115                 }
00116                 catch (Exception ex)
00117                 {
00118                     ShowExceptionMessage(ex);
00119                 }
00120             });
00121         }
00122
00123         public async void RecordLimitationExceeded(Windows.Media.Capture.MediaCapture currentCaptureObject)
00124         {
00125             try
00126             {
00127                 if (m_bRecording)
00128                 {
00129                     await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
00130                     {
00131                         try
00132                         {
00133                             ShowStatusMessage("Stopping Record on exceeding max record duration");
00134                             await m_mediaCaptureMgr.StopRecordAsync();
00135                             m_bRecording = false;
00136                             SwitchRecordButtonContent();
00137                             EnableButton(true, "StartStopRecord");
00138                             ShowStatusMessage("Stopped record on exceeding max record duration:" + m_recordStorageFile.Path);
00139                         }
00140                         catch (Exception e)
00141                         {
00142                             ShowExceptionMessage(e);
00143                         }
00144                     });
00145                 }
00146             }
00147             catch (Exception e)
00148             {
00149                 ShowExceptionMessage(e);
00150                 m_bRecording = false;
00151                 SwitchRecordButtonContent();
00152                 EnableButton(true, "StartStopRecord");
00153             }
00154         }
00155
00156         public async void Failed(Windows.Media.Capture.MediaCapture currentCaptureObject, MediaCaptureFailedEventArgs currentFailure)
00157         {
00158             try
00159             {
00160                 await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00161                 {
00162                     ShowStatusMessage("Fatal error" + currentFailure.Message);
00163                 });
00164             }
00165             catch (Exception e)
00166             {
00167                 ShowExceptionMessage(e);
00168             }
00169         }
00170
00171         private void ScenarioReset()
00172         {
00173             previewCanvas1.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
00174             ScenarioInit();
00175         }
00176
00177
00178
00179         internal async void btnStartDevice_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e)
00180         {
00181             try
00182             {
00183                 EnableButton(false, "StartDevice");
00184                 ShowStatusMessage("Starting device");
00185                 m_mediaCaptureMgr = new Windows.Media.Capture.MediaCapture();
00186                 await m_mediaCaptureMgr.InitializeAsync();
00187
00188                 EnableButton(true, "StartPreview");
00189                 EnableButton(true, "StartStopRecord");
00190                 EnableButton(true, "TakePhoto");
00191                 ShowStatusMessage("Device initialized successful");
00192
00193                 m_mediaCaptureMgr.RecordLimitationExceeded += new Windows.Media.Capture.RecordLimitationExceededEventHandler(RecordLimitationExceeded); ;
00194                 m_mediaCaptureMgr.Failed += new Windows.Media.Capture.MediaCaptureFailedEventHandler(Failed); ;
00195
00196             }
00197             catch (Exception exception)
00198             {
00199                 ShowExceptionMessage(exception);
00200             }
00201         }
00202
00203         internal async void btnStartPreview_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e)
00204         {
00205             m_bPreviewing = false;
00206             try
00207             {
00208                 ShowStatusMessage("Starting preview");
00209                 EnableButton(false, "StartPreview");
00210
00211                 previewCanvas1.Visibility = Windows.UI.Xaml.Visibility.Visible;
00212                 previewElement1.Source = m_mediaCaptureMgr;
00213                 await m_mediaCaptureMgr.StartPreviewAsync();
00214                 if ((m_mediaCaptureMgr.VideoDeviceController.Brightness != null) && m_mediaCaptureMgr.VideoDeviceController.Brightness.Capabilities.Supported)
00215                 {
00216                     SetupVideoDeviceControl(m_mediaCaptureMgr.VideoDeviceController.Brightness, sldBrightness);
00217                 }
00218                 if ((m_mediaCaptureMgr.VideoDeviceController.Contrast != null) && m_mediaCaptureMgr.VideoDeviceController.Contrast.Capabilities.Supported)
00219                 {
00220                     SetupVideoDeviceControl(m_mediaCaptureMgr.VideoDeviceController.Contrast, sldContrast);
00221                 }
00222                 m_bPreviewing = true;
00223                 ShowStatusMessage("Start preview successful");
00224
00225             }
00226             catch (Exception exception)
00227             {
00228                 m_bPreviewing = false;
00229                 previewElement1.Source = null;
00230                 EnableButton(true, "StartPreview");
00231                 ShowExceptionMessage(exception);
00232             }
00233         }
00234
00235         internal async void btnTakePhoto_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e)
00236         {
00237             try
00238             {
00239                 ShowStatusMessage("Taking photo");
00240                 EnableButton(false, "TakePhoto");
00241
00242                 m_photoStorageFile = await Windows.Storage.KnownFolders.PicturesLibrary.CreateFileAsync(PHOTO_FILE_NAME, Windows.Storage.CreationCollisionOption.GenerateUniqueName);
00243
00244                 ShowStatusMessage("Create photo file successful");
00245                 ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg();
00246
00247                 await m_mediaCaptureMgr.CapturePhotoToStorageFileAsync(imageProperties, m_photoStorageFile);
00248
00249                 EnableButton(true, "TakePhoto");
00250                 ShowStatusMessage("Photo taken");
00251
00252                 var photoStream = await m_photoStorageFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
00253
00254                 ShowStatusMessage("File open successful");
00255                 var bmpimg = new BitmapImage();
00256
00257                 bmpimg.SetSource(photoStream);
00258                 imageElement1.Source = bmpimg;
00259                 ShowStatusMessage(this.m_photoStorageFile.Path);
00260
00261
00262
00263
00264
00265             }
00266             catch (Exception exception)
00267             {
00268                 ShowExceptionMessage(exception);
00269                 EnableButton(true, "TakePhoto");
00270             }
00271         }
00272
00273         internal async void btnStartStopRecord_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e)
00274         {
00275             try
00276             {
00277                 String fileName;
00278                 EnableButton(false, "StartStopRecord");
00279
00280                 if (!m_bRecording)
00281                 {
00282                     ShowStatusMessage("Starting Record");
00283
00284                     fileName = VIDEO_FILE_NAME;
00285
00286                     m_recordStorageFile = await Windows.Storage.KnownFolders.VideosLibrary.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.GenerateUniqueName);
00287
00288                     ShowStatusMessage("Create record file successful");
00289
00290                     MediaEncodingProfile recordProfile = null;
00291                     recordProfile = MediaEncodingProfile.CreateMp4(Windows.Media.MediaProperties.VideoEncodingQuality.Auto);
00292
00293                     await m_mediaCaptureMgr.StartRecordToStorageFileAsync(recordProfile, m_recordStorageFile);
00294                     m_bRecording = true;
00295                     SwitchRecordButtonContent();
00296                     EnableButton(true, "StartStopRecord");
00297
00298                     ShowStatusMessage("Start Record successful");
00299
00300
00301
00302                 }
00303                 else
00304                 {
00305                     ShowStatusMessage("Stopping Record");
00306
00307                     await m_mediaCaptureMgr.StopRecordAsync();
00308
00309                     m_bRecording = false;
00310                     EnableButton(true, "StartStopRecord");
00311                     SwitchRecordButtonContent();
00312
00313                     ShowStatusMessage("Stop record successful");
00314                     if (!m_bSuspended)
00315                     {
00316                         var stream = await m_recordStorageFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
00317
00318                         ShowStatusMessage("Record file opened");
00319                         ShowStatusMessage(this.m_recordStorageFile.Path);
00320                         playbackElement1.AutoPlay = true;
00321                         playbackElement1.SetSource(stream, this.m_recordStorageFile.FileType);
00322                         playbackElement1.Play();
00323
00324
00325                     }
00326
00327                 }
00328             }
00329             catch (Exception ex)
00330             {
00331                 ShowExceptionMessage(ex);
00332                 m_bRecording = false;
00333                 SwitchRecordButtonContent();
00334                 EnableButton(true, "StartStopRecord");
00335             }
00336
00337         }
00338
00339         private void SetupVideoDeviceControl(Windows.Media.Devices.MediaDeviceControl videoDeviceControl, Slider slider)
00340         {
00341             try
00342             {
00343                 if ((videoDeviceControl.Capabilities).Supported)
00344                 {
00345                     slider.IsEnabled = true;
00346                     slider.Maximum = videoDeviceControl.Capabilities.Max;
00347                     slider.Minimum = videoDeviceControl.Capabilities.Min;
00348                     slider.StepFrequency = videoDeviceControl.Capabilities.Step;
00349                     double controlValue = 0;
00350                     if (videoDeviceControl.TryGetValue(out controlValue))
00351                     {
00352                         slider.Value = controlValue;
00353                     }
00354                 }
00355                 else
00356                 {
00357                     slider.IsEnabled = false;
00358                 }
00359             }
00360             catch (Exception e)
00361             {
00362                 ShowExceptionMessage(e);
00363             }
00364         }
00365
00366         // VideoDeviceControllers
00367         internal void sldBrightness_ValueChanged(Object sender, Windows.UI.Xaml.Controls.Primitives.RangeBaseValueChangedEventArgs e)
00368         {
00369             try
00370             {
00371                 bool succeeded = m_mediaCaptureMgr.VideoDeviceController.Brightness.TrySetValue(sldBrightness.Value);
00372                 if (!succeeded)
00373                 {
00374                     ShowStatusMessage("Set Brightness failed");
00375                 }
00376             }
00377             catch (Exception exception)
00378             {
00379                 ShowExceptionMessage(exception);
00380             }
00381         }
00382
00383         internal void sldContrast_ValueChanged(Object sender, Windows.UI.Xaml.Controls.Primitives.RangeBaseValueChangedEventArgs e)
00384         {
00385             try
00386             {
00387                 bool succeeded = m_mediaCaptureMgr.VideoDeviceController.Contrast.TrySetValue(sldContrast.Value);
00388                 if (!succeeded)
00389                 {
00390                     ShowStatusMessage("Set Contrast failed");
00391                 }
00392             }
00393             catch (Exception exception)
00394             {
00395                 ShowExceptionMessage(exception);
00396             }
00397         }
00398
00399         private void ShowStatusMessage(String text)
00400         {
00401             rootPage.NotifyUser(text, NotifyType.StatusMessage);
00402         }
00403
00404         private void ShowExceptionMessage(Exception ex)
00405         {
00406             rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
00407         }
00408
00409         private void SwitchRecordButtonContent()
00410         {
00411             {
00412                 if (m_bRecording)
00413                 {
00414                     btnStartStopRecord1.Content = "StopRecord";
00415                 }
00416                 else
00417                 {
00418                     btnStartStopRecord1.Content = "StartRecord";
00419                 }
00420             }
00421         }
00422
00423         private void EnableButton(bool enabled, String name)
00424         {
00425             if (name.Equals("StartDevice"))
00426             {
00427                 btnStartDevice1.IsEnabled = enabled;
00428             }
00429             else if (name.Equals("StartPreview"))
00430             {
00431                 btnStartPreview1.IsEnabled = enabled;
00432             }
00433             else if (name.Equals("StartStopRecord"))
00434             {
00435                 btnStartStopRecord1.IsEnabled = enabled;
00436             }
00437             else if (name.Equals("TakePhoto"))
00438             {
00439                 btnTakePhoto1.IsEnabled = enabled;
00440             }
00441         }
00442     }
00443 }
Generated on Sat Nov 23 2024 16:08:19 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Check if current session is remote/C++/MainPage.xaml.h Source File

  • Check if current session is remote

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D stereoscopic 3D/C++/DDSTextureLoader.cpp Source File

  • Direct3D stereoscopic 3D

DDSTextureLoader.cpp

Go to the documentation of this file.
00001 //--------------------------------------------------------------------------------------
00002 // File: DDSTextureLoader.cpp
00003 //
00004 // Function for loading a DDS texture and creating a Direct3D 11 runtime resource for it
00005 //
00006 // Note this function is 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
00018 #include "pch.h"
00019 #include <dxgiformat.h>
00020 #include <assert.h>
00021 #include <memory>
00022 #include <algorithm>
00023 #include "DDSTextureLoader.h"
00024 #include "DirectXSample.h"
00025
00026 using namespace Microsoft::WRL;
00027
00028 //--------------------------------------------------------------------------------------
00029 // Macros
00030 //--------------------------------------------------------------------------------------
00031 #ifndef MAKEFOURCC
00032     #define MAKEFOURCC(ch0, ch1, ch2, ch3)                              \
00033                 ((uint32)(byte)(ch0) | ((uint32)(byte)(ch1) << 8) |       \
00034                 ((uint32)(byte)(ch2) << 16) | ((uint32)(byte)(ch3) << 24))
00035 #endif /* defined(MAKEFOURCC) */
00036
00037 //--------------------------------------------------------------------------------------
00038 // DDS file structure definitions
00039 //
00040 // See DDS.h in the 'Texconv' sample and the 'DirectXTex' library
00041 //--------------------------------------------------------------------------------------
00042 #pragma pack(push, 1)
00043
00044 #define DDS_MAGIC 0x20534444 // "DDS "
00045
00046 struct DDS_PIXELFORMAT
00047 {
00048     uint32  size;
00049     uint32  flags;
00050     uint32  fourCC;
00051     uint32  RGBBitCount;
00052     uint32  RBitMask;
00053     uint32  GBitMask;
00054     uint32  BBitMask;
00055     uint32  ABitMask;
00056 };
00057
00058 #define DDS_FOURCC      0x00000004  // DDPF_FOURCC
00059 #define DDS_RGB         0x00000040  // DDPF_RGB
00060 #define DDS_RGBA        0x00000041  // DDPF_RGB | DDPF_ALPHAPIXELS
00061 #define DDS_LUMINANCE   0x00020000  // DDPF_LUMINANCE
00062 #define DDS_LUMINANCEA  0x00020001  // DDPF_LUMINANCE | DDPF_ALPHAPIXELS
00063 #define DDS_ALPHA       0x00000002  // DDPF_ALPHA
00064 #define DDS_PAL8        0x00000020  // DDPF_PALETTEINDEXED8
00065
00066 #define DDS_HEADER_FLAGS_TEXTURE        0x00001007  // DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT
00067 #define DDS_HEADER_FLAGS_MIPMAP         0x00020000  // DDSD_MIPMAPCOUNT
00068 #define DDS_HEADER_FLAGS_VOLUME         0x00800000  // DDSD_DEPTH
00069 #define DDS_HEADER_FLAGS_PITCH          0x00000008  // DDSD_PITCH
00070 #define DDS_HEADER_FLAGS_LINEARSIZE     0x00080000  // DDSD_LINEARSIZE
00071
00072 #define DDS_HEIGHT 0x00000002 // DDSD_HEIGHT
00073 #define DDS_WIDTH  0x00000004 // DDSD_WIDTH
00074
00075 #define DDS_SURFACE_FLAGS_TEXTURE 0x00001000 // DDSCAPS_TEXTURE
00076 #define DDS_SURFACE_FLAGS_MIPMAP  0x00400008 // DDSCAPS_COMPLEX | DDSCAPS_MIPMAP
00077 #define DDS_SURFACE_FLAGS_CUBEMAP 0x00000008 // DDSCAPS_COMPLEX
00078
00079 #define DDS_CUBEMAP_POSITIVEX 0x00000600 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEX
00080 #define DDS_CUBEMAP_NEGATIVEX 0x00000a00 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEX
00081 #define DDS_CUBEMAP_POSITIVEY 0x00001200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEY
00082 #define DDS_CUBEMAP_NEGATIVEY 0x00002200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEY
00083 #define DDS_CUBEMAP_POSITIVEZ 0x00004200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEZ
00084 #define DDS_CUBEMAP_NEGATIVEZ 0x00008200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEZ
00085
00086 #define DDS_CUBEMAP_ALLFACES (DDS_CUBEMAP_POSITIVEX | DDS_CUBEMAP_NEGATIVEX |\
00087                               DDS_CUBEMAP_POSITIVEY | DDS_CUBEMAP_NEGATIVEY |\
00088                               DDS_CUBEMAP_POSITIVEZ | DDS_CUBEMAP_NEGATIVEZ)
00089
00090 #define DDS_CUBEMAP 0x00000200 // DDSCAPS2_CUBEMAP
00091
00092 #define DDS_FLAGS_VOLUME 0x00200000 // DDSCAPS2_VOLUME
00093
00094 typedef struct
00095 {
00096     uint32          size;
00097     uint32          flags;
00098     uint32          height;
00099     uint32          width;
00100     uint32          pitchOrLinearSize;
00101     uint32          depth; // only if DDS_HEADER_FLAGS_VOLUME is set in flags
00102     uint32          mipMapCount;
00103     uint32          reserved1[11];
00104     DDS_PIXELFORMAT ddspf;
00105     uint32          caps;
00106     uint32          caps2;
00107     uint32          caps3;
00108     uint32          caps4;
00109     uint32          reserved2;
00110 } DDS_HEADER;
00111
00112 typedef struct
00113 {
00114     DXGI_FORMAT dxgiFormat;
00115     uint32      resourceDimension;
00116     uint32      miscFlag; // see D3D11_RESOURCE_MISC_FLAG
00117     uint32      arraySize;
00118     uint32      reserved;
00119 } DDS_HEADER_DXT10;
00120
00121 #pragma pack(pop)
00122
00123 //--------------------------------------------------------------------------------------
00124 // Return the BPP for a particular format
00125 //--------------------------------------------------------------------------------------
00126 static size_t BitsPerPixel(_In_ DXGI_FORMAT fmt)
00127 {
00128     switch (fmt)
00129     {
00130     case DXGI_FORMAT_R32G32B32A32_TYPELESS:
00131     case DXGI_FORMAT_R32G32B32A32_FLOAT:
00132     case DXGI_FORMAT_R32G32B32A32_UINT:
00133     case DXGI_FORMAT_R32G32B32A32_SINT:
00134         return 128;
00135
00136     case DXGI_FORMAT_R32G32B32_TYPELESS:
00137     case DXGI_FORMAT_R32G32B32_FLOAT:
00138     case DXGI_FORMAT_R32G32B32_UINT:
00139     case DXGI_FORMAT_R32G32B32_SINT:
00140         return 96;
00141
00142     case DXGI_FORMAT_R16G16B16A16_TYPELESS:
00143     case DXGI_FORMAT_R16G16B16A16_FLOAT:
00144     case DXGI_FORMAT_R16G16B16A16_UNORM:
00145     case DXGI_FORMAT_R16G16B16A16_UINT:
00146     case DXGI_FORMAT_R16G16B16A16_SNORM:
00147     case DXGI_FORMAT_R16G16B16A16_SINT:
00148     case DXGI_FORMAT_R32G32_TYPELESS:
00149     case DXGI_FORMAT_R32G32_FLOAT:
00150     case DXGI_FORMAT_R32G32_UINT:
00151     case DXGI_FORMAT_R32G32_SINT:
00152     case DXGI_FORMAT_R32G8X24_TYPELESS:
00153     case DXGI_FORMAT_D32_FLOAT_S8X24_UINT:
00154     case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS:
00155     case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT:
00156         return 64;
00157
00158     case DXGI_FORMAT_R10G10B10A2_TYPELESS:
00159     case DXGI_FORMAT_R10G10B10A2_UNORM:
00160     case DXGI_FORMAT_R10G10B10A2_UINT:
00161     case DXGI_FORMAT_R11G11B10_FLOAT:
00162     case DXGI_FORMAT_R8G8B8A8_TYPELESS:
00163     case DXGI_FORMAT_R8G8B8A8_UNORM:
00164     case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
00165     case DXGI_FORMAT_R8G8B8A8_UINT:
00166     case DXGI_FORMAT_R8G8B8A8_SNORM:
00167     case DXGI_FORMAT_R8G8B8A8_SINT:
00168     case DXGI_FORMAT_R16G16_TYPELESS:
00169     case DXGI_FORMAT_R16G16_FLOAT:
00170     case DXGI_FORMAT_R16G16_UNORM:
00171     case DXGI_FORMAT_R16G16_UINT:
00172     case DXGI_FORMAT_R16G16_SNORM:
00173     case DXGI_FORMAT_R16G16_SINT:
00174     case DXGI_FORMAT_R32_TYPELESS:
00175     case DXGI_FORMAT_D32_FLOAT:
00176     case DXGI_FORMAT_R32_FLOAT:
00177     case DXGI_FORMAT_R32_UINT:
00178     case DXGI_FORMAT_R32_SINT:
00179     case DXGI_FORMAT_R24G8_TYPELESS:
00180     case DXGI_FORMAT_D24_UNORM_S8_UINT:
00181     case DXGI_FORMAT_R24_UNORM_X8_TYPELESS:
00182     case DXGI_FORMAT_X24_TYPELESS_G8_UINT:
00183     case DXGI_FORMAT_R9G9B9E5_SHAREDEXP:
00184     case DXGI_FORMAT_R8G8_B8G8_UNORM:
00185     case DXGI_FORMAT_G8R8_G8B8_UNORM:
00186     case DXGI_FORMAT_B8G8R8A8_UNORM:
00187     case DXGI_FORMAT_B8G8R8X8_UNORM:
00188     case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM:
00189     case DXGI_FORMAT_B8G8R8A8_TYPELESS:
00190     case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
00191     case DXGI_FORMAT_B8G8R8X8_TYPELESS:
00192     case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB:
00193         return 32;
00194
00195     case DXGI_FORMAT_R8G8_TYPELESS:
00196     case DXGI_FORMAT_R8G8_UNORM:
00197     case DXGI_FORMAT_R8G8_UINT:
00198     case DXGI_FORMAT_R8G8_SNORM:
00199     case DXGI_FORMAT_R8G8_SINT:
00200     case DXGI_FORMAT_R16_TYPELESS:
00201     case DXGI_FORMAT_R16_FLOAT:
00202     case DXGI_FORMAT_D16_UNORM:
00203     case DXGI_FORMAT_R16_UNORM:
00204     case DXGI_FORMAT_R16_UINT:
00205     case DXGI_FORMAT_R16_SNORM:
00206     case DXGI_FORMAT_R16_SINT:
00207     case DXGI_FORMAT_B5G6R5_UNORM:
00208     case DXGI_FORMAT_B5G5R5A1_UNORM:
00209     case DXGI_FORMAT_B4G4R4A4_UNORM:
00210         return 16;
00211
00212     case DXGI_FORMAT_R8_TYPELESS:
00213     case DXGI_FORMAT_R8_UNORM:
00214     case DXGI_FORMAT_R8_UINT:
00215     case DXGI_FORMAT_R8_SNORM:
00216     case DXGI_FORMAT_R8_SINT:
00217     case DXGI_FORMAT_A8_UNORM:
00218         return 8;
00219
00220     case DXGI_FORMAT_R1_UNORM:
00221         return 1;
00222
00223     case DXGI_FORMAT_BC1_TYPELESS:
00224     case DXGI_FORMAT_BC1_UNORM:
00225     case DXGI_FORMAT_BC1_UNORM_SRGB:
00226     case DXGI_FORMAT_BC4_TYPELESS:
00227     case DXGI_FORMAT_BC4_UNORM:
00228     case DXGI_FORMAT_BC4_SNORM:
00229         return 4;
00230
00231     case DXGI_FORMAT_BC2_TYPELESS:
00232     case DXGI_FORMAT_BC2_UNORM:
00233     case DXGI_FORMAT_BC2_UNORM_SRGB:
00234     case DXGI_FORMAT_BC3_TYPELESS:
00235     case DXGI_FORMAT_BC3_UNORM:
00236     case DXGI_FORMAT_BC3_UNORM_SRGB:
00237     case DXGI_FORMAT_BC5_TYPELESS:
00238     case DXGI_FORMAT_BC5_UNORM:
00239     case DXGI_FORMAT_BC5_SNORM:
00240     case DXGI_FORMAT_BC6H_TYPELESS:
00241     case DXGI_FORMAT_BC6H_UF16:
00242     case DXGI_FORMAT_BC6H_SF16:
00243     case DXGI_FORMAT_BC7_TYPELESS:
00244     case DXGI_FORMAT_BC7_UNORM:
00245     case DXGI_FORMAT_BC7_UNORM_SRGB:
00246         return 8;
00247
00248     default:
00249         return 0;
00250     }
00251 }
00252
00253
00254 //--------------------------------------------------------------------------------------
00255 // Get surface information for a particular format
00256 //--------------------------------------------------------------------------------------
00257 static void GetSurfaceInfo(
00258     _In_ size_t width,
00259     _In_ size_t height,
00260     _In_ DXGI_FORMAT fmt,
00261     _Out_opt_ size_t* outNumBytes,
00262     _Out_opt_ size_t* outRowBytes,
00263     _Out_opt_ size_t* outNumRows
00264     )
00265 {
00266     size_t numBytes = 0;
00267     size_t rowBytes = 0;
00268     size_t numRows = 0;
00269
00270     bool bc = false;
00271     bool packed  = false;
00272     size_t bcnumBytesPerBlock = 0;
00273     switch (fmt)
00274     {
00275     case DXGI_FORMAT_BC1_TYPELESS:
00276     case DXGI_FORMAT_BC1_UNORM:
00277     case DXGI_FORMAT_BC1_UNORM_SRGB:
00278     case DXGI_FORMAT_BC4_TYPELESS:
00279     case DXGI_FORMAT_BC4_UNORM:
00280     case DXGI_FORMAT_BC4_SNORM:
00281         bc = true;
00282         bcnumBytesPerBlock = 8;
00283         break;
00284
00285     case DXGI_FORMAT_BC2_TYPELESS:
00286     case DXGI_FORMAT_BC2_UNORM:
00287     case DXGI_FORMAT_BC2_UNORM_SRGB:
00288     case DXGI_FORMAT_BC3_TYPELESS:
00289     case DXGI_FORMAT_BC3_UNORM:
00290     case DXGI_FORMAT_BC3_UNORM_SRGB:
00291     case DXGI_FORMAT_BC5_TYPELESS:
00292     case DXGI_FORMAT_BC5_UNORM:
00293     case DXGI_FORMAT_BC5_SNORM:
00294     case DXGI_FORMAT_BC6H_TYPELESS:
00295     case DXGI_FORMAT_BC6H_UF16:
00296     case DXGI_FORMAT_BC6H_SF16:
00297     case DXGI_FORMAT_BC7_TYPELESS:
00298     case DXGI_FORMAT_BC7_UNORM:
00299     case DXGI_FORMAT_BC7_UNORM_SRGB:
00300         bc = true;
00301         bcnumBytesPerBlock = 16;
00302         break;
00303
00304     case DXGI_FORMAT_R8G8_B8G8_UNORM:
00305     case DXGI_FORMAT_G8R8_G8B8_UNORM:
00306         packed = true;
00307         break;
00308     }
00309
00310     if (bc)
00311     {
00312         size_t numBlocksWide = 0;
00313         if (width > 0)
00314         {
00315             numBlocksWide = std::max<size_t>(1, (width + 3) / 4);
00316         }
00317         size_t numBlocksHigh = 0;
00318         if (height > 0)
00319         {
00320             numBlocksHigh = std::max<size_t>(1, (height + 3) / 4);
00321         }
00322         rowBytes = numBlocksWide * bcnumBytesPerBlock;
00323         numRows = numBlocksHigh;
00324     }
00325     else if (packed)
00326     {
00327         rowBytes = ((width + 1) >> 1) * 4;
00328         numRows = height;
00329     }
00330     else
00331     {
00332         size_t bpp = BitsPerPixel(fmt);
00333         rowBytes = (width * bpp + 7) / 8; // round up to nearest byte
00334         numRows = height;
00335     }
00336
00337     numBytes = rowBytes * numRows;
00338     if (outNumBytes)
00339     {
00340         *outNumBytes = numBytes;
00341     }
00342     if (outRowBytes)
00343     {
00344         *outRowBytes = rowBytes;
00345     }
00346     if (outNumRows)
00347     {
00348         *outNumRows = numRows;
00349     }
00350 }
00351
00352
00353 //--------------------------------------------------------------------------------------
00354 #define ISBITMASK(r, g, b, a) (ddpf.RBitMask == r && ddpf.GBitMask == g && ddpf.BBitMask == b && ddpf.ABitMask == a)
00355
00356 static DXGI_FORMAT GetDXGIFormat(const DDS_PIXELFORMAT& ddpf)
00357 {
00358     if (ddpf.flags & DDS_RGB)
00359     {
00360         // Note that sRGB formats are written using the "DX10" extended header
00361
00362         switch (ddpf.RGBBitCount)
00363         {
00364         case 32:
00365             if (ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000))
00366             {
00367                 return DXGI_FORMAT_R8G8B8A8_UNORM;
00368             }
00369
00370             if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000))
00371             {
00372                 return DXGI_FORMAT_B8G8R8A8_UNORM;
00373             }
00374
00375             if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0x00000000))
00376             {
00377                 return DXGI_FORMAT_B8G8R8X8_UNORM;
00378             }
00379
00380             // No DXGI format maps to ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0x00000000) aka D3DFMT_X8B8G8R8
00381
00382             // Note that many common DDS reader/writers (including D3DX) swap the
00383             // the RED/BLUE masks for 10:10:10:2 formats. We assumme
00384             // below that the 'backwards' header mask is being used since it is most
00385             // likely written by D3DX. The more robust solution is to use the 'DX10'
00386             // header extension and specify the DXGI_FORMAT_R10G10B10A2_UNORM format directly
00387
00388             // For 'correct' writers, this should be 0x000003ff, 0x000ffc00, 0x3ff00000 for RGB data
00389             if (ISBITMASK(0x3ff00000, 0x000ffc00, 0x000003ff, 0xc0000000))
00390             {
00391                 return DXGI_FORMAT_R10G10B10A2_UNORM;
00392             }
00393
00394             // No DXGI format maps to ISBITMASK(0x000003ff, 0x000ffc00, 0x3ff00000, 0xc0000000) aka D3DFMT_A2R10G10B10
00395
00396             if (ISBITMASK(0x0000ffff, 0xffff0000, 0x00000000, 0x00000000))
00397             {
00398                 return DXGI_FORMAT_R16G16_UNORM;
00399             }
00400
00401             if (ISBITMASK(0xffffffff, 0x00000000, 0x00000000, 0x00000000))
00402             {
00403                 // Only 32-bit color channel format in D3D9 was R32F
00404                 return DXGI_FORMAT_R32_FLOAT; // D3DX writes this out as a FourCC of 114
00405             }
00406             break;
00407
00408         case 24:
00409             // No 24bpp DXGI formats aka D3DFMT_R8G8B8
00410             break;
00411
00412         case 16:
00413             if (ISBITMASK(0x7c00, 0x03e0, 0x001f, 0x8000))
00414             {
00415                 return DXGI_FORMAT_B5G5R5A1_UNORM;
00416             }
00417             if (ISBITMASK(0xf800, 0x07e0, 0x001f, 0x0000))
00418             {
00419                 return DXGI_FORMAT_B5G6R5_UNORM;
00420             }
00421
00422             // No DXGI format maps to ISBITMASK(0x7c00, 0x03e0, 0x001f, 0x0000) aka D3DFMT_X1R5G5B5
00423             if (ISBITMASK(0x0f00, 0x00f0, 0x000f, 0xf000))
00424             {
00425                 return DXGI_FORMAT_B4G4R4A4_UNORM;
00426             }
00427
00428             // No DXGI format maps to ISBITMASK(0x0f00, 0x00f0, 0x000f, 0x0000) aka D3DFMT_X4R4G4B4
00429
00430             // No 3:3:2, 3:3:2:8, or paletted DXGI formats aka D3DFMT_A8R3G3B2, D3DFMT_R3G3B2, D3DFMT_P8, D3DFMT_A8P8, etc.
00431             break;
00432         }
00433     }
00434     else if (ddpf.flags & DDS_LUMINANCE)
00435     {
00436         if (8 == ddpf.RGBBitCount)
00437         {
00438             if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x00000000))
00439             {
00440                 return DXGI_FORMAT_R8_UNORM; // D3DX10/11 writes this out as DX10 extension
00441             }
00442
00443             // No DXGI format maps to ISBITMASK(0x0f, 0x00, 0x00, 0xf0) aka D3DFMT_A4L4
00444         }
00445
00446         if (16 == ddpf.RGBBitCount)
00447         {
00448             if (ISBITMASK(0x0000ffff, 0x00000000, 0x00000000, 0x00000000))
00449             {
00450                 return DXGI_FORMAT_R16_UNORM; // D3DX10/11 writes this out as DX10 extension
00451             }
00452             if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x0000ff00))
00453             {
00454                 return DXGI_FORMAT_R8G8_UNORM; // D3DX10/11 writes this out as DX10 extension
00455             }
00456         }
00457     }
00458     else if (ddpf.flags & DDS_ALPHA)
00459     {
00460         if (8 == ddpf.RGBBitCount)
00461         {
00462             return DXGI_FORMAT_A8_UNORM;
00463         }
00464     }
00465     else if (ddpf.flags & DDS_FOURCC)
00466     {
00467         if (MAKEFOURCC('D', 'X', 'T', '1') == ddpf.fourCC)
00468         {
00469             return DXGI_FORMAT_BC1_UNORM;
00470         }
00471         if (MAKEFOURCC('D', 'X', 'T', '3') == ddpf.fourCC)
00472         {
00473             return DXGI_FORMAT_BC2_UNORM;
00474         }
00475         if (MAKEFOURCC('D', 'X', 'T', '5') == ddpf.fourCC)
00476         {
00477             return DXGI_FORMAT_BC3_UNORM;
00478         }
00479
00480         // While pre-mulitplied alpha isn't directly supported by the DXGI formats,
00481         // they are basically the same as these BC formats so they can be mapped
00482         if (MAKEFOURCC('D', 'X', 'T', '2') == ddpf.fourCC)
00483         {
00484             return DXGI_FORMAT_BC2_UNORM;
00485         }
00486         if (MAKEFOURCC('D', 'X', 'T', '4') == ddpf.fourCC)
00487         {
00488             return DXGI_FORMAT_BC3_UNORM;
00489         }
00490
00491         if (MAKEFOURCC('A', 'T', 'I', '1') == ddpf.fourCC)
00492         {
00493             return DXGI_FORMAT_BC4_UNORM;
00494         }
00495         if (MAKEFOURCC('B', 'C', '4', 'U') == ddpf.fourCC)
00496         {
00497             return DXGI_FORMAT_BC4_UNORM;
00498         }
00499         if (MAKEFOURCC('B', 'C', '4', 'S') == ddpf.fourCC)
00500         {
00501             return DXGI_FORMAT_BC4_SNORM;
00502         }
00503
00504         if (MAKEFOURCC('A', 'T', 'I', '2') == ddpf.fourCC)
00505         {
00506             return DXGI_FORMAT_BC5_UNORM;
00507         }
00508         if (MAKEFOURCC('B', 'C', '5', 'U') == ddpf.fourCC)
00509         {
00510             return DXGI_FORMAT_BC5_UNORM;
00511         }
00512         if (MAKEFOURCC('B', 'C', '5', 'S') == ddpf.fourCC)
00513         {
00514             return DXGI_FORMAT_BC5_SNORM;
00515         }
00516
00517         // BC6H and BC7 are written using the "DX10" extended header
00518
00519         if (MAKEFOURCC('R', 'G', 'B', 'G') == ddpf.fourCC)
00520         {
00521             return DXGI_FORMAT_R8G8_B8G8_UNORM;
00522         }
00523         if (MAKEFOURCC('G', 'R', 'G', 'B') == ddpf.fourCC)
00524         {
00525             return DXGI_FORMAT_G8R8_G8B8_UNORM;
00526         }
00527
00528         // Check for D3DFORMAT enums being set here
00529         switch (ddpf.fourCC)
00530         {
00531         case 36: // D3DFMT_A16B16G16R16
00532             return DXGI_FORMAT_R16G16B16A16_UNORM;
00533
00534         case 110: // D3DFMT_Q16W16V16U16
00535             return DXGI_FORMAT_R16G16B16A16_SNORM;
00536
00537         case 111: // D3DFMT_R16F
00538             return DXGI_FORMAT_R16_FLOAT;
00539
00540         case 112: // D3DFMT_G16R16F
00541             return DXGI_FORMAT_R16G16_FLOAT;
00542
00543         case 113: // D3DFMT_A16B16G16R16F
00544             return DXGI_FORMAT_R16G16B16A16_FLOAT;
00545
00546         case 114: // D3DFMT_R32F
00547             return DXGI_FORMAT_R32_FLOAT;
00548
00549         case 115: // D3DFMT_G32R32F
00550             return DXGI_FORMAT_R32G32_FLOAT;
00551
00552         case 116: // D3DFMT_A32B32G32R32F
00553             return DXGI_FORMAT_R32G32B32A32_FLOAT;
00554         }
00555     }
00556
00557     return DXGI_FORMAT_UNKNOWN;
00558 }
00559
00560
00561 //--------------------------------------------------------------------------------------
00562 static void FillInitData(
00563     _In_ size_t width,
00564     _In_ size_t height,
00565     _In_ size_t depth,
00566     _In_ size_t mipCount,
00567     _In_ size_t arraySize,
00568     _In_ DXGI_FORMAT format,
00569     _In_ size_t maxsize,
00570     _In_ size_t bitSize,
00571     _In_reads_bytes_(bitSize) const byte* bitData,
00572     _Out_ size_t& twidth,
00573     _Out_ size_t& theight,
00574     _Out_ size_t& tdepth,
00575     _Out_ size_t& skipMip,
00576     _Out_writes_(mipCount*arraySize) D3D11_SUBRESOURCE_DATA* initData
00577     )
00578 {
00579     if (!bitData || !initData)
00580     {
00581         throw ref new Platform::InvalidArgumentException();
00582     }
00583
00584     skipMip = 0;
00585     twidth = 0;
00586     theight = 0;
00587     tdepth = 0;
00588
00589     size_t NumBytes = 0;
00590     size_t RowBytes = 0;
00591     size_t NumRows = 0;
00592     const byte* pSrcBits = bitData;
00593     const byte* pEndBits = bitData + bitSize;
00594
00595     size_t index = 0;
00596     for (size_t j = 0; j < arraySize; j++)
00597     {
00598         size_t w = width;
00599         size_t h = height;
00600         size_t d = depth;
00601         for (size_t i = 0; i < mipCount; i++)
00602         {
00603             GetSurfaceInfo(w, h, format, &NumBytes, &RowBytes, &NumRows);
00604
00605             if ((mipCount <= 1) || !maxsize || (w <= maxsize && h <= maxsize && d <= maxsize))
00606             {
00607                 if (!twidth)
00608                 {
00609                     twidth = w;
00610                     theight = h;
00611                     tdepth = d;
00612                 }
00613
00614                 initData[index].pSysMem = (const void*)pSrcBits;
00615                 initData[index].SysMemPitch = static_cast<UINT>(RowBytes);
00616                 initData[index].SysMemSlicePitch = static_cast<UINT>(NumBytes);
00617                 ++index;
00618             }
00619             else
00620             {
00621                 ++skipMip;
00622             }
00623
00624             if (pSrcBits + (NumBytes*d) > pEndBits)
00625             {
00626                 throw ref new Platform::OutOfBoundsException();
00627             }
00628
00629             pSrcBits += NumBytes * d;
00630
00631             w = w >> 1;
00632             h = h >> 1;
00633             d = d >> 1;
00634             if (w == 0)
00635             {
00636                 w = 1;
00637             }
00638             if (h == 0)
00639             {
00640                 h = 1;
00641             }
00642             if (d == 0)
00643             {
00644                 d = 1;
00645             }
00646         }
00647     }
00648
00649     if (!index)
00650     {
00651         throw ref new Platform::FailureException();
00652     }
00653 }
00654
00655
00656 //--------------------------------------------------------------------------------------
00657 static HRESULT CreateD3DResources(
00658     _In_ ID3D11Device* d3dDevice,
00659     _In_ uint32 resDim,
00660     _In_ size_t width,
00661     _In_ size_t height,
00662     _In_ size_t depth,
00663     _In_ size_t mipCount,
00664     _In_ size_t arraySize,
00665     _In_ DXGI_FORMAT format,
00666     _In_ bool isCubeMap,
00667     _In_reads_(mipCount*arraySize) D3D11_SUBRESOURCE_DATA* initData,
00668     _Out_opt_ ID3D11Resource** texture,
00669     _Out_opt_ ID3D11ShaderResourceView** textureView
00670     )
00671 {
00672     if (!d3dDevice || !initData)
00673     {
00674         return E_INVALIDARG;
00675     }
00676
00677     HRESULT hr = E_FAIL;
00678
00679     switch (resDim)
00680     {
00681         case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
00682             {
00683                 D3D11_TEXTURE1D_DESC desc;
00684                 desc.Width = static_cast<UINT>(width);
00685                 desc.MipLevels = static_cast<UINT>(mipCount);
00686                 desc.ArraySize = static_cast<UINT>(arraySize);
00687                 desc.Format = format;
00688                 desc.Usage = D3D11_USAGE_DEFAULT;
00689                 desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
00690                 desc.CPUAccessFlags = 0;
00691                 desc.MiscFlags = 0;
00692
00693                 ID3D11Texture1D* tex = nullptr;
00694                 hr = d3dDevice->CreateTexture1D(&desc, initData, &tex);
00695
00696                 if (SUCCEEDED(hr) && tex != 0)
00697                 {
00698                     if (textureView != 0)
00699                     {
00700                         D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
00701                         memset(&SRVDesc, 0, sizeof(SRVDesc));
00702                         SRVDesc.Format = format;
00703
00704                         if (arraySize > 1)
00705                         {
00706                             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE1DARRAY;
00707                             SRVDesc.Texture1DArray.MipLevels = desc.MipLevels;
00708                             SRVDesc.Texture1DArray.ArraySize = static_cast<UINT>(arraySize);
00709                         }
00710                         else
00711                         {
00712                             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE1D;
00713                             SRVDesc.Texture1D.MipLevels = desc.MipLevels;
00714                         }
00715
00716                         hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView);
00717
00718                         if (FAILED(hr))
00719                         {
00720                             tex->Release();
00721                             return hr;
00722                         }
00723                     }
00724
00725                     if (texture != 0)
00726                     {
00727                         *texture = tex;
00728                     }
00729                     else
00730                     {
00731                         tex->Release();
00732                     }
00733                 }
00734             }
00735             break;
00736
00737         case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
00738             {
00739                 D3D11_TEXTURE2D_DESC desc;
00740                 desc.Width = static_cast<UINT>(width);
00741                 desc.Height = static_cast<UINT>(height);
00742                 desc.MipLevels = static_cast<UINT>(mipCount);
00743                 desc.ArraySize = static_cast<UINT>(arraySize);
00744                 desc.Format = format;
00745                 desc.SampleDesc.Count = 1;
00746                 desc.SampleDesc.Quality = 0;
00747                 desc.Usage = D3D11_USAGE_DEFAULT;
00748                 desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
00749                 desc.CPUAccessFlags = 0;
00750                 desc.MiscFlags = (isCubeMap) ? D3D11_RESOURCE_MISC_TEXTURECUBE : 0;
00751
00752                 ID3D11Texture2D* tex = nullptr;
00753                 hr = d3dDevice->CreateTexture2D(&desc, initData, &tex);
00754
00755                 if (SUCCEEDED(hr) && tex != 0)
00756                 {
00757                     if (textureView != 0)
00758                     {
00759                         D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
00760                         memset(&SRVDesc, 0, sizeof(SRVDesc));
00761                         SRVDesc.Format = format;
00762
00763                         if (isCubeMap)
00764                         {
00765                             if (arraySize > 6)
00766                             {
00767                                 SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURECUBEARRAY;
00768                                 SRVDesc.TextureCubeArray.MipLevels = desc.MipLevels;
00769
00770                                 // Earlier we set arraySize to (NumCubes * 6)
00771                                 SRVDesc.TextureCubeArray.NumCubes = static_cast<UINT>(arraySize / 6);
00772                             }
00773                             else
00774                             {
00775                                 SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURECUBE;
00776                                 SRVDesc.TextureCube.MipLevels = desc.MipLevels;
00777                             }
00778                         }
00779                         else if (arraySize > 1)
00780                         {
00781                             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE2DARRAY;
00782                             SRVDesc.Texture2DArray.MipLevels = desc.MipLevels;
00783                             SRVDesc.Texture2DArray.ArraySize = static_cast<UINT>(arraySize);
00784                         }
00785                         else
00786                         {
00787                             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE2D;
00788                             SRVDesc.Texture2D.MipLevels = desc.MipLevels;
00789                         }
00790
00791                         hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView);
00792
00793                         if (FAILED(hr))
00794                         {
00795                             tex->Release();
00796                             return hr;
00797                         }
00798                     }
00799
00800                     if (texture != 0)
00801                     {
00802                         *texture = tex;
00803                     }
00804                     else
00805                     {
00806                         tex->Release();
00807                     }
00808                 }
00809             }
00810             break;
00811
00812         case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
00813             {
00814                 D3D11_TEXTURE3D_DESC desc;
00815                 desc.Width = static_cast<UINT>(width);
00816                 desc.Height = static_cast<UINT>(height);
00817                 desc.Depth = static_cast<UINT>(depth);
00818                 desc.MipLevels = static_cast<UINT>(mipCount);
00819                 desc.Format = format;
00820                 desc.Usage = D3D11_USAGE_DEFAULT;
00821                 desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
00822                 desc.CPUAccessFlags = 0;
00823                 desc.MiscFlags = 0;
00824
00825                 ID3D11Texture3D* tex = nullptr;
00826                 hr = d3dDevice->CreateTexture3D(&desc, initData, &tex);
00827
00828                 if (SUCCEEDED(hr) && tex != 0)
00829                 {
00830                     if (textureView != 0)
00831                     {
00832                         D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
00833                         memset(&SRVDesc, 0, sizeof(SRVDesc));
00834                         SRVDesc.Format = format;
00835                         SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE3D;
00836                         SRVDesc.Texture3D.MipLevels = desc.MipLevels;
00837
00838                         hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView);
00839
00840                         if (FAILED(hr))
00841                         {
00842                             tex->Release();
00843                             return hr;
00844                         }
00845                     }
00846
00847                     if (texture != 0)
00848                     {
00849                         *texture = tex;
00850                     }
00851                     else
00852                     {
00853                         tex->Release();
00854                     }
00855                 }
00856             }
00857             break;
00858     }
00859
00860     return hr;
00861 }
00862
00863
00864 //--------------------------------------------------------------------------------------
00865 static void CreateTextureFromDDS(
00866     _In_ ID3D11Device* d3dDevice,
00867     _In_ const DDS_HEADER* header,
00868     _In_reads_bytes_(bitSize) const byte* bitData,
00869     _In_ size_t bitSize,
00870     _Out_opt_ ID3D11Resource** texture,
00871     _Out_opt_ ID3D11ShaderResourceView** textureView,
00872     _In_ size_t maxsize
00873     )
00874 {
00875     HRESULT hr = S_OK;
00876
00877     size_t width = header->width;
00878     size_t height = header->height;
00879     size_t depth = header->depth;
00880
00881     uint32 resDim = D3D11_RESOURCE_DIMENSION_UNKNOWN;
00882     size_t arraySize = 1;
00883     DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;
00884     bool isCubeMap = false;
00885
00886     size_t mipCount = header->mipMapCount;
00887     if (0 == mipCount)
00888     {
00889         mipCount = 1;
00890     }
00891
00892     if ((header->ddspf.flags & DDS_FOURCC) &&
00893         (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC))
00894     {
00895         const DDS_HEADER_DXT10* d3d10ext = reinterpret_cast<const DDS_HEADER_DXT10*>((const char*)header + sizeof(DDS_HEADER));
00896
00897         arraySize = d3d10ext->arraySize;
00898         if (arraySize == 0)
00899         {
00900             throw ref new Platform::FailureException();
00901         }
00902
00903         if (BitsPerPixel(d3d10ext->dxgiFormat) == 0)
00904         {
00905             throw ref new Platform::FailureException();
00906         }
00907
00908         format = d3d10ext->dxgiFormat;
00909
00910         switch (d3d10ext->resourceDimension)
00911         {
00912         case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
00913             // D3DX writes 1D textures with a fixed Height of 1
00914             if ((header->flags & DDS_HEIGHT) && height != 1)
00915             {
00916                 throw ref new Platform::FailureException();
00917             }
00918             height = depth = 1;
00919             break;
00920
00921         case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
00922             if (d3d10ext->miscFlag & D3D11_RESOURCE_MISC_TEXTURECUBE)
00923             {
00924                 arraySize *= 6;
00925                 isCubeMap = true;
00926             }
00927             depth = 1;
00928             break;
00929
00930         case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
00931             if (!(header->flags & DDS_HEADER_FLAGS_VOLUME))
00932             {
00933                 throw ref new Platform::FailureException();
00934             }
00935
00936             if (arraySize > 1)
00937             {
00938                 throw ref new Platform::FailureException();
00939             }
00940             break;
00941
00942         default:
00943             return throw ref new Platform::FailureException();
00944         }
00945
00946         resDim = d3d10ext->resourceDimension;
00947     }
00948     else
00949     {
00950         format = GetDXGIFormat(header->ddspf);
00951
00952         if (format == DXGI_FORMAT_UNKNOWN)
00953         {
00954             return throw ref new Platform::FailureException();
00955         }
00956
00957         if (header->flags & DDS_HEADER_FLAGS_VOLUME)
00958         {
00959             resDim = D3D11_RESOURCE_DIMENSION_TEXTURE3D;
00960         }
00961         else
00962         {
00963             if (header->caps2 & DDS_CUBEMAP)
00964             {
00965                 // We require all six faces to be defined
00966                 if ((header->caps2 & DDS_CUBEMAP_ALLFACES) != DDS_CUBEMAP_ALLFACES)
00967                 {
00968                     return throw ref new Platform::FailureException();
00969                 }
00970
00971                 arraySize = 6;
00972                 isCubeMap = true;
00973             }
00974
00975             depth = 1;
00976             resDim = D3D11_RESOURCE_DIMENSION_TEXTURE2D;
00977
00978             // Note there's no way for a legacy Direct3D 9 DDS to express a '1D' texture
00979         }
00980
00981         assert(BitsPerPixel(format) != 0);
00982     }
00983
00984     // Bound sizes (for security purposes we don't trust DDS file metadata larger than the D3D 11.x hardware requirements)
00985     if (mipCount > D3D11_REQ_MIP_LEVELS)
00986     {
00987         return throw ref new Platform::FailureException();
00988     }
00989
00990     switch (resDim)
00991     {
00992         case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
00993             if ((arraySize > D3D11_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION) ||
00994                 (width > D3D11_REQ_TEXTURE1D_U_DIMENSION))
00995             {
00996                 return throw ref new Platform::FailureException();
00997             }
00998             break;
00999
01000         case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
01001             if (isCubeMap)
01002             {
01003                 // This is the right bound because we set arraySize to (NumCubes*6) above
01004                 if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) ||
01005                     (width > D3D11_REQ_TEXTURECUBE_DIMENSION) ||
01006                     (height > D3D11_REQ_TEXTURECUBE_DIMENSION))
01007                 {
01008                     return throw ref new Platform::FailureException();
01009                 }
01010             }
01011             else if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) ||
01012                     (width > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION) ||
01013                     (height > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION))
01014             {
01015                 return throw ref new Platform::FailureException();
01016             }
01017             break;
01018
01019         case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
01020             if ((arraySize > 1) ||
01021                 (width > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) ||
01022                 (height > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) ||
01023                 (depth > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION))
01024             {
01025                 return throw ref new Platform::FailureException();
01026             }
01027             break;
01028     }
01029
01030     // Create the texture
01031     std::unique_ptr<D3D11_SUBRESOURCE_DATA> initData(new D3D11_SUBRESOURCE_DATA[mipCount * arraySize]);
01032
01033     size_t skipMip = 0;
01034     size_t twidth = 0;
01035     size_t theight = 0;
01036     size_t tdepth = 0;
01037     FillInitData(width, height, depth, mipCount, arraySize, format, maxsize, bitSize, bitData, twidth, theight, tdepth, skipMip, initData.get());
01038
01039     hr = CreateD3DResources(d3dDevice, resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize, format, isCubeMap, initData.get(), texture, textureView);
01040
01041     if (FAILED(hr) && !maxsize && (mipCount > 1))
01042     {
01043         // Retry with a maxsize determined by feature level
01044         switch (d3dDevice->GetFeatureLevel())
01045         {
01046         case D3D_FEATURE_LEVEL_9_1:
01047         case D3D_FEATURE_LEVEL_9_2:
01048             if (isCubeMap)
01049             {
01050                 maxsize = D3D_FL9_1_REQ_TEXTURECUBE_DIMENSION;
01051             }
01052             else
01053             {
01054                 maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D)
01055                     ? D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION
01056                     : D3D_FL9_1_REQ_TEXTURE2D_U_OR_V_DIMENSION;
01057             }
01058             break;
01059
01060         case D3D_FEATURE_LEVEL_9_3:
01061             maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D)
01062                 ? D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION
01063                 : D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION;
01064             break;
01065
01066         default: // D3D_FEATURE_LEVEL_10_0 & D3D_FEATURE_LEVEL_10_1
01067             maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D)
01068                 ? D3D10_REQ_TEXTURE3D_U_V_OR_W_DIMENSION
01069                 : D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION;
01070             break;
01071         }
01072
01073         FillInitData(width, height, depth, mipCount, arraySize, format, maxsize, bitSize, bitData, twidth, theight, tdepth, skipMip, initData.get());
01074
01075         hr = CreateD3DResources(d3dDevice, resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize, format, isCubeMap, initData.get(), texture, textureView);
01076     }
01077
01078     DX::ThrowIfFailed(hr);
01079 }
01080
01081 //--------------------------------------------------------------------------------------
01082 void CreateDDSTextureFromMemory(
01083     _In_ ID3D11Device* d3dDevice,
01084     _In_reads_bytes_(ddsDataSize) const byte* ddsData,
01085     _In_ size_t ddsDataSize,
01086     _Out_opt_ ID3D11Resource** texture,
01087     _Out_opt_ ID3D11ShaderResourceView** textureView,
01088     _In_ size_t maxsize
01089     )
01090 {
01091     if (!d3dDevice || !ddsData || (!texture && !textureView))
01092     {
01093         throw ref new Platform::InvalidArgumentException();
01094     }
01095
01096     // Validate DDS file in memory
01097     if (ddsDataSize < (sizeof(uint32) + sizeof(DDS_HEADER)))
01098     {
01099         throw ref new Platform::FailureException();
01100     }
01101
01102     uint32 dwMagicNumber = *(const uint32*)(ddsData);
01103     if (dwMagicNumber != DDS_MAGIC)
01104     {
01105         throw ref new Platform::FailureException();
01106     }
01107
01108     const DDS_HEADER* header = reinterpret_cast<const DDS_HEADER*>(ddsData + sizeof(uint32));
01109
01110     // Verify header to validate DDS file
01111     if (header->size != sizeof(DDS_HEADER) ||
01112         header->ddspf.size != sizeof(DDS_PIXELFORMAT))
01113     {
01114         throw ref new Platform::FailureException();
01115     }
01116
01117     // Check for DX10 extension
01118     bool bDXT10Header = false;
01119     if ((header->ddspf.flags & DDS_FOURCC) &&
01120         (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC))
01121     {
01122         // Must be long enough for both headers and magic value
01123         if (ddsDataSize < (sizeof(DDS_HEADER) + sizeof(uint32) + sizeof(DDS_HEADER_DXT10)))
01124         {
01125             throw ref new Platform::FailureException();
01126         }
01127
01128         bDXT10Header = true;
01129     }
01130
01131     ptrdiff_t offset = sizeof(uint32) + sizeof(DDS_HEADER) + (bDXT10Header ? sizeof(DDS_HEADER_DXT10) : 0);
01132
01133     CreateTextureFromDDS(d3dDevice, header, ddsData + offset, ddsDataSize - offset, texture, textureView, maxsize);
01134 }
Generated on Sat Nov 23 2024 16:08:10 for Win8-Examples by doxygen 1.7.1


Win8-Examples: App settings/C++/common/LayoutAwarePage.h Source File

  • App settings
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

TGA_FOOTER Member List

This is the complete list of members for TGA_FOOTER, including all inherited members.
dwDeveloperOffset | TGA_FOOTER
dwExtensionOffset | TGA_FOOTER
Signature | TGA_FOOTER
Generated on Sat Nov 23 2024 16:09:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows account authorization/C++/common/suspensionmanager.h Source File

  • Windows account authorization
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

CInvertModule Member List

This is the complete list of members for CInvertModule, including all inherited members.
Initialize(ID3D11Device *pDevice, UINT uiWidth, UINT uiHeight) | CInvertModule | [virtual]
Initialize(ID3D11Device *pDevice, UINT uiWidth, UINT uiHeight) | CInvertModule | [virtual]
Invalidate() | CInvertModule | [virtual]
Invalidate() | CInvertModule | [virtual]
m_pPixelShader | CInvertModule | [private]
m_pSampleStateLinear | CInvertModule | [private]
m_pScreenQuadVB | CInvertModule | [private]
m_pVertexShader | CInvertModule | [private]
m_spQuadLayout | CInvertModule | [private]
m_uiHeight | CInvertModule | [private]
m_uiWidth | CInvertModule | [private]
ProcessFrame(ID3D11Device *pDevice, ID3D11Texture2D *pInput, UINT uiInIndex, ID3D11Texture2D *pOutput, UINT uiOutIndex) | CInvertModule | [virtual]
ProcessFrame(ID3D11Device *pDevice, ID3D11Texture2D *pInput, UINT uiInIndex, ID3D11Texture2D *pOutput, UINT uiOutIndex) | CInvertModule | [virtual]
~CInvertModule() | CInvertModule | [virtual]
~CInvertModule() | CInvertModule | [virtual]
Generated on Sat Nov 23 2024 16:09:08 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playback Manager Companion/C++/Constants.h Source File

  • Playback Manager Companion

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"Playback Manager 2");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044
00045
00046 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Gyrometer sensor/C++/pch.cpp Source File

  • Gyrometer sensor

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/texconv/DirectXTexUtil.cpp Source File

  • Direct3D resource loading
  • texconv

DirectXTexUtil.cpp

Go to the documentation of this file.
00001 //-------------------------------------------------------------------------------------
00002 // DirectXTexUtil.cpp
00003 //
00004 // DirectX Texture Library - Utilities
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 #include "directxtexp.h"
00015
00016 //-------------------------------------------------------------------------------------
00017 // WIC Pixel Format Translation Data
00018 //-------------------------------------------------------------------------------------
00019 struct WICTranslate
00020 {
00021     GUID        wic;
00022     DXGI_FORMAT format;
00023 };
00024
00025 static WICTranslate g_WICFormats[] =
00026 {
00027     { GUID_WICPixelFormat128bppRGBAFloat,       DXGI_FORMAT_R32G32B32A32_FLOAT },
00028
00029     { GUID_WICPixelFormat64bppRGBAHalf,         DXGI_FORMAT_R16G16B16A16_FLOAT },
00030     { GUID_WICPixelFormat64bppRGBA,             DXGI_FORMAT_R16G16B16A16_UNORM },
00031
00032     { GUID_WICPixelFormat32bppRGBA,             DXGI_FORMAT_R8G8B8A8_UNORM },
00033     { GUID_WICPixelFormat32bppBGRA,             DXGI_FORMAT_B8G8R8A8_UNORM }, // DXGI 1.1
00034     { GUID_WICPixelFormat32bppBGR,              DXGI_FORMAT_B8G8R8X8_UNORM }, // DXGI 1.1
00035
00036     { GUID_WICPixelFormat32bppRGBA1010102XR,    DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM }, // DXGI 1.1
00037     { GUID_WICPixelFormat32bppRGBA1010102,      DXGI_FORMAT_R10G10B10A2_UNORM },
00038     { GUID_WICPixelFormat32bppRGBE,             DXGI_FORMAT_R9G9B9E5_SHAREDEXP },
00039
00040     { GUID_WICPixelFormat16bppBGRA5551,         DXGI_FORMAT_B5G5R5A1_UNORM },
00041     { GUID_WICPixelFormat16bppBGR565,           DXGI_FORMAT_B5G6R5_UNORM },
00042
00043     { GUID_WICPixelFormat32bppGrayFloat,        DXGI_FORMAT_R32_FLOAT },
00044     { GUID_WICPixelFormat16bppGrayHalf,         DXGI_FORMAT_R16_FLOAT },
00045     { GUID_WICPixelFormat16bppGray,             DXGI_FORMAT_R16_UNORM },
00046     { GUID_WICPixelFormat8bppGray,              DXGI_FORMAT_R8_UNORM },
00047
00048     { GUID_WICPixelFormat8bppAlpha,             DXGI_FORMAT_A8_UNORM },
00049
00050     { GUID_WICPixelFormatBlackWhite,            DXGI_FORMAT_R1_UNORM },
00051
00052 #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8)
00053     { GUID_WICPixelFormat96bppRGBFloat,         DXGI_FORMAT_R32G32B32_FLOAT },
00054 #endif
00055 };
00056
00057 namespace DirectX
00058 {
00059
00060 //=====================================================================================
00061 // WIC Utilities
00062 //=====================================================================================
00063
00064 _Use_decl_annotations_
00065 DXGI_FORMAT _WICToDXGI( const GUID& guid )
00066 {
00067     for( size_t i=0; i < _countof(g_WICFormats); ++i )
00068     {
00069         if ( memcmp( &g_WICFormats[i].wic, &guid, sizeof(GUID) ) == 0 )
00070             return g_WICFormats[i].format;
00071     }
00072
00073     return DXGI_FORMAT_UNKNOWN;
00074 }
00075
00076 _Use_decl_annotations_
00077 bool _DXGIToWIC( DXGI_FORMAT format, GUID& guid )
00078 {
00079     for( size_t i=0; i < _countof(g_WICFormats); ++i )
00080     {
00081         if ( g_WICFormats[i].format == format )
00082         {
00083             memcpy( &guid, &g_WICFormats[i].wic, sizeof(GUID) );
00084             return true;
00085         }
00086     }
00087
00088     // Special cases
00089     switch( format )
00090     {
00091     case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
00092         memcpy( &guid, &GUID_WICPixelFormat32bppRGBA, sizeof(GUID) );
00093         return true;
00094
00095     case DXGI_FORMAT_D32_FLOAT:
00096         memcpy( &guid, &GUID_WICPixelFormat32bppGrayFloat, sizeof(GUID) );
00097         return true;
00098
00099     case DXGI_FORMAT_D16_UNORM:
00100         memcpy( &guid, &GUID_WICPixelFormat16bppGray, sizeof(GUID) );
00101         return true;
00102
00103     case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
00104         memcpy( &guid, &GUID_WICPixelFormat32bppBGRA, sizeof(GUID) );
00105         return true;
00106
00107     case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB:
00108         memcpy( &guid, &GUID_WICPixelFormat32bppBGR, sizeof(GUID) );
00109         return true;
00110     }
00111
00112     memcpy( &guid, &GUID_NULL, sizeof(GUID) );
00113     return false;
00114 }
00115
00116 _Use_decl_annotations_
00117 size_t _WICBitsPerPixel( REFGUID targetGuid )
00118 {
00119     IWICImagingFactory* pWIC = _GetWIC();
00120     if ( !pWIC )
00121         return 0;
00122
00123     ScopedObject<IWICComponentInfo> cinfo;
00124     if ( FAILED( pWIC->CreateComponentInfo( targetGuid, &cinfo ) ) )
00125         return 0;
00126
00127     WICComponentType type;
00128     if ( FAILED( cinfo->GetComponentType( &type ) ) )
00129         return 0;
00130
00131     if ( type != WICPixelFormat )
00132         return 0;
00133
00134     ScopedObject<IWICPixelFormatInfo> pfinfo;
00135     if ( FAILED( cinfo->QueryInterface( __uuidof(IWICPixelFormatInfo), reinterpret_cast<void**>( &pfinfo )  ) ) )
00136         return 0;
00137
00138     UINT bpp;
00139     if ( FAILED( pfinfo->GetBitsPerPixel( &bpp ) ) )
00140         return 0;
00141
00142     return bpp;
00143 }
00144
00145 IWICImagingFactory* _GetWIC()
00146 {
00147     static IWICImagingFactory* s_Factory = nullptr;
00148
00149     if ( s_Factory )
00150         return s_Factory;
00151
00152     HRESULT hr = CoCreateInstance(
00153         CLSID_WICImagingFactory,
00154         nullptr,
00155         CLSCTX_INPROC_SERVER,
00156         __uuidof(IWICImagingFactory),
00157         (LPVOID*)&s_Factory
00158         );
00159
00160     if ( FAILED(hr) )
00161     {
00162         s_Factory = nullptr;
00163         return nullptr;
00164     }
00165
00166     return s_Factory;
00167 }
00168
00169
00170 //-------------------------------------------------------------------------------------
00171 // Public helper function to get common WIC codec GUIDs
00172 //-------------------------------------------------------------------------------------
00173 _Use_decl_annotations_
00174 REFGUID GetWICCodec( WICCodecs codec )
00175 {
00176     switch( codec )
00177     {
00178     case WIC_CODEC_BMP:
00179         return GUID_ContainerFormatBmp;
00180
00181     case WIC_CODEC_JPEG:
00182         return GUID_ContainerFormatJpeg;
00183
00184     case WIC_CODEC_PNG:
00185         return GUID_ContainerFormatPng;
00186
00187     case WIC_CODEC_TIFF:
00188         return GUID_ContainerFormatTiff;
00189
00190     case WIC_CODEC_GIF:
00191         return GUID_ContainerFormatGif;
00192
00193     case WIC_CODEC_WMP:
00194         return GUID_ContainerFormatWmp;
00195
00196     case WIC_CODEC_ICO:
00197         return GUID_ContainerFormatIco;
00198
00199     default:
00200         return GUID_NULL;
00201     }
00202 }
00203
00204
00205 //=====================================================================================
00206 // DXGI Format Utilities
00207 //=====================================================================================
00208
00209 //-------------------------------------------------------------------------------------
00210 // Returns bits-per-pixel for a given DXGI format, or 0 on failure
00211 //-------------------------------------------------------------------------------------
00212 _Use_decl_annotations_
00213 size_t BitsPerPixel( DXGI_FORMAT fmt )
00214 {
00215     switch( fmt )
00216     {
00217     case DXGI_FORMAT_R32G32B32A32_TYPELESS:
00218     case DXGI_FORMAT_R32G32B32A32_FLOAT:
00219     case DXGI_FORMAT_R32G32B32A32_UINT:
00220     case DXGI_FORMAT_R32G32B32A32_SINT:
00221         return 128;
00222
00223     case DXGI_FORMAT_R32G32B32_TYPELESS:
00224     case DXGI_FORMAT_R32G32B32_FLOAT:
00225     case DXGI_FORMAT_R32G32B32_UINT:
00226     case DXGI_FORMAT_R32G32B32_SINT:
00227         return 96;
00228
00229     case DXGI_FORMAT_R16G16B16A16_TYPELESS:
00230     case DXGI_FORMAT_R16G16B16A16_FLOAT:
00231     case DXGI_FORMAT_R16G16B16A16_UNORM:
00232     case DXGI_FORMAT_R16G16B16A16_UINT:
00233     case DXGI_FORMAT_R16G16B16A16_SNORM:
00234     case DXGI_FORMAT_R16G16B16A16_SINT:
00235     case DXGI_FORMAT_R32G32_TYPELESS:
00236     case DXGI_FORMAT_R32G32_FLOAT:
00237     case DXGI_FORMAT_R32G32_UINT:
00238     case DXGI_FORMAT_R32G32_SINT:
00239     case DXGI_FORMAT_R32G8X24_TYPELESS:
00240     case DXGI_FORMAT_D32_FLOAT_S8X24_UINT:
00241     case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS:
00242     case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT:
00243         return 64;
00244
00245     case DXGI_FORMAT_R10G10B10A2_TYPELESS:
00246     case DXGI_FORMAT_R10G10B10A2_UNORM:
00247     case DXGI_FORMAT_R10G10B10A2_UINT:
00248     case DXGI_FORMAT_R11G11B10_FLOAT:
00249     case DXGI_FORMAT_R8G8B8A8_TYPELESS:
00250     case DXGI_FORMAT_R8G8B8A8_UNORM:
00251     case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
00252     case DXGI_FORMAT_R8G8B8A8_UINT:
00253     case DXGI_FORMAT_R8G8B8A8_SNORM:
00254     case DXGI_FORMAT_R8G8B8A8_SINT:
00255     case DXGI_FORMAT_R16G16_TYPELESS:
00256     case DXGI_FORMAT_R16G16_FLOAT:
00257     case DXGI_FORMAT_R16G16_UNORM:
00258     case DXGI_FORMAT_R16G16_UINT:
00259     case DXGI_FORMAT_R16G16_SNORM:
00260     case DXGI_FORMAT_R16G16_SINT:
00261     case DXGI_FORMAT_R32_TYPELESS:
00262     case DXGI_FORMAT_D32_FLOAT:
00263     case DXGI_FORMAT_R32_FLOAT:
00264     case DXGI_FORMAT_R32_UINT:
00265     case DXGI_FORMAT_R32_SINT:
00266     case DXGI_FORMAT_R24G8_TYPELESS:
00267     case DXGI_FORMAT_D24_UNORM_S8_UINT:
00268     case DXGI_FORMAT_R24_UNORM_X8_TYPELESS:
00269     case DXGI_FORMAT_X24_TYPELESS_G8_UINT:
00270     case DXGI_FORMAT_R9G9B9E5_SHAREDEXP:
00271     case DXGI_FORMAT_R8G8_B8G8_UNORM:
00272     case DXGI_FORMAT_G8R8_G8B8_UNORM:
00273     case DXGI_FORMAT_B8G8R8A8_UNORM:
00274     case DXGI_FORMAT_B8G8R8X8_UNORM:
00275     case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM:
00276     case DXGI_FORMAT_B8G8R8A8_TYPELESS:
00277     case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
00278     case DXGI_FORMAT_B8G8R8X8_TYPELESS:
00279     case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB:
00280         return 32;
00281
00282     case DXGI_FORMAT_R8G8_TYPELESS:
00283     case DXGI_FORMAT_R8G8_UNORM:
00284     case DXGI_FORMAT_R8G8_UINT:
00285     case DXGI_FORMAT_R8G8_SNORM:
00286     case DXGI_FORMAT_R8G8_SINT:
00287     case DXGI_FORMAT_R16_TYPELESS:
00288     case DXGI_FORMAT_R16_FLOAT:
00289     case DXGI_FORMAT_D16_UNORM:
00290     case DXGI_FORMAT_R16_UNORM:
00291     case DXGI_FORMAT_R16_UINT:
00292     case DXGI_FORMAT_R16_SNORM:
00293     case DXGI_FORMAT_R16_SINT:
00294     case DXGI_FORMAT_B5G6R5_UNORM:
00295     case DXGI_FORMAT_B5G5R5A1_UNORM:
00296         return 16;
00297
00298     case DXGI_FORMAT_R8_TYPELESS:
00299     case DXGI_FORMAT_R8_UNORM:
00300     case DXGI_FORMAT_R8_UINT:
00301     case DXGI_FORMAT_R8_SNORM:
00302     case DXGI_FORMAT_R8_SINT:
00303     case DXGI_FORMAT_A8_UNORM:
00304         return 8;
00305
00306     case DXGI_FORMAT_R1_UNORM:
00307         return 1;
00308
00309     case DXGI_FORMAT_BC1_TYPELESS:
00310     case DXGI_FORMAT_BC1_UNORM:
00311     case DXGI_FORMAT_BC1_UNORM_SRGB:
00312     case DXGI_FORMAT_BC4_TYPELESS:
00313     case DXGI_FORMAT_BC4_UNORM:
00314     case DXGI_FORMAT_BC4_SNORM:
00315         return 4;
00316
00317     case DXGI_FORMAT_BC2_TYPELESS:
00318     case DXGI_FORMAT_BC2_UNORM:
00319     case DXGI_FORMAT_BC2_UNORM_SRGB:
00320     case DXGI_FORMAT_BC3_TYPELESS:
00321     case DXGI_FORMAT_BC3_UNORM:
00322     case DXGI_FORMAT_BC3_UNORM_SRGB:
00323     case DXGI_FORMAT_BC5_TYPELESS:
00324     case DXGI_FORMAT_BC5_UNORM:
00325     case DXGI_FORMAT_BC5_SNORM:
00326     case DXGI_FORMAT_BC6H_TYPELESS:
00327     case DXGI_FORMAT_BC6H_UF16:
00328     case DXGI_FORMAT_BC6H_SF16:
00329     case DXGI_FORMAT_BC7_TYPELESS:
00330     case DXGI_FORMAT_BC7_UNORM:
00331     case DXGI_FORMAT_BC7_UNORM_SRGB:
00332         return 8;
00333
00334     case DXGI_FORMAT_B4G4R4A4_UNORM:
00335         return 16;
00336
00337     // We don't support the video formats ( see IsVideo function )
00338
00339     default:
00340         return 0;
00341     }
00342 }
00343
00344
00345 //-------------------------------------------------------------------------------------
00346 // Computes the image row pitch in bytes, and the slice ptich (size in bytes of the image)
00347 // based on DXGI format, width, and height
00348 //-------------------------------------------------------------------------------------
00349 _Use_decl_annotations_
00350 void ComputePitch( DXGI_FORMAT fmt, size_t width, size_t height,
00351                    size_t& rowPitch, size_t& slicePitch, DWORD flags )
00352 {
00353     assert( IsValid(fmt) && !IsVideo(fmt) );
00354
00355     if ( IsCompressed(fmt) )
00356     {
00357         size_t bpb = ( fmt == DXGI_FORMAT_BC1_TYPELESS
00358                      || fmt == DXGI_FORMAT_BC1_UNORM
00359                      || fmt == DXGI_FORMAT_BC1_UNORM_SRGB
00360                      || fmt == DXGI_FORMAT_BC4_TYPELESS
00361                      || fmt == DXGI_FORMAT_BC4_UNORM
00362                      || fmt == DXGI_FORMAT_BC4_SNORM) ? 8 : 16;
00363         size_t nbw = std::max<size_t>( 1, (width + 3) / 4 );
00364         size_t nbh = std::max<size_t>( 1, (height + 3) / 4 );
00365         rowPitch = nbw * bpb;
00366
00367         slicePitch = rowPitch * nbh;
00368     }
00369     else if ( IsPacked(fmt) )
00370     {
00371         rowPitch = ( ( width + 1 ) >> 1) * 4;
00372
00373         slicePitch = rowPitch * height;
00374     }
00375     else
00376     {
00377         size_t bpp;
00378
00379         if ( flags & CP_FLAGS_24BPP )
00380             bpp = 24;
00381         else if ( flags & CP_FLAGS_16BPP )
00382             bpp = 16;
00383         else if ( flags & CP_FLAGS_8BPP )
00384             bpp = 8;
00385         else
00386             bpp = BitsPerPixel( fmt );
00387
00388         if ( flags & CP_FLAGS_LEGACY_DWORD )
00389         {
00390             // Special computation for some incorrectly created DDS files based on
00391             // legacy DirectDraw assumptions about pitch alignment
00392             rowPitch = ( ( width * bpp + 31 ) / 32 ) * sizeof(uint32_t);
00393             slicePitch = rowPitch * height;
00394         }
00395         else
00396         {
00397             rowPitch = ( width * bpp + 7 ) / 8;
00398             slicePitch = rowPitch * height;
00399         }
00400     }
00401 }
00402
00403
00404 //-------------------------------------------------------------------------------------
00405 // Converts to an SRGB equivalent type if available
00406 //-------------------------------------------------------------------------------------
00407 _Use_decl_annotations_
00408 DXGI_FORMAT MakeSRGB( DXGI_FORMAT fmt )
00409 {
00410     switch( fmt )
00411     {
00412     case DXGI_FORMAT_R8G8B8A8_UNORM:
00413         return DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
00414
00415     case DXGI_FORMAT_BC1_UNORM:
00416         return DXGI_FORMAT_BC1_UNORM_SRGB;
00417
00418     case DXGI_FORMAT_BC2_UNORM:
00419         return DXGI_FORMAT_BC2_UNORM_SRGB;
00420
00421     case DXGI_FORMAT_BC3_UNORM:
00422         return DXGI_FORMAT_BC3_UNORM_SRGB;
00423
00424     case DXGI_FORMAT_B8G8R8A8_UNORM:
00425         return DXGI_FORMAT_B8G8R8A8_UNORM_SRGB;
00426
00427     case DXGI_FORMAT_B8G8R8X8_UNORM:
00428         return DXGI_FORMAT_B8G8R8X8_UNORM_SRGB;
00429
00430     case DXGI_FORMAT_BC7_UNORM:
00431         return DXGI_FORMAT_BC7_UNORM_SRGB;
00432
00433     default:
00434         return fmt;
00435     }
00436 }
00437
00438
00439 //=====================================================================================
00440 // TexMetadata
00441 //=====================================================================================
00442
00443 _Use_decl_annotations_
00444 size_t TexMetadata::ComputeIndex( size_t mip, size_t item, size_t slice ) const
00445 {
00446     if ( mip >= mipLevels )
00447         return size_t(-1);
00448
00449     switch( dimension )
00450     {
00451     case TEX_DIMENSION_TEXTURE1D:
00452     case TEX_DIMENSION_TEXTURE2D:
00453         if ( slice > 0 )
00454             return size_t(-1);
00455
00456         if ( item >= arraySize )
00457             return size_t(-1);
00458
00459         return (item*( mipLevels ) + mip);
00460
00461     case TEX_DIMENSION_TEXTURE3D:
00462         if ( item > 0 )
00463         {
00464             // No support for arrays of volumes
00465             return size_t(-1);
00466         }
00467         else
00468         {
00469             size_t index = 0;
00470             size_t d = depth;
00471
00472             for( size_t level = 0; level < mip; ++level )
00473             {
00474                 index += d;
00475                 if ( d > 1 )
00476                     d >>= 1;
00477             }
00478
00479             if ( slice >= d )
00480                 return size_t(-1);
00481
00482             index += slice;
00483
00484             return index;
00485         }
00486         break;
00487
00488     default:
00489         return size_t(-1);
00490     }
00491 }
00492
00493
00494 //=====================================================================================
00495 // Blob - Bitmap image container
00496 //=====================================================================================
00497
00498 void Blob::Release()
00499 {
00500     if ( _buffer )
00501     {
00502         _aligned_free( _buffer );
00503         _buffer = nullptr;
00504     }
00505
00506     _size = 0;
00507 }
00508
00509 _Use_decl_annotations_
00510 HRESULT Blob::Initialize( size_t size )
00511 {
00512     if ( !size )
00513         return E_INVALIDARG;
00514
00515     Release();
00516
00517     _buffer = _aligned_malloc( size, 16 );
00518     if ( !_buffer )
00519     {
00520         Release();
00521         return E_OUTOFMEMORY;
00522     }
00523
00524     _size = size;
00525
00526     return S_OK;
00527 }
00528
00529 }; // namespace
Generated on Sat Nov 23 2024 16:08:12 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media engine native C++ video playback/C++/frameworkview.cpp Source File

  • Media engine native C++ video playback

frameworkview.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002
00003 #include "FrameworkView.h"
00004 #include "VideoView.h"
00005
00006 using namespace Windows::ApplicationModel::Core;
00007 using namespace Windows::UI::Core;
00008 using namespace Windows::ApplicationModel::Activation;
00009
00010 FrameworkView::FrameworkView()
00011 {
00012     m_activationEntryPoint = ActivationEntryPoint::Unknown;
00013 }
00014
00015 void FrameworkView::Initialize(
00016     _In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView
00017     )
00018 {
00019     m_applicationView = applicationView;
00020 }
00021
00022 // this method is called after Initialize
00023 void FrameworkView::SetWindow(
00024     _In_ Windows::UI::Core::CoreWindow^ window
00025     )
00026 {
00027     m_window = window;
00028 }
00029
00030 void FrameworkView::Load(Platform::String^ entryPoint )
00031 {
00032     if (entryPoint == "MEPlaybackNative.App")
00033     {
00034         m_activationEntryPoint = ActivationEntryPoint::MEPlaybackNative;
00035     }
00036 }
00037
00038 // this method is called after Load
00039 void FrameworkView::Run()
00040 {
00041     if (m_activationEntryPoint == ActivationEntryPoint::MEPlaybackNative)
00042     {
00043         auto view = ref new VideoView();
00044         view->Initialize(m_window, m_applicationView);
00045         view->Run();
00046
00047         // Must delete the view explicitly in order to break a circular dependency
00048         // between View and CoreWindow. View holds on to a CoreWindow reference most
00049         // typically for window activation, while CoreWindow refers back to View when
00050         // event handlers are hooked up. Without breaking this circular dependency,
00051         // neither View nor CoreWindow object gets to clean up. It's also important
00052         // to note that a 'delete' call on a ref class instance simply means calling
00053         // into a class destructor in order to explicitly break a cycle. It doesn't
00054         // actually deallocate any memory.
00055         delete view;
00056     }
00057     else
00058     {
00059         MEDIA::ThrowIfFailed(E_UNEXPECTED);
00060     }
00061 }
00062
00063 void FrameworkView::Uninitialize()
00064 {
00065 }
Generated on Sat Nov 23 2024 16:08:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Trial app and in-app purchase/C++/AppListingUri.xaml.h Source File

  • Trial app and in-app purchase

AppListingUri.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 // AppListingUri.xaml.h
00013 // Declaration of the AppListingUri class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "AppListingUri.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace StoreSample
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 AppListingUri sealed
00031         {
00032         public:
00033             AppListingUri();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037             virtual void OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^ e) override;
00038         private:
00039             MainPage^ rootPage;
00040             Windows::Foundation::EventRegistrationToken eventRegistrationToken;
00041
00042             void LoadAppListingUriProxyFile();
00043             void AppListingUriRefreshScenario();
00044
00045             void DisplayLink_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00046         };
00047     }
00048 }
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML data binding/C++/App.xaml.cpp Source File

  • XAML data binding

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:28 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D animation/C++/DirectXSample.h Source File

  • Direct2D animation

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
00010 // This header defines helper utilities to make DirectX APIs work with exceptions.
00011 namespace DX
00012 {
00013     inline void ThrowIfFailed(HRESULT hr)
00014     {
00015         if (FAILED(hr))
00016         {
00017             // Set a breakpoint on this line to catch DX API errors.
00018             throw Platform::Exception::CreateException(hr);
00019         }
00020     }
00021 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::ListViewSampleDataSource::sealed Member List

This is the complete list of members for SDKSample::ListViewSampleDataSource::sealed, including all inherited members.
_Category | SDKSample::ListViewSampleDataSource::sealed |
_Content | SDKSample::ListViewSampleDataSource::sealed |
_Description | SDKSample::ListViewSampleDataSource::sealed |
_Image | SDKSample::ListViewSampleDataSource::sealed |
_items | SDKSample::ListViewSampleDataSource::sealed |
_Link | SDKSample::ListViewSampleDataSource::sealed |
_PropertyChanged | SDKSample::ListViewSampleDataSource::sealed |
_Subtitle | SDKSample::ListViewSampleDataSource::sealed |
_Title | SDKSample::ListViewSampleDataSource::sealed |
Item() | SDKSample::ListViewSampleDataSource::sealed |
OnPropertyChanged(Platform::String^propertyName) | SDKSample::ListViewSampleDataSource::sealed | [inline]
StoreData() | SDKSample::ListViewSampleDataSource::sealed | [inline]
Generated on Sat Nov 23 2024 16:09:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML animation library/C++/App.xaml.cpp Source File

  • XAML animation library

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:28 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Portable device API/C++/EventCallback.h Source File

  • Portable device API

EventCallback.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 //
00009 // EventCallback.h
00010 // Declaration of the EventCallback class.
00011 //
00012
00013 #pragma once
00014
00015 #include <wrl\implements.h>
00016
00017 namespace SDKSample
00018 {
00019     namespace PortableDeviceCPP
00020     {
00021         // Delegate used by MainPage to be notified of events
00022         public delegate void EventReceived(Platform::String^ deviceId, Platform::String^ eventData);
00023
00024         // IPortableDeviceEventCallback implementation for use with device events.
00025         class EventCallback : public Microsoft::WRL::RuntimeClass<
00026             Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::RuntimeClassType::ClassicCom>,
00027             IPortableDeviceEventCallback>
00028         {
00029         public:
00030             EventCallback(EventReceived^ eventReceived) : _eventReceived(eventReceived) {}
00031
00032             ~EventCallback() {}
00033
00034             IFACEMETHODIMP OnEvent(_In_ IPortableDeviceValues* eventParameters)
00035             {
00036                 if (eventParameters != nullptr && _eventReceived != nullptr)
00037                 {
00038                     // Extract event data. For simplicity, we'll just display the event type and some basic data.
00039                     GUID eventId;
00040                     if (SUCCEEDED(eventParameters->GetGuidValue(WPD_EVENT_PARAMETER_EVENT_ID, &eventId)))
00041                     {
00042                         Platform::String^ eventData;
00043                         if (eventId == WPD_EVENT_OBJECT_ADDED)
00044                         {
00045                             eventData = "Object Added";
00046                             PWSTR newObjectId = nullptr;
00047                             if (SUCCEEDED(eventParameters->GetStringValue(WPD_OBJECT_ID, &newObjectId)))
00048                             {
00049                                 CoTaskMemString newObjectIdPtr(newObjectId);
00050                                 eventData += ", Object id: " + ref new Platform::String(newObjectId);
00051                             }
00052                         }
00053                         else if (eventId == WPD_EVENT_OBJECT_REMOVED)
00054                         {
00055                             eventData = "Object Removed";
00056                             PWSTR removedObjectId = nullptr;
00057                             if (SUCCEEDED(eventParameters->GetStringValue(WPD_OBJECT_ID, &removedObjectId)))
00058                             {
00059                                 CoTaskMemString removedObjectIdPtr(removedObjectId);
00060                                 eventData += ", Object id: " + ref new Platform::String(removedObjectId);
00061                             }
00062                         }
00063                         else if (eventId == WPD_EVENT_OBJECT_UPDATED)
00064                         {
00065                             eventData = "Object Updated";
00066                             PWSTR updatedObjectId = nullptr;
00067                             if (SUCCEEDED(eventParameters->GetStringValue(WPD_OBJECT_ID, &updatedObjectId)))
00068                             {
00069                                 CoTaskMemString updatedObjectIdPtr(updatedObjectId);
00070                                 eventData += ", Object id: " + ref new Platform::String(updatedObjectId);
00071                             }
00072                         }
00073                         else
00074                         {
00075                             // Handle more events as needed
00076                             eventData = "Other event";
00077                         }
00078
00079                         PWSTR deviceId = nullptr;
00080                         if (SUCCEEDED(eventParameters->GetStringValue(WPD_EVENT_PARAMETER_PNP_DEVICE_ID, &deviceId)))
00081                         {
00082                             //  Invoke the delegate
00083                             CoTaskMemString deviceIdPtr(deviceId);
00084                             _eventReceived(ref new Platform::String(deviceId), eventData);
00085                         }
00086                     }
00087                 }
00088                 return S_OK;
00089             }
00090
00091         private:
00092             EventReceived^ _eventReceived;
00093         };
00094     }
00095 }
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Thread pool/C++/DelayTimerScenario.xaml.h Source File

  • Thread pool

DelayTimerScenario.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 // DelayTimerScenario.xaml.h
00013 // Declaration of the DelayTimerScenario class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Constants.h"
00020 #include "DelayTimerScenario.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKSample
00024 {
00025     namespace ThreadPool
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 DelayTimerScenario sealed
00032         {
00033         public:
00034             DelayTimerScenario();
00035             void UpdateUI(ThreadPool::Status status);
00036
00037         protected:
00038             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00039             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00040         private:
00041             MainPage^ rootPage;
00042             void CreateDelayTimer(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00043             void CancelDelayTimer(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00044         };
00045     }
00046 }
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/Photo.cpp Source File

  • Hilo C++
  • Hilo

Photo.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 #include "Photo.h"
00009 #include "ExceptionPolicy.h"
00010 #include "TaskExceptionsExtensions.h"
00011
00012 using namespace concurrency;
00013 using namespace Hilo;
00014 using namespace Platform;
00015 using namespace std;
00016 using namespace Windows::ApplicationModel::Core;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Globalization::DateTimeFormatting;
00019 using namespace Windows::Storage::BulkAccess;
00020 using namespace Windows::Storage::FileProperties;
00021 using namespace Windows::Storage::Streams;
00022 using namespace Windows::System::UserProfile;
00023 using namespace Windows::UI::Core;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Media::Imaging;
00026
00027 Photo::Photo(FileInformation^ fileInfo, IPhotoGroup^ photoGroup, shared_ptr<ExceptionPolicy> exceptionPolicy) : m_fileInfo(fileInfo), m_weakPhotoGroup(photoGroup),
00028     m_exceptionPolicy(exceptionPolicy),
00029     m_columnSpan(1), m_rowSpan(1), m_queryPhotoImageAsyncIsRunning(false), m_isInvalidThumbnail(false)
00030 {
00031     m_thumbnailUpdatedEventToken = m_fileInfo->ThumbnailUpdated::add(ref new TypedEventHandler<IStorageItemInformation^, Object^>(this, &Photo::OnThumbnailUpdated));
00032 }
00033
00034 Photo::~Photo()
00035 {
00036     if (nullptr != m_fileInfo)
00037     {
00038         m_fileInfo->ThumbnailUpdated::remove(m_thumbnailUpdatedEventToken);
00039     }
00040
00041     if (nullptr != m_image && m_imageFailedEventToken.Value != 0)
00042     {
00043         // Remove the event handler on the UI thread because BitmapImage methods
00044         // must be called on the UI thread.
00045         auto image = m_image;
00046         auto imageFailedEventToken = m_imageFailedEventToken;
00047         run_async_non_interactive([image, imageFailedEventToken]()
00048         {
00049             image->ImageFailed::remove(imageFailedEventToken);
00050         });
00051     }
00052 }
00053
00054 void Photo::OnPropertyChanged(String^ propertyName)
00055 {
00056     assert(IsMainThread());
00057     PropertyChanged(this, ref new Windows::UI::Xaml::Data::PropertyChangedEventArgs(propertyName));
00058 }
00059
00060 void Photo::OnThumbnailUpdated(IStorageItemInformation^ sender, Object^ e)
00061 {
00062     CoreWindow^ wnd = CoreApplication::MainView->CoreWindow;
00063     CoreDispatcher^ dispatcher = wnd->Dispatcher;
00064     dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this] ()
00065     {
00066         OnPropertyChanged("Thumbnail");
00067     }));
00068 }
00069
00070 IPhotoGroup^ Photo::Group::get()
00071 {
00072     return m_weakPhotoGroup.Resolve<IPhotoGroup>();
00073 }
00074
00075 String^ Photo::Name::get()
00076 {
00077     return m_fileInfo->Name;
00078 }
00079
00080 String^ Photo::Path::get()
00081 {
00082     return m_fileInfo->Path;
00083 }
00084
00085 String^ Photo::FormattedPath::get()
00086 {
00087     wstring pathAndFileName = m_fileInfo->Path->Data();
00088     basic_string<char>::size_type index;
00089     index = pathAndFileName.rfind('\\');
00090     wstring path = pathAndFileName.substr(0, index);
00091     return ref new String(path.c_str());
00092 }
00093
00094 String^ Photo::FileType::get()
00095 {
00096     return m_fileInfo->FileType;
00097 }
00098
00099 DateTime Photo::DateTaken::get()
00100 {
00101     auto dateTaken = m_fileInfo->ImageProperties->DateTaken;
00102     if (dateTaken.UniversalTime == 0)
00103     {
00104         dateTaken = m_fileInfo->BasicProperties->DateModified;
00105     }
00106     return dateTaken;
00107 }
00108
00109 String^ Photo::FormattedDateTaken::get()
00110 {
00111     DateTimeFormatter dtf("shortdate", GlobalizationPreferences::Languages);
00112     return dtf.Format(DateTaken);
00113 }
00114
00115 String^ Photo::FormattedTimeTaken::get()
00116 {
00117     DateTimeFormatter dtf("shorttime", GlobalizationPreferences::Languages);
00118     return dtf.Format(DateTaken);
00119 }
00120
00121 String^ Photo::Resolution::get()
00122 {
00123     return m_fileInfo->ImageProperties->Width + " x " + m_fileInfo->ImageProperties->Height;
00124 }
00125
00126 uint64 Photo::FileSize::get()
00127 {
00128     return m_fileInfo->BasicProperties->Size;
00129 }
00130
00131 String^ Photo::DisplayType::get()
00132 {
00133     return m_fileInfo->DisplayType;
00134 }
00135
00136 BitmapImage^ Photo::Thumbnail::get()
00137 {
00138     assert(IsMainThread());
00139     IRandomAccessStream^ thumbnailStream = dynamic_cast<IRandomAccessStream^>(m_fileInfo->Thumbnail);
00140     if (nullptr == thumbnailStream)
00141     {
00142         m_isInvalidThumbnail = true;
00143         return ref new BitmapImage(ref new Uri("ms-appx:///Assets/HiloLogo.png"));
00144     }
00145
00146     auto thumbnail = ref new BitmapImage();
00147     create_task(thumbnail->SetSourceAsync(thumbnailStream)).then(ObserveException<void>(m_exceptionPolicy));
00148
00149     m_isInvalidThumbnail = false;
00150     return thumbnail;
00151 }
00152
00153 BitmapImage^ Photo::Image::get()
00154 {
00155     assert(IsMainThread());
00156     if (nullptr == m_image && !m_queryPhotoImageAsyncIsRunning)
00157     {
00158         m_queryPhotoImageAsyncIsRunning = true;
00159         QueryPhotoImageAsync().then([this](task<void> priorTask)
00160             {
00161                 m_queryPhotoImageAsyncIsRunning = false;
00162                 priorTask.get();
00163                 OnPropertyChanged("Image");
00164             }).then(ObserveException<void>(m_exceptionPolicy));
00165     }
00166     return m_image;
00167 }
00168
00169 bool Photo::IsInvalidThumbnail::get()
00170 {
00171     return m_isInvalidThumbnail;
00172 }
00173
00174 task<void> Photo::QueryPhotoImageAsync()
00175 {
00176     auto imageStreamTask = create_task(m_fileInfo->OpenReadAsync());
00177     return imageStreamTask.then([this](task<IRandomAccessStreamWithContentType^> priorTask) -> task<void>
00178     {
00179         assert(IsMainThread());
00180         IRandomAccessStreamWithContentType^ imageData = priorTask.get();
00181         m_image = ref new BitmapImage();
00182         m_imageFailedEventToken = m_image->ImageFailed::add(ref new ExceptionRoutedEventHandler(this, &Photo::OnImageFailedToOpen));
00183         return create_task(m_image->SetSourceAsync(imageData));
00184     }).then([this](task<void> priorTask) {
00185         assert(IsMainThread());
00186         try
00187         {
00188             priorTask.get();
00189         }
00190         catch (Exception^ e)
00191         {
00192            OnImageFailedToOpen(nullptr, nullptr);
00193         }
00194     });
00195 }
00196
00197 void Photo::OnImageFailedToOpen(Object^ sender, ExceptionRoutedEventArgs^ e)
00198 {
00199     assert(IsMainThread());
00200
00201     // Load a default image.
00202     m_image = ref new BitmapImage(ref new Uri("ms-appx:///Assets/HiloLogo.png"));
00203 }
00204
00205 void Photo::ClearImageData()
00206 {
00207     if (nullptr != m_image && m_imageFailedEventToken.Value != 0)
00208     {
00209         m_image->ImageFailed::remove(m_imageFailedEventToken);
00210     }
00211     m_image = nullptr;
00212 }
00213
00214 IAsyncOperation<IRandomAccessStreamWithContentType^>^ Photo::OpenReadAsync()
00215 {
00216     return m_fileInfo->OpenReadAsync();
00217 }
00218
00219 int Photo::RowSpan::get()
00220 {
00221     return m_rowSpan;
00222 }
00223
00224 void Photo::RowSpan::set(int value)
00225 {
00226     m_rowSpan = value;
00227 }
00228
00229 int Photo::ColumnSpan::get()
00230 {
00231     return m_columnSpan;
00232 }
00233
00234 void Photo::ColumnSpan::set(int value)
00235 {
00236     m_columnSpan = value;
00237 }
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D sprite/C++/DirectXApp.h Source File

  • Direct3D sprite

DirectXApp.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 "SimpleSprites.h"
00011
00012 ref class DirectXApp : public Windows::ApplicationModel::Core::IFrameworkView
00013 {
00014 internal:
00015     DirectXApp();
00016
00017 public:
00018     // IFrameworkView Methods
00019     virtual void Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00020     virtual void SetWindow(_In_ Windows::UI::Core::CoreWindow^ window);
00021     virtual void Load(_In_ Platform::String^ entryPoint);
00022     virtual void Run();
00023     virtual void Uninitialize();
00024
00025 private:
00026     // Event Handlers
00027     void OnWindowSizeChanged(
00028         _In_ Windows::UI::Core::CoreWindow^ sender,
00029         _In_ Windows::UI::Core::WindowSizeChangedEventArgs^ args
00030         );
00031
00032     void OnVisibilityChanged(
00033         _In_ Windows::UI::Core::CoreWindow^ sender,
00034         _In_ Windows::UI::Core::VisibilityChangedEventArgs^ args
00035         );
00036
00037     void OnLogicalDpiChanged(
00038         _In_ Platform::Object^ sender
00039         );
00040
00041     void OnActivated(
00042         _In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView,
00043         _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^ args
00044         );
00045
00046     void OnSuspending(
00047         _In_ Platform::Object^ sender,
00048         _In_ Windows::ApplicationModel::SuspendingEventArgs^ args
00049         );
00050
00051     void OnWindowClosed(
00052         _In_ Windows::UI::Core::CoreWindow^ sender,
00053         _In_ Windows::UI::Core::CoreWindowEventArgs^ args
00054         );
00055
00056     // CoreWindow Input Events
00057     void OnPointerPressed(
00058         _In_ Windows::UI::Core::CoreWindow^ sender,
00059         _In_ Windows::UI::Core::PointerEventArgs^ args
00060         );
00061
00062     void OnPointerReleased(
00063         _In_ Windows::UI::Core::CoreWindow^ sender,
00064         _In_ Windows::UI::Core::PointerEventArgs^ args
00065         );
00066
00067     void OnPointerMoved(
00068         _In_ Windows::UI::Core::CoreWindow^ sender,
00069         _In_ Windows::UI::Core::PointerEventArgs^ args
00070         );
00071
00072     SimpleSprites^ m_renderer;
00073     bool m_windowClosed;
00074     bool m_windowVisible;
00075 };
00076
00077 ref class DirectXAppSource : Windows::ApplicationModel::Core::IFrameworkViewSource
00078 {
00079 public:
00080     virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00081 };
Generated on Sat Nov 23 2024 16:08:07 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML user and custom controls/C++/common/LayoutAwarePage.h Source File

  • XAML user and custom controls
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Secondary tiles/C#,C++/pch.h Source File

  • Secondary tiles
  • C#,C++

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include "Sample-Utils\CppSamplesUtils.h"
00019 #include <ppltasks.h>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: SimpleOrientationSensor/C++/Scenario1.xaml.cpp Source File

  • SimpleOrientationSensor

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::SimpleOrientationSensorCPP;
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::Devices::Sensors;
00025 using namespace Windows::Foundation;
00026 using namespace Windows::UI::Core;
00027 using namespace Platform;
00028
00029 Scenario1::Scenario1() : rootPage(MainPage::Current)
00030 {
00031     InitializeComponent();
00032
00033     sensor = SimpleOrientationSensor::GetDefault();
00034     if (sensor == nullptr)
00035     {
00036         rootPage->NotifyUser("No simple orientation sensor found", NotifyType::ErrorMessage);
00037     }
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 void Scenario1::OnNavigatedTo(NavigationEventArgs^ e)
00046 {
00047     ScenarioEnableButton->IsEnabled = true;
00048     ScenarioDisableButton->IsEnabled = false;
00049 }
00050
00051 /// <summary>
00052 /// Invoked when this page is no longer displayed.
00053 /// </summary>
00054 /// <param name="e"></param>
00055 void Scenario1::OnNavigatedFrom(NavigationEventArgs^ e)
00056 {
00057     if (ScenarioDisableButton->IsEnabled)
00058     {
00059         Window::Current->VisibilityChanged::remove(visibilityToken);
00060         sensor->OrientationChanged::remove(orientationToken);
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 Scenario1::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             orientationToken = sensor->OrientationChanged::add(ref new TypedEventHandler<SimpleOrientationSensor^, SimpleOrientationSensorOrientationChangedEventArgs^>(this, &Scenario1::OrientationChanged));
00081         }
00082         else
00083         {
00084             // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00085             sensor->OrientationChanged::remove(orientationToken);
00086         }
00087     }
00088 }
00089
00090 void Scenario1::DisplayOrientation(SimpleOrientation orientation)
00091 {
00092     switch (orientation)
00093     {
00094         case SimpleOrientation::NotRotated:
00095             ScenarioOutput_Orientation->Text = "Not Rotated";
00096             break;
00097         case SimpleOrientation::Rotated90DegreesCounterclockwise:
00098             ScenarioOutput_Orientation->Text = "Rotated 90 Degrees Counterclockwise";
00099             break;
00100         case SimpleOrientation::Rotated180DegreesCounterclockwise:
00101             ScenarioOutput_Orientation->Text = "Rotated 180 Degrees Counterclockwise";
00102             break;
00103         case SimpleOrientation::Rotated270DegreesCounterclockwise:
00104             ScenarioOutput_Orientation->Text = "Rotated 270 Degrees Counterclockwise";
00105             break;
00106         case SimpleOrientation::Faceup:
00107             ScenarioOutput_Orientation->Text = "Faceup";
00108             break;
00109         case SimpleOrientation::Facedown:
00110             ScenarioOutput_Orientation->Text = "Facedown";
00111             break;
00112         default:
00113             ScenarioOutput_Orientation->Text = "Unknown orientation";
00114             break;
00115     }
00116 }
00117
00118 void Scenario1::OrientationChanged(SimpleOrientationSensor^ sender, SimpleOrientationSensorOrientationChangedEventArgs^ e)
00119 {
00120     // We need to dispatch to the UI thread to display the output
00121     Dispatcher->RunAsync(
00122         CoreDispatcherPriority::Normal,
00123         ref new DispatchedHandler(
00124             [this, e]()
00125             {
00126                 DisplayOrientation(e->Orientation);
00127             },
00128             CallbackContext::Any
00129             )
00130         );
00131 }
00132
00133 void Scenario1::ScenarioEnable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00134 {
00135     if (sensor != nullptr)
00136     {
00137         visibilityToken = Window::Current->VisibilityChanged::add(ref new WindowVisibilityChangedEventHandler(this, &Scenario1::VisibilityChanged));
00138         orientationToken = sensor->OrientationChanged::add(ref new TypedEventHandler<SimpleOrientationSensor^, SimpleOrientationSensorOrientationChangedEventArgs^>(this, &Scenario1::OrientationChanged));
00139
00140         // Display the current orientation once while waiting for the next orientation change
00141         DisplayOrientation(sensor->GetCurrentOrientation());
00142
00143         ScenarioEnableButton->IsEnabled = false;
00144         ScenarioDisableButton->IsEnabled = true;
00145     }
00146     else
00147     {
00148         rootPage->NotifyUser("No simple orientation sensor found", NotifyType::ErrorMessage);
00149     }
00150 }
00151
00152 void Scenario1::ScenarioDisable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00153 {
00154     Window::Current->VisibilityChanged::remove(visibilityToken);
00155     sensor->OrientationChanged::remove(orientationToken);
00156
00157     ScenarioEnableButton->IsEnabled = true;
00158     ScenarioDisableButton->IsEnabled = false;
00159 }
Generated on Sat Nov 23 2024 16:07:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Credential picker/C++/App.xaml.cpp Source File

  • Credential picker

App.xaml.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 //
00009 // App.xaml.cpp
00010 // Implementation of the App.xaml class.
00011 //
00012
00013 #include "pch.h"
00014 #include "App.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace Windows::UI::Xaml;
00018 using namespace Windows::UI::Xaml::Controls;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::ApplicationModel;
00021 using namespace Windows::ApplicationModel::Activation;
00022 using namespace CppSamplesUtils;
00023 using namespace CredentialPickerCPP;
00024 using namespace Windows::UI::Xaml::Interop;
00025
00026 App::App()
00027 {
00028     InitializeComponent();
00029     this->Suspending += ref new SuspendingEventHandler(this, &CredentialPickerCPP::App::OnSuspending);
00030 }
00031
00032
00033
00034 void App::OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs)
00035 {
00036     auto deferral = pArgs->SuspendingOperation->GetDeferral();
00037     SuspensionManager::StartSaveTask().then([=]() {
00038         deferral->Complete();
00039     });
00040 }
00041
00042 void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs)
00043 {
00044     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Terminated)
00045     {
00046         SuspensionManager::StartRestoreTask().then([=]() {
00047             Window::Current->Content = ref new MainPage();
00048             Window::Current->Activate();
00049         });
00050     }
00051     else
00052     {
00053         auto rootFrame = ref new Frame();
00054         TypeName pageType = { "CredentialPickerCPP.MainPage", TypeKind::Custom };
00055         rootFrame->Navigate(pageType);
00056         Window::Current->Content = rootFrame;
00057         Window::Current->Activate();
00058     }
00059 }
00060
00061
Generated on Sat Nov 23 2024 16:07:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Real-time communication/C#,C++/Properties/AssemblyInfo.cs Source File

  • Real-time communication
  • C#,C++
  • 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("SimpleCommunication CS 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 Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAudio2 audio file playback/C++/BasicTimer.h Source File

  • XAudio2 audio file playback

BasicTimer.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 timer class used to drive the render loop of the actively-animated
00011 // DirectX SDK samples. Uses the QueryPerformanceCounter function to retrieve
00012 // high-resolution timing information.
00013 ref class BasicTimer
00014 {
00015 private:
00016     LARGE_INTEGER m_frequency;
00017     LARGE_INTEGER m_currentTime;
00018     LARGE_INTEGER m_startTime;
00019     LARGE_INTEGER m_lastTime;
00020     float m_total;
00021     float m_delta;
00022
00023 internal:
00024     BasicTimer();
00025     void Reset();
00026     void Update();
00027     property float Total
00028     {
00029         float get();
00030     }
00031     property float Delta
00032     {
00033         float get();
00034     }
00035 };
Generated on Sat Nov 23 2024 16:08:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

MediaExtensionsCS::ScenarioInput3 Member List

This is the complete list of members for MediaExtensionsCS::ScenarioInput3, including all inherited members.
__pad0__ | Element |
AcceptChildNode(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^childXmlNode) override | Page | [virtual]
AddChild(_In_ Element^element) | Element |
AddSibling(_In_ Element^element) | Element |
BindResource(_In_ Element^rootElement) | Element | [virtual]
Create(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^xmlNode) | Element | [static]
Draw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
GetFirstChild() | Element | [inline]
GetName() | Element | [inline]
GetNextSibling() | Element | [inline]
GetOpacity() | Element | [inline, virtual]
GetParent() | Element | [inline]
GetSize() | Element | [inline]
Initialize(_In_ Document^document, _In_ Windows::Data::Xml::Dom::XmlElement^xmlElement) | Element | [virtual]
Measure(_In_ Document^document, D2D1_SIZE_F const &parentSize, _Out_ D2D1_RECT_F *bounds) | Element | [virtual]
OnNavigatedFrom(NavigationEventArgs e) | MediaExtensionsCS::ScenarioInput3 | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | MediaExtensionsCS::ScenarioInput3 | [inline, protected]
Open_Click(object sender, RoutedEventArgs e) | MediaExtensionsCS::ScenarioInput3 | [inline, private]
outputVideo | MediaExtensionsCS::ScenarioInput3 | [private]
outputVideoStabilized | MediaExtensionsCS::ScenarioInput3 | [private]
PrepareToDraw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
ReleaseParent() | Element | [virtual]
rootPage | MediaExtensionsCS::ScenarioInput3 | [private]
rootPage_OutputFrameLoaded(object sender, object e) | MediaExtensionsCS::ScenarioInput3 | [inline, private]
ScenarioInput3() | MediaExtensionsCS::ScenarioInput3 | [inline]
Stop_Click(object sender, RoutedEventArgs e) | MediaExtensionsCS::ScenarioInput3 | [inline, private]
Generated on Sat Nov 23 2024 16:09:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::MessageDialogSample::sealed Member List

This is the complete list of members for SDKSample::MessageDialogSample::sealed, including all inherited members.
CancelCommand() | SDKSample::MessageDialogSample::sealed |
CancelCommandButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::MessageDialogSample::sealed | [private]
CommandInvokedHandler(Windows::UI::Popups::IUICommand^command) | SDKSample::MessageDialogSample::sealed | [private]
CompletedCallback() | SDKSample::MessageDialogSample::sealed |
CompletedCallbackButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::MessageDialogSample::sealed | [private]
CustomCommand() | SDKSample::MessageDialogSample::sealed |
CustomCommandButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::MessageDialogSample::sealed | [private]
DefaultCloseCommand() | SDKSample::MessageDialogSample::sealed |
DefaultCloseCommandButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::MessageDialogSample::sealed | [private]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::MessageDialogSample::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::MessageDialogSample::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::MessageDialogSample::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::MessageDialogSample::sealed | [protected, virtual]
rootPage | SDKSample::MessageDialogSample::sealed | [private]
Generated on Sat Nov 23 2024 16:09:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML WebView control/C++/Constants.h Source File

  • XAML WebView control

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"WebView control sample");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: App tiles and badges/C#,C++/common/suspensionmanager.h Source File

  • App tiles and badges
  • C#,C++
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Geolocation/C++/common/SuspensionManager.cpp Source File

  • Geolocation
  • common

SuspensionManager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:36 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Device enumeration/C++/Containers.xaml.cpp Source File

  • Device enumeration

Containers.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 // Containers.xaml.cpp
00013 // Implementation of the Containers class
00014 //
00015
00016 #include "pch.h"
00017 #include "Containers.xaml.h"
00018
00019 using namespace SDKSample::DeviceEnumeration;
00020
00021 Containers::Containers()
00022 {
00023     InitializeComponent();
00024 }
00025
00026 void Containers::EnumerateDeviceContainers(Object^ sender, RoutedEventArgs^ eventArgs)
00027 {
00028     Windows::UI::Xaml::FocusState focusState = EnumerateContainersButton->FocusState;
00029     EnumerateContainersButton->IsEnabled = false;
00030
00031     DeviceContainersOutputList->Items->Clear();
00032
00033     auto properties = ref new Vector<String^>();
00034     properties->Append("System.ItemNameDisplay");
00035     properties->Append("System.Devices.ModelName");
00036     properties->Append("System.Devices.Connected");
00037
00038     task<PnpObjectCollection^>(
00039         PnpObject::FindAllAsync(PnpObjectType::DeviceContainer, properties))
00040         .then([this](PnpObjectCollection^ containers)
00041     {
00042         rootPage->NotifyUser(containers->Size + " device container(s) found\n\n", NotifyType::StatusMessage);
00043 ;
00044
00045         std::for_each(begin(containers), end(containers),
00046             [this](PnpObject^ container)
00047         {
00048             DisplayDeviceContainer(container);
00049         });
00050     });
00051
00052     EnumerateContainersButton->IsEnabled = true;
00053     EnumerateContainersButton->Focus(focusState);
00054 }
00055
00056 void Containers::DisplayDeviceContainer(PnpObject^ container)
00057 {
00058     String^ id = "Id: " + container->Id;
00059
00060     String^ name = dynamic_cast<String^>(container->Properties->Lookup("System.ItemNameDisplay"));
00061     if (name == nullptr)
00062     {
00063         name = "*Unnamed*";
00064     }
00065
00066     String^ properties = "Property store count is: " +
00067         container->Properties->Size + "\n";
00068
00069     std::for_each(begin(container->Properties), end(container->Properties),
00070         [&properties](IKeyValuePair<String^, Object^>^ prop)
00071     {
00072         properties += prop->Key + ": ";
00073         if (prop->Value != nullptr)
00074         {
00075             properties += prop->Value->ToString();
00076         }
00077         properties += "\n";
00078     });
00079
00080     auto item = ref new ContainerDisplayItem(id, name, properties);
00081
00082     DeviceContainersOutputList->Items->Append(item);
00083 }
00084
00085 /// <summary>
00086 /// Invoked when this page is about to be displayed in a Frame.
00087 /// </summary>
00088 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00089 /// property is typically used to configure the page.</param>
00090 void Containers::OnNavigatedTo(NavigationEventArgs^ e)
00091 {
00092     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00093     // as NotifyUser()
00094     rootPage = MainPage::Current;
00095 }
Generated on Sat Nov 23 2024 16:08:02 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Secondary tiles/C#,C++/PinFromAppbar.xaml.cpp Source File

  • Secondary tiles
  • C#,C++

PinFromAppbar.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 // PinFromAppbar.xaml.cpp
00013 // Implementation of the PinFromAppbar class
00014 //
00015
00016 #include "pch.h"
00017 #include "PinFromAppbar.xaml.h"
00018
00019 using namespace SecondaryTiles;
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::StartScreen;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024 using namespace Windows::UI::StartScreen;
00025 using namespace Windows::Foundation;
00026 using namespace Windows::Globalization;
00027 using namespace Windows::Globalization::DateTimeFormatting;
00028 using namespace Platform;
00029 using namespace concurrency;
00030
00031 PinFromAppbar::PinFromAppbar()
00032 {
00033     InitializeComponent();
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 PinFromAppbar::OnNavigatedTo(NavigationEventArgs^ e)
00042 {
00043     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00044     // as NotifyUser()
00045     rootPage = MainPage::current;
00046     Init();
00047 }
00048
00049 void PinFromAppbar::OnNavigatingFrom(NavigatingCancelEventArgs^ e)
00050 {
00051     if (rightPanel != nullptr)
00052     {
00053         rootPage->BottomAppBar->Opened -= appBarOpenedToken;
00054         pinToAppBar->Click -= buttonClickToken;
00055         rightPanel->Children->Clear();
00056         rightPanel = nullptr;
00057     }
00058 }
00059
00060 void PinFromAppbar::Init()
00061 {
00062     rootPage->NotifyUser("To show the bar swipe up from the bottom of the screen, right-click, or press Windows Logo + z. To dismiss the bar, swipe, right-click, or press Windows Logo + z again.", NotifyType::StatusMessage);
00063     rootPage->BottomAppBar->IsOpen = true;
00064     rightPanel = safe_cast<StackPanel^>(rootPage->BottomAppBar->FindName("RightPanel"));
00065     rootPage->BottomAppBar->IsOpen = false;
00066
00067     if (rightPanel != nullptr)
00068     {
00069         pinToAppBar = ref new Button();
00070         ToggleAppBarButton(!SecondaryTile::Exists(rootPage->appbarTileId));
00071         appBarOpenedToken = rootPage->BottomAppBar->Opened += ref new Windows::Foundation::EventHandler<Object^>(this, &PinFromAppbar::BottomAppBar_Opened);
00072         buttonClickToken = pinToAppBar->Click += ref new RoutedEventHandler(this, &PinFromAppbar::Button_Click);
00073         rightPanel->Children->Append(pinToAppBar);
00074     }
00075 }
00076
00077 // This toggles the Pin and unpin button in the app bar
00078 void PinFromAppbar::ToggleAppBarButton(bool showPinButton)
00079 {
00080     if (pinToAppBar != nullptr)
00081     {
00082         pinToAppBar->Style = (showPinButton) ? (safe_cast<Windows::UI::Xaml::Style^>(Resources->Lookup("PinAppBarButtonStyle"))) : (safe_cast<Windows::UI::Xaml::Style^>(Resources->Lookup("UnpinAppBarButtonStyle")));
00083     }
00084 }
00085
00086 void SecondaryTiles::PinFromAppbar::BottomAppBar_Opened(Platform::Object^ sender, Platform::Object^ e)
00087 {
00088     ToggleAppBarButton(!SecondaryTile::Exists(rootPage->appbarTileId));
00089 }
00090
00091 void SecondaryTiles::PinFromAppbar::Button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00092 {
00093     Button^ button = safe_cast<Button^>(sender);
00094     if (button != nullptr)
00095     {
00096         rootPage->BottomAppBar->IsSticky = true;
00097         // Let us first verify if we need to pin or unpin
00098         if (SecondaryTile::Exists(rootPage->appbarTileId))
00099         {
00100             // First prepare the tile to be unpinned
00101             auto secondaryTile = ref new SecondaryTile(rootPage->appbarTileId);
00102             // Now make the delete request
00103             auto const rect = rootPage->GetElementRect(safe_cast<FrameworkElement^>(sender));
00104             create_task(secondaryTile->RequestDeleteForSelectionAsync(rect, Windows::UI::Popups::Placement::Above)).then([this](bool isUnPinned)
00105             {
00106                 if (isUnPinned)
00107                 {
00108                     rootPage->NotifyUser("Secondary tile successfully unpinned.", NotifyType::StatusMessage);
00109                     ToggleAppBarButton(isUnPinned);
00110                 }
00111                 else
00112                 {
00113                     rootPage->NotifyUser("Secondary tile not unpinned.", NotifyType::ErrorMessage);
00114                 }
00115                 rootPage->BottomAppBar->IsSticky = false;
00116             });
00117         }
00118         else
00119         {
00120             // Prepare package images for use as the Tile Logo and small logo in the tile to be pinned.
00121             // The path provided is a relative path to the package
00122             auto logo = ref new Uri("ms-appx:///Assets/squareTile-sdk.png");
00123             Calendar^ cal = ref new Calendar();
00124             auto longtime = ref new DateTimeFormatter("longtime");
00125             DateTime time = cal->GetDateTime();
00126             bool isPinned = false;
00127
00128             // During creation of secondary tile, an application may set additional arguments on the tile that will be passed in during activation.
00129             // These arguments should be meaningful to the application. In this sample, we will just pass a text as an argument.
00130             String^ tileActivationArguments = rootPage->appbarTileId + " WasPinnedAt=" + longtime->Format(time);
00131
00132             auto secondaryTile = ref new SecondaryTile(rootPage->appbarTileId,
00133                                                        "Secondary tile pinned via AppBar",
00134                                                        "SDK Sample Secondary Tile pinned from AppBar",
00135                                                        tileActivationArguments,
00136                                                        Windows::UI::StartScreen::TileOptions::ShowNameOnLogo,
00137                                                        logo);
00138
00139             // The tile background color is inherited from the parent unless a separate value is specified.
00140             // This operation will over-ride the default.
00141             secondaryTile->ForegroundText = ForegroundText::Dark;
00142
00143             // OK, the tile is created and we can now attempt to pin the tile.
00144             // Note that the status message is updated when the async operation to pin the tile completes.
00145             auto const rect = rootPage->GetElementRect(safe_cast<FrameworkElement^>(sender));
00146             create_task(secondaryTile->RequestCreateForSelectionAsync(rect, Windows::UI::Popups::Placement::Above)).then([this](bool isCreated)
00147             {
00148                 if (isCreated)
00149                 {
00150                     rootPage->NotifyUser("Secondary tile successfully pinned.", NotifyType::StatusMessage);
00151                     ToggleAppBarButton(!isCreated);
00152                 }
00153                 else
00154                 {
00155                     rootPage->NotifyUser("Secondary tile not pinned.", NotifyType::ErrorMessage);
00156                 }
00157                 rootPage->BottomAppBar->IsSticky = false;
00158             });
00159         }
00160     }
00161 }
Generated on Sat Nov 23 2024 16:08:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

InlineImage Member List

This is the complete list of members for InlineImage, including all inherited members.
AddRef() | InlineImage |
baseline | InlineImage | [private]
bitmap | InlineImage | [private]
deviceContext | InlineImage | [private]
Draw(_In_opt_ void *clientDrawingContext, IDWriteTextRenderer *renderer, FLOAT originX, FLOAT originY, BOOL isSideways, BOOL isRightToLeft, IUnknown *clientDrawingEffect) | InlineImage |
GetBreakConditions(_Out_ DWRITE_BREAK_CONDITION *breakConditionBefore, _Out_ DWRITE_BREAK_CONDITION *breakConditionAfter) | InlineImage |
GetMetrics(_Out_ DWRITE_INLINE_OBJECT_METRICS *metrics) | InlineImage |
GetOverhangMetrics(_Out_ DWRITE_OVERHANG_METRICS *overhangs) | InlineImage |
InlineImage(Microsoft::WRL::ComPtr< ID2D1DeviceContext > deviceContext, Microsoft::WRL::ComPtr< IWICImagingFactory > IWICFactory, PCWSTR uri) | InlineImage |
LoadBitmapFromFile(Microsoft::WRL::ComPtr< ID2D1DeviceContext > deviceContext, Microsoft::WRL::ComPtr< IWICImagingFactory > IWICFactory, PCWSTR uri, _Outptr_ ID2D1Bitmap **ppBitmap) | InlineImage | [private]
QueryInterface(IID const &riid, void **ppvObject) | InlineImage |
rect | InlineImage | [private]
refCount | InlineImage | [private]
Release() | InlineImage |
Generated on Sat Nov 23 2024 16:09:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite vertical text/C++/SampleOverlay.h Source File

  • DirectWrite vertical text

SampleOverlay.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 "DirectXSample.h"
00011
00012 // This class is responsible for initializing and rendering the title overlay visible
00013 // at the top of the DirectX SDK samples.
00014 ref class SampleOverlay
00015 {
00016 internal:
00017     SampleOverlay();
00018
00019     void Initialize(
00020         _In_ ID2D1Device*         d2dDevice,
00021         _In_ ID2D1DeviceContext*  d2dContext,
00022         _In_ IWICImagingFactory*  wicFactory,
00023         _In_ IDWriteFactory*      dwriteFactory,
00024         _In_ Platform::String^    caption
00025         );
00026
00027     void ResetDirectXResources();
00028
00029     void UpdateForWindowSizeChange();
00030
00031     void Render();
00032
00033     float GetTitleHeightInDips();
00034
00035 private:
00036
00037     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00038     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00039     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00040     Microsoft::WRL::ComPtr<IDWriteFactory>          m_dwriteFactory;
00041     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_whiteBrush;
00042     Microsoft::WRL::ComPtr<ID2D1DrawingStateBlock>  m_stateBlock;
00043
00044     Microsoft::WRL::ComPtr<IWICImagingFactory>      m_wicFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Bitmap>             m_logoBitmap;
00046     Microsoft::WRL::ComPtr<IDWriteTextLayout>       m_textLayout;
00047
00048     UINT                                            m_idIncrement;
00049     bool                                            m_drawOverlay;
00050     Platform::String^                               m_sampleName;
00051     float                                           m_padding;
00052     float                                           m_textVerticalOffset;
00053     D2D1_SIZE_F                                     m_logoSize;
00054     float                                           m_overlayWidth;
00055 };
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D and DirectWrite animated text on a path/C++/pch.h Source File

  • Direct2D and DirectWrite animated text on a path

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 <d3d11_1.h>
00012 #include <d2d1_1.h>
00013 #include <d2d1effects.h>
00014 #include <d2d1_1helper.h>
00015 #include <dwrite_1.h>
00016 #include <wincodec.h>
00017 #include <math.h>
00018 #include <agile.h>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Audio Session (WASAPI)/C++/Scenario2.xaml.cpp Source File

  • Windows Audio Session (WASAPI)
  • C++

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 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::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::Navigation;
00030
00031
00032 Scenario2::Scenario2() :
00033     m_IsMFLoaded( false ),
00034     m_ContentStream( nullptr ),
00035     m_StateChangedEvent( nullptr ),
00036     m_spRenderer( nullptr ),
00037     m_ContentType( ContentType::ContentTypeTone )
00038 {
00039     InitializeComponent();
00040
00041     // Initialize MF
00042     HRESULT hr = MFStartup( MF_VERSION, MFSTARTUP_LITE );
00043     if (SUCCEEDED( hr ))
00044     {
00045         m_IsMFLoaded = true;
00046     }
00047     else
00048     {
00049         ThrowIfFailed( hr );
00050     }
00051
00052     m_CoreDispatcher = CoreWindow::GetForCurrentThread()->Dispatcher;
00053
00054     // Register for Media Transport controls.  This is required to support background
00055     // audio scenarios.
00056     m_MediaControlPlayToken = MediaControl::PlayPressed += ref new Windows::Foundation::EventHandler<Object^>( this, &Scenario2::StartDevice );
00057     m_MediaControlPauseToken = MediaControl::PausePressed += ref new Windows::Foundation::EventHandler<Object^>( this, &Scenario2::PauseDevice );
00058     m_MediaControlStopToken = MediaControl::StopPressed += ref new Windows::Foundation::EventHandler<Object^>( this, &Scenario2::StopDevice );
00059     m_MediaControlPlayPauseToken = MediaControl::PlayPauseTogglePressed += ref new Windows::Foundation::EventHandler<Object^>( this, &Scenario2::PlayPauseToggle );
00060 }
00061
00062 Scenario2::~Scenario2()
00063 {
00064     MediaControl::PlayPressed -= m_MediaControlPlayToken;
00065     MediaControl::PausePressed -= m_MediaControlPauseToken;
00066     MediaControl::StopPressed -= m_MediaControlStopToken;
00067     MediaControl::PlayPauseTogglePressed -= m_MediaControlPlayPauseToken;
00068
00069     if (m_deviceStateChangeToken.Value != 0)
00070     {
00071         m_StateChangedEvent->StateChangedEvent -= m_deviceStateChangeToken;
00072
00073         m_StateChangedEvent = nullptr;
00074         m_deviceStateChangeToken.Value = 0;
00075     }
00076
00077     // Uninitialize MF
00078     if (m_IsMFLoaded)
00079     {
00080         MFShutdown();
00081         m_IsMFLoaded = false;
00082     }
00083 }
00084
00085 /// <summary>
00086 /// Invoked when this page is about to be displayed in a Frame.
00087 /// </summary>
00088 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00089 /// property is typically used to configure the page.</param>
00090 void Scenario2::OnNavigatedTo(NavigationEventArgs^ e)
00091 {
00092     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00093     // as NotifyUser()
00094     rootPage = MainPage::Current;
00095     UpdateContentUI( false );
00096 }
00097
00098 /// <summary>
00099 /// Invoked when about to leave this page.
00100 /// </summary>
00101 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00102 /// property is typically used to configure the page.</param>
00103 void Scenario2::OnNavigatedFrom(NavigationEventArgs^ e)
00104 {
00105     if (nullptr != m_StateChangedEvent)
00106     {
00107         DeviceState deviceState = m_StateChangedEvent->GetState();
00108
00109         if (deviceState == DeviceState::DeviceStatePlaying)
00110         {
00111             StopDevice( this, e );
00112         }
00113     }
00114 }
00115
00116 #pragma region UI Related Code
00117 void Scenario2::ShowStatusMessage( Platform::String^ str, NotifyType messageType )
00118 {
00119     m_CoreDispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler(
00120         [this, str, messageType]()
00121     {
00122         rootPage->NotifyUser( str, messageType );
00123     }));
00124 }
00125
00126 // Updates content controls based on selected option
00127 void Scenario2::UpdateContentUI( Platform::Boolean disableAll )
00128 {
00129     if ( (nullptr != btnFilePicker) &&
00130          (nullptr != sliderFrequency) )
00131     {
00132         if (disableAll)
00133         {
00134             btnFilePicker->IsEnabled = false;
00135             sliderFrequency->IsEnabled = false;
00136             radioFile->IsEnabled = false;
00137             radioTone->IsEnabled = false;
00138         }
00139         else
00140         {
00141             radioFile->IsEnabled = true;
00142             radioTone->IsEnabled = true;
00143
00144             switch ( m_ContentType )
00145             {
00146             case ContentType::ContentTypeTone:
00147                 btnFilePicker->IsEnabled = false;
00148                 sliderFrequency->IsEnabled = true;
00149                 UpdateContentProps( sliderFrequency->Value.ToString() + " Hz" );
00150                 break;
00151
00152             case ContentType::ContentTypeFile:
00153                 btnFilePicker->IsEnabled = true;
00154                 sliderFrequency->IsEnabled = false;
00155                 break;
00156
00157             default:
00158                 break;
00159             }
00160         }
00161     }
00162 }
00163
00164 // Updates transport controls based on current playstate
00165 void Scenario2::UpdateMediaControlUI( DeviceState deviceState )
00166 {
00167     switch( deviceState )
00168     {
00169     case DeviceState::DeviceStatePlaying:
00170         btnPlay->IsEnabled = false;
00171         btnStop->IsEnabled = true;
00172         btnPlayPause->IsEnabled = true;
00173         btnPause->IsEnabled = true;
00174         break;
00175
00176     case DeviceState::DeviceStateStopped:
00177     case DeviceState::DeviceStateInError:
00178         btnPlay->IsEnabled = true;
00179         btnStop->IsEnabled = false;
00180         btnPlayPause->IsEnabled = true;
00181         btnPause->IsEnabled = false;
00182
00183         UpdateContentUI( false );
00184         break;
00185
00186     case DeviceState::DeviceStatePaused:
00187         btnPlay->IsEnabled = true;
00188         btnStop->IsEnabled = true;
00189         btnPlayPause->IsEnabled = true;
00190         btnPause->IsEnabled = false;
00191         break;
00192
00193     case DeviceState::DeviceStateStarting:
00194     case DeviceState::DeviceStateStopping:
00195         btnPlay->IsEnabled = false;
00196         btnStop->IsEnabled = false;
00197         btnPlayPause->IsEnabled = false;
00198         btnPause->IsEnabled = false;
00199
00200         UpdateContentUI( true );
00201         break;
00202     }
00203 }
00204
00205 // Updates textbox on UI thread
00206 void Scenario2::UpdateContentProps( String^ str )
00207 {
00208     String^ text = str;
00209
00210     if (nullptr != txtContentProps)
00211     {
00212         // The event handler may be invoked on a background thread, so use the Dispatcher to invoke the UI-related code on the UI thread.
00213         txtContentProps->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler(
00214             [this, text]()
00215         {
00216             Windows::UI::Xaml::Media::SolidColorBrush ^brush;
00217             txtContentProps->Text = text;
00218
00219             if ( ("" == text) && (m_ContentType == ContentType::ContentTypeFile) )
00220             {
00221                 brush = ref new Windows::UI::Xaml::Media::SolidColorBrush( Windows::UI::ColorHelper::FromArgb( 0xCC, 0xFF, 0x00, 0x00 ) );
00222             }
00223             else
00224             {
00225                 brush = ref new Windows::UI::Xaml::Media::SolidColorBrush( Windows::UI::ColorHelper::FromArgb( 0xFF, 0xFF, 0xFF, 0xFF ) );
00226             }
00227
00228             txtContentProps->Background = brush;
00229         }));
00230     }
00231 }
00232
00233 #pragma endregion
00234
00235 #pragma region UI Event Handlers
00236 void Scenario2::sliderFrequency_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e)
00237 {
00238     Slider^ s = safe_cast<Slider^>(sender);
00239     if (s != nullptr)
00240     {
00241         UpdateContentProps( s->Value.ToString() + " Hz" );
00242     }
00243 }
00244
00245 void Scenario2::sliderVolume_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e)
00246 {
00247     Slider^ s = safe_cast<Slider^>(sender);
00248     if (s != nullptr)
00249     {
00250         OnSetVolume( static_cast<UINT32>( s->Value ) );
00251     }
00252 }
00253
00254 void Scenario2::radioTone_Checked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00255 {
00256     m_ContentType = ContentType::ContentTypeTone;
00257     UpdateContentProps( "" );
00258     m_ContentStream = nullptr;
00259     UpdateContentUI( false );
00260 }
00261
00262 void Scenario2::radioFile_Checked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00263 {
00264     m_ContentType = ContentType::ContentTypeFile;
00265     UpdateContentProps( "" );
00266     m_ContentStream = nullptr;
00267     UpdateContentUI( false );
00268 }
00269
00270 void Scenario2::btnPlay_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00271 {
00272     StartDevice( sender, e );
00273 }
00274
00275 void Scenario2::btnPause_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00276 {
00277     PauseDevice( sender, e );
00278 }
00279
00280 void Scenario2::btnPlayPause_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00281 {
00282     PlayPauseToggle( sender, e );
00283 }
00284
00285 void Scenario2::btnStop_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00286 {
00287     StopDevice( sender, e );
00288 }
00289
00290 void Scenario2::btnFilePicker_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00291 {
00292     OnPickFileAsync();
00293 }
00294
00295 #pragma endregion
00296
00297 // Event callback from WASAPI renderer for changes in device state
00298 void Scenario2::OnDeviceStateChange( Object^ sender, DeviceStateChangedEventArgs^ e )
00299 {
00300     // Update Control Buttons
00301     m_CoreDispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler(
00302         [this, e]()
00303     {
00304         UpdateMediaControlUI( e->State );
00305     }));
00306
00307     // Handle state specific messages
00308     switch( e->State )
00309     {
00310     case DeviceState::DeviceStateInitialized:
00311         StartDevice( sender, e );
00312         break;
00313
00314     case DeviceState::DeviceStatePlaying:
00315         ShowStatusMessage( "Playback Started", NotifyType::StatusMessage );
00316         break;
00317
00318     case DeviceState::DeviceStatePaused:
00319         ShowStatusMessage( "Playback Paused", NotifyType::StatusMessage );
00320         break;
00321
00322     case DeviceState::DeviceStateStopped:
00323         m_spRenderer = nullptr;
00324
00325         if (m_deviceStateChangeToken.Value != 0)
00326         {
00327             m_StateChangedEvent->StateChangedEvent -= m_deviceStateChangeToken;
00328             m_StateChangedEvent = nullptr;
00329             m_deviceStateChangeToken.Value = 0;
00330         }
00331
00332         ShowStatusMessage( "Playback Stopped", NotifyType::StatusMessage );
00333         break;
00334
00335     case DeviceState::DeviceStateInError:
00336         HRESULT hr = e->hr;
00337
00338         if (m_deviceStateChangeToken.Value != 0)
00339         {
00340             m_StateChangedEvent->StateChangedEvent -= m_deviceStateChangeToken;
00341             m_StateChangedEvent = nullptr;
00342             m_deviceStateChangeToken.Value = 0;
00343         }
00344
00345         m_spRenderer = nullptr;
00346
00347         wchar_t hrVal[11];
00348         swprintf_s( hrVal, 11, L"0x%08x\0", hr );
00349         String^ strHRVal = ref new String( hrVal );
00350
00351         String^ strMessage = "";
00352
00353         // Specifically handle a couple of known errors
00354         switch( hr )
00355         {
00356         case AUDCLNT_E_ENDPOINT_OFFLOAD_NOT_CAPABLE:
00357             strMessage = "ERROR: Endpoint Does Not Support HW Offload (" + strHRVal + ")";
00358             ShowStatusMessage( strMessage, NotifyType::ErrorMessage );
00359             break;
00360
00361         case AUDCLNT_E_RESOURCES_INVALIDATED:
00362             strMessage = "ERROR: Endpoint Lost Access To Resources (" + strHRVal + ")";
00363             ShowStatusMessage( strMessage, NotifyType::ErrorMessage );
00364             break;
00365
00366         default:
00367             strMessage = "ERROR: " + strHRVal + " has occurred.";
00368             ShowStatusMessage( strMessage, NotifyType::ErrorMessage );
00369         }
00370     }
00371 }
00372
00373 //
00374 //  OnPickFileAsync()
00375 //
00376 //  File chooser for MF Source playback.  Retrieves a pointer to IRandomAccessStream
00377 //
00378 void Scenario2::OnPickFileAsync()
00379 {
00380     Pickers::FileOpenPicker^ filePicker = ref new Pickers::FileOpenPicker();
00381     filePicker->ViewMode = Pickers::PickerViewMode::List;
00382     filePicker->SuggestedStartLocation = Pickers::PickerLocationId::MusicLibrary;
00383     filePicker->FileTypeFilter->Append(".wav");
00384     filePicker->FileTypeFilter->Append(".mp3");
00385     filePicker->FileTypeFilter->Append(".wma");
00386
00387     concurrency::create_task(filePicker->PickSingleFileAsync()).then(
00388         [this]( Windows::Storage::StorageFile^ file )
00389     {
00390         if (nullptr != file)
00391         {
00392             // Open the stream
00393             concurrency::create_task(file->OpenAsync(FileAccessMode::Read)).then(
00394                 [this, file]( IRandomAccessStream^ stream )
00395             {
00396                 if (stream != nullptr)
00397                 {
00398                     m_ContentStream = stream;
00399                     UpdateContentProps( file->Path );
00400                 }
00401             });
00402         }
00403     });
00404 }
00405
00406 //
00407 //  OnSetVolume()
00408 //
00409 //  Updates the session volume
00410 //
00411 void Scenario2::OnSetVolume( UINT32 volume)
00412 {
00413     if (m_spRenderer)
00414     {
00415         // Updates the Session volume on the AudioClient
00416         m_spRenderer->SetVolumeOnSession( volume );
00417     }
00418 }
00419
00420 //
00421 //  InitializeDevice()
00422 //
00423 //  Sets up a new instance of the WASAPI renderer
00424 //
00425 void Scenario2::InitializeDevice()
00426 {
00427     HRESULT hr = S_OK;
00428
00429     if (!m_spRenderer)
00430     {
00431         // Create a new WASAPI instance
00432         m_spRenderer = Make<WASAPIRenderer>();
00433
00434         if (nullptr == m_spRenderer)
00435         {
00436             OnDeviceStateChange( this, ref new DeviceStateChangedEventArgs( DeviceState::DeviceStateInError, E_OUTOFMEMORY ));
00437             return;
00438         }
00439
00440         // Get a pointer to the device event interface
00441         m_StateChangedEvent = m_spRenderer->GetDeviceStateEvent();
00442
00443         if (nullptr == m_StateChangedEvent)
00444         {
00445             OnDeviceStateChange( this, ref new DeviceStateChangedEventArgs( DeviceState::DeviceStateInError, E_FAIL ));
00446             return;
00447         }
00448
00449         // Register for events
00450         m_deviceStateChangeToken = m_StateChangedEvent->StateChangedEvent += ref new DeviceStateChangedHandler( this, &Scenario2::OnDeviceStateChange );
00451
00452         // Configure user based properties
00453         DEVICEPROPS props;
00454         int BufferSize = 0;
00455         swscanf_s( txtHWBuffer->Text->Data(), L"%d", &BufferSize );
00456
00457         switch( m_ContentType )
00458         {
00459         case ContentType::ContentTypeTone:
00460             props.IsTonePlayback = true;
00461             props.Frequency = static_cast<DWORD>(sliderFrequency->Value);
00462             break;
00463
00464         case ContentType::ContentTypeFile:
00465             props.IsTonePlayback = false;
00466             props.ContentStream = m_ContentStream;
00467             break;
00468         }
00469
00470         props.IsHWOffload = static_cast<Platform::Boolean>(toggleHWOffload->IsOn);
00471         props.IsBackground = static_cast<Platform::Boolean>(toggleBackgroundAudio->IsOn);
00472         props.hnsBufferDuration = static_cast<REFERENCE_TIME>(BufferSize);
00473
00474         m_spRenderer->SetProperties( props );
00475
00476         // Selects the Default Audio Device
00477         m_spRenderer->InitializeAudioDeviceAsync();
00478     }
00479 }
00480
00481 //
00482 //  StartDevice()
00483 //
00484 void Scenario2::StartDevice( Platform::Object^ sender, Object^ e )
00485 {
00486     if (nullptr == m_spRenderer)
00487     {
00488         // Call from main UI thread
00489         InitializeDevice();
00490     }
00491     else
00492     {
00493         // Starts a work item to begin playback, likely in the paused state
00494         m_spRenderer->StartPlaybackAsync();
00495     }
00496 }
00497
00498 //
00499 //  StopDevice()
00500 //
00501 void Scenario2::StopDevice( Platform::Object^ sender, Object^ e )
00502 {
00503     if (m_spRenderer)
00504     {
00505         // Set the event to stop playback
00506         m_spRenderer->StopPlaybackAsync();
00507     }
00508 }
00509
00510 //
00511 //  PauseDevice()
00512 //
00513 void Scenario2::PauseDevice( Platform::Object^ sender, Object^ e )
00514 {
00515     if (m_spRenderer)
00516     {
00517         DeviceState deviceState = m_StateChangedEvent->GetState();
00518
00519         if (deviceState == DeviceState::DeviceStatePlaying)
00520         {
00521             // Starts a work item to pause playback
00522             m_spRenderer->PausePlaybackAsync();
00523         }
00524     }
00525 }
00526
00527 //
00528 //  PlayPauseToggle()
00529 //
00530 //  Handles the Play / Pause media transport control
00531 //
00532 void Scenario2::PlayPauseToggle( Platform::Object^ sender, Object^ e )
00533 {
00534     if (m_spRenderer)
00535     {
00536         DeviceState deviceState = m_StateChangedEvent->GetState();
00537
00538         if (deviceState == DeviceState::DeviceStatePlaying)
00539         {
00540             // Starts a work item to pause playback
00541             m_spRenderer->PausePlaybackAsync();
00542         }
00543         else if (deviceState == DeviceState::DeviceStatePaused)
00544         {
00545             // Starts a work item to pause playback
00546             m_spRenderer->StartPlaybackAsync();
00547         }
00548     }
00549     else
00550     {
00551         StartDevice( sender, e );
00552     }
00553 }
00554
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Edge gesture invocation/C++/CppSamplesUtils.h Source File

  • Edge gesture invocation

CppSamplesUtils.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 <string>
00014 #include <sstream>
00015 #include <algorithm>
00016 #include <collection.h>
00017 #include <ppltasks.h>
00018
00019 namespace CppSamplesUtils
00020 {
00021     namespace Details
00022     {
00023         static Windows::Foundation::Collections::PropertySet^ sessionState = nullptr;
00024         static Platform::String^ sessionStateFileName = ref new Platform::String(L"_cppSessionState.xml");
00025
00026         concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file);
00027         concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file);
00028     }
00029
00030     class SuspensionManager
00031     {
00032     public:
00033         static Windows::Foundation::Collections::PropertySet^ SessionState()
00034         {
00035             using namespace Windows::Foundation::Collections;
00036             using namespace Details;
00037
00038             if (sessionState == nullptr)
00039             {
00040                 sessionState = ref new PropertySet();
00041             }
00042             return sessionState;
00043         }
00044
00045         static concurrency::task<void> StartRestoreTask()
00046         {
00047             using namespace Windows::Foundation;
00048             using namespace Windows::Storage;
00049             using namespace Windows::Storage::Streams;
00050             using namespace Details;
00051
00052             auto state = SessionState();
00053             state->Clear();
00054
00055             concurrency::task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFileName));
00056             return getFileTask.then([=](StorageFile^ file)
00057             {
00058                 return DeserializeSessionState(file);
00059             });
00060         }
00061
00062         static concurrency::task<void> StartSaveTask()
00063         {
00064             using namespace Windows::Foundation;
00065             using namespace Windows::Storage;
00066             using namespace Windows::Storage::Streams;
00067             using namespace Details;
00068
00069             concurrency::task<StorageFile^> createFileTask(ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFileName, CreationCollisionOption::ReplaceExisting));
00070             return createFileTask.then([=](StorageFile^ file)
00071             {
00072                 return SerializeSessionState(file);
00073             });
00074         }
00075     };
00076
00077     namespace Details
00078     {
00079         template <class T>
00080         inline Platform::String^ ToString(T value)
00081         {
00082             std::wstringstream wss;
00083             wss << value;
00084             return ref new Platform::String(wss.str().c_str());
00085         }
00086
00087         template <class T>
00088         inline T FromStringTo(Platform::String^ str)
00089         {
00090             std::wistringstream wiss(str->Data());
00091             T value = 0;
00092             wiss >> value;
00093             return value;
00094         }
00095
00096         template <class T>
00097         inline T FromHexStringTo(Platform::String^ str)
00098         {
00099             std::wistringstream wiss(str->Data());
00100             T value = 0;
00101             wiss >> std::hex >> value;
00102             return value;
00103         }
00104
00105         template <>
00106         inline Platform::Guid FromStringTo<Platform::Guid>(Platform::String^ str)
00107         {
00108             using namespace Platform;
00109
00110             if (str->Length() != 38)
00111             {
00112                 throw ref new InvalidArgumentException;
00113             }
00114             std::wstring ws(str->Data());
00115             if (ws[0] != L'{' || ws[37] != L'}' || ws[9] != L'-' || ws[14] != L'-' || ws[19] != L'-' || ws[24] != L'-')
00116             {
00117                 throw ref new InvalidArgumentException;
00118             }
00119             ws[0] = ws[37] = ws[9] = ws[14] = ws[19] =ws[24] = L' ';
00120             std::wistringstream wiss(ws);
00121             unsigned int a = 0;
00122             unsigned short b = 0;
00123             unsigned short c = 0;
00124             unsigned short d = 0;
00125             unsigned long long e = 0;
00126             static_assert(sizeof(d) == sizeof(char) * 2, "sizeof(d) == sizeof(char) * 2");
00127             static_assert(sizeof(e) == sizeof(char) * 8, "sizeof(e) == sizeof(char) * 8");
00128             wiss >> std::hex >> a >> b >> c >> d >> e;
00129             unsigned char *ad = (unsigned char*)(&d);
00130             unsigned char *ae = (unsigned char*)(&e);
00131             return Platform::Guid(a, b, c, ad[1], ad[0], ae[5], ae[4], ae[3], ae[2], ae[1], ae[0]);
00132         }
00133
00134         inline Platform::Object^ ConvertStringToObject(Windows::Foundation::PropertyType type, Platform::String^ str)
00135         {
00136             using namespace Platform;
00137             using namespace Windows::Foundation;
00138
00139             if (type == PropertyType::String)
00140             {
00141                 return PropertyValue::CreateString(str);
00142             }
00143
00144             switch (type)
00145             {
00146             case PropertyType::UInt8:
00147                 return PropertyValue::CreateUInt8((unsigned char)FromStringTo<unsigned short>(str));
00148             case PropertyType::UInt16:
00149                 return PropertyValue::CreateUInt16(FromStringTo<unsigned short>(str));
00150             case PropertyType::UInt32:
00151                 return PropertyValue::CreateUInt32(FromStringTo<unsigned int>(str));
00152             case PropertyType::UInt64:
00153                 return PropertyValue::CreateUInt64(FromStringTo<unsigned long long>(str));
00154             case PropertyType::Int16:
00155                 return PropertyValue::CreateInt16(FromStringTo<short>(str));
00156             case PropertyType::Int32:
00157                 return PropertyValue::CreateInt32(FromStringTo<int>(str));
00158             case PropertyType::Int64:
00159                 return PropertyValue::CreateInt64(FromStringTo<long long>(str));
00160             case PropertyType::Single:
00161                 return PropertyValue::CreateSingle(FromStringTo<float>(str));
00162             case PropertyType::Double:
00163                 return PropertyValue::CreateDouble(FromStringTo<double>(str));
00164             case PropertyType::Boolean:
00165                 return PropertyValue::CreateBoolean(FromStringTo<bool>(str));
00166             case PropertyType::Char16:
00167                 return PropertyValue::CreateChar16(str->Data()[0]);
00168             case PropertyType::Guid:
00169                 return PropertyValue::CreateGuid(FromStringTo<Guid>(str));
00170             default:
00171                 throw ref new Platform::InvalidCastException;
00172             }
00173         }
00174
00175         inline Platform::String^ ConvertPropertyValueToString(Windows::Foundation::IPropertyValue^ pv)
00176         {
00177             using namespace Platform;
00178             using namespace Windows::Foundation;
00179
00180             String^ valueString;
00181
00182             switch (pv->Type)
00183             {
00184             case PropertyType::String:
00185                 valueString = pv->GetString();
00186                 break;
00187
00188             case PropertyType::UInt8:
00189             case PropertyType::UInt16:
00190             case PropertyType::UInt32:
00191             case PropertyType::UInt64:
00192                 valueString = ToString(pv->GetUInt64());
00193                 break;
00194
00195             case PropertyType::Int16:
00196             case PropertyType::Int32:
00197             case PropertyType::Int64:
00198                 valueString = ToString(pv->GetInt64());
00199                 break;
00200
00201             case PropertyType::Single:
00202                 valueString = ToString(pv->GetSingle());
00203                 break;
00204
00205             case PropertyType::Double:
00206                 valueString = ToString(pv->GetDouble());
00207                 break;
00208
00209             case PropertyType::Boolean:
00210                 valueString = ToString(pv->GetBoolean());
00211                 break;
00212
00213             case PropertyType::Char16:
00214                 wchar_t buffer[2];
00215                 buffer[0] = pv->GetChar16();
00216                 buffer[1] = 0;
00217                 valueString = ref new String(buffer);
00218                 break;
00219
00220             case PropertyType::Guid:
00221                 valueString = pv->GetGuid().ToString();
00222                 break;
00223
00224             default:
00225                 throw ref new InvalidCastException;
00226             }
00227
00228             return valueString;
00229         }
00230
00231         inline Windows::Data::Xml::Dom::XmlElement^ CreateXmlElementFromObject(Windows::Data::Xml::Dom::XmlDocument^ doc, Platform::String^ name, Platform::Object^ value)
00232         {
00233             using namespace Platform;
00234             using namespace Windows::Foundation;
00235             using namespace Windows::Data::Xml::Dom;
00236
00237             XmlElement^ element = doc->CreateElement("item");
00238             element->SetAttribute("name", name);
00239
00240             IPropertyValue^ pv = (IPropertyValue^)value;
00241             element->SetAttribute("type", ToString((int)pv->Type));
00242             element->SetAttribute("value", ConvertPropertyValueToString(pv));
00243
00244             return element;
00245         }
00246
00247         inline concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file)
00248         {
00249             using namespace Windows::Data::Xml::Dom;
00250             using namespace Windows::Foundation;
00251             namespace WFC = Windows::Foundation::Collections;
00252             typedef Windows::Foundation::Collections::IKeyValuePair<Platform::String^, Platform::Object^> KVPair;
00253
00254             XmlDocument^ doc = ref new XmlDocument;
00255             doc->AppendChild(doc->CreateElement("items"));
00256             auto sessionState = SuspensionManager::SessionState();
00257
00258             std::for_each(WFC::begin(sessionState), WFC::end(sessionState), [doc](KVPair^ item)
00259             {
00260                 doc->DocumentElement->AppendChild(CreateXmlElementFromObject(doc, item->Key, item->Value));
00261             });
00262
00263             return concurrency::task<void>(doc->SaveToFileAsync(file));
00264         }
00265
00266         inline Windows::Foundation::PropertyType PropertyTypeFromString(Platform::String^ str)
00267         {
00268             int value = FromStringTo<int>(str);
00269             return (Windows::Foundation::PropertyType)value;
00270         }
00271
00272         inline concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file)
00273         {
00274             using namespace Platform;
00275             using namespace Windows::Foundation;
00276             using namespace Windows::Data::Xml::Dom;
00277             namespace WFC = Windows::Foundation::Collections;
00278
00279             concurrency::task<XmlDocument^> loadFileTask(XmlDocument::LoadFromFileAsync(file));
00280             return loadFileTask.then([=](concurrency::task<XmlDocument^> docTask)
00281             {
00282                 try
00283                 {
00284                     auto doc = docTask.get();
00285                     auto items = doc->SelectNodes("/items/item");
00286                     auto sessionState = SuspensionManager::SessionState();
00287
00288                     std::for_each(WFC::begin(items), WFC::end(items), [sessionState](IXmlNode^ node)
00289                     {
00290                         auto element = (IXmlElement^)node;
00291                         String^ name = element->GetAttribute("name");
00292                         String^ value = element->GetAttribute("value");
00293                         PropertyType type = PropertyTypeFromString(element->GetAttribute("type"));
00294
00295                         Object^ valueObject = ConvertStringToObject(type, value);
00296                         sessionState->Insert(name, valueObject);
00297                     });
00298
00299                 }
00300                 catch (Platform::Exception^)
00301                 {
00302                     // Restoring is best effort
00303                 }
00304             });
00305         }
00306     } // namespace Details
00307 } // namespace CppSamplesUtils
Generated on Sat Nov 23 2024 16:07:53 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Lock screen apps/C#,C++/NotificationsExtensions/TileContent.cs Source File

  • Lock screen apps
  • C#,C++
  • NotificationsExtensions

TileContent.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 System;
00009 using System.Text;
00010 #if !WINRT_NOT_PRESENT
00011 using Windows.Data.Xml.Dom;
00012 using Windows.UI.Notifications;
00013 #endif
00014
00015 namespace NotificationsExtensions.TileContent
00016 {
00017     internal abstract class TileNotificationBase : NotificationBase
00018     {
00019         public TileNotificationBase(string templateName, int imageCount, int textCount) : base(templateName, imageCount, textCount)
00020         {
00021         }
00022
00023         public TileBranding Branding
00024         {
00025             get { return m_Branding; }
00026             set
00027             {
00028                 if (!Enum.IsDefined(typeof(TileBranding), value))
00029                 {
00030                     throw new ArgumentOutOfRangeException("value");
00031                 }
00032                 m_Branding = value;
00033             }
00034         }
00035
00036 #if !WINRT_NOT_PRESENT
00037         public TileNotification CreateNotification()
00038         {
00039             XmlDocument xmlDoc = new XmlDocument();
00040             xmlDoc.LoadXml(GetContent());
00041             return new TileNotification(xmlDoc);
00042         }
00043 #endif
00044
00045         private TileBranding m_Branding = TileBranding.Logo;
00046     }
00047
00048     internal interface ISquareTileInternal
00049     {
00050         string SerializeBinding(string globalLang, string globalBaseUri, TileBranding globalBranding, bool globalAddImageQuery);
00051     }
00052
00053     internal class TileSquareBase : TileNotificationBase, ISquareTileInternal
00054     {
00055         public TileSquareBase(string templateName, int imageCount, int textCount) : base(templateName, imageCount, textCount)
00056         {
00057         }
00058
00059         public override string GetContent()
00060         {
00061             StringBuilder builder = new StringBuilder(String.Empty);
00062             builder.AppendFormat("<tile><visual version='{0}'", Util.NOTIFICATION_CONTENT_VERSION);
00063             if (!String.IsNullOrWhiteSpace(Lang))
00064             {
00065                 builder.AppendFormat(" lang='{0}'", Util.HttpEncode(Lang));
00066             }
00067             if (Branding != TileBranding.Logo)
00068             {
00069                 builder.AppendFormat(" branding='{0}'", Branding.ToString().ToLowerInvariant());
00070             }
00071             if (!String.IsNullOrWhiteSpace(BaseUri))
00072             {
00073                 builder.AppendFormat(" baseUri='{0}'", Util.HttpEncode(BaseUri));
00074             }
00075             if (AddImageQuery)
00076             {
00077                 builder.AppendFormat(" addImageQuery='true'");
00078             }
00079             builder.Append(">");
00080             builder.Append(SerializeBinding(Lang, BaseUri, Branding, AddImageQuery));
00081             builder.Append("</visual></tile>");
00082             return builder.ToString();
00083         }
00084
00085         public string SerializeBinding(string globalLang, string globalBaseUri, TileBranding globalBranding, bool globalAddImageQuery)
00086         {
00087             StringBuilder bindingNode = new StringBuilder(String.Empty);
00088             bindingNode.AppendFormat("<binding template='{0}'", TemplateName);
00089             if (!String.IsNullOrWhiteSpace(Lang) && !Lang.Equals(globalLang))
00090             {
00091                 bindingNode.AppendFormat(" lang='{0}'", Util.HttpEncode(Lang));
00092                 globalLang = Lang;
00093             }
00094             if (Branding != TileBranding.Logo && Branding != globalBranding)
00095             {
00096                 bindingNode.AppendFormat(" branding='{0}'", Branding.ToString().ToLowerInvariant());
00097             }
00098             if (!String.IsNullOrWhiteSpace(BaseUri) && !BaseUri.Equals(globalBaseUri))
00099             {
00100                 bindingNode.AppendFormat(" baseUri='{0}'", Util.HttpEncode(BaseUri));
00101                 globalBaseUri = BaseUri;
00102             }
00103             if (AddImageQueryNullable != null && AddImageQueryNullable != globalAddImageQuery)
00104             {
00105                 bindingNode.AppendFormat(" addImageQuery='{0}'", AddImageQuery.ToString().ToLowerInvariant());
00106                 globalAddImageQuery = AddImageQuery;
00107             }
00108             bindingNode.AppendFormat(">{0}</binding>", SerializeProperties(globalLang, globalBaseUri, globalAddImageQuery));
00109
00110             return bindingNode.ToString();
00111         }
00112     }
00113
00114     internal class TileWideBase : TileNotificationBase
00115     {
00116         public TileWideBase(string templateName, int imageCount, int textCount) : base(templateName, imageCount, textCount)
00117         {
00118         }
00119
00120         public ISquareTileNotificationContent SquareContent
00121         {
00122             get { return m_SquareContent; }
00123             set { m_SquareContent = value; }
00124         }
00125
00126         public bool RequireSquareContent
00127         {
00128             get { return m_RequireSquareContent; }
00129             set { m_RequireSquareContent = value; }
00130         }
00131
00132         public override string GetContent()
00133         {
00134             if (RequireSquareContent && SquareContent == null)
00135             {
00136                 throw new NotificationContentValidationException(
00137                     "Square tile content should be included with each wide tile. " +
00138                     "If this behavior is undesired, use the RequireSquareContent property.");
00139             }
00140
00141             StringBuilder visualNode = new StringBuilder(String.Empty);
00142             visualNode.AppendFormat("<visual version='{0}'", Util.NOTIFICATION_CONTENT_VERSION);
00143             if (!String.IsNullOrWhiteSpace(Lang))
00144             {
00145                 visualNode.AppendFormat(" lang='{0}'", Util.HttpEncode(Lang));
00146             }
00147             if (Branding != TileBranding.Logo)
00148             {
00149                 visualNode.AppendFormat(" branding='{0}'", Branding.ToString().ToLowerInvariant());
00150             }
00151             if (!String.IsNullOrWhiteSpace(BaseUri))
00152             {
00153                 visualNode.AppendFormat(" baseUri='{0}'", Util.HttpEncode(BaseUri));
00154             }
00155             if (AddImageQuery)
00156             {
00157                 visualNode.AppendFormat(" addImageQuery='true'");
00158             }
00159             visualNode.Append(">");
00160
00161             StringBuilder builder = new StringBuilder(String.Empty);
00162             builder.AppendFormat("<tile>{0}<binding template='{1}'>{2}</binding>", visualNode, TemplateName, SerializeProperties(Lang, BaseUri, AddImageQuery));
00163             if (SquareContent != null)
00164             {
00165                 ISquareTileInternal squareBase = SquareContent as ISquareTileInternal;
00166                 if (squareBase == null)
00167                 {
00168                     throw new NotificationContentValidationException("The provided square tile content class is unsupported.");
00169                 }
00170                 builder.Append(squareBase.SerializeBinding(Lang, BaseUri, Branding, AddImageQuery));
00171             }
00172             builder.Append("</visual></tile>");
00173
00174             return builder.ToString();
00175         }
00176
00177         private ISquareTileNotificationContent m_SquareContent = null;
00178         private bool m_RequireSquareContent = true;
00179     }
00180
00181     internal class TileSquareBlock : TileSquareBase, ITileSquareBlock
00182     {
00183         public TileSquareBlock() : base(templateName: "TileSquareBlock", imageCount: 0, textCount: 2)
00184         {
00185         }
00186
00187         public INotificationContentText TextBlock { get { return TextFields[0]; } }
00188         public INotificationContentText TextSubBlock { get { return TextFields[1]; } }
00189     }
00190
00191     internal class TileSquareImage : TileSquareBase, ITileSquareImage
00192     {
00193         public TileSquareImage() : base(templateName: "TileSquareImage", imageCount: 1, textCount: 0)
00194         {
00195         }
00196
00197         public INotificationContentImage Image { get { return Images[0]; } }
00198     }
00199
00200     internal class TileSquarePeekImageAndText01 : TileSquareBase, ITileSquarePeekImageAndText01
00201     {
00202         public TileSquarePeekImageAndText01() : base(templateName: "TileSquarePeekImageAndText01", imageCount: 1, textCount: 4)
00203         {
00204         }
00205
00206         public INotificationContentImage Image { get { return Images[0]; } }
00207
00208         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00209         public INotificationContentText TextBody1 { get { return TextFields[1]; } }
00210         public INotificationContentText TextBody2 { get { return TextFields[2]; } }
00211         public INotificationContentText TextBody3 { get { return TextFields[3]; } }
00212     }
00213
00214     internal class TileSquarePeekImageAndText02 : TileSquareBase, ITileSquarePeekImageAndText02
00215     {
00216         public TileSquarePeekImageAndText02() : base(templateName: "TileSquarePeekImageAndText02", imageCount: 1, textCount: 2)
00217         {
00218         }
00219
00220         public INotificationContentImage Image { get { return Images[0]; } }
00221
00222         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00223         public INotificationContentText TextBodyWrap { get { return TextFields[1]; } }
00224     }
00225
00226     internal class TileSquarePeekImageAndText03 : TileSquareBase, ITileSquarePeekImageAndText03
00227     {
00228         public TileSquarePeekImageAndText03() : base(templateName: "TileSquarePeekImageAndText03", imageCount: 1, textCount: 4)
00229         {
00230         }
00231
00232         public INotificationContentImage Image { get { return Images[0]; } }
00233
00234         public INotificationContentText TextBody1 { get { return TextFields[0]; } }
00235         public INotificationContentText TextBody2 { get { return TextFields[1]; } }
00236         public INotificationContentText TextBody3 { get { return TextFields[2]; } }
00237         public INotificationContentText TextBody4 { get { return TextFields[3]; } }
00238     }
00239
00240     internal class TileSquarePeekImageAndText04 : TileSquareBase, ITileSquarePeekImageAndText04
00241     {
00242         public TileSquarePeekImageAndText04() : base(templateName: "TileSquarePeekImageAndText04", imageCount: 1, textCount: 1)
00243         {
00244         }
00245
00246         public INotificationContentImage Image { get { return Images[0]; } }
00247
00248         public INotificationContentText TextBodyWrap { get { return TextFields[0]; } }
00249     }
00250
00251     internal class TileSquareText01 : TileSquareBase, ITileSquareText01
00252     {
00253         public TileSquareText01() : base(templateName: "TileSquareText01", imageCount: 0, textCount: 4)
00254         {
00255         }
00256
00257         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00258         public INotificationContentText TextBody1 { get { return TextFields[1]; } }
00259         public INotificationContentText TextBody2 { get { return TextFields[2]; } }
00260         public INotificationContentText TextBody3 { get { return TextFields[3]; } }
00261     }
00262
00263     internal class TileSquareText02 : TileSquareBase, ITileSquareText02
00264     {
00265         public TileSquareText02() : base(templateName: "TileSquareText02", imageCount: 0, textCount: 2)
00266         {
00267         }
00268
00269         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00270         public INotificationContentText TextBodyWrap { get { return TextFields[1]; } }
00271     }
00272
00273     internal class TileSquareText03 : TileSquareBase, ITileSquareText03
00274     {
00275         public TileSquareText03() : base(templateName: "TileSquareText03", imageCount: 0, textCount: 4)
00276         {
00277         }
00278
00279         public INotificationContentText TextBody1 { get { return TextFields[0]; } }
00280         public INotificationContentText TextBody2 { get { return TextFields[1]; } }
00281         public INotificationContentText TextBody3 { get { return TextFields[2]; } }
00282         public INotificationContentText TextBody4 { get { return TextFields[3]; } }
00283     }
00284
00285     internal class TileSquareText04 : TileSquareBase, ITileSquareText04
00286     {
00287         public TileSquareText04() : base(templateName: "TileSquareText04", imageCount: 0, textCount: 1)
00288         {
00289         }
00290
00291         public INotificationContentText TextBodyWrap { get { return TextFields[0]; } }
00292     }
00293
00294     internal class TileWideBlockAndText01 : TileWideBase, ITileWideBlockAndText01
00295     {
00296         public TileWideBlockAndText01() : base(templateName: "TileWideBlockAndText01", imageCount: 0, textCount: 6)
00297         {
00298         }
00299
00300         public INotificationContentText TextBody1 { get { return TextFields[0]; } }
00301         public INotificationContentText TextBody2 { get { return TextFields[1]; } }
00302         public INotificationContentText TextBody3 { get { return TextFields[2]; } }
00303         public INotificationContentText TextBody4 { get { return TextFields[3]; } }
00304         public INotificationContentText TextBlock { get { return TextFields[4]; } }
00305         public INotificationContentText TextSubBlock { get { return TextFields[5]; } }
00306     }
00307
00308     internal class TileWideBlockAndText02 : TileWideBase, ITileWideBlockAndText02
00309     {
00310         public TileWideBlockAndText02() : base(templateName: "TileWideBlockAndText02", imageCount: 0, textCount: 6)
00311         {
00312         }
00313
00314         public INotificationContentText TextBodyWrap { get { return TextFields[0]; } }
00315         public INotificationContentText TextBlock { get { return TextFields[1]; } }
00316         public INotificationContentText TextSubBlock { get { return TextFields[2]; } }
00317     }
00318
00319     internal class TileWideImage : TileWideBase, ITileWideImage
00320     {
00321         public TileWideImage() : base(templateName: "TileWideImage", imageCount: 1, textCount: 0)
00322         {
00323         }
00324
00325         public INotificationContentImage Image { get { return Images[0]; } }
00326     }
00327
00328     internal class TileWideImageAndText01 : TileWideBase, ITileWideImageAndText01
00329     {
00330         public TileWideImageAndText01() : base(templateName: "TileWideImageAndText01", imageCount: 1, textCount: 1)
00331         {
00332         }
00333
00334         public INotificationContentImage Image { get { return Images[0]; } }
00335
00336         public INotificationContentText TextCaptionWrap { get { return TextFields[0]; } }
00337     }
00338
00339     internal class TileWideImageAndText02 : TileWideBase, ITileWideImageAndText02
00340     {
00341         public TileWideImageAndText02() : base(templateName: "TileWideImageAndText02", imageCount: 1, textCount: 2)
00342         {
00343         }
00344
00345         public INotificationContentImage Image { get { return Images[0]; } }
00346
00347         public INotificationContentText TextCaption1 { get { return TextFields[0]; } }
00348         public INotificationContentText TextCaption2 { get { return TextFields[1]; } }
00349     }
00350
00351     internal class TileWideImageCollection : TileWideBase, ITileWideImageCollection
00352     {
00353         public TileWideImageCollection() : base(templateName: "TileWideImageCollection", imageCount: 5, textCount: 0)
00354         {
00355         }
00356
00357         public INotificationContentImage ImageMain { get { return Images[0]; } }
00358         public INotificationContentImage ImageSmallColumn1Row1 { get { return Images[1]; } }
00359         public INotificationContentImage ImageSmallColumn2Row1 { get { return Images[2]; } }
00360         public INotificationContentImage ImageSmallColumn1Row2 { get { return Images[3]; } }
00361         public INotificationContentImage ImageSmallColumn2Row2 { get { return Images[4]; } }
00362     }
00363
00364     internal class TileWidePeekImage01 : TileWideBase, ITileWidePeekImage01
00365     {
00366         public TileWidePeekImage01() : base(templateName: "TileWidePeekImage01", imageCount: 1, textCount: 2)
00367         {
00368         }
00369
00370         public INotificationContentImage Image { get { return Images[0]; } }
00371
00372         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00373         public INotificationContentText TextBodyWrap { get { return TextFields[1]; } }
00374     }
00375
00376     internal class TileWidePeekImage02 : TileWideBase, ITileWidePeekImage02
00377     {
00378         public TileWidePeekImage02() : base(templateName: "TileWidePeekImage02", imageCount: 1, textCount: 5)
00379         {
00380         }
00381
00382         public INotificationContentImage Image { get { return Images[0]; } }
00383
00384         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00385         public INotificationContentText TextBody1 { get { return TextFields[1]; } }
00386         public INotificationContentText TextBody2 { get { return TextFields[2]; } }
00387         public INotificationContentText TextBody3 { get { return TextFields[3]; } }
00388         public INotificationContentText TextBody4 { get { return TextFields[4]; } }
00389     }
00390
00391     internal class TileWidePeekImage03 : TileWideBase, ITileWidePeekImage03
00392     {
00393         public TileWidePeekImage03() : base(templateName: "TileWidePeekImage03", imageCount: 1, textCount: 1)
00394         {
00395         }
00396
00397         public INotificationContentImage Image { get { return Images[0]; } }
00398
00399         public INotificationContentText TextHeadingWrap { get { return TextFields[0]; } }
00400     }
00401
00402     internal class TileWidePeekImage04 : TileWideBase, ITileWidePeekImage04
00403     {
00404         public TileWidePeekImage04() : base(templateName: "TileWidePeekImage04", imageCount: 1, textCount: 1)
00405         {
00406         }
00407
00408         public INotificationContentImage Image { get { return Images[0]; } }
00409
00410         public INotificationContentText TextBodyWrap { get { return TextFields[0]; } }
00411     }
00412
00413     internal class TileWidePeekImage05 : TileWideBase, ITileWidePeekImage05
00414     {
00415         public TileWidePeekImage05() : base(templateName: "TileWidePeekImage05", imageCount: 2, textCount: 2)
00416         {
00417         }
00418
00419         public INotificationContentImage ImageMain { get { return Images[0]; } }
00420         public INotificationContentImage ImageSecondary { get { return Images[1]; } }
00421
00422         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00423         public INotificationContentText TextBodyWrap { get { return TextFields[1]; } }
00424     }
00425
00426     internal class TileWidePeekImage06 : TileWideBase, ITileWidePeekImage06
00427     {
00428         public TileWidePeekImage06() : base(templateName: "TileWidePeekImage06", imageCount: 2, textCount: 1)
00429         {
00430         }
00431
00432         public INotificationContentImage ImageMain { get { return Images[0]; } }
00433         public INotificationContentImage ImageSecondary { get { return Images[1]; } }
00434
00435         public INotificationContentText TextHeadingWrap { get { return TextFields[0]; } }
00436     }
00437
00438     internal class TileWidePeekImageAndText01 : TileWideBase, ITileWidePeekImageAndText01
00439     {
00440         public TileWidePeekImageAndText01() : base(templateName: "TileWidePeekImageAndText01", imageCount: 1, textCount: 1)
00441         {
00442         }
00443
00444         public INotificationContentImage Image { get { return Images[0]; } }
00445
00446         public INotificationContentText TextBodyWrap { get { return TextFields[0]; } }
00447     }
00448
00449     internal class TileWidePeekImageAndText02 : TileWideBase, ITileWidePeekImageAndText02
00450     {
00451         public TileWidePeekImageAndText02() : base(templateName: "TileWidePeekImageAndText02", imageCount: 1, textCount: 5)
00452         {
00453         }
00454
00455         public INotificationContentImage Image { get { return Images[0]; } }
00456
00457         public INotificationContentText TextBody1 { get { return TextFields[0]; } }
00458         public INotificationContentText TextBody2 { get { return TextFields[1]; } }
00459         public INotificationContentText TextBody3 { get { return TextFields[2]; } }
00460         public INotificationContentText TextBody4 { get { return TextFields[3]; } }
00461         public INotificationContentText TextBody5 { get { return TextFields[4]; } }
00462     }
00463
00464     internal class TileWidePeekImageCollection01 : TileWideBase, ITileWidePeekImageCollection01
00465     {
00466         public TileWidePeekImageCollection01() : base(templateName: "TileWidePeekImageCollection01", imageCount: 5, textCount: 2)
00467         {
00468         }
00469
00470         public INotificationContentImage ImageMain { get { return Images[0]; } }
00471         public INotificationContentImage ImageSmallColumn1Row1 { get { return Images[1]; } }
00472         public INotificationContentImage ImageSmallColumn2Row1 { get { return Images[2]; } }
00473         public INotificationContentImage ImageSmallColumn1Row2 { get { return Images[3]; } }
00474         public INotificationContentImage ImageSmallColumn2Row2 { get { return Images[4]; } }
00475
00476         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00477         public INotificationContentText TextBodyWrap { get { return TextFields[1]; } }
00478     }
00479
00480     internal class TileWidePeekImageCollection02 : TileWideBase, ITileWidePeekImageCollection02
00481     {
00482         public TileWidePeekImageCollection02() : base(templateName: "TileWidePeekImageCollection02", imageCount: 5, textCount: 5)
00483         {
00484         }
00485
00486         public INotificationContentImage ImageMain { get { return Images[0]; } }
00487         public INotificationContentImage ImageSmallColumn1Row1 { get { return Images[1]; } }
00488         public INotificationContentImage ImageSmallColumn2Row1 { get { return Images[2]; } }
00489         public INotificationContentImage ImageSmallColumn1Row2 { get { return Images[3]; } }
00490         public INotificationContentImage ImageSmallColumn2Row2 { get { return Images[4]; } }
00491
00492         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00493         public INotificationContentText TextBody1 { get { return TextFields[1]; } }
00494         public INotificationContentText TextBody2 { get { return TextFields[2]; } }
00495         public INotificationContentText TextBody3 { get { return TextFields[3]; } }
00496         public INotificationContentText TextBody4 { get { return TextFields[4]; } }
00497     }
00498
00499     internal class TileWidePeekImageCollection03 : TileWideBase, ITileWidePeekImageCollection03
00500     {
00501         public TileWidePeekImageCollection03() : base(templateName: "TileWidePeekImageCollection03", imageCount: 5, textCount: 1)
00502         {
00503         }
00504
00505         public INotificationContentImage ImageMain { get { return Images[0]; } }
00506         public INotificationContentImage ImageSmallColumn1Row1 { get { return Images[1]; } }
00507         public INotificationContentImage ImageSmallColumn2Row1 { get { return Images[2]; } }
00508         public INotificationContentImage ImageSmallColumn1Row2 { get { return Images[3]; } }
00509         public INotificationContentImage ImageSmallColumn2Row2 { get { return Images[4]; } }
00510
00511         public INotificationContentText TextHeadingWrap { get { return TextFields[0]; } }
00512     }
00513
00514     internal class TileWidePeekImageCollection04 : TileWideBase, ITileWidePeekImageCollection04
00515     {
00516         public TileWidePeekImageCollection04() : base(templateName: "TileWidePeekImageCollection04", imageCount: 5, textCount: 1)
00517         {
00518         }
00519
00520         public INotificationContentImage ImageMain { get { return Images[0]; } }
00521         public INotificationContentImage ImageSmallColumn1Row1 { get { return Images[1]; } }
00522         public INotificationContentImage ImageSmallColumn2Row1 { get { return Images[2]; } }
00523         public INotificationContentImage ImageSmallColumn1Row2 { get { return Images[3]; } }
00524         public INotificationContentImage ImageSmallColumn2Row2 { get { return Images[4]; } }
00525
00526         public INotificationContentText TextBodyWrap { get { return TextFields[0]; } }
00527     }
00528
00529     internal class TileWidePeekImageCollection05 : TileWideBase, ITileWidePeekImageCollection05
00530     {
00531         public TileWidePeekImageCollection05() : base(templateName: "TileWidePeekImageCollection05", imageCount: 6, textCount: 2)
00532         {
00533         }
00534
00535         public INotificationContentImage ImageMain { get { return Images[0]; } }
00536         public INotificationContentImage ImageSmallColumn1Row1 { get { return Images[1]; } }
00537         public INotificationContentImage ImageSmallColumn2Row1 { get { return Images[2]; } }
00538         public INotificationContentImage ImageSmallColumn1Row2 { get { return Images[3]; } }
00539         public INotificationContentImage ImageSmallColumn2Row2 { get { return Images[4]; } }
00540         public INotificationContentImage ImageSecondary { get { return Images[5]; } }
00541
00542         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00543         public INotificationContentText TextBodyWrap { get { return TextFields[1]; } }
00544     }
00545
00546     internal class TileWidePeekImageCollection06 : TileWideBase, ITileWidePeekImageCollection06
00547     {
00548         public TileWidePeekImageCollection06() : base(templateName: "TileWidePeekImageCollection06", imageCount: 6, textCount: 1)
00549         {
00550         }
00551
00552         public INotificationContentImage ImageMain { get { return Images[0]; } }
00553         public INotificationContentImage ImageSmallColumn1Row1 { get { return Images[1]; } }
00554         public INotificationContentImage ImageSmallColumn2Row1 { get { return Images[2]; } }
00555         public INotificationContentImage ImageSmallColumn1Row2 { get { return Images[3]; } }
00556         public INotificationContentImage ImageSmallColumn2Row2 { get { return Images[4]; } }
00557         public INotificationContentImage ImageSecondary { get { return Images[5]; } }
00558
00559         public INotificationContentText TextHeadingWrap { get { return TextFields[0]; } }
00560     }
00561
00562     internal class TileWideSmallImageAndText01 : TileWideBase, ITileWideSmallImageAndText01
00563     {
00564         public TileWideSmallImageAndText01() : base(templateName: "TileWideSmallImageAndText01", imageCount: 1, textCount: 1)
00565         {
00566         }
00567
00568         public INotificationContentImage Image { get { return Images[0]; } }
00569
00570         public INotificationContentText TextHeadingWrap { get { return TextFields[0]; } }
00571     }
00572
00573     internal class TileWideSmallImageAndText02 : TileWideBase, ITileWideSmallImageAndText02
00574     {
00575         public TileWideSmallImageAndText02() : base(templateName: "TileWideSmallImageAndText02", imageCount: 1, textCount: 5)
00576         {
00577         }
00578
00579         public INotificationContentImage Image { get { return Images[0]; } }
00580
00581         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00582         public INotificationContentText TextBody1 { get { return TextFields[1]; } }
00583         public INotificationContentText TextBody2 { get { return TextFields[2]; } }
00584         public INotificationContentText TextBody3 { get { return TextFields[3]; } }
00585         public INotificationContentText TextBody4 { get { return TextFields[4]; } }
00586     }
00587
00588     internal class TileWideSmallImageAndText03 : TileWideBase, ITileWideSmallImageAndText03
00589     {
00590         public TileWideSmallImageAndText03() : base(templateName: "TileWideSmallImageAndText03", imageCount: 1, textCount: 1)
00591         {
00592         }
00593
00594         public INotificationContentImage Image { get { return Images[0]; } }
00595
00596         public INotificationContentText TextBodyWrap { get { return TextFields[0]; } }
00597     }
00598
00599     internal class TileWideSmallImageAndText04 : TileWideBase, ITileWideSmallImageAndText04
00600     {
00601         public TileWideSmallImageAndText04() : base(templateName: "TileWideSmallImageAndText04", imageCount: 1, textCount: 2)
00602         {
00603         }
00604
00605         public INotificationContentImage Image { get { return Images[0]; } }
00606
00607         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00608         public INotificationContentText TextBodyWrap { get { return TextFields[1]; } }
00609     }
00610
00611     internal class TileWideSmallImageAndText05 : TileWideBase, ITileWideSmallImageAndText05
00612     {
00613         public TileWideSmallImageAndText05() : base(templateName: "TileWideSmallImageAndText05", imageCount: 1, textCount: 2)
00614         {
00615         }
00616
00617         public INotificationContentImage Image { get { return Images[0]; } }
00618
00619         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00620         public INotificationContentText TextBodyWrap { get { return TextFields[1]; } }
00621     }
00622
00623     internal class TileWideText01 : TileWideBase, ITileWideText01
00624     {
00625         public TileWideText01() : base(templateName: "TileWideText01", imageCount: 0, textCount: 5)
00626         {
00627         }
00628
00629         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00630         public INotificationContentText TextBody1 { get { return TextFields[1]; } }
00631         public INotificationContentText TextBody2 { get { return TextFields[2]; } }
00632         public INotificationContentText TextBody3 { get { return TextFields[3]; } }
00633         public INotificationContentText TextBody4 { get { return TextFields[4]; } }
00634     }
00635
00636     internal class TileWideText02 : TileWideBase, ITileWideText02
00637     {
00638         public TileWideText02() : base(templateName: "TileWideText02", imageCount: 0, textCount: 9)
00639         {
00640         }
00641
00642         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00643         public INotificationContentText TextColumn1Row1 { get { return TextFields[1]; } }
00644         public INotificationContentText TextColumn2Row1 { get { return TextFields[2]; } }
00645         public INotificationContentText TextColumn1Row2 { get { return TextFields[3]; } }
00646         public INotificationContentText TextColumn2Row2 { get { return TextFields[4]; } }
00647         public INotificationContentText TextColumn1Row3 { get { return TextFields[5]; } }
00648         public INotificationContentText TextColumn2Row3 { get { return TextFields[6]; } }
00649         public INotificationContentText TextColumn1Row4 { get { return TextFields[7]; } }
00650         public INotificationContentText TextColumn2Row4 { get { return TextFields[8]; } }
00651     }
00652
00653     internal class TileWideText03 : TileWideBase, ITileWideText03
00654     {
00655         public TileWideText03() : base(templateName: "TileWideText03", imageCount: 0, textCount: 1)
00656         {
00657         }
00658
00659         public INotificationContentText TextHeadingWrap { get { return TextFields[0]; } }
00660     }
00661
00662     internal class TileWideText04 : TileWideBase, ITileWideText04
00663     {
00664         public TileWideText04() : base(templateName: "TileWideText04", imageCount: 0, textCount: 1)
00665         {
00666         }
00667
00668         public INotificationContentText TextBodyWrap { get { return TextFields[0]; } }
00669     }
00670
00671     internal class TileWideText05 : TileWideBase, ITileWideText05
00672     {
00673         public TileWideText05() : base(templateName: "TileWideText05", imageCount: 0, textCount: 5)
00674         {
00675         }
00676
00677         public INotificationContentText TextBody1 { get { return TextFields[0]; } }
00678         public INotificationContentText TextBody2 { get { return TextFields[1]; } }
00679         public INotificationContentText TextBody3 { get { return TextFields[2]; } }
00680         public INotificationContentText TextBody4 { get { return TextFields[3]; } }
00681         public INotificationContentText TextBody5 { get { return TextFields[4]; } }
00682     }
00683
00684     internal class TileWideText06 : TileWideBase, ITileWideText06
00685     {
00686         public TileWideText06() : base(templateName: "TileWideText06", imageCount: 0, textCount: 10)
00687         {
00688         }
00689
00690         public INotificationContentText TextColumn1Row1 { get { return TextFields[0]; } }
00691         public INotificationContentText TextColumn2Row1 { get { return TextFields[1]; } }
00692         public INotificationContentText TextColumn1Row2 { get { return TextFields[2]; } }
00693         public INotificationContentText TextColumn2Row2 { get { return TextFields[3]; } }
00694         public INotificationContentText TextColumn1Row3 { get { return TextFields[4]; } }
00695         public INotificationContentText TextColumn2Row3 { get { return TextFields[5]; } }
00696         public INotificationContentText TextColumn1Row4 { get { return TextFields[6]; } }
00697         public INotificationContentText TextColumn2Row4 { get { return TextFields[7]; } }
00698         public INotificationContentText TextColumn1Row5 { get { return TextFields[8]; } }
00699         public INotificationContentText TextColumn2Row5 { get { return TextFields[9]; } }
00700     }
00701
00702     internal class TileWideText07 : TileWideBase, ITileWideText07
00703     {
00704         public TileWideText07() : base(templateName: "TileWideText07", imageCount: 0, textCount: 9)
00705         {
00706         }
00707
00708         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00709         public INotificationContentText TextShortColumn1Row1 { get { return TextFields[1]; } }
00710         public INotificationContentText TextColumn2Row1 { get { return TextFields[2]; } }
00711         public INotificationContentText TextShortColumn1Row2 { get { return TextFields[3]; } }
00712         public INotificationContentText TextColumn2Row2 { get { return TextFields[4]; } }
00713         public INotificationContentText TextShortColumn1Row3 { get { return TextFields[5]; } }
00714         public INotificationContentText TextColumn2Row3 { get { return TextFields[6]; } }
00715         public INotificationContentText TextShortColumn1Row4 { get { return TextFields[7]; } }
00716         public INotificationContentText TextColumn2Row4 { get { return TextFields[8]; } }
00717     }
00718
00719     internal class TileWideText08 : TileWideBase, ITileWideText08
00720     {
00721         public TileWideText08() : base(templateName: "TileWideText08", imageCount: 0, textCount: 10)
00722         {
00723         }
00724
00725         public INotificationContentText TextShortColumn1Row1 { get { return TextFields[0]; } }
00726         public INotificationContentText TextColumn2Row1 { get { return TextFields[1]; } }
00727         public INotificationContentText TextShortColumn1Row2 { get { return TextFields[2]; } }
00728         public INotificationContentText TextColumn2Row2 { get { return TextFields[3]; } }
00729         public INotificationContentText TextShortColumn1Row3 { get { return TextFields[4]; } }
00730         public INotificationContentText TextColumn2Row3 { get { return TextFields[5]; } }
00731         public INotificationContentText TextShortColumn1Row4 { get { return TextFields[6]; } }
00732         public INotificationContentText TextColumn2Row4 { get { return TextFields[7]; } }
00733         public INotificationContentText TextShortColumn1Row5 { get { return TextFields[8]; } }
00734         public INotificationContentText TextColumn2Row5 { get { return TextFields[9]; } }
00735     }
00736
00737     internal class TileWideText09 : TileWideBase, ITileWideText09
00738     {
00739         public TileWideText09() : base(templateName: "TileWideText09", imageCount: 0, textCount: 2)
00740         {
00741         }
00742
00743         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00744         public INotificationContentText TextBodyWrap { get { return TextFields[1]; } }
00745     }
00746
00747     internal class TileWideText10 : TileWideBase, ITileWideText10
00748     {
00749         public TileWideText10() : base(templateName: "TileWideText10", imageCount: 0, textCount: 9)
00750         {
00751         }
00752
00753         public INotificationContentText TextHeading { get { return TextFields[0]; } }
00754         public INotificationContentText TextPrefixColumn1Row1 { get { return TextFields[1]; } }
00755         public INotificationContentText TextColumn2Row1 { get { return TextFields[2]; } }
00756         public INotificationContentText TextPrefixColumn1Row2 { get { return TextFields[3]; } }
00757         public INotificationContentText TextColumn2Row2 { get { return TextFields[4]; } }
00758         public INotificationContentText TextPrefixColumn1Row3 { get { return TextFields[5]; } }
00759         public INotificationContentText TextColumn2Row3 { get { return TextFields[6]; } }
00760         public INotificationContentText TextPrefixColumn1Row4 { get { return TextFields[7]; } }
00761         public INotificationContentText TextColumn2Row4 { get { return TextFields[8]; } }
00762     }
00763
00764     internal class TileWideText11 : TileWideBase, ITileWideText11
00765     {
00766         public TileWideText11() : base(templateName: "TileWideText11", imageCount: 0, textCount: 10)
00767         {
00768         }
00769
00770         public INotificationContentText TextPrefixColumn1Row1 { get { return TextFields[0]; } }
00771         public INotificationContentText TextColumn2Row1 { get { return TextFields[1]; } }
00772         public INotificationContentText TextPrefixColumn1Row2 { get { return TextFields[2]; } }
00773         public INotificationContentText TextColumn2Row2 { get { return TextFields[3]; } }
00774         public INotificationContentText TextPrefixColumn1Row3 { get { return TextFields[4]; } }
00775         public INotificationContentText TextColumn2Row3 { get { return TextFields[5]; } }
00776         public INotificationContentText TextPrefixColumn1Row4 { get { return TextFields[6]; } }
00777         public INotificationContentText TextColumn2Row4 { get { return TextFields[7]; } }
00778         public INotificationContentText TextPrefixColumn1Row5 { get { return TextFields[8]; } }
00779         public INotificationContentText TextColumn2Row5 { get { return TextFields[9]; } }
00780     }
00781
00782     /// <summary>
00783     /// A factory which creates tile content objects for all of the toast template types.
00784     /// </summary>
00785     public sealed class TileContentFactory
00786     {
00787         /// <summary>
00788         /// Creates a tile content object for the TileSquareBlock template.
00789         /// </summary>
00790         /// <returns>A tile content object for the TileSquareBlock template.</returns>
00791         public static ITileSquareBlock CreateTileSquareBlock()
00792         {
00793             return new TileSquareBlock();
00794         }
00795
00796         /// <summary>
00797         /// Creates a tile content object for the TileSquareImage template.
00798         /// </summary>
00799         /// <returns>A tile content object for the TileSquareImage template.</returns>
00800         public static ITileSquareImage CreateTileSquareImage()
00801         {
00802             return new TileSquareImage();
00803         }
00804
00805         /// <summary>
00806         /// Creates a tile content object for the TileSquarePeekImageAndText01 template.
00807         /// </summary>
00808         /// <returns>A tile content object for the TileSquarePeekImageAndText01 template.</returns>
00809         public static ITileSquarePeekImageAndText01 CreateTileSquarePeekImageAndText01()
00810         {
00811             return new TileSquarePeekImageAndText01();
00812         }
00813
00814         /// <summary>
00815         /// Creates a tile content object for the TileSquarePeekImageAndText02 template.
00816         /// </summary>
00817         /// <returns>A tile content object for the TileSquarePeekImageAndText02 template.</returns>
00818         public static ITileSquarePeekImageAndText02 CreateTileSquarePeekImageAndText02()
00819         {
00820             return new TileSquarePeekImageAndText02();
00821         }
00822
00823         /// <summary>
00824         /// Creates a tile content object for the TileSquarePeekImageAndText03 template.
00825         /// </summary>
00826         /// <returns>A tile content object for the TileSquarePeekImageAndText03 template.</returns>
00827         public static ITileSquarePeekImageAndText03 CreateTileSquarePeekImageAndText03()
00828         {
00829             return new TileSquarePeekImageAndText03();
00830         }
00831
00832         /// <summary>
00833         /// Creates a tile content object for the TileSquarePeekImageAndText04 template.
00834         /// </summary>
00835         /// <returns>A tile content object for the TileSquarePeekImageAndText04 template.</returns>
00836         public static ITileSquarePeekImageAndText04 CreateTileSquarePeekImageAndText04()
00837         {
00838             return new TileSquarePeekImageAndText04();
00839         }
00840
00841         /// <summary>
00842         /// Creates a tile content object for the TileSquareText01 template.
00843         /// </summary>
00844         /// <returns>A tile content object for the TileSquareText01 template.</returns>
00845         public static ITileSquareText01 CreateTileSquareText01()
00846         {
00847             return new TileSquareText01();
00848         }
00849
00850         /// <summary>
00851         /// Creates a tile content object for the TileSquareText02 template.
00852         /// </summary>
00853         /// <returns>A tile content object for the TileSquareText02 template.</returns>
00854         public static ITileSquareText02 CreateTileSquareText02()
00855         {
00856             return new TileSquareText02();
00857         }
00858
00859         /// <summary>
00860         /// Creates a tile content object for the TileSquareText03 template.
00861         /// </summary>
00862         /// <returns>A tile content object for the TileSquareText03 template.</returns>
00863         public static ITileSquareText03 CreateTileSquareText03()
00864         {
00865             return new TileSquareText03();
00866         }
00867
00868         /// <summary>
00869         /// Creates a tile content object for the TileSquareText04 template.
00870         /// </summary>
00871         /// <returns>A tile content object for the TileSquareText04 template.</returns>
00872         public static ITileSquareText04 CreateTileSquareText04()
00873         {
00874             return new TileSquareText04();
00875         }
00876
00877         /// <summary>
00878         /// Creates a tile content object for the TileWideBlockAndText01 template.
00879         /// </summary>
00880         /// <returns>A tile content object for the TileWideBlockAndText01 template.</returns>
00881         public static ITileWideBlockAndText01 CreateTileWideBlockAndText01()
00882         {
00883             return new TileWideBlockAndText01();
00884         }
00885
00886         /// <summary>
00887         /// Creates a tile content object for the TileWideBlockAndText02 template.
00888         /// </summary>
00889         /// <returns>A tile content object for the TileWideBlockAndText02 template.</returns>
00890         public static ITileWideBlockAndText02 CreateTileWideBlockAndText02()
00891         {
00892             return new TileWideBlockAndText02();
00893         }
00894
00895         /// <summary>
00896         /// Creates a tile content object for the TileWideImage template.
00897         /// </summary>
00898         /// <returns>A tile content object for the TileWideImage template.</returns>
00899         public static ITileWideImage CreateTileWideImage()
00900         {
00901             return new TileWideImage();
00902         }
00903
00904         /// <summary>
00905         /// Creates a tile content object for the TileWideImageAndText01 template.
00906         /// </summary>
00907         /// <returns>A tile content object for the TileWideImageAndText01 template.</returns>
00908         public static ITileWideImageAndText01 CreateTileWideImageAndText01()
00909         {
00910             return new TileWideImageAndText01();
00911         }
00912
00913         /// <summary>
00914         /// Creates a tile content object for the TileWideImageAndText02 template.
00915         /// </summary>
00916         /// <returns>A tile content object for the TileWideImageAndText02 template.</returns>
00917         public static ITileWideImageAndText02 CreateTileWideImageAndText02()
00918         {
00919             return new TileWideImageAndText02();
00920         }
00921
00922         /// <summary>
00923         /// Creates a tile content object for the TileWideImageCollection template.
00924         /// </summary>
00925         /// <returns>A tile content object for the TileWideImageCollection template.</returns>
00926         public static ITileWideImageCollection CreateTileWideImageCollection()
00927         {
00928             return new TileWideImageCollection();
00929         }
00930
00931         /// <summary>
00932         /// Creates a tile content object for the TileWidePeekImage01 template.
00933         /// </summary>
00934         /// <returns>A tile content object for the TileWidePeekImage01 template.</returns>
00935         public static ITileWidePeekImage01 CreateTileWidePeekImage01()
00936         {
00937             return new TileWidePeekImage01();
00938         }
00939
00940         /// <summary>
00941         /// Creates a tile content object for the TileWidePeekImage02 template.
00942         /// </summary>
00943         /// <returns>A tile content object for the TileWidePeekImage02 template.</returns>
00944         public static ITileWidePeekImage02 CreateTileWidePeekImage02()
00945         {
00946             return new TileWidePeekImage02();
00947         }
00948
00949         /// <summary>
00950         /// Creates a tile content object for the TileWidePeekImage03 template.
00951         /// </summary>
00952         /// <returns>A tile content object for the TileWidePeekImage03 template.</returns>
00953         public static ITileWidePeekImage03 CreateTileWidePeekImage03()
00954         {
00955             return new TileWidePeekImage03();
00956         }
00957
00958         /// <summary>
00959         /// Creates a tile content object for the TileWidePeekImage04 template.
00960         /// </summary>
00961         /// <returns>A tile content object for the TileWidePeekImage04 template.</returns>
00962         public static ITileWidePeekImage04 CreateTileWidePeekImage04()
00963         {
00964             return new TileWidePeekImage04();
00965         }
00966
00967         /// <summary>
00968         /// Creates a tile content object for the TileWidePeekImage05 template.
00969         /// </summary>
00970         /// <returns>A tile content object for the TileWidePeekImage05 template.</returns>
00971         public static ITileWidePeekImage05 CreateTileWidePeekImage05()
00972         {
00973             return new TileWidePeekImage05();
00974         }
00975
00976         /// <summary>
00977         /// Creates a tile content object for the TileWidePeekImage06 template.
00978         /// </summary>
00979         /// <returns>A tile content object for the TileWidePeekImage06 template.</returns>
00980         public static ITileWidePeekImage06 CreateTileWidePeekImage06()
00981         {
00982             return new TileWidePeekImage06();
00983         }
00984
00985         /// <summary>
00986         /// Creates a tile content object for the TileWidePeekImageAndText01 template.
00987         /// </summary>
00988         /// <returns>A tile content object for the TileWidePeekImageAndText01 template.</returns>
00989         public static ITileWidePeekImageAndText01 CreateTileWidePeekImageAndText01()
00990         {
00991             return new TileWidePeekImageAndText01();
00992         }
00993
00994         /// <summary>
00995         /// Creates a tile content object for the TileWidePeekImageAndText02 template.
00996         /// </summary>
00997         /// <returns>A tile content object for the TileWidePeekImageAndText02 template.</returns>
00998         public static ITileWidePeekImageAndText02 CreateTileWidePeekImageAndText02()
00999         {
01000             return new TileWidePeekImageAndText02();
01001         }
01002
01003         /// <summary>
01004         /// Creates a tile content object for the TileWidePeekImageCollection01 template.
01005         /// </summary>
01006         /// <returns>A tile content object for the TileWidePeekImageCollection01 template.</returns>
01007         public static ITileWidePeekImageCollection01 CreateTileWidePeekImageCollection01()
01008         {
01009             return new TileWidePeekImageCollection01();
01010         }
01011
01012         /// <summary>
01013         /// Creates a tile content object for the TileWidePeekImageCollection02 template.
01014         /// </summary>
01015         /// <returns>A tile content object for the TileWidePeekImageCollection02 template.</returns>
01016         public static ITileWidePeekImageCollection02 CreateTileWidePeekImageCollection02()
01017         {
01018             return new TileWidePeekImageCollection02();
01019         }
01020
01021         /// <summary>
01022         /// Creates a tile content object for the TileWidePeekImageCollection03 template.
01023         /// </summary>
01024         /// <returns>A tile content object for the TileWidePeekImageCollection03 template.</returns>
01025         public static ITileWidePeekImageCollection03 CreateTileWidePeekImageCollection03()
01026         {
01027             return new TileWidePeekImageCollection03();
01028         }
01029
01030         /// <summary>
01031         /// Creates a tile content object for the TileWidePeekImageCollection04 template.
01032         /// </summary>
01033         /// <returns>A tile content object for the TileWidePeekImageCollection04 template.</returns>
01034         public static ITileWidePeekImageCollection04 CreateTileWidePeekImageCollection04()
01035         {
01036             return new TileWidePeekImageCollection04();
01037         }
01038
01039         /// <summary>
01040         /// Creates a tile content object for the TileWidePeekImageCollection05 template.
01041         /// </summary>
01042         /// <returns>A tile content object for the TileWidePeekImageCollection05 template.</returns>
01043         public static ITileWidePeekImageCollection05 CreateTileWidePeekImageCollection05()
01044         {
01045             return new TileWidePeekImageCollection05();
01046         }
01047
01048         /// <summary>
01049         /// Creates a tile content object for the TileWidePeekImageCollection06 template.
01050         /// </summary>
01051         /// <returns>A tile content object for the TileWidePeekImageCollection06 template.</returns>
01052         public static ITileWidePeekImageCollection06 CreateTileWidePeekImageCollection06()
01053         {
01054             return new TileWidePeekImageCollection06();
01055         }
01056
01057         /// <summary>
01058         /// Creates a tile content object for the TileWideSmallImageAndText01 template.
01059         /// </summary>
01060         /// <returns>A tile content object for the TileWideSmallImageAndText01 template.</returns>
01061         public static ITileWideSmallImageAndText01 CreateTileWideSmallImageAndText01()
01062         {
01063             return new TileWideSmallImageAndText01();
01064         }
01065
01066         /// <summary>
01067         /// Creates a tile content object for the TileWideSmallImageAndText02 template.
01068         /// </summary>
01069         /// <returns>A tile content object for the TileWideSmallImageAndText02 template.</returns>
01070         public static ITileWideSmallImageAndText02 CreateTileWideSmallImageAndText02()
01071         {
01072             return new TileWideSmallImageAndText02();
01073         }
01074
01075         /// <summary>
01076         /// Creates a tile content object for the TileWideSmallImageAndText03 template.
01077         /// </summary>
01078         /// <returns>A tile content object for the TileWideSmallImageAndText03 template.</returns>
01079
01080         public static ITileWideSmallImageAndText03 CreateTileWideSmallImageAndText03()
01081         {
01082             return new TileWideSmallImageAndText03();
01083         }
01084
01085         /// <summary>
01086         /// Creates a tile content object for the TileWideSmallImageAndText04 template.
01087         /// </summary>
01088         /// <returns>A tile content object for the TileWideSmallImageAndText04 template.</returns>
01089         public static ITileWideSmallImageAndText04 CreateTileWideSmallImageAndText04()
01090         {
01091             return new TileWideSmallImageAndText04();
01092         }
01093
01094         /// <summary>
01095         /// Creates a tile content object for the TileWideSmallImageAndText05 template.
01096         /// </summary>
01097         /// <returns>A tile content object for the TileWideSmallImageAndText05 template.</returns>
01098         public static ITileWideSmallImageAndText05 CreateTileWideSmallImageAndText05()
01099         {
01100             return new TileWideSmallImageAndText05();
01101         }
01102
01103         /// <summary>
01104         /// Creates a tile content object for the TileWideText01 template.
01105         /// </summary>
01106         /// <returns>A tile content object for the TileWideText01 template.</returns>
01107         public static ITileWideText01 CreateTileWideText01()
01108         {
01109             return new TileWideText01();
01110         }
01111
01112         /// <summary>
01113         /// Creates a tile content object for the TileWideText02 template.
01114         /// </summary>
01115         /// <returns>A tile content object for the TileWideText02 template.</returns>
01116         public static ITileWideText02 CreateTileWideText02()
01117         {
01118             return new TileWideText02();
01119         }
01120
01121         /// <summary>
01122         /// Creates a tile content object for the TileWideText03 template.
01123         /// </summary>
01124         /// <returns>A tile content object for the TileWideText03 template.</returns>
01125         public static ITileWideText03 CreateTileWideText03()
01126         {
01127             return new TileWideText03();
01128         }
01129
01130         /// <summary>
01131         /// Creates a tile content object for the TileWideText04 template.
01132         /// </summary>
01133         /// <returns>A tile content object for the TileWideText04 template.</returns>
01134         public static ITileWideText04 CreateTileWideText04()
01135         {
01136             return new TileWideText04();
01137         }
01138
01139         /// <summary>
01140         /// Creates a tile content object for the TileWideText05 template.
01141         /// </summary>
01142         /// <returns>A tile content object for the TileWideText05 template.</returns>
01143         public static ITileWideText05 CreateTileWideText05()
01144         {
01145             return new TileWideText05();
01146         }
01147
01148         /// <summary>
01149         /// Creates a tile content object for the TileWideText06 template.
01150         /// </summary>
01151         /// <returns>A tile content object for the TileWideText06 template.</returns>
01152         public static ITileWideText06 CreateTileWideText06()
01153         {
01154             return new TileWideText06();
01155         }
01156
01157         /// <summary>
01158         /// Creates a tile content object for the TileWideText07 template.
01159         /// </summary>
01160         /// <returns>A tile content object for the TileWideText07 template.</returns>
01161         public static ITileWideText07 CreateTileWideText07()
01162         {
01163             return new TileWideText07();
01164         }
01165
01166         /// <summary>
01167         /// Creates a tile content object for the TileWideText08 template.
01168         /// </summary>
01169         /// <returns>A tile content object for the TileWideText08 template.</returns>
01170         public static ITileWideText08 CreateTileWideText08()
01171         {
01172             return new TileWideText08();
01173         }
01174
01175         /// <summary>
01176         /// Creates a tile content object for the TileWideText09 template.
01177         /// </summary>
01178         /// <returns>A tile content object for the TileWideText09 template.</returns>
01179         public static ITileWideText09 CreateTileWideText09()
01180         {
01181             return new TileWideText09();
01182         }
01183
01184         /// <summary>
01185         /// Creates a tile content object for the TileWideText10 template.
01186         /// </summary>
01187         /// <returns>A tile content object for the TileWideText10 template.</returns>
01188         public static ITileWideText10 CreateTileWideText10()
01189         {
01190             return new TileWideText10();
01191         }
01192
01193         /// <summary>
01194         /// Creates a tile content object for the TileWideText11 template.
01195         /// </summary>
01196         /// <returns>A tile content object for the TileWideText11 template.</returns>
01197         public static ITileWideText11 CreateTileWideText11()
01198         {
01199             return new TileWideText11();
01200         }
01201     }
01202 }
Generated on Sat Nov 23 2024 16:08:19 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Network status background/C++/NetworkStatusTask/BackgroundTask.h Source File

  • Network status background
  • NetworkStatusTask

BackgroundTask.h

Go to the documentation of this file.
00001 ﻿#pragma once
00002
00003 #include "pch.h"
00004
00005 using namespace Windows::ApplicationModel::Background;
00006 using namespace Windows::System::Threading;
00007
00008 namespace NetworkStatusTask
00009 {
00010     public ref class BackgroundTask sealed : public IBackgroundTask
00011     {
00012     public:
00013         BackgroundTask();
00014
00015         virtual void Run(IBackgroundTaskInstance^ taskInstance);
00016         void OnCanceled(IBackgroundTaskInstance^ taskInstance, BackgroundTaskCancellationReason reason);
00017
00018     private:
00019         ~BackgroundTask();
00020     };
00021 }
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Scheduled notifications/C#,C++/MainPage.xaml.h Source File

  • Scheduled notifications
  • C#,C++

MainPage.xaml.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 //
00009 // MainPage.xaml.h
00010 // Declaration of the MainPage.xaml class.
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "MainPage.g.h"
00017
00018 namespace ScheduledNotificationsSampleCPP
00019 {
00020   public enum class NotifyType
00021   {
00022     StatusMessage,
00023     ErrorMessage
00024   };
00025
00026   [Windows::Foundation::Metadata::WebHostHidden]
00027   public ref class MainPage sealed
00028   {
00029   public:
00030     MainPage();
00031
00032     property Windows::UI::Xaml::Controls::Frame^ ScenariosFrame
00033     {
00034       Windows::UI::Xaml::Controls::Frame^ get() { return _scenariosFrame; }
00035     }
00036     property Windows::UI::Xaml::Controls::Frame^ InputFrame
00037     {
00038       Windows::UI::Xaml::Controls::Frame^ get() { return _inputFrame; }
00039     }
00040     property Windows::UI::Xaml::Controls::Frame^ OutputFrame
00041     {
00042       Windows::UI::Xaml::Controls::Frame^ get() { return _outputFrame; }
00043     }
00044
00045     event Windows::Foundation::EventHandler<Platform::Object^>^ InputFrameLoaded;
00046     event Windows::Foundation::EventHandler<Platform::Object^>^ OutputFrameLoaded;
00047
00048     void NotifyUser(Platform::String^ strMessage, NotifyType type);
00049     void DoNavigation(Windows::UI::Xaml::Interop::TypeName inPageType, Windows::UI::Xaml::Controls::Frame^ inFrame, Windows::UI::Xaml::Interop::TypeName outPageType, Windows::UI::Xaml::Controls::Frame^ outFrame);
00050     Platform::String^ ConvertViewState(Windows::UI::ViewManagement::ApplicationViewState state);
00051     Platform::String^ ConvertResolution(Windows::Graphics::Display::ResolutionScale scale);
00052
00053   private:
00054     ~MainPage();
00055     Windows::UI::Xaml::Controls::Frame^ _scenariosFrame;
00056     Windows::UI::Xaml::Controls::Frame^ _inputFrame;
00057     Windows::UI::Xaml::Controls::Frame^ _outputFrame;
00058     void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00059     Windows::Foundation::EventRegistrationToken _displayHandlerToken;
00060     Windows::Foundation::EventRegistrationToken _pageLoadedHandlerToken;
00061     Windows::Foundation::EventRegistrationToken _logicalDpiChangedToken;
00062     Windows::Foundation::EventRegistrationToken _inputFrameLoadedToken;
00063     Windows::Foundation::EventRegistrationToken _outputFrameLoadedToken;
00064     Windows::Foundation::EventRegistrationToken _resizeHandlerToken;
00065     void Page_SizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00066     void DisplayProperties_LogicalDpiChanged(Object^ sender);
00067     void Page_Loaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00068     void CheckResolutionAndViewState();
00069     void SetFeatureName(Platform::String^ strFeature);
00070     void inputFrameNavigated(Object^ sender, Windows::UI::Xaml::Navigation::NavigationEventArgs^ e);
00071     void outputFrameNavigated(Object^ sender,  Windows::UI::Xaml::Navigation::NavigationEventArgs^ e);
00072   };
00073 }
Generated on Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: HttpClient/C++/pch.h Source File

  • HttpClient

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <msxml6.h>
00019 #include <collection.h>
00020 #include <ppltasks.h>
00021 #include <wrl.h>
00022 #include "Common\LayoutAwarePage.h"
00023 #include "Common\SuspensionManager.h"
00024 #include "App.xaml.h"
00025 #include <sstream>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Manipulations and gestures (C++)/C++/BackgroundObject.h Source File

  • Input Manipulations and gestures (C++)
  • C++

BackgroundObject.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 "ManipulatableObject.h"
00011
00012 ref class BackgroundObject sealed : public ManipulatableObject
00013 {
00014 public:
00015     BackgroundObject(_In_opt_ ManipulatableObject^ parent, _In_ IRenderer^ renderer);
00016
00017     // Initialize object state.
00018     void Initialize();
00019
00020     // Set current pointer device at the beginning of the interaction.
00021     void SetDevice(_In_opt_ Windows::Devices::Input::IPointerDevice^ pointerDevice);
00022
00023     // Attaches/detaches gesture recognizer to/from the object.
00024     void Attach(_In_ Windows::UI::Input::GestureRecognizer^ gestureRecognizer);
00025     void Detach(_In_ Windows::UI::Input::GestureRecognizer^ gestureRecognizer);
00026
00027 internal:
00028     // Base class ManipulatableObject overrides.
00029     virtual D2D1::Matrix3x2F Transform() override;
00030
00031     // Draw background, given D2D objects.
00032     void DrawBackground(
00033         _In_ ID2D1DeviceContext* deviceContext,
00034         _In_ ID2D1SolidColorBrush* brush);
00035
00036     // Draw overlay text, given D2D objects.
00037     void DrawOverlay(
00038         _In_ ID2D1DeviceContext* deviceContext,
00039         _In_ IDWriteTextFormat* textFormat,
00040         _In_ ID2D1SolidColorBrush* brush);
00041
00042 private:
00043     void GetDeviceDescription();
00044     ~BackgroundObject();
00045
00046     // GestureRecognizer event handlers.
00047     void OnHolding(
00048         _In_ Windows::UI::Input::GestureRecognizer^ sender,
00049         _In_ Windows::UI::Input::HoldingEventArgs^ args);
00050     void OnRightTapped(
00051         _In_ Windows::UI::Input::GestureRecognizer^ sender,
00052         _In_ Windows::UI::Input::RightTappedEventArgs^ args);
00053     void OnManipulationStarted(
00054         _In_ Windows::UI::Input::GestureRecognizer^ sender,
00055         _In_ Windows::UI::Input::ManipulationStartedEventArgs^ args);
00056     void OnManipulationUpdated(
00057         _In_ Windows::UI::Input::GestureRecognizer^ sender,
00058         _In_ Windows::UI::Input::ManipulationUpdatedEventArgs^ args);
00059     void OnManipulationInertiaStarting(
00060         _In_ Windows::UI::Input::GestureRecognizer^ sender,
00061         _In_ Windows::UI::Input::ManipulationInertiaStartingEventArgs^ args);
00062     void OnManipulationCompleted(
00063         _In_ Windows::UI::Input::GestureRecognizer^ sender,
00064         _In_ Windows::UI::Input::ManipulationCompletedEventArgs^ args);
00065
00066 private:
00067     IRenderer^ _renderer;
00068
00069     // Data
00070     Windows::Devices::Input::IPointerDevice^ _pointerDevice;
00071     WCHAR _deviceDesc[1024];
00072
00073     // Event tokens for GestureRecognizer events
00074     Windows::Foundation::EventRegistrationToken _tokenRightTapped;
00075     Windows::Foundation::EventRegistrationToken _tokenHolding;
00076     Windows::Foundation::EventRegistrationToken _tokenManipulationStarted;
00077     Windows::Foundation::EventRegistrationToken _tokenManipulationUpdated;
00078     Windows::Foundation::EventRegistrationToken _tokenManipulationInertiaStarting;
00079     Windows::Foundation::EventRegistrationToken _tokenManipulationCompleted;
00080 };
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Folder enumeration/C++/Scenario3.xaml.h Source File

  • Folder enumeration

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 Scenario2 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario3.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace FolderEnumeration
00025     {
00026         [Windows::Foundation::Metadata::WebHostHidden]
00027         public ref class Scenario3 sealed
00028         {
00029         public:
00030             Scenario3();
00031
00032         protected:
00033             void GetFilesButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00034             Platform::String^ GetPropertyDisplayValue(Platform::Object^ property);
00035             Windows::UI::Xaml::Controls::TextBlock^ CreateHeaderTextBlock(Platform::String^ contents);
00036             Windows::UI::Xaml::Controls::TextBlock^ CreateLineItemTextBlock();
00037
00038         private:
00039             static Platform::String^ CopyrightProperty;
00040             static Platform::String^ ColorSpaceProperty;
00041         };
00042     }
00043 }
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Certificate enrollment/C++/Scenario_Enroll.xaml.h Source File

  • Certificate enrollment

Scenario_Enroll.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 // Scenario_Enroll.xaml.h
00013 // Declaration of the Scenario_Enroll class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario_Enroll.g.h"
00020 #include "MainPage.xaml.h"
00021 #include "HttpRequest.h"
00022
00023 namespace SDKSample
00024 {
00025     namespace CertificateEnrollment
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 Scenario_Enroll sealed
00032         {
00033         public:
00034             Scenario_Enroll();
00035
00036         protected:
00037             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00038         private:
00039             MainPage^ rootPage;
00040             Platform::String ^ certificateRequest;
00041
00042             Web::HttpRequest httpRequest;
00043             void CreateRequest_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00044             void InstallCertifiate_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00045             void SubmitCertificateRequestAndGetResponse(Platform::String^ certificateRequest, Platform::String^ url);
00046         };
00047     }
00048 }
Generated on Sat Nov 23 2024 16:07:58 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Association launching/C++/ScenarioList.xaml.cpp Source File

  • Association launching

ScenarioList.xaml.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 //
00009 // ScenarioList.xaml.cpp
00010 // Implementation of the ScenarioList class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioList.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace AssociationLaunching;
00018
00019 using namespace Platform;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Graphics::Display;
00023 using namespace Windows::UI::ViewManagement;
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 using namespace Windows::UI::Xaml::Interop;
00032
00033 ScenarioList::ScenarioList()
00034 {
00035     InitializeComponent();
00036 }
00037
00038 ScenarioList::~ScenarioList()
00039 {
00040 }
00041
00042 void ScenarioList::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00043 {
00044     if (Scenarios->SelectedItem != nullptr)
00045     {
00046         rootPage->NotifyUser("", NotifyType::StatusMessage);
00047
00048         ListBoxItem^ selectedListBoxItem = dynamic_cast<ListBoxItem^>(Scenarios->SelectedItem);
00049         SuspensionManager::SessionState()->Insert("SelectedScenario", selectedListBoxItem->Name);
00050
00051         if (rootPage->InputFrame != nullptr && rootPage->OutputFrame != nullptr)
00052         {
00053             //Load the input and output pages for the current scenario into their respective frames.
00054             TypeName inputPage = { "AssociationLaunching" + "." + selectedListBoxItem->Name + "Input", TypeKind::Custom };
00055             TypeName outputPage = { "AssociationLaunching" + "." + selectedListBoxItem->Name + "Output", TypeKind::Custom };
00056             rootPage->DoNavigation(inputPage, rootPage->InputFrame);
00057             rootPage->DoNavigation(outputPage, rootPage->OutputFrame);
00058         }
00059     }
00060 }
00061
00062 void ScenarioList::OnNavigatedTo(NavigationEventArgs^ e)
00063 {
00064     rootPage = dynamic_cast<MainPage^>(e->Parameter);
00065
00066     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &ScenarioList::Scenarios_SelectionChanged);
00067     ListBoxItem^ startingScenario = nullptr;
00068
00069     auto ps = SuspensionManager::SessionState();
00070     if (rootPage->FileEvent != nullptr)
00071     {
00072         startingScenario = dynamic_cast<ListBoxItem^>(this->FindName("ReceiveFile"));
00073     }
00074     else if (rootPage->ProtocolEvent != nullptr)
00075     {
00076         startingScenario = dynamic_cast<ListBoxItem^>(this->FindName("ReceiveUri"));
00077     }
00078     else if (ps->HasKey("SelectedScenario"))
00079     {
00080         PropertyValue^ pv;
00081         String^ item = dynamic_cast<String^>(ps->Lookup("SelectedScenario"));
00082         startingScenario = dynamic_cast<ListBoxItem^>(this->FindName(item));
00083     }
00084
00085     Scenarios->SelectedItem = startingScenario != nullptr ? startingScenario : LaunchFile;
00086 }
Generated on Sat Nov 23 2024 16:07:57 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Connecting with WebSockets/C++/MainPage.xaml.cpp Source File

  • Connecting with WebSockets

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:41 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Device auto rotation preferences/C++/common/suspensionmanager.h Source File

  • Device auto rotation preferences
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML accessibility/C++/Scenario1.xaml.cpp Source File

  • XAML accessibility

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::Accessibility;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 Scenario1::Scenario1()
00026 {
00027     InitializeComponent();
00028
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 Scenario1::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 }
Generated on Sat Nov 23 2024 16:07:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/GameInfoOverlay.h Source File

  • DirectX 3D shooting game

GameInfoOverlay.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 // GameInfoOverlay:
00011 // This class maintains a D2D1 Bitmap surface to provide information to the player
00012 // on the state of the game when the game is not in active play.
00013 // This class has several different status modes:
00014 //     GameLoading - this displays a title and a series of dots to show progress.
00015 //     GameStats - this displays a title and the Max level achieved, the hit and shot counts.
00016 //     GameOver - this displays a title and the game status.
00017 //     Pause - this displays only a title - 'Paused'.
00018 // In addition to the status modes, there is a region at the bottom that displays what the
00019 // player is expected to do next.  This can be one of four things:
00020 //     None - the action is blank.  This is usually set when the game does not currently have focus.
00021 //     TapToContinue - the game is waiting for the player to provide input that they are ready to
00022 //         proceed.
00023 //     PleaseWait - the game is actively doing some background processing (like loading a level).
00024 //     PlayAgain - the game has completed and is waiting for the player to indicate they are ready
00025 //         to play another round of the game.
00026
00027 namespace GameInfoOverlayConstant
00028 {
00029     static const float Width    = 750.0f;
00030     static const float Height   = 380.0f;
00031 };
00032
00033 enum class GameInfoOverlayCommand
00034 {
00035     None,
00036     TapToContinue,
00037     PleaseWait,
00038     PlayAgain,
00039 };
00040
00041 ref class GameInfoOverlay
00042 {
00043 internal:
00044     GameInfoOverlay();
00045
00046     void CreateDeviceIndependentResources(_In_ IDWriteFactory* dwriteFactory);
00047     void CreateDeviceResources(_In_ ID2D1DeviceContext*  d2dContext);
00048     void CreateDpiDependentResources(float dpi);
00049
00050     void SetGameLoading(uint32 dots);
00051     void SetGameStats(int maxLevel, int hitCount, int shotCount);
00052     void SetGameOver(bool win, int maxLevel, int hitCount, int shotCount, int highScore);
00053     void SetLevelStart(int level, Platform::String^ objective, float timeLimit, float bonusTime);
00054     void SetPause();
00055     void SetAction(GameInfoOverlayCommand action);
00056     void HideGameInfoOverlay() { m_visible = false; };
00057     void ShowGameInfoOverlay() { m_visible = true; };
00058     bool Visible() { return m_visible; };
00059     ID2D1Bitmap1* Bitmap() { return m_levelBitmap.Get(); }
00060
00061 private:
00062     float                                           m_dpi;
00063     bool                                            m_visible;
00064
00065     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00066     Microsoft::WRL::ComPtr<IDWriteFactory>          m_dwriteFactory;
00067
00068     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_levelBitmap;
00069     Microsoft::WRL::ComPtr<IDWriteTextFormat>       m_textFormatTitle;
00070     Microsoft::WRL::ComPtr<IDWriteTextFormat>       m_textFormatBody;
00071     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_textBrush;
00072     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_backgroundBrush;
00073     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_actionBrush;
00074 };
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D interpolation modes/C++/SampleOverlay.h Source File

  • Direct2D interpolation modes

SampleOverlay.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 "DirectXSample.h"
00011
00012 // This class is responsible for initializing and rendering the title overlay visible
00013 // at the top of the DirectX SDK samples.
00014 ref class SampleOverlay
00015 {
00016 internal:
00017     SampleOverlay();
00018
00019     void Initialize(
00020         _In_ ID2D1Device*         d2dDevice,
00021         _In_ ID2D1DeviceContext*  d2dContext,
00022         _In_ IWICImagingFactory*  wicFactory,
00023         _In_ IDWriteFactory*      dwriteFactory,
00024         _In_ Platform::String^    caption
00025         );
00026
00027     void ResetDirectXResources();
00028
00029     void UpdateForWindowSizeChange();
00030
00031     void Render();
00032
00033     float GetTitleHeightInDips();
00034
00035 private:
00036
00037     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00038     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00039     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00040     Microsoft::WRL::ComPtr<IDWriteFactory>          m_dwriteFactory;
00041     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_whiteBrush;
00042     Microsoft::WRL::ComPtr<ID2D1DrawingStateBlock>  m_stateBlock;
00043
00044     Microsoft::WRL::ComPtr<IWICImagingFactory>      m_wicFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Bitmap>             m_logoBitmap;
00046     Microsoft::WRL::ComPtr<IDWriteTextLayout>       m_textLayout;
00047
00048     UINT                                            m_idIncrement;
00049     bool                                            m_drawOverlay;
00050     Platform::String^                               m_sampleName;
00051     float                                           m_padding;
00052     float                                           m_textVerticalOffset;
00053     D2D1_SIZE_F                                     m_logoSize;
00054     float                                           m_overlayWidth;
00055 };
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Toast notifications/C#,C++/pch.h Source File

  • Toast notifications
  • C#,C++

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 //
00009 // pch.h
00010 // Header for standard system include files.
00011 //
00012
00013 #pragma once
00014 #include <ppltasks.h>
00015 #include "CppSamplesUtils.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/texconv/scoped.h Source File

  • Direct3D resource loading
  • texconv

scoped.h

Go to the documentation of this file.
00001 //-------------------------------------------------------------------------------------
00002 // scoped.h
00003 //
00004 // Utility header with helper classes for exception-safe handling of resources
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 #if defined(_MSC_VER) && (_MSC_VER > 1000)
00015 #pragma once
00016 #endif
00017
00018 #include <assert.h>
00019 #include <memory>
00020 #include <malloc.h>
00021
00022 //---------------------------------------------------------------------------------
00023 struct aligned_deleter { void operator()(void* p) { _aligned_free(p); } };
00024
00025 typedef std::unique_ptr<float, aligned_deleter> ScopedAlignedArrayFloat;
00026 typedef std::unique_ptr<DirectX::XMVECTOR, aligned_deleter> ScopedAlignedArrayXMVECTOR;
00027
00028 //---------------------------------------------------------------------------------
00029 struct handle_closer { void operator()(HANDLE h) { assert(h != INVALID_HANDLE_VALUE); if (h) CloseHandle(h); } };
00030
00031 typedef public std::unique_ptr<void, handle_closer> ScopedHandle;
00032
00033 inline HANDLE safe_handle( HANDLE h ) { return (h == INVALID_HANDLE_VALUE) ? 0 : h; }
00034
00035
00036 //---------------------------------------------------------------------------------
00037 template<class T> class ScopedObject
00038 {
00039 public:
00040     explicit ScopedObject( T *p = 0 ) : _pointer(p) {}
00041     ~ScopedObject()
00042     {
00043         if ( _pointer )
00044         {
00045             _pointer->Release();
00046             _pointer = nullptr;
00047         }
00048     }
00049
00050     bool IsNull() const { return (!_pointer); }
00051
00052     T& operator*() { return *_pointer; }
00053     T* operator->() { return _pointer; }
00054     T** operator&() { return &_pointer; }
00055
00056     void Reset(T *p = 0) { if ( _pointer ) { _pointer->Release(); } _pointer = p; }
00057
00058     T* Get() const { return _pointer; }
00059
00060 private:
00061     ScopedObject(const ScopedObject&);
00062     ScopedObject& operator=(const ScopedObject&);
00063
00064     T* _pointer;
00065 };
Generated on Sat Nov 23 2024 16:08:12 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Removable storage/C++/App.xaml.cpp Source File

  • Removable storage

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:28 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application resources and localization/C++/App.xaml.h Source File

  • Application resources and localization

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Lock screen apps/C#,C++/CppSamplesUtils.h Source File

  • Lock screen apps
  • C#,C++

CppSamplesUtils.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 <string>
00014 #include <sstream>
00015 #include <algorithm>
00016 #include <collection.h>
00017 #include <ppltasks.h>
00018
00019 namespace CppSamplesUtils
00020 {
00021     namespace Details
00022     {
00023         static Windows::Foundation::Collections::PropertySet^ sessionState = nullptr;
00024         static Platform::String^ sessionStateFileName = ref new Platform::String(L"_cppSessionState.xml");
00025
00026         concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file);
00027         concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file);
00028     }
00029
00030     class SuspensionManager
00031     {
00032     public:
00033         static Windows::Foundation::Collections::PropertySet^ SessionState()
00034         {
00035             using namespace Windows::Foundation::Collections;
00036             using namespace Details;
00037
00038             if (sessionState == nullptr)
00039             {
00040                 sessionState = ref new PropertySet();
00041             }
00042             return sessionState;
00043         }
00044
00045         static concurrency::task<void> StartRestoreTask()
00046         {
00047             using namespace Windows::Foundation;
00048             using namespace Windows::Storage;
00049             using namespace Windows::Storage::Streams;
00050             using namespace Details;
00051
00052             auto state = SessionState();
00053             state->Clear();
00054
00055             concurrency::task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFileName));
00056             return getFileTask.then([=](StorageFile^ file)
00057             {
00058                 return DeserializeSessionState(file);
00059             });
00060         }
00061
00062         static concurrency::task<void> StartSaveTask()
00063         {
00064             using namespace Windows::Foundation;
00065             using namespace Windows::Storage;
00066             using namespace Windows::Storage::Streams;
00067             using namespace Details;
00068
00069             concurrency::task<StorageFile^> createFileTask(ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFileName, CreationCollisionOption::ReplaceExisting));
00070             return createFileTask.then([=](StorageFile^ file)
00071             {
00072                 return SerializeSessionState(file);
00073             });
00074         }
00075     };
00076
00077     namespace Details
00078     {
00079         template <class T>
00080         inline Platform::String^ ToString(T value)
00081         {
00082             std::wstringstream wss;
00083             wss << value;
00084             return ref new Platform::String(wss.str().c_str());
00085         }
00086
00087         template <class T>
00088         inline T FromStringTo(Platform::String^ str)
00089         {
00090             std::wistringstream wiss(str->Data());
00091             T value = 0;
00092             wiss >> value;
00093             return value;
00094         }
00095
00096         template <class T>
00097         inline T FromHexStringTo(Platform::String^ str)
00098         {
00099             std::wistringstream wiss(str->Data());
00100             T value = 0;
00101             wiss >> std::hex >> value;
00102             return value;
00103         }
00104
00105         template <>
00106         inline Platform::Guid FromStringTo<Platform::Guid>(Platform::String^ str)
00107         {
00108             using namespace Platform;
00109
00110             if (str->Length() != 38)
00111             {
00112                 throw ref new InvalidArgumentException;
00113             }
00114             std::wstring ws(str->Data());
00115             if (ws[0] != L'{' || ws[37] != L'}' || ws[9] != L'-' || ws[14] != L'-' || ws[19] != L'-' || ws[24] != L'-')
00116             {
00117                 throw ref new InvalidArgumentException;
00118             }
00119             ws[0] = ws[37] = ws[9] = ws[14] = ws[19] =ws[24] = L' ';
00120             std::wistringstream wiss(ws);
00121             unsigned int a = 0;
00122             unsigned short b = 0;
00123             unsigned short c = 0;
00124             unsigned short d = 0;
00125             unsigned long long e = 0;
00126             static_assert(sizeof(d) == sizeof(char) * 2, "sizeof(d) == sizeof(char) * 2");
00127             static_assert(sizeof(e) == sizeof(char) * 8, "sizeof(e) == sizeof(char) * 8");
00128             wiss >> std::hex >> a >> b >> c >> d >> e;
00129             unsigned char *ad = (unsigned char*)(&d);
00130             unsigned char *ae = (unsigned char*)(&e);
00131             return Platform::Guid(a, b, c, ad[1], ad[0], ae[5], ae[4], ae[3], ae[2], ae[1], ae[0]);
00132         }
00133
00134         inline Platform::Object^ ConvertStringToObject(Windows::Foundation::PropertyType type, Platform::String^ str)
00135         {
00136             using namespace Platform;
00137             using namespace Windows::Foundation;
00138
00139             if (type == PropertyType::String)
00140             {
00141                 return PropertyValue::CreateString(str);
00142             }
00143
00144             switch (type)
00145             {
00146             case PropertyType::UInt8:
00147                 return PropertyValue::CreateUInt8((unsigned char)FromStringTo<unsigned short>(str));
00148             case PropertyType::UInt16:
00149                 return PropertyValue::CreateUInt16(FromStringTo<unsigned short>(str));
00150             case PropertyType::UInt32:
00151                 return PropertyValue::CreateUInt32(FromStringTo<unsigned int>(str));
00152             case PropertyType::UInt64:
00153                 return PropertyValue::CreateUInt64(FromStringTo<unsigned long long>(str));
00154             case PropertyType::Int16:
00155                 return PropertyValue::CreateInt16(FromStringTo<short>(str));
00156             case PropertyType::Int32:
00157                 return PropertyValue::CreateInt32(FromStringTo<int>(str));
00158             case PropertyType::Int64:
00159                 return PropertyValue::CreateInt64(FromStringTo<long long>(str));
00160             case PropertyType::Single:
00161                 return PropertyValue::CreateSingle(FromStringTo<float>(str));
00162             case PropertyType::Double:
00163                 return PropertyValue::CreateDouble(FromStringTo<double>(str));
00164             case PropertyType::Boolean:
00165                 return PropertyValue::CreateBoolean(FromStringTo<bool>(str));
00166             case PropertyType::Char16:
00167                 return PropertyValue::CreateChar16(str->Data()[0]);
00168             case PropertyType::Guid:
00169                 return PropertyValue::CreateGuid(FromStringTo<Guid>(str));
00170             default:
00171                 throw ref new Platform::InvalidCastException;
00172             }
00173         }
00174
00175         inline Platform::String^ ConvertPropertyValueToString(Windows::Foundation::IPropertyValue^ pv)
00176         {
00177             using namespace Platform;
00178             using namespace Windows::Foundation;
00179
00180             String^ valueString;
00181
00182             switch (pv->Type)
00183             {
00184             case PropertyType::String:
00185                 valueString = pv->GetString();
00186                 break;
00187
00188             case PropertyType::UInt8:
00189             case PropertyType::UInt16:
00190             case PropertyType::UInt32:
00191             case PropertyType::UInt64:
00192                 valueString = ToString(pv->GetUInt64());
00193                 break;
00194
00195             case PropertyType::Int16:
00196             case PropertyType::Int32:
00197             case PropertyType::Int64:
00198                 valueString = ToString(pv->GetInt64());
00199                 break;
00200
00201             case PropertyType::Single:
00202                 valueString = ToString(pv->GetSingle());
00203                 break;
00204
00205             case PropertyType::Double:
00206                 valueString = ToString(pv->GetDouble());
00207                 break;
00208
00209             case PropertyType::Boolean:
00210                 valueString = ToString(pv->GetBoolean());
00211                 break;
00212
00213             case PropertyType::Char16:
00214                 wchar_t buffer[2];
00215                 buffer[0] = pv->GetChar16();
00216                 buffer[1] = 0;
00217                 valueString = ref new String(buffer);
00218                 break;
00219
00220             case PropertyType::Guid:
00221                 valueString = pv->GetGuid().ToString();
00222                 break;
00223
00224             default:
00225                 throw ref new InvalidCastException;
00226             }
00227
00228             return valueString;
00229         }
00230
00231         inline Windows::Data::Xml::Dom::XmlElement^ CreateXmlElementFromObject(Windows::Data::Xml::Dom::XmlDocument^ doc, Platform::String^ name, Platform::Object^ value)
00232         {
00233             using namespace Platform;
00234             using namespace Windows::Foundation;
00235             using namespace Windows::Data::Xml::Dom;
00236
00237             XmlElement^ element = doc->CreateElement("item");
00238             element->SetAttribute("name", name);
00239
00240             IPropertyValue^ pv = (IPropertyValue^)value;
00241             element->SetAttribute("type", ToString((int)pv->Type));
00242             element->SetAttribute("value", ConvertPropertyValueToString(pv));
00243
00244             return element;
00245         }
00246
00247         inline concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file)
00248         {
00249             using namespace Windows::Data::Xml::Dom;
00250             using namespace Windows::Foundation;
00251             namespace WFC = Windows::Foundation::Collections;
00252             typedef Windows::Foundation::Collections::IKeyValuePair<Platform::String^, Platform::Object^> KVPair;
00253
00254             XmlDocument^ doc = ref new XmlDocument;
00255             doc->AppendChild(doc->CreateElement("items"));
00256             auto sessionState = SuspensionManager::SessionState();
00257
00258             std::for_each(WFC::begin(sessionState), WFC::end(sessionState), [doc](KVPair^ item)
00259             {
00260                 doc->DocumentElement->AppendChild(CreateXmlElementFromObject(doc, item->Key, item->Value));
00261             });
00262
00263             return concurrency::task<void>(doc->SaveToFileAsync(file));
00264         }
00265
00266         inline Windows::Foundation::PropertyType PropertyTypeFromString(Platform::String^ str)
00267         {
00268             int value = FromStringTo<int>(str);
00269             return (Windows::Foundation::PropertyType)value;
00270         }
00271
00272         inline concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file)
00273         {
00274             using namespace Platform;
00275             using namespace Windows::Foundation;
00276             using namespace Windows::Data::Xml::Dom;
00277             namespace WFC = Windows::Foundation::Collections;
00278
00279             concurrency::task<XmlDocument^> loadFileTask(XmlDocument::LoadFromFileAsync(file));
00280             return loadFileTask.then([=](concurrency::task<XmlDocument^> docTask)
00281             {
00282                 try
00283                 {
00284                     auto doc = docTask.get();
00285                     auto items = doc->SelectNodes("/items/item");
00286                     auto sessionState = SuspensionManager::SessionState();
00287
00288                     std::for_each(WFC::begin(items), WFC::end(items), [sessionState](IXmlNode^ node)
00289                     {
00290                         auto element = (IXmlElement^)node;
00291                         String^ name = element->GetAttribute("name");
00292                         String^ value = element->GetAttribute("value");
00293                         PropertyType type = PropertyTypeFromString(element->GetAttribute("type"));
00294
00295                         Object^ valueObject = ConvertStringToObject(type, value);
00296                         sessionState->Insert(name, valueObject);
00297                     });
00298
00299                 }
00300                 catch (Platform::Exception^)
00301                 {
00302                     // Restoring is best effort
00303                 }
00304             });
00305         }
00306     } // namespace Details
00307 } // namespace CppSamplesUtils
Generated on Sat Nov 23 2024 16:07:53 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Gyrometer sensor/C++/App.xaml.cpp Source File

  • Gyrometer sensor

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: App settings/C++/App.xaml.cpp Source File

  • App settings

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
00115
00116 void App::OnWindowCreated(WindowCreatedEventArgs^ pArgs)
00117 {
00118     (void) pArgs; // Unused parameter
00119     // Place your CommandsRequested handler here to ensure your settings are available at all times in your app
00120 }
Generated on Sat Nov 23 2024 16:07:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: StreamSocket/C++/App.xaml.cpp Source File

  • StreamSocket

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "App.xaml.h"
00018 #include "MainPage.xaml.h"
00019
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Controls;
00022 using namespace Windows::ApplicationModel;
00023 using namespace Windows::ApplicationModel::Activation;
00024 using namespace CppSamplesUtils;
00025 using namespace StreamSocketSample;
00026 using namespace Windows::UI::Xaml::Interop;
00027
00028 App::App()
00029 {
00030     InitializeComponent();
00031     this->Suspending += ref new SuspendingEventHandler(this, &StreamSocketSample::App::OnSuspending);
00032 }
00033
00034 void App::OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs)
00035 {
00036     auto deferral = pArgs->SuspendingOperation->GetDeferral();
00037     SuspensionManager::StartSaveTask().then([=]()
00038     {
00039         deferral->Complete();
00040     });
00041 }
00042
00043 void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs)
00044 {
00045     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Terminated)
00046     {
00047         SuspensionManager::StartRestoreTask().then([=](concurrency::task<void> restoreTask)
00048         {
00049             try
00050             {
00051                 restoreTask.get();
00052             }
00053             catch (Platform::Exception^)
00054             {
00055                 // If restore fails, the app should proceed as though there was no restored state.
00056             }
00057         });
00058     }
00059     if (Window::Current->Content == nullptr)
00060     {
00061         rootFrame = ref new Frame();
00062         TypeName pageType = { "StreamSocketSample.MainPage", TypeKind::Custom };
00063         rootFrame->Navigate(pageType);
00064         Window::Current->Content = rootFrame;
00065     }
00066     MainPage^ p = safe_cast<MainPage^>(rootFrame->Content);
00067     p->LaunchArgs = pArgs;
00068     Window::Current->Activate();
00069 }
00070
Generated on Sat Nov 23 2024 16:07:28 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML vector-based drawing/C++/App.xaml.h Source File

  • XAML vector-based drawing

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:30 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/texconv/DirectXTexMipmaps.cpp Source File

  • Direct3D resource loading
  • texconv

DirectXTexMipmaps.cpp

Go to the documentation of this file.
00001 //-------------------------------------------------------------------------------------
00002 // DirectXTexMipMaps.cpp
00003 //
00004 // DirectX Texture Library - Mip-map generation
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 #include "directxtexp.h"
00015
00016 namespace DirectX
00017 {
00018
00019 static const XMVECTORF32 s_boxScale = { 0.25f, 0.25f, 0.25f, 0.25f };
00020 static const XMVECTORF32 s_boxScale3D = { 0.125f, 0.125f, 0.125f, 0.125f };
00021
00022 //-------------------------------------------------------------------------------------
00023 // Mipmap helper functions
00024 //-------------------------------------------------------------------------------------
00025 inline static bool ispow2( _In_ size_t x )
00026 {
00027     return ((x != 0) && !(x & (x - 1)));
00028 }
00029
00030 static size_t _CountMips( _In_ size_t width, _In_ size_t height )
00031 {
00032     size_t mipLevels = 1;
00033
00034     while ( height > 1 || width > 1 )
00035     {
00036         if ( height > 1 )
00037             height >>= 1;
00038
00039         if ( width > 1 )
00040             width >>= 1;
00041
00042         ++mipLevels;
00043     }
00044
00045     return mipLevels;
00046 }
00047
00048 bool _CalculateMipLevels( _In_ size_t width, _In_ size_t height, _Inout_ size_t& mipLevels )
00049 {
00050     if ( mipLevels > 1 )
00051     {
00052         size_t maxMips = _CountMips(width,height);
00053         if ( mipLevels > maxMips )
00054             return false;
00055     }
00056     else if ( mipLevels == 0 )
00057     {
00058         mipLevels = _CountMips(width,height);
00059     }
00060     else
00061     {
00062         mipLevels = 1;
00063     }
00064     return true;
00065 }
00066
00067 static size_t _CountMips3D( _In_ size_t width, _In_ size_t height, _In_ size_t depth )
00068 {
00069     size_t mipLevels = 1;
00070
00071     while ( height > 1 || width > 1 || depth > 1 )
00072     {
00073         if ( height > 1 )
00074             height >>= 1;
00075
00076         if ( width > 1 )
00077             width >>= 1;
00078
00079         if ( depth > 1 )
00080             depth >>= 1;
00081
00082         ++mipLevels;
00083     }
00084
00085     return mipLevels;
00086 }
00087
00088 bool _CalculateMipLevels3D( _In_ size_t width, _In_ size_t height, _In_ size_t depth, _Inout_ size_t& mipLevels )
00089 {
00090     if ( mipLevels > 1 )
00091     {
00092         if ( !ispow2(width) || !ispow2(height) || !ispow2(depth) )
00093             return false;
00094
00095         size_t maxMips = _CountMips3D(width,height,depth);
00096         if ( mipLevels > maxMips )
00097             return false;
00098     }
00099     else if ( mipLevels == 0 && ispow2(width) && ispow2(height) && ispow2(depth) )
00100     {
00101         mipLevels = _CountMips3D(width,height,depth);
00102     }
00103     else
00104     {
00105         mipLevels = 1;
00106     }
00107     return true;
00108 }
00109
00110 static HRESULT _EnsureWicBitmapPixelFormat( _In_ IWICImagingFactory* pWIC, _In_ IWICBitmap* src, _In_ DWORD filter,
00111                                             _In_ const WICPixelFormatGUID& desiredPixelFormat,
00112                                             _Deref_out_ IWICBitmap** dest )
00113 {
00114     if ( !pWIC || !src || !dest )
00115         return E_POINTER;
00116
00117     *dest = nullptr;
00118
00119     WICPixelFormatGUID actualPixelFormat;
00120     HRESULT hr = src->GetPixelFormat( &actualPixelFormat );
00121
00122     if ( SUCCEEDED(hr) )
00123     {
00124         if ( memcmp( &actualPixelFormat, &desiredPixelFormat, sizeof(WICPixelFormatGUID) ) == 0 )
00125         {
00126             src->AddRef();
00127             *dest = src;
00128         }
00129         else
00130         {
00131             ScopedObject<IWICFormatConverter> converter;
00132             hr = pWIC->CreateFormatConverter( &converter );
00133             if ( SUCCEEDED(hr) )
00134             {
00135                 hr = converter->Initialize( src, desiredPixelFormat, _GetWICDither(filter), 0, 0, WICBitmapPaletteTypeCustom );
00136             }
00137
00138             if ( SUCCEEDED(hr) )
00139             {
00140                 hr = pWIC->CreateBitmapFromSource( converter.Get(), WICBitmapCacheOnDemand, dest );
00141             }
00142         }
00143     }
00144
00145     return hr;
00146 }
00147
00148 HRESULT _ResizeSeparateColorAndAlpha( _In_ IWICImagingFactory* pWIC, _In_ IWICBitmap* original,
00149                                       _In_ size_t newWidth, _In_ size_t newHeight, _In_ DWORD filter, _Inout_ const Image* img )
00150 {
00151     if ( !pWIC || !original || !img )
00152         return E_POINTER;
00153
00154     const WICBitmapInterpolationMode interpolationMode = _GetWICInterp(filter);
00155
00156     WICPixelFormatGUID desiredPixelFormat = GUID_WICPixelFormatUndefined;
00157     HRESULT hr = original->GetPixelFormat( &desiredPixelFormat );
00158
00159     size_t colorBytesInPixel = 0;
00160     size_t colorBytesPerPixel = 0;
00161     size_t colorWithAlphaBytesPerPixel = 0;
00162     WICPixelFormatGUID colorPixelFormat = GUID_WICPixelFormatUndefined;
00163     WICPixelFormatGUID colorWithAlphaPixelFormat = GUID_WICPixelFormatUndefined;
00164
00165     if ( SUCCEEDED(hr) )
00166     {
00167         ScopedObject<IWICComponentInfo> componentInfo;
00168         hr = pWIC->CreateComponentInfo( desiredPixelFormat, &componentInfo );
00169
00170         ScopedObject<IWICPixelFormatInfo> pixelFormatInfo;
00171         if ( SUCCEEDED(hr) )
00172         {
00173             hr = componentInfo->QueryInterface( __uuidof(IWICPixelFormatInfo), (void**)&pixelFormatInfo );
00174         }
00175
00176         UINT bitsPerPixel = 0;
00177         if ( SUCCEEDED(hr) )
00178         {
00179             hr = pixelFormatInfo->GetBitsPerPixel( &bitsPerPixel );
00180         }
00181
00182         if ( SUCCEEDED(hr) )
00183         {
00184             if ( bitsPerPixel <= 32 )
00185             {
00186                 colorBytesInPixel = colorBytesPerPixel = 3;
00187                 colorPixelFormat = GUID_WICPixelFormat24bppBGR;
00188
00189                 colorWithAlphaBytesPerPixel = 4;
00190                 colorWithAlphaPixelFormat = GUID_WICPixelFormat32bppBGRA;
00191             }
00192             else
00193             {
00194 #if(_WIN32_WINNT >= _WIN32_WINNT_WIN8)
00195                 colorBytesInPixel = colorBytesPerPixel = 12;
00196                 colorPixelFormat = GUID_WICPixelFormat96bppRGBFloat;
00197 #else
00198                 colorBytesInPixel = 12;
00199                 colorBytesPerPixel = 16;
00200                 colorPixelFormat = GUID_WICPixelFormat128bppRGBFloat;
00201 #endif
00202                 colorWithAlphaBytesPerPixel = 16;
00203                 colorWithAlphaPixelFormat = GUID_WICPixelFormat128bppRGBAFloat;
00204             }
00205         }
00206     }
00207
00208     // Resize color only image (no alpha channel)
00209     ScopedObject<IWICBitmap> resizedColor;
00210     if ( SUCCEEDED(hr) )
00211     {
00212         ScopedObject<IWICBitmapScaler> colorScaler;
00213
00214         hr = pWIC->CreateBitmapScaler(&colorScaler);
00215         if ( SUCCEEDED(hr) )
00216         {
00217             ScopedObject<IWICBitmap> converted;
00218
00219             hr = _EnsureWicBitmapPixelFormat( pWIC, original, filter, colorPixelFormat, &converted );
00220             if ( SUCCEEDED(hr) )
00221             {
00222                 hr = colorScaler->Initialize( converted.Get(), static_cast<UINT>(newWidth), static_cast<UINT>(newHeight), interpolationMode );
00223             }
00224         }
00225
00226         if ( SUCCEEDED(hr) )
00227         {
00228             ScopedObject<IWICBitmap> resized;
00229
00230             hr = pWIC->CreateBitmapFromSource( colorScaler.Get(), WICBitmapCacheOnDemand, &resized );
00231             if ( SUCCEEDED(hr) )
00232             {
00233                 hr = _EnsureWicBitmapPixelFormat( pWIC, resized.Get(), filter, colorPixelFormat, &resizedColor );
00234             }
00235         }
00236     }
00237
00238     // Resize color+alpha image
00239     ScopedObject<IWICBitmap> resizedColorWithAlpha;
00240     if ( SUCCEEDED(hr) )
00241     {
00242         ScopedObject<IWICBitmapScaler> colorWithAlphaScaler;
00243
00244         hr = pWIC->CreateBitmapScaler( &colorWithAlphaScaler );
00245         if ( SUCCEEDED(hr) )
00246         {
00247             ScopedObject<IWICBitmap> converted;
00248
00249             hr = _EnsureWicBitmapPixelFormat( pWIC, original, filter, colorWithAlphaPixelFormat, &converted );
00250             if ( SUCCEEDED(hr) )
00251             {
00252                 hr = colorWithAlphaScaler->Initialize( converted.Get(), static_cast<UINT>(newWidth), static_cast<UINT>(newHeight), interpolationMode );
00253             }
00254         }
00255
00256         if ( SUCCEEDED(hr) )
00257         {
00258             ScopedObject<IWICBitmap> resized;
00259
00260             hr = pWIC->CreateBitmapFromSource( colorWithAlphaScaler.Get(), WICBitmapCacheOnDemand, &resized );
00261             if ( SUCCEEDED(hr) )
00262             {
00263                 hr = _EnsureWicBitmapPixelFormat( pWIC, resized.Get(), filter, colorWithAlphaPixelFormat, &resizedColorWithAlpha );
00264             }
00265         }
00266     }
00267
00268     // Merge pixels (copying color channels from color only image to color+alpha image)
00269     if ( SUCCEEDED(hr) )
00270     {
00271         ScopedObject<IWICBitmapLock> colorLock;
00272         ScopedObject<IWICBitmapLock> colorWithAlphaLock;
00273
00274         hr = resizedColor->Lock( nullptr, WICBitmapLockRead, &colorLock );
00275         if ( SUCCEEDED(hr) )
00276         {
00277             hr = resizedColorWithAlpha->Lock( nullptr, WICBitmapLockWrite, &colorWithAlphaLock );
00278         }
00279
00280         if ( SUCCEEDED(hr) )
00281         {
00282             WICInProcPointer colorWithAlphaData = nullptr;
00283             UINT colorWithAlphaSizeInBytes = 0;
00284             UINT colorWithAlphaStride = 0;
00285
00286             hr = colorWithAlphaLock->GetDataPointer( &colorWithAlphaSizeInBytes, &colorWithAlphaData );
00287             if ( SUCCEEDED(hr) )
00288             {
00289                 if ( !colorWithAlphaData )
00290                 {
00291                     hr = E_POINTER;
00292                 }
00293                 else
00294                 {
00295                     hr = colorWithAlphaLock->GetStride( &colorWithAlphaStride );
00296                 }
00297             }
00298
00299             WICInProcPointer colorData = nullptr;
00300             UINT colorSizeInBytes = 0;
00301             UINT colorStride = 0;
00302             if ( SUCCEEDED(hr) )
00303             {
00304                 hr = colorLock->GetDataPointer( &colorSizeInBytes, &colorData );
00305                 if ( SUCCEEDED(hr) )
00306                 {
00307                     if ( !colorData )
00308                     {
00309                         hr = E_POINTER;
00310                     }
00311                     else
00312                     {
00313                         hr = colorLock->GetStride( &colorStride );
00314                     }
00315                 }
00316             }
00317
00318             for ( size_t j = 0; SUCCEEDED(hr) && j < newHeight; j++ )
00319             {
00320                 for ( size_t i = 0; SUCCEEDED(hr) && i < newWidth; i++ )
00321                 {
00322                     size_t colorWithAlphaIndex = (j * colorWithAlphaStride) + (i * colorWithAlphaBytesPerPixel);
00323                     size_t colorIndex = (j * colorStride) + (i * colorBytesPerPixel);
00324
00325                     if ( ((colorWithAlphaIndex + colorBytesInPixel) > colorWithAlphaSizeInBytes)
00326                          || ( (colorIndex + colorBytesPerPixel) > colorSizeInBytes) )
00327                     {
00328                         hr = E_INVALIDARG;
00329                     }
00330                     else
00331                     {
00332                         memcpy_s( colorWithAlphaData + colorWithAlphaIndex, colorWithAlphaBytesPerPixel, colorData + colorIndex, colorBytesInPixel );
00333                     }
00334                 }
00335             }
00336         }
00337     }
00338
00339     if ( SUCCEEDED(hr) )
00340     {
00341         ScopedObject<IWICBitmap> wicBitmap;
00342         hr = _EnsureWicBitmapPixelFormat( pWIC, resizedColorWithAlpha.Get(), filter, desiredPixelFormat, &wicBitmap );
00343         if ( SUCCEEDED(hr) )
00344         {
00345             hr = wicBitmap->CopyPixels( nullptr, static_cast<UINT>(img->rowPitch), static_cast<UINT>(img->slicePitch), img->pixels );
00346         }
00347     }
00348
00349     return hr;
00350 }
00351
00352
00353 //-------------------------------------------------------------------------------------
00354 // Generate a (2D) mip-map chain from a base image using WIC's image scaler
00355 //-------------------------------------------------------------------------------------
00356 static HRESULT _GenerateMipMapsUsingWIC( _In_ const Image& baseImage, _In_ DWORD filter, _In_ size_t levels,
00357                                          _In_ const WICPixelFormatGUID& pfGUID, _In_ const ScratchImage& mipChain, _In_ size_t item )
00358 {
00359     assert( levels > 1 );
00360
00361     if ( !baseImage.pixels || !mipChain.GetPixels() )
00362         return E_POINTER;
00363
00364     IWICImagingFactory* pWIC = _GetWIC();
00365     if ( !pWIC )
00366         return E_NOINTERFACE;
00367
00368     size_t width = baseImage.width;
00369     size_t height = baseImage.height;
00370
00371     ScopedObject<IWICBitmap> source;
00372     HRESULT hr = pWIC->CreateBitmapFromMemory( static_cast<UINT>( width ), static_cast<UINT>( height ), pfGUID,
00373                                                static_cast<UINT>( baseImage.rowPitch ), static_cast<UINT>( baseImage.slicePitch ),
00374                                                baseImage.pixels, &source );
00375     if ( FAILED(hr) )
00376         return hr;
00377
00378     // Copy base image to top miplevel
00379     const Image *img0 = mipChain.GetImage( 0, item, 0 );
00380     if ( !img0 )
00381         return E_POINTER;
00382
00383     uint8_t* pDest = img0->pixels;
00384     if ( !pDest )
00385         return E_POINTER;
00386
00387     const uint8_t *pSrc = baseImage.pixels;
00388     for( size_t h=0; h < height; ++h )
00389     {
00390         size_t msize = std::min<size_t>( img0->rowPitch, baseImage.rowPitch );
00391         memcpy_s( pDest, img0->rowPitch, pSrc, msize );
00392         pSrc += baseImage.rowPitch;
00393         pDest += img0->rowPitch;
00394     }
00395
00396     ScopedObject<IWICComponentInfo> componentInfo;
00397     hr = pWIC->CreateComponentInfo( pfGUID, &componentInfo );
00398     if ( FAILED(hr) )
00399         return hr;
00400
00401     ScopedObject<IWICPixelFormatInfo2> pixelFormatInfo;
00402     hr = componentInfo->QueryInterface( __uuidof(IWICPixelFormatInfo2), (void**)&pixelFormatInfo );
00403     if ( FAILED(hr) )
00404         return hr;
00405
00406     BOOL supportsTransparency = FALSE;
00407     hr = pixelFormatInfo->SupportsTransparency( &supportsTransparency );
00408     if ( FAILED(hr) )
00409         return hr;
00410
00411     // Resize base image to each target mip level
00412     for( size_t level = 1; level < levels; ++level )
00413     {
00414         const Image *img = mipChain.GetImage( level, item, 0 );
00415         if ( !img )
00416             return E_POINTER;
00417
00418         if ( height > 1 )
00419             height >>= 1;
00420
00421         if ( width > 1 )
00422             width >>= 1;
00423
00424         assert( img->width == width && img->height == height && img->format == baseImage.format );
00425
00426         if ( (filter & TEX_FILTER_SEPARATE_ALPHA) && supportsTransparency )
00427         {
00428             hr = _ResizeSeparateColorAndAlpha( pWIC, source.Get(), width, height, filter, img );
00429             if ( FAILED(hr) )
00430                 return hr;
00431         }
00432         else
00433         {
00434             ScopedObject<IWICBitmapScaler> scaler;
00435             hr = pWIC->CreateBitmapScaler( &scaler );
00436             if ( FAILED(hr) )
00437                 return hr;
00438
00439             hr = scaler->Initialize( source.Get(), static_cast<UINT>( width ), static_cast<UINT>( height ), _GetWICInterp( filter ) );
00440             if ( FAILED(hr) )
00441                 return hr;
00442
00443             WICPixelFormatGUID pfScaler;
00444             hr = scaler->GetPixelFormat( &pfScaler );
00445             if ( FAILED(hr) )
00446                 return hr;
00447
00448             if ( memcmp( &pfScaler, &pfGUID, sizeof(WICPixelFormatGUID) ) == 0 )
00449             {
00450                 hr = scaler->CopyPixels( 0, static_cast<UINT>( img->rowPitch ), static_cast<UINT>( img->slicePitch ), img->pixels );
00451                 if ( FAILED(hr) )
00452                     return hr;
00453             }
00454             else
00455             {
00456                 // The WIC bitmap scaler is free to return a different pixel format than the source image, so here we
00457                 // convert it back
00458                 ScopedObject<IWICFormatConverter> FC;
00459                 hr = pWIC->CreateFormatConverter( &FC );
00460                 if ( FAILED(hr) )
00461                     return hr;
00462
00463                 hr = FC->Initialize( scaler.Get(), pfGUID, _GetWICDither( filter ), 0, 0, WICBitmapPaletteTypeCustom );
00464                 if ( FAILED(hr) )
00465                     return hr;
00466
00467                 hr = FC->CopyPixels( 0, static_cast<UINT>( img->rowPitch ), static_cast<UINT>( img->slicePitch ), img->pixels );
00468                 if ( FAILED(hr) )
00469                     return hr;
00470             }
00471         }
00472     }
00473
00474     return S_OK;
00475 }
00476
00477
00478 //-------------------------------------------------------------------------------------
00479 // Generate volume mip-map helpers
00480 //-------------------------------------------------------------------------------------
00481 static HRESULT _Setup3DMips( _In_reads_(depth) const Image* baseImages, _In_ size_t depth, size_t levels,
00482                              _Out_ ScratchImage& mipChain )
00483 {
00484     if ( !baseImages || !depth )
00485         return E_INVALIDARG;
00486
00487     assert( levels > 1 );
00488
00489     size_t width = baseImages[0].width;
00490     size_t height = baseImages[0].height;
00491
00492     HRESULT hr = mipChain.Initialize3D( baseImages[0].format, width, height, depth, levels );
00493     if ( FAILED(hr) )
00494         return hr;
00495
00496     // Copy base images to top slice
00497     for( size_t slice=0; slice < depth; ++slice )
00498     {
00499         const Image& src = baseImages[slice];
00500
00501         const Image *dest = mipChain.GetImage( 0, 0, slice );
00502         if ( !dest )
00503         {
00504             mipChain.Release();
00505             return E_POINTER;
00506         }
00507
00508         assert( src.format == dest->format );
00509
00510         uint8_t* pDest = dest->pixels;
00511         if ( !pDest )
00512         {
00513             mipChain.Release();
00514             return E_POINTER;
00515         }
00516
00517         const uint8_t *pSrc = src.pixels;
00518         size_t rowPitch = src.rowPitch;
00519         for( size_t h=0; h < height; ++h )
00520         {
00521             size_t msize = std::min<size_t>( dest->rowPitch, rowPitch );
00522             memcpy_s( pDest, dest->rowPitch, pSrc, msize );
00523             pSrc += rowPitch;
00524             pDest += dest->rowPitch;
00525         }
00526     }
00527
00528     return S_OK;
00529 }
00530
00531 static HRESULT _Generate3DMipsPointFilter( _In_ size_t depth, _In_ size_t levels, _In_ const ScratchImage& mipChain )
00532 {
00533     if ( !depth || !mipChain.GetImages() )
00534         return E_INVALIDARG;
00535
00536     // This assumes that the base images are already placed into the mipChain at the top level... (see _Setup3DMips)
00537
00538     assert( levels > 1 );
00539
00540     size_t width = mipChain.GetMetadata().width;
00541     size_t height = mipChain.GetMetadata().height;
00542
00543     assert( ispow2(width) && ispow2(height) && ispow2(depth) );
00544
00545     // Allocate temporary space (2 scanlines)
00546     ScopedAlignedArrayXMVECTOR scanline( reinterpret_cast<XMVECTOR*>( _aligned_malloc( (sizeof(XMVECTOR)*width*2), 16 ) ) );
00547     if ( !scanline )
00548         return E_OUTOFMEMORY;
00549
00550     XMVECTOR* target = scanline.get();
00551
00552     XMVECTOR* row = target + width;
00553
00554     // Resize base image to each target mip level
00555     for( size_t level=1; level < levels; ++level )
00556     {
00557         if ( depth > 1 )
00558         {
00559             // 3D point filter
00560             for( size_t slice=0; slice < depth; slice += 2 )
00561             {
00562                 const Image* src = mipChain.GetImage( level-1, 0, slice );
00563                 const Image* dest = mipChain.GetImage( level, 0, slice >> 1 );
00564
00565                 if ( !src || !dest )
00566                     return E_POINTER;
00567
00568                 const uint8_t* pSrc = src->pixels;
00569                 uint8_t* pDest = dest->pixels;
00570
00571                 size_t rowPitch = src->rowPitch;
00572
00573                 size_t nheight = height >> 1;
00574
00575                 for( size_t y = 0; y < nheight; ++y )
00576                 {
00577                     if ( !_LoadScanline( row, width, pSrc, rowPitch, src->format ) )
00578                         return E_FAIL;
00579                     pSrc += rowPitch*2;
00580
00581                     size_t nwidth = width >> 1;
00582
00583                     for( size_t x = 0; x < nwidth; ++x )
00584                     {
00585                         target[ x ] = row[ x*2 ];
00586                     }
00587
00588                     if ( !_StoreScanline( pDest, dest->rowPitch, dest->format, target, nwidth ) )
00589                         return E_FAIL;
00590                     pDest += dest->rowPitch;
00591                 }
00592             }
00593         }
00594         else
00595         {
00596             // 2D point filter
00597             const Image* src = mipChain.GetImage( level-1, 0, 0 );
00598             const Image* dest = mipChain.GetImage( level, 0, 0 );
00599
00600             if ( !src || !dest )
00601                 return E_POINTER;
00602
00603             const uint8_t* pSrc = src->pixels;
00604             uint8_t* pDest = dest->pixels;
00605
00606             size_t rowPitch = src->rowPitch;
00607
00608             size_t nheight = height >> 1;
00609
00610             for( size_t y = 0; y < nheight; ++y )
00611             {
00612                 if ( !_LoadScanline( row, width, pSrc, rowPitch, src->format ) )
00613                     return E_FAIL;
00614                 pSrc += rowPitch*2;
00615
00616                 size_t nwidth = width >> 1;
00617
00618                 for( size_t x = 0; x < nwidth; ++x )
00619                 {
00620                     target[ x ] = row[ x*2 ];
00621                 }
00622
00623                 if ( !_StoreScanline( pDest, dest->rowPitch, dest->format, target, nwidth ) )
00624                     return E_FAIL;
00625                 pDest += dest->rowPitch;
00626             }
00627         }
00628
00629         if ( height > 1 )
00630             height >>= 1;
00631
00632         if ( width > 1 )
00633             width >>= 1;
00634
00635         if ( depth > 1 )
00636             depth >>= 1;
00637     }
00638
00639     assert( height == 1 && width == 1 && depth == 1 );
00640
00641     return S_OK;
00642 }
00643
00644 static HRESULT _Generate3DMipsBoxFilter( _In_ size_t depth, _In_ size_t levels, _In_ const ScratchImage& mipChain )
00645 {
00646     if ( !depth || !mipChain.GetImages() )
00647         return E_INVALIDARG;
00648
00649     // This assumes that the base images are already placed into the mipChain at the top level... (see _Setup3DMips)
00650
00651     assert( levels > 1 );
00652
00653     size_t width = mipChain.GetMetadata().width;
00654     size_t height = mipChain.GetMetadata().height;
00655
00656     assert( ispow2(width) && ispow2(height) && ispow2(depth) );
00657
00658     // Allocate temporary space (5 scanlines)
00659     ScopedAlignedArrayXMVECTOR scanline( reinterpret_cast<XMVECTOR*>( _aligned_malloc( (sizeof(XMVECTOR)*width*5), 16 ) ) );
00660     if ( !scanline )
00661         return E_OUTOFMEMORY;
00662
00663     XMVECTOR* target = scanline.get();
00664
00665     XMVECTOR* urow0 = target + width;
00666     XMVECTOR* urow1 = target + width*2;
00667     XMVECTOR* vrow0 = target + width*3;
00668     XMVECTOR* vrow1 = target + width*4;
00669
00670     const XMVECTOR* urow2 = urow0 + 1;
00671     const XMVECTOR* urow3 = urow1 + 1;
00672     const XMVECTOR* vrow2 = vrow0 + 1;
00673     const XMVECTOR* vrow3 = vrow1 + 1;
00674
00675     // Resize base image to each target mip level
00676     for( size_t level=1; level < levels; ++level )
00677     {
00678         if ( height == 1)
00679         {
00680             urow0 = vrow0;
00681             urow1 = vrow1;
00682         }
00683
00684         if ( width == 1 )
00685         {
00686             urow2 = urow0;
00687             urow3 = urow1;
00688             vrow2 = vrow0;
00689             vrow3 = vrow1;
00690         }
00691
00692         if ( depth > 1 )
00693         {
00694             // 3D box filter
00695             for( size_t slice=0; slice < depth; slice += 2 )
00696             {
00697                 const Image* srca = mipChain.GetImage( level-1, 0, slice );
00698                 const Image* srcb = mipChain.GetImage( level-1, 0, slice+1 );
00699                 const Image* dest = mipChain.GetImage( level, 0, slice >> 1 );
00700
00701                 if ( !srca || !srcb || !dest )
00702                     return E_POINTER;
00703
00704                 const uint8_t* pSrc1 = srca->pixels;
00705                 const uint8_t* pSrc2 = srcb->pixels;
00706                 uint8_t* pDest = dest->pixels;
00707
00708                 size_t aRowPitch = srca->rowPitch;
00709                 size_t bRowPitch = srcb->rowPitch;
00710
00711                 size_t nheight = height >> 1;
00712
00713                 for( size_t y = 0; y < nheight; ++y )
00714                 {
00715                     if ( !_LoadScanline( urow0, width, pSrc1, aRowPitch, srca->format ) )
00716                         return E_FAIL;
00717                     pSrc1 += aRowPitch;
00718
00719                     if ( urow0 != urow1 )
00720                     {
00721                         if ( !_LoadScanline( urow1, width, pSrc1, aRowPitch, srca->format ) )
00722                             return E_FAIL;
00723                         pSrc1 += aRowPitch;
00724                     }
00725
00726                     if ( urow0 != vrow0 )
00727                     {
00728                         if ( !_LoadScanline( vrow0, width, pSrc2, bRowPitch, srcb->format ) )
00729                             return E_FAIL;
00730                         pSrc2 += bRowPitch;
00731                     }
00732
00733                     if ( urow0 != vrow1 && vrow0 != vrow1 )
00734                     {
00735                         if ( !_LoadScanline( vrow1, width, pSrc2, bRowPitch, srcb->format ) )
00736                             return E_FAIL;
00737                         pSrc2 += bRowPitch;
00738                     }
00739
00740                     size_t nwidth = width >> 1;
00741
00742                     for( size_t x = 0; x < nwidth; ++x )
00743                     {
00744                         size_t x2 = x*2;
00745
00746                         // Box filter: Average 2x2x2 pixels
00747                         XMVECTOR v = XMVectorAdd( urow0[ x2 ], urow1[ x2 ] );
00748                         v = XMVectorAdd( v, urow2[ x2 ] );
00749                         v = XMVectorAdd( v, urow3[ x2 ] );
00750                         v = XMVectorAdd( v, vrow0[ x2 ] );
00751                         v = XMVectorAdd( v, vrow1[ x2 ] );
00752                         v = XMVectorAdd( v, vrow2[ x2 ] );
00753                         v = XMVectorAdd( v, vrow3[ x2 ] );
00754
00755                         target[ x ] = XMVectorMultiply( v, s_boxScale3D );
00756                     }
00757
00758                     if ( !_StoreScanline( pDest, dest->rowPitch, dest->format, target, nwidth ) )
00759                         return E_FAIL;
00760                     pDest += dest->rowPitch;
00761                 }
00762             }
00763         }
00764         else
00765         {
00766             // 2D box filter
00767             const Image* src = mipChain.GetImage( level-1, 0, 0 );
00768             const Image* dest = mipChain.GetImage( level, 0, 0 );
00769
00770             if ( !src || !dest )
00771                 return E_POINTER;
00772
00773             const uint8_t* pSrc = src->pixels;
00774             uint8_t* pDest = dest->pixels;
00775
00776             size_t rowPitch = src->rowPitch;
00777
00778             size_t nheight = height >> 1;
00779
00780             for( size_t y = 0; y < nheight; ++y )
00781             {
00782                 if ( !_LoadScanline( urow0, width, pSrc, rowPitch, src->format ) )
00783                     return E_FAIL;
00784                 pSrc += rowPitch;
00785
00786                 if ( urow0 != urow1 )
00787                 {
00788                     if ( !_LoadScanline( urow1, width, pSrc, rowPitch, src->format ) )
00789                         return E_FAIL;
00790                     pSrc += rowPitch;
00791                 }
00792
00793                 size_t nwidth = width >> 1;
00794
00795                 for( size_t x = 0; x < nwidth; ++x )
00796                 {
00797                     size_t x2 = x*2;
00798
00799                     // Box filter: Average 2x2 pixels
00800                     XMVECTOR v = XMVectorAdd( urow0[ x2 ], urow1[ x2 ] );
00801                     v = XMVectorAdd( v, urow2[ x2 ] );
00802                     v = XMVectorAdd( v, urow3[ x2 ] );
00803
00804                     target[ x ] = XMVectorMultiply( v, s_boxScale );
00805                 }
00806
00807                 if ( !_StoreScanline( pDest, dest->rowPitch, dest->format, target, nwidth ) )
00808                     return E_FAIL;
00809                 pDest += dest->rowPitch;
00810             }
00811         }
00812
00813         if ( height > 1 )
00814             height >>= 1;
00815
00816         if ( width > 1 )
00817             width >>= 1;
00818
00819         if ( depth > 1 )
00820             depth >>= 1;
00821     }
00822
00823     assert( height == 1 && width == 1 && depth == 1 );
00824
00825     return S_OK;
00826 }
00827
00828
00829 //=====================================================================================
00830 // Entry-points
00831 //=====================================================================================
00832
00833 //-------------------------------------------------------------------------------------
00834 // Generate mipmap chain
00835 //-------------------------------------------------------------------------------------
00836 _Use_decl_annotations_
00837 HRESULT GenerateMipMaps( const Image& baseImage, DWORD filter, size_t levels, ScratchImage& mipChain, bool allow1D )
00838 {
00839     if ( !IsValid( baseImage.format ) )
00840         return E_INVALIDARG;
00841
00842     if ( !baseImage.pixels )
00843         return E_POINTER;
00844
00845     if ( !_CalculateMipLevels(baseImage.width, baseImage.height, levels) )
00846         return E_INVALIDARG;
00847
00848     if ( IsCompressed( baseImage.format ) || IsVideo( baseImage.format ) )
00849     {
00850         return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
00851     }
00852
00853     static_assert( TEX_FILTER_POINT == 0x100000, "TEX_FILTER_ flag values don't match TEX_FILTER_MASK" );
00854     switch(filter & TEX_FILTER_MASK)
00855     {
00856     case 0:
00857     case TEX_FILTER_POINT:
00858     case TEX_FILTER_FANT: // Equivalent to Box filter
00859     case TEX_FILTER_LINEAR:
00860     case TEX_FILTER_CUBIC:
00861         {
00862             WICPixelFormatGUID pfGUID;
00863             if ( _DXGIToWIC( baseImage.format, pfGUID ) )
00864             {
00865                 // Case 1: Base image format is supported by Windows Imaging Component
00866                 HRESULT hr = (baseImage.height > 1 || !allow1D)
00867                              ? mipChain.Initialize2D( baseImage.format, baseImage.width, baseImage.height, 1, levels )
00868                              : mipChain.Initialize1D( baseImage.format, baseImage.width, 1, levels );
00869                 if ( FAILED(hr) )
00870                     return hr;
00871
00872                 return _GenerateMipMapsUsingWIC( baseImage, filter, levels, pfGUID, mipChain, 0 );
00873             }
00874             else
00875             {
00876                 // Case 2: Base image format is not supported by WIC, so we have to convert, generate, and convert back
00877                 assert( baseImage.format != DXGI_FORMAT_R32G32B32A32_FLOAT );
00878                 ScratchImage temp;
00879                 HRESULT hr = _ConvertToR32G32B32A32( baseImage, temp );
00880                 if ( FAILED(hr) )
00881                     return hr;
00882
00883                 const Image *timg = temp.GetImage( 0, 0, 0 );
00884                 if ( !timg )
00885                     return E_POINTER;
00886
00887                 ScratchImage tMipChain;
00888                 hr = _GenerateMipMapsUsingWIC( *timg, filter, levels, GUID_WICPixelFormat128bppRGBAFloat, tMipChain, 0 );
00889                 if ( FAILED(hr) )
00890                     return hr;
00891
00892                 temp.Release();
00893
00894                 return _ConvertFromR32G32B32A32( tMipChain.GetImages(), tMipChain.GetImageCount(), tMipChain.GetMetadata(), baseImage.format, mipChain );
00895             }
00896         }
00897         break;
00898
00899     default:
00900         return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
00901     }
00902 }
00903
00904 _Use_decl_annotations_
00905 HRESULT GenerateMipMaps( const Image* srcImages, size_t nimages, const TexMetadata& metadata,
00906                          DWORD filter, size_t levels, ScratchImage& mipChain )
00907 {
00908     if ( !srcImages || !nimages || !IsValid(metadata.format) )
00909         return E_INVALIDARG;
00910
00911     if ( metadata.dimension == TEX_DIMENSION_TEXTURE3D
00912          || IsCompressed( metadata.format ) || IsVideo( metadata.format ) )
00913         return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
00914
00915     if ( !_CalculateMipLevels(metadata.width, metadata.height, levels) )
00916         return E_INVALIDARG;
00917
00918     static_assert( TEX_FILTER_POINT == 0x100000, "TEX_FILTER_ flag values don't match TEX_FILTER_MASK" );
00919     switch(filter & TEX_FILTER_MASK)
00920     {
00921     case 0:
00922     case TEX_FILTER_POINT:
00923     case TEX_FILTER_FANT: // Equivalent to Box filter
00924     case TEX_FILTER_LINEAR:
00925     case TEX_FILTER_CUBIC:
00926         {
00927             WICPixelFormatGUID pfGUID;
00928             if ( _DXGIToWIC( metadata.format, pfGUID ) )
00929             {
00930                 // Case 1: Base image format is supported by Windows Imaging Component
00931                 TexMetadata mdata2 = metadata;
00932                 mdata2.mipLevels = levels;
00933                 HRESULT hr = mipChain.Initialize( mdata2 );
00934                 if ( FAILED(hr) )
00935                     return hr;
00936
00937                 for( size_t item = 0; item < metadata.arraySize; ++item )
00938                 {
00939                     size_t index = metadata.ComputeIndex( 0, item, 0 );
00940                     if ( index >= nimages )
00941                     {
00942                         mipChain.Release();
00943                         return E_FAIL;
00944                     }
00945
00946                     const Image& baseImage = srcImages[ index ];
00947
00948                     hr = _GenerateMipMapsUsingWIC( baseImage, filter, levels, pfGUID, mipChain, item );
00949                     if ( FAILED(hr) )
00950                     {
00951                         mipChain.Release();
00952                         return hr;
00953                     }
00954                 }
00955
00956                 return S_OK;
00957             }
00958             else
00959             {
00960                 // Case 2: Base image format is not supported by WIC, so we have to convert, generate, and convert back
00961                 assert( metadata.format != DXGI_FORMAT_R32G32B32A32_FLOAT );
00962
00963                 TexMetadata mdata2 = metadata;
00964                 mdata2.mipLevels = levels;
00965                 mdata2.format = DXGI_FORMAT_R32G32B32A32_FLOAT;
00966                 ScratchImage tMipChain;
00967                 HRESULT hr = tMipChain.Initialize( mdata2 );
00968                 if ( FAILED(hr) )
00969                     return hr;
00970
00971                 for( size_t item = 0; item < metadata.arraySize; ++item )
00972                 {
00973                     size_t index = metadata.ComputeIndex( 0, item, 0 );
00974                     if ( index >= nimages )
00975                         return E_FAIL;
00976
00977                     const Image& baseImage = srcImages[ index ];
00978
00979                     ScratchImage temp;
00980                     hr = _ConvertToR32G32B32A32( baseImage, temp );
00981                     if ( FAILED(hr) )
00982                         return hr;
00983
00984                     const Image *timg = temp.GetImage( 0, 0, 0 );
00985                     if ( !timg )
00986                         return E_POINTER;
00987
00988                     hr = _GenerateMipMapsUsingWIC( *timg, filter, levels, GUID_WICPixelFormat128bppRGBAFloat, tMipChain, item );
00989                     if ( FAILED(hr) )
00990                         return hr;
00991                 }
00992
00993                 return _ConvertFromR32G32B32A32( tMipChain.GetImages(), tMipChain.GetImageCount(), tMipChain.GetMetadata(), metadata.format, mipChain );
00994             }
00995         }
00996         break;
00997
00998     default:
00999         return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );;
01000     }
01001 }
01002
01003
01004 //-------------------------------------------------------------------------------------
01005 // Generate mipmap chain for volume texture
01006 //-------------------------------------------------------------------------------------
01007 _Use_decl_annotations_
01008 HRESULT GenerateMipMaps3D( const Image* baseImages, size_t depth, DWORD filter, size_t levels, ScratchImage& mipChain )
01009 {
01010     if ( !baseImages || !depth )
01011         return E_INVALIDARG;
01012
01013     DXGI_FORMAT format = baseImages[0].format;
01014     size_t width = baseImages[0].width;
01015     size_t height = baseImages[0].height;
01016
01017     if ( !ispow2(width) || !ispow2(height) || !ispow2(depth) )
01018         return E_INVALIDARG;
01019
01020     if ( !_CalculateMipLevels3D(width, height, depth, levels) )
01021         return E_INVALIDARG;
01022
01023     for( size_t slice=0; slice < depth; ++slice )
01024     {
01025         if ( !baseImages[slice].pixels )
01026             return E_POINTER;
01027
01028         if ( baseImages[slice].format != format || baseImages[slice].width != width || baseImages[slice].height != height )
01029         {
01030             // All base images must be the same format, width, and height
01031             return E_FAIL;
01032         }
01033     }
01034
01035     if ( IsCompressed( format ) )
01036     {
01037         // We don't support generating mipmaps from compressed images, as those should be generated before compression
01038         return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
01039     }
01040
01041     HRESULT hr;
01042
01043     static_assert( TEX_FILTER_POINT == 0x100000, "TEX_FILTER_ flag values don't match TEX_FILTER_MASK" );
01044     switch( filter & TEX_FILTER_MASK )
01045     {
01046     case 0:
01047     case TEX_FILTER_FANT:
01048         hr = _Setup3DMips( baseImages, depth, levels, mipChain );
01049         if ( FAILED(hr) )
01050             return hr;
01051
01052         // For decimation, Fant is equivalent to a Box filter
01053         hr = _Generate3DMipsBoxFilter( depth, levels, mipChain );
01054         if ( FAILED(hr) )
01055             mipChain.Release();
01056         return hr;
01057
01058     case WIC_FLAGS_FILTER_POINT:
01059         hr = _Setup3DMips( baseImages, depth, levels, mipChain );
01060         if ( FAILED(hr) )
01061             return hr;
01062
01063         hr = _Generate3DMipsPointFilter( depth, levels, mipChain );
01064         if ( FAILED(hr) )
01065             mipChain.Release();
01066         return hr;
01067
01068     case WIC_FLAGS_FILTER_LINEAR:
01069         // Need to implement a 3D bi-linear filter (2x2x2)
01070         return E_NOTIMPL;
01071
01072     case WIC_FLAGS_FILTER_CUBIC:
01073         // Need to implement a 3D bi-cubic filter (3x3x3)
01074         return E_NOTIMPL;
01075
01076     default:
01077         return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );;
01078     }
01079 }
01080
01081 _Use_decl_annotations_
01082 HRESULT GenerateMipMaps3D( const Image* srcImages, size_t nimages, const TexMetadata& metadata,
01083                            DWORD filter, size_t levels, ScratchImage& mipChain )
01084 {
01085     if ( !srcImages || !nimages || !IsValid(metadata.format)
01086          || !ispow2(metadata.width) || !ispow2(metadata.height) || !ispow2(metadata.depth) )
01087         return E_INVALIDARG;
01088
01089     if ( metadata.dimension != TEX_DIMENSION_TEXTURE3D
01090          || IsCompressed( metadata.format ) || IsVideo( metadata.format ) )
01091         return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
01092
01093     if ( !_CalculateMipLevels3D(metadata.width, metadata.height, metadata.depth, levels) )
01094         return E_INVALIDARG;
01095
01096     std::vector<const Image> baseImages;
01097     baseImages.reserve( metadata.depth );
01098     for( size_t slice=0; slice < metadata.depth; ++slice )
01099     {
01100         size_t index = metadata.ComputeIndex( 0, 0, slice );
01101         if ( index >= nimages )
01102             return E_FAIL;
01103
01104         const Image& src = srcImages[ index ];
01105         if ( !src.pixels )
01106             return E_POINTER;
01107
01108         if ( src.format != metadata.format || src.width != metadata.width || src.height != metadata.height )
01109         {
01110             // All base images must be the same format, width, and height
01111             return E_FAIL;
01112         }
01113
01114         baseImages.push_back( src );
01115     }
01116
01117     assert( baseImages.size() == metadata.depth );
01118
01119     HRESULT hr;
01120
01121     static_assert( TEX_FILTER_POINT == 0x100000, "TEX_FILTER_ flag values don't match TEX_FILTER_MASK" );
01122     switch( filter & TEX_FILTER_MASK )
01123     {
01124     case 0:
01125     case TEX_FILTER_FANT:
01126         hr = _Setup3DMips( &baseImages[0], metadata.depth, levels, mipChain );
01127         if ( FAILED(hr) )
01128             return hr;
01129
01130         // For decimation, Fant is equivalent to a Box filter
01131         hr = _Generate3DMipsBoxFilter( metadata.depth, levels, mipChain );
01132         if ( FAILED(hr) )
01133             mipChain.Release();
01134         return hr;
01135
01136     case WIC_FLAGS_FILTER_POINT:
01137         hr = _Setup3DMips( &baseImages[0], metadata.depth, levels, mipChain );
01138         if ( FAILED(hr) )
01139             return hr;
01140
01141         hr = _Generate3DMipsPointFilter( metadata.depth, levels, mipChain );
01142         if ( FAILED(hr) )
01143             mipChain.Release();
01144         return hr;
01145
01146     case WIC_FLAGS_FILTER_LINEAR:
01147         // Need to implement a 3D bi-linear filter (2x2x2)
01148         return E_NOTIMPL;
01149
01150     case WIC_FLAGS_FILTER_CUBIC:
01151         // Need to implement a 3D bi-cubic filter (3x3x3)
01152         return E_NOTIMPL;
01153
01154     default:
01155         return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );;
01156     }
01157 }
01158
01159 }; // namespace
Generated on Sat Nov 23 2024 16:08:12 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D tutorial/C++/Lesson4.Textures/Main.cpp Source File

  • Direct3D tutorial
  • Lesson4.Textures

Main.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 "DirectXSample.h"
00010 #include "BasicMath.h"
00011 #include "BasicReaderWriter.h"
00012
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::UI::Core;
00015 using namespace Windows::Foundation;
00016 using namespace Windows::ApplicationModel::Core;
00017 using namespace Windows::ApplicationModel::Activation;
00018
00019 struct BasicVertex
00020 {
00021     float3 pos;  // position
00022     float3 norm; // surface normal vector
00023     float2 tex;  // texture coordinate
00024 };
00025
00026 struct ConstantBuffer
00027 {
00028     float4x4 model;
00029     float4x4 view;
00030     float4x4 projection;
00031 };
00032
00033 // This class defines the application as a whole.
00034 ref class Direct3DTutorialFrameworkView : public IFrameworkView
00035 {
00036 private:
00037     Platform::Agile<CoreWindow> m_window;
00038     ComPtr<IDXGISwapChain1> m_swapChain;
00039     ComPtr<ID3D11Device1> m_d3dDevice;
00040     ComPtr<ID3D11DeviceContext1> m_d3dDeviceContext;
00041     ComPtr<ID3D11RenderTargetView> m_renderTargetView;
00042     ComPtr<ID3D11DepthStencilView> m_depthStencilView;
00043     ComPtr<ID3D11Buffer> m_constantBuffer;
00044     ConstantBuffer m_constantBufferData;
00045
00046 public:
00047     // This method is called on application launch.
00048     virtual void Initialize(
00049         _In_ CoreApplicationView^ applicationView
00050         )
00051     {
00052         applicationView->Activated +=
00053             ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &Direct3DTutorialFrameworkView::OnActivated);
00054     }
00055
00056     // This method is called after Initialize.
00057     virtual void SetWindow(
00058         _In_ CoreWindow^ window
00059         )
00060     {
00061         m_window = window;
00062
00063         // Specify the cursor type as the standard arrow cursor.
00064         m_window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
00065
00066         // Allow the application to respond when the window size changes.
00067         m_window->SizeChanged +=
00068             ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(
00069                 this,
00070                 &Direct3DTutorialFrameworkView::OnWindowSizeChanged
00071                 );
00072     }
00073
00074     void OnActivated(
00075         _In_ CoreApplicationView^ applicationView,
00076         _In_ IActivatedEventArgs^ args
00077         )
00078     {
00079         // Activate the application window, making it visible and enabling it to receive events.
00080         CoreWindow::GetForCurrentThread()->Activate();
00081     }
00082
00083     virtual void Load(_In_ Platform::String^ entryPoint)
00084     {
00085     }
00086
00087     // This method is called after Load.
00088     virtual void Run()
00089     {
00090         // First, create the Direct3D device.
00091
00092         // This flag is required in order to enable compatibility with Direct2D.
00093         UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00094
00095 #if defined(_DEBUG)
00096         // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00097         creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00098 #endif
00099
00100         // This array defines the ordering of feature levels that D3D should attempt to create.
00101         D3D_FEATURE_LEVEL featureLevels[] =
00102         {
00103             D3D_FEATURE_LEVEL_11_1,
00104             D3D_FEATURE_LEVEL_11_0,
00105             D3D_FEATURE_LEVEL_10_1,
00106             D3D_FEATURE_LEVEL_10_0,
00107             D3D_FEATURE_LEVEL_9_3,
00108             D3D_FEATURE_LEVEL_9_1
00109         };
00110
00111         ComPtr<ID3D11Device> d3dDevice;
00112         ComPtr<ID3D11DeviceContext> d3dDeviceContext;
00113         DX::ThrowIfFailed(
00114             D3D11CreateDevice(
00115                 nullptr,                    // specify nullptr to use the default adapter
00116                 D3D_DRIVER_TYPE_HARDWARE,
00117                 nullptr,                    // leave as nullptr if hardware is used
00118                 creationFlags,              // optionally set debug and Direct2D compatibility flags
00119                 featureLevels,
00120                 ARRAYSIZE(featureLevels),
00121                 D3D11_SDK_VERSION,          // always set this to D3D11_SDK_VERSION
00122                 &d3dDevice,
00123                 nullptr,
00124                 &d3dDeviceContext
00125                 )
00126             );
00127
00128         // Retrieve the Direct3D 11.1 interfaces.
00129         DX::ThrowIfFailed(
00130             d3dDevice.As(&m_d3dDevice)
00131             );
00132
00133         DX::ThrowIfFailed(
00134             d3dDeviceContext.As(&m_d3dDeviceContext)
00135             );
00136
00137
00138         // After the D3D device is created, create additional application resources.
00139         CreateWindowSizeDependentResources();
00140
00141         // Create a Basic Reader-Writer class to load data from disk.  This class is examined
00142         // in the Resource Loading sample.
00143         BasicReaderWriter^ reader = ref new BasicReaderWriter();
00144
00145         // Load the raw vertex shader bytecode from disk and create a vertex shader with it.
00146         auto vertexShaderBytecode = reader->ReadData("SimpleVertexShader.cso");
00147         ComPtr<ID3D11VertexShader> vertexShader;
00148         DX::ThrowIfFailed(
00149             m_d3dDevice->CreateVertexShader(
00150                 vertexShaderBytecode->Data,
00151                 vertexShaderBytecode->Length,
00152                 nullptr,
00153                 &vertexShader
00154                 )
00155             );
00156
00157         // Create an input layout that matches the layout defined in the vertex shader code.
00158         // These correspond to the elements of the BasicVertex struct defined above.
00159         const D3D11_INPUT_ELEMENT_DESC basicVertexLayoutDesc[] =
00160         {
00161             { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0,  0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
00162             { "NORMAL",   0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
00163             { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT,    0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 },
00164         };
00165
00166         ComPtr<ID3D11InputLayout> inputLayout;
00167         DX::ThrowIfFailed(
00168             m_d3dDevice->CreateInputLayout(
00169                 basicVertexLayoutDesc,
00170                 ARRAYSIZE(basicVertexLayoutDesc),
00171                 vertexShaderBytecode->Data,
00172                 vertexShaderBytecode->Length,
00173                 &inputLayout
00174                 )
00175             );
00176
00177         // Load the raw pixel shader bytecode from disk and create a pixel shader with it.
00178         auto pixelShaderBytecode = reader->ReadData("SimplePixelShader.cso");
00179         ComPtr<ID3D11PixelShader> pixelShader;
00180         DX::ThrowIfFailed(
00181             m_d3dDevice->CreatePixelShader(
00182                 pixelShaderBytecode->Data,
00183                 pixelShaderBytecode->Length,
00184                 nullptr,
00185                 &pixelShader
00186                 )
00187             );
00188
00189         // Create vertex and index buffers that define a simple unit cube.
00190
00191         // In the array below, which will be used to initialize the cube vertex buffers,
00192         // multiple vertices are used for each corner to allow different normal vectors and
00193         // texture coordinates to be defined for each face.
00194         BasicVertex cubeVertices[] =
00195         {
00196             { float3(-0.5f, 0.5f, -0.5f), float3(0.0f, 1.0f, 0.0f), float2(0.0f, 0.0f) }, // +Y (top face)
00197             { float3( 0.5f, 0.5f, -0.5f), float3(0.0f, 1.0f, 0.0f), float2(1.0f, 0.0f) },
00198             { float3( 0.5f, 0.5f,  0.5f), float3(0.0f, 1.0f, 0.0f), float2(1.0f, 1.0f) },
00199             { float3(-0.5f, 0.5f,  0.5f), float3(0.0f, 1.0f, 0.0f), float2(0.0f, 1.0f) },
00200
00201             { float3(-0.5f, -0.5f,  0.5f), float3(0.0f, -1.0f, 0.0f), float2(0.0f, 0.0f) }, // -Y (bottom face)
00202             { float3( 0.5f, -0.5f,  0.5f), float3(0.0f, -1.0f, 0.0f), float2(1.0f, 0.0f) },
00203             { float3( 0.5f, -0.5f, -0.5f), float3(0.0f, -1.0f, 0.0f), float2(1.0f, 1.0f) },
00204             { float3(-0.5f, -0.5f, -0.5f), float3(0.0f, -1.0f, 0.0f), float2(0.0f, 1.0f) },
00205
00206             { float3(0.5f,  0.5f,  0.5f), float3(1.0f, 0.0f, 0.0f), float2(0.0f, 0.0f) }, // +X (right face)
00207             { float3(0.5f,  0.5f, -0.5f), float3(1.0f, 0.0f, 0.0f), float2(1.0f, 0.0f) },
00208             { float3(0.5f, -0.5f, -0.5f), float3(1.0f, 0.0f, 0.0f), float2(1.0f, 1.0f) },
00209             { float3(0.5f, -0.5f,  0.5f), float3(1.0f, 0.0f, 0.0f), float2(0.0f, 1.0f) },
00210
00211             { float3(-0.5f,  0.5f, -0.5f), float3(-1.0f, 0.0f, 0.0f), float2(0.0f, 0.0f) }, // -X (left face)
00212             { float3(-0.5f,  0.5f,  0.5f), float3(-1.0f, 0.0f, 0.0f), float2(1.0f, 0.0f) },
00213             { float3(-0.5f, -0.5f,  0.5f), float3(-1.0f, 0.0f, 0.0f), float2(1.0f, 1.0f) },
00214             { float3(-0.5f, -0.5f, -0.5f), float3(-1.0f, 0.0f, 0.0f), float2(0.0f, 1.0f) },
00215
00216             { float3(-0.5f,  0.5f, 0.5f), float3(0.0f, 0.0f, 1.0f), float2(0.0f, 0.0f) }, // +Z (front face)
00217             { float3( 0.5f,  0.5f, 0.5f), float3(0.0f, 0.0f, 1.0f), float2(1.0f, 0.0f) },
00218             { float3( 0.5f, -0.5f, 0.5f), float3(0.0f, 0.0f, 1.0f), float2(1.0f, 1.0f) },
00219             { float3(-0.5f, -0.5f, 0.5f), float3(0.0f, 0.0f, 1.0f), float2(0.0f, 1.0f) },
00220
00221             { float3( 0.5f,  0.5f, -0.5f), float3(0.0f, 0.0f, -1.0f), float2(0.0f, 0.0f) }, // -Z (back face)
00222             { float3(-0.5f,  0.5f, -0.5f), float3(0.0f, 0.0f, -1.0f), float2(1.0f, 0.0f) },
00223             { float3(-0.5f, -0.5f, -0.5f), float3(0.0f, 0.0f, -1.0f), float2(1.0f, 1.0f) },
00224             { float3( 0.5f, -0.5f, -0.5f), float3(0.0f, 0.0f, -1.0f), float2(0.0f, 1.0f) },
00225         };
00226
00227         unsigned short cubeIndices[] =
00228         {
00229             0, 1, 2,
00230             0, 2, 3,
00231
00232             4, 5, 6,
00233             4, 6, 7,
00234
00235             8, 9, 10,
00236             8, 10, 11,
00237
00238             12, 13, 14,
00239             12, 14, 15,
00240
00241             16, 17, 18,
00242             16, 18, 19,
00243
00244             20, 21, 22,
00245             20, 22, 23
00246         };
00247
00248         D3D11_BUFFER_DESC vertexBufferDesc = {0};
00249         vertexBufferDesc.ByteWidth = sizeof(BasicVertex) * ARRAYSIZE(cubeVertices);
00250         vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
00251         vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
00252         vertexBufferDesc.CPUAccessFlags = 0;
00253         vertexBufferDesc.MiscFlags = 0;
00254         vertexBufferDesc.StructureByteStride = 0;
00255
00256         D3D11_SUBRESOURCE_DATA vertexBufferData;
00257         vertexBufferData.pSysMem = cubeVertices;
00258         vertexBufferData.SysMemPitch = 0;
00259         vertexBufferData.SysMemSlicePitch = 0;
00260
00261         ComPtr<ID3D11Buffer> vertexBuffer;
00262         DX::ThrowIfFailed(
00263             m_d3dDevice->CreateBuffer(
00264                 &vertexBufferDesc,
00265                 &vertexBufferData,
00266                 &vertexBuffer
00267                 )
00268             );
00269
00270         D3D11_BUFFER_DESC indexBufferDesc;
00271         indexBufferDesc.ByteWidth = sizeof(unsigned short) * ARRAYSIZE(cubeIndices);
00272         indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
00273         indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
00274         indexBufferDesc.CPUAccessFlags = 0;
00275         indexBufferDesc.MiscFlags = 0;
00276         indexBufferDesc.StructureByteStride = 0;
00277
00278         D3D11_SUBRESOURCE_DATA indexBufferData;
00279         indexBufferData.pSysMem = cubeIndices;
00280         indexBufferData.SysMemPitch = 0;
00281         indexBufferData.SysMemSlicePitch = 0;
00282
00283         ComPtr<ID3D11Buffer> indexBuffer;
00284         DX::ThrowIfFailed(
00285             m_d3dDevice->CreateBuffer(
00286                 &indexBufferDesc,
00287                 &indexBufferData,
00288                 &indexBuffer
00289                 )
00290             );
00291
00292
00293         // Create a constant buffer for passing model, view, and projection matrices
00294         // to the vertex shader.  This will allow us to rotate the cube and apply
00295         // a perspective projection to it.
00296
00297         D3D11_BUFFER_DESC constantBufferDesc = {0};
00298         constantBufferDesc.ByteWidth = sizeof(m_constantBufferData);
00299         constantBufferDesc.Usage = D3D11_USAGE_DEFAULT;
00300         constantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
00301         constantBufferDesc.CPUAccessFlags = 0;
00302         constantBufferDesc.MiscFlags = 0;
00303         constantBufferDesc.StructureByteStride = 0;
00304         DX::ThrowIfFailed(
00305             m_d3dDevice->CreateBuffer(
00306                 &constantBufferDesc,
00307                 nullptr,
00308                 &m_constantBuffer
00309                 )
00310             );
00311
00312         // Specify the view transform corresponding to a camera position of
00313         // X = 0, Y = 1, Z = 2.  See Lesson 5 for a generalized camera class.
00314
00315         m_constantBufferData.view = float4x4(
00316             -1.00000000f, 0.00000000f,  0.00000000f,  0.00000000f,
00317              0.00000000f, 0.89442718f,  0.44721359f,  0.00000000f,
00318              0.00000000f, 0.44721359f, -0.89442718f, -2.23606800f,
00319              0.00000000f, 0.00000000f,  0.00000000f,  1.00000000f
00320             );
00321
00322
00323         // Load the raw texture data from disk and construct a subresource description that references it.
00324         auto textureData = reader->ReadData("texturedata.bin");
00325         D3D11_SUBRESOURCE_DATA textureSubresourceData = {0};
00326         textureSubresourceData.pSysMem = textureData->Data;
00327
00328         // Specify the size of a row in bytes, known a priori about the texture data.
00329         textureSubresourceData.SysMemPitch = 1024;
00330
00331         // As this is not a texture array or 3D texture, this parameter is ignored.
00332         textureSubresourceData.SysMemSlicePitch = 0;
00333
00334         // Create a texture description from information known a priori about the data.
00335         // Generalized texture loading code can be found in the Resource Loading sample.
00336         D3D11_TEXTURE2D_DESC textureDesc = {0};
00337         textureDesc.Width = 256;
00338         textureDesc.Height = 256;
00339         textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
00340         textureDesc.Usage = D3D11_USAGE_DEFAULT;
00341         textureDesc.CPUAccessFlags = 0;
00342         textureDesc.MiscFlags = 0;
00343
00344         // Most textures contain more than one MIP level.  For simplicity, this sample uses only one.
00345         textureDesc.MipLevels = 1;
00346
00347         // As this will not be a texture array, this parameter is ignored.
00348         textureDesc.ArraySize = 1;
00349
00350         // Don't use multi-sampling.
00351         textureDesc.SampleDesc.Count = 1;
00352         textureDesc.SampleDesc.Quality = 0;
00353
00354         // Allow the texture to be bound as a shader resource.
00355         textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
00356
00357         ComPtr<ID3D11Texture2D> texture;
00358         DX::ThrowIfFailed(
00359             m_d3dDevice->CreateTexture2D(
00360                 &textureDesc,
00361                 &textureSubresourceData,
00362                 &texture
00363                 )
00364             );
00365
00366         // Once the texture is created, we must create a shader resource view of it
00367         // so that shaders may use it.  In general, the view description will match
00368         // the texture description.
00369         D3D11_SHADER_RESOURCE_VIEW_DESC textureViewDesc;
00370         ZeroMemory(&textureViewDesc, sizeof(textureViewDesc));
00371         textureViewDesc.Format = textureDesc.Format;
00372         textureViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
00373         textureViewDesc.Texture2D.MipLevels = textureDesc.MipLevels;
00374         textureViewDesc.Texture2D.MostDetailedMip = 0;
00375
00376         ComPtr<ID3D11ShaderResourceView> textureView;
00377         DX::ThrowIfFailed(
00378             m_d3dDevice->CreateShaderResourceView(
00379                 texture.Get(),
00380                 &textureViewDesc,
00381                 &textureView
00382                 )
00383             );
00384
00385         // Once the texture view is created, create a sampler.  This defines how the color
00386         // for a particular texture coordinate is determined using the relevant texture data.
00387         D3D11_SAMPLER_DESC samplerDesc;
00388         ZeroMemory(&samplerDesc, sizeof(samplerDesc));
00389
00390         samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
00391
00392         // The sampler does not use anisotropic filtering, so this parameter is ignored.
00393         samplerDesc.MaxAnisotropy = 0;
00394
00395         // Specify how texture coordinates outside of the range 0..1 are resolved.
00396         samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
00397         samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
00398         samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
00399
00400         // Use no special MIP clamping or bias.
00401         samplerDesc.MipLODBias = 0.0f;
00402         samplerDesc.MinLOD = 0;
00403         samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
00404
00405         // Don't use a comparison function.
00406         samplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
00407
00408         // Border address mode is not used, so this parameter is ignored.
00409         samplerDesc.BorderColor[0] = 0.0f;
00410         samplerDesc.BorderColor[1] = 0.0f;
00411         samplerDesc.BorderColor[2] = 0.0f;
00412         samplerDesc.BorderColor[3] = 0.0f;
00413
00414         ComPtr<ID3D11SamplerState> sampler;
00415         DX::ThrowIfFailed(
00416             m_d3dDevice->CreateSamplerState(
00417                 &samplerDesc,
00418                 &sampler
00419                 )
00420             );
00421
00422
00423         // This value will be used to animate the cube by rotating it every frame;
00424         float degree = 0.0f;
00425
00426         // Enter the render loop. Note that Windows Store apps should never exit.
00427         while (true)
00428         {
00429             // Process events incoming to the window.
00430             m_window->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
00431
00432             // Update the constant buffer to rotate the cube model.
00433             m_constantBufferData.model = rotationY(-degree);
00434             degree += 1.0f;
00435
00436             m_d3dDeviceContext->UpdateSubresource(
00437                 m_constantBuffer.Get(),
00438                 0,
00439                 nullptr,
00440                 &m_constantBufferData,
00441                 0,
00442                 0
00443                 );
00444
00445             // Specify the render target and depth stencil we created as the output target.
00446             m_d3dDeviceContext->OMSetRenderTargets(
00447                 1,
00448                 m_renderTargetView.GetAddressOf(),
00449                 m_depthStencilView.Get()
00450                 );
00451
00452             // Clear the render target to a solid color, and reset the depth stencil.
00453             const float clearColor[4] = { 0.071f, 0.04f, 0.561f, 1.0f };
00454             m_d3dDeviceContext->ClearRenderTargetView(
00455                 m_renderTargetView.Get(),
00456                 clearColor
00457                 );
00458
00459             m_d3dDeviceContext->ClearDepthStencilView(
00460                 m_depthStencilView.Get(),
00461                 D3D11_CLEAR_DEPTH,
00462                 1.0f,
00463                 0
00464                 );
00465
00466             m_d3dDeviceContext->IASetInputLayout(inputLayout.Get());
00467
00468             // Set the vertex and index buffers, and specify the way they define geometry.
00469             UINT stride = sizeof(BasicVertex);
00470             UINT offset = 0;
00471             m_d3dDeviceContext->IASetVertexBuffers(
00472                 0,
00473                 1,
00474                 vertexBuffer.GetAddressOf(),
00475                 &stride,
00476                 &offset
00477                 );
00478
00479             m_d3dDeviceContext->IASetIndexBuffer(
00480                 indexBuffer.Get(),
00481                 DXGI_FORMAT_R16_UINT,
00482                 0
00483                 );
00484
00485             m_d3dDeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
00486
00487             // Set the vertex and pixel shader stage state.
00488             m_d3dDeviceContext->VSSetShader(
00489                 vertexShader.Get(),
00490                 nullptr,
00491                 0
00492                 );
00493
00494             m_d3dDeviceContext->VSSetConstantBuffers(
00495                 0,
00496                 1,
00497                 m_constantBuffer.GetAddressOf()
00498                 );
00499
00500             m_d3dDeviceContext->PSSetShader(
00501                 pixelShader.Get(),
00502                 nullptr,
00503                 0
00504                 );
00505
00506             m_d3dDeviceContext->PSSetShaderResources(
00507                 0,
00508                 1,
00509                 textureView.GetAddressOf()
00510                 );
00511
00512             m_d3dDeviceContext->PSSetSamplers(
00513                 0,
00514                 1,
00515                 sampler.GetAddressOf()
00516                 );
00517
00518             // Draw the cube.
00519             m_d3dDeviceContext->DrawIndexed(
00520                 ARRAYSIZE(cubeIndices),
00521                 0,
00522                 0
00523                 );
00524
00525             // Present the rendered image to the window.  Because the maximum frame latency is set to 1,
00526             // the render loop will generally be throttled to the screen refresh rate, typically around
00527             // 60Hz, by sleeping the application on Present until the screen is refreshed.
00528             DX::ThrowIfFailed(
00529                 m_swapChain->Present(1, 0)
00530                 );
00531         }
00532     }
00533
00534     // This method is called before the application exits.
00535     virtual void Uninitialize()
00536     {
00537     }
00538
00539 private:
00540
00541     // This method is called whenever the application window size changes.
00542     void OnWindowSizeChanged(
00543         _In_ CoreWindow^ sender,
00544         _In_ WindowSizeChangedEventArgs^ args
00545         )
00546     {
00547         m_renderTargetView = nullptr;
00548         m_depthStencilView = nullptr;
00549         CreateWindowSizeDependentResources();
00550     }
00551
00552     // This method creates all application resources that depend on
00553     // the application window size.  It is called at app initialization,
00554     // and whenever the application window size changes.
00555     void CreateWindowSizeDependentResources()
00556     {
00557         if (m_swapChain != nullptr)
00558         {
00559             // If the swap chain already exists, resize it.
00560             DX::ThrowIfFailed(
00561                 m_swapChain->ResizeBuffers(
00562                     2,
00563                     0,
00564                     0,
00565                     DXGI_FORMAT_B8G8R8A8_UNORM,
00566                     0
00567                     )
00568                 );
00569         }
00570         else
00571         {
00572             // If the swap chain does not exist, create it.
00573             DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00574
00575             swapChainDesc.Stereo = false;
00576             swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00577             swapChainDesc.Scaling = DXGI_SCALING_NONE;
00578             swapChainDesc.Flags = 0;
00579
00580             // Use automatic sizing.
00581             swapChainDesc.Width = 0;
00582             swapChainDesc.Height = 0;
00583
00584             // This is the most common swap chain format.
00585             swapChainDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
00586
00587             // Don't use multi-sampling.
00588             swapChainDesc.SampleDesc.Count = 1;
00589             swapChainDesc.SampleDesc.Quality = 0;
00590
00591             // Use two buffers to enable flip effect.
00592             swapChainDesc.BufferCount = 2;
00593
00594             // We recommend using this swap effect for all applications.
00595             swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
00596
00597
00598             // Once the swap chain description is configured, it must be
00599             // created on the same adapter as the existing D3D Device.
00600
00601             // First, retrieve the underlying DXGI Device from the D3D Device.
00602             ComPtr<IDXGIDevice2> dxgiDevice;
00603             DX::ThrowIfFailed(
00604                 m_d3dDevice.As(&dxgiDevice)
00605                 );
00606
00607             // Ensure that DXGI does not queue more than one frame at a time. This both reduces
00608             // latency and ensures that the application will only render after each VSync, minimizing
00609             // power consumption.
00610             DX::ThrowIfFailed(
00611                 dxgiDevice->SetMaximumFrameLatency(1)
00612                 );
00613
00614             // Next, get the parent factory from the DXGI Device.
00615             ComPtr<IDXGIAdapter> dxgiAdapter;
00616             DX::ThrowIfFailed(
00617                 dxgiDevice->GetAdapter(&dxgiAdapter)
00618                 );
00619
00620             ComPtr<IDXGIFactory2> dxgiFactory;
00621             DX::ThrowIfFailed(
00622                 dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00623                 );
00624
00625             // Finally, create the swap chain.
00626             CoreWindow^ window = m_window.Get();
00627             DX::ThrowIfFailed(
00628                 dxgiFactory->CreateSwapChainForCoreWindow(
00629                     m_d3dDevice.Get(),
00630                     reinterpret_cast<IUnknown*>(window),
00631                     &swapChainDesc,
00632                     nullptr, // allow on all displays
00633                     &m_swapChain
00634                     )
00635                 );
00636         }
00637
00638         // Once the swap chain is created, create a render target view.  This will
00639         // allow Direct3D to render graphics to the window.
00640
00641         ComPtr<ID3D11Texture2D> backBuffer;
00642         DX::ThrowIfFailed(
00643             m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00644             );
00645
00646         DX::ThrowIfFailed(
00647             m_d3dDevice->CreateRenderTargetView(
00648                 backBuffer.Get(),
00649                 nullptr,
00650                 &m_renderTargetView
00651                 )
00652             );
00653
00654         // Once the render target view is created, create a depth stencil view.  This
00655         // allows Direct3D to efficiently render objects closer to the camera in front
00656         // of objects further from the camera.
00657
00658         D3D11_TEXTURE2D_DESC backBufferDesc = {0};
00659         backBuffer->GetDesc(&backBufferDesc);
00660
00661         D3D11_TEXTURE2D_DESC depthStencilDesc;
00662         depthStencilDesc.Width = backBufferDesc.Width;
00663         depthStencilDesc.Height = backBufferDesc.Height;
00664         depthStencilDesc.MipLevels = 1;
00665         depthStencilDesc.ArraySize = 1;
00666         depthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
00667         depthStencilDesc.SampleDesc.Count = 1;
00668         depthStencilDesc.SampleDesc.Quality = 0;
00669         depthStencilDesc.Usage = D3D11_USAGE_DEFAULT;
00670         depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
00671         depthStencilDesc.CPUAccessFlags = 0;
00672         depthStencilDesc.MiscFlags = 0;
00673         ComPtr<ID3D11Texture2D> depthStencil;
00674         DX::ThrowIfFailed(
00675             m_d3dDevice->CreateTexture2D(
00676                 &depthStencilDesc,
00677                 nullptr,
00678                 &depthStencil
00679                 )
00680             );
00681
00682         D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
00683         depthStencilViewDesc.Format = depthStencilDesc.Format;
00684         depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
00685         depthStencilViewDesc.Flags = 0;
00686         depthStencilViewDesc.Texture2D.MipSlice = 0;
00687         DX::ThrowIfFailed(
00688             m_d3dDevice->CreateDepthStencilView(
00689                 depthStencil.Get(),
00690                 &depthStencilViewDesc,
00691                 &m_depthStencilView
00692                 )
00693             );
00694
00695         // After the render target and depth stencil views are created, specify that
00696         // the viewport, which describes what portion of the window to draw to, should
00697         // cover the entire window.
00698
00699         D3D11_VIEWPORT viewport;
00700         viewport.TopLeftX = 0.0f;
00701         viewport.TopLeftY = 0.0f;
00702         viewport.Width = static_cast<float>(backBufferDesc.Width);
00703         viewport.Height = static_cast<float>(backBufferDesc.Height);
00704         viewport.MinDepth = D3D11_MIN_DEPTH;
00705         viewport.MaxDepth = D3D11_MAX_DEPTH;
00706
00707         m_d3dDeviceContext->RSSetViewports(1, &viewport);
00708
00709         // Finally, update the constant buffer perspective projection parameters
00710         // to account for the size of the application window.  In this sample,
00711         // the parameters are fixed to a 70-degree field of view, with a depth
00712         // range of 0.01 to 100.  See Lesson 5 for a generalized camera class.
00713
00714         float xScale = 1.42814801f;
00715         float yScale = 1.42814801f;
00716         if (backBufferDesc.Width > backBufferDesc.Height)
00717         {
00718             xScale = yScale *
00719                 static_cast<float>(backBufferDesc.Height) /
00720                 static_cast<float>(backBufferDesc.Width);
00721         }
00722         else
00723         {
00724             yScale = xScale *
00725                 static_cast<float>(backBufferDesc.Width) /
00726                 static_cast<float>(backBufferDesc.Height);
00727         }
00728
00729         m_constantBufferData.projection = float4x4(
00730             xScale, 0.0f,    0.0f,  0.0f,
00731             0.0f,   yScale,  0.0f,  0.0f,
00732             0.0f,   0.0f,   -1.0f, -0.01f,
00733             0.0f,   0.0f,   -1.0f,  0.0f
00734             );
00735     }
00736 };
00737
00738 // This class defines how to create the custom View Provider defined above.
00739 ref class Direct3DTutorialFrameworkViewSource : IFrameworkViewSource
00740 {
00741 public:
00742     virtual IFrameworkView^ CreateView()
00743     {
00744         return ref new Direct3DTutorialFrameworkView();
00745     }
00746 };
00747
00748 [Platform::MTAThread]
00749 int main(Platform::Array<Platform::String^>^)
00750 {
00751     auto frameworkViewSource = ref new Direct3DTutorialFrameworkViewSource();
00752     Windows::ApplicationModel::Core::CoreApplication::Run(frameworkViewSource);
00753     return 0;
00754 }
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D stereoscopic 3D/C++/DirectXSample.h Source File

  • Direct3D stereoscopic 3D

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
00010 // This header defines helper utilities to make DirectX APIs work with exceptions.
00011 namespace DX
00012 {
00013     inline void ThrowIfFailed(HRESULT hr)
00014     {
00015         if (FAILED(hr))
00016         {
00017             // Set a breakpoint on this line to catch DX API errors.
00018             throw Platform::Exception::CreateException(hr);
00019         }
00020     }
00021 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Background::sealed Member List

This is the complete list of members for Background::sealed, including all inherited members.
InvokeSimpleToast(String^msgReceived) | Background::sealed |
InvokeSimpleToast(String^messageReceived) | Background::sealed |
Run(IBackgroundTaskInstance^taskInstance) | Background::sealed | [virtual]
Run(IBackgroundTaskInstance^taskInstance) | Background::sealed | [virtual]
Run(IBackgroundTaskInstance^taskInstance) | Background::sealed | [virtual]
Run(IBackgroundTaskInstance^taskInstance) | Background::sealed | [virtual]
Run(IBackgroundTaskInstance^taskInstance) | Background::sealed | [virtual]
Run(IBackgroundTaskInstance^taskInstance) | Background::sealed | [virtual]
Generated on Sat Nov 23 2024 16:09:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playlist/C++/Constants.cpp Source File

  • Playlist

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Array<Scenario>^ MainPage::scenariosInner = ref new Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
00021     { "Create a playlist", "SDKSample.Playlists.Create"},
00022     { "Display a playlist", "SDKSample.Playlists.Display"},
00023     { "Add items to a playlist", "SDKSample.Playlists.Add"},
00024     { "Remove an item from a playlist", "SDKSample.Playlists.Remove"},
00025     { "Clear a playlist", "SDKSample.Playlists.Clear"}
00026 };
00027
00028 Array<String^>^ MainPage::audioExtensionsInner = ref new Array<String^>
00029 {
00030     L".wma",  L".mp3",  L".mp2",  L".aac", L".adt", L".adts", L".m4a"
00031 };
00032
00033 Array<String^>^ MainPage::playlistExtensionsInner = ref new Array<String^>
00034 {
00035     L".m3u", L".wpl", L".zpl"
00036 };
00037
00038 Playlist^ MainPage::playlistInner = nullptr;
00039
00040 FileOpenPicker^ MainPage::CreateFilePicker(Array<String^>^ extensions)
00041 {
00042     FileOpenPicker^ picker = ref new FileOpenPicker();
00043     picker->SuggestedStartLocation = PickerLocationId::MusicLibrary;
00044
00045     // Load the picker with the desired extensions.
00046     for(unsigned int i = 0; i < extensions->Length; i++)
00047     {
00048         picker->FileTypeFilter->Append(extensions[i]);
00049     }
00050
00051     return picker;
00052 }
00053
00054 task<Playlist^> MainPage::PickPlaylist()
00055 {
00056     // Pick a file, then load it as a playlist.
00057     FileOpenPicker^ picker = MainPage::CreateFilePicker(MainPage::playlistExtensions);
00058     return task<StorageFile^>(picker->PickSingleFileAsync()).then([](StorageFile^ file)
00059     {
00060         return Playlist::LoadAsync(file);
00061     });
00062 }
00063
00064 bool MainPage::EnsureUnsnapped()
00065 {
00066     bool success = true;
00067
00068     // Try to unsnap if we are currently snapped
00069     if(ApplicationView::Value == ApplicationViewState::Snapped)
00070     {
00071         success = ApplicationView::TryUnsnap();
00072     }
00073
00074     return success;
00075 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite vertical text/C++/DWriteVerticalText.cpp Source File

  • DirectWrite vertical text

DWriteVerticalText.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 "DWriteVerticalText.h"
00010
00011 using namespace Microsoft::WRL;
00012 using namespace Windows::ApplicationModel;
00013 using namespace Windows::ApplicationModel::Core;
00014 using namespace Windows::ApplicationModel::Activation;
00015 using namespace Windows::UI::Core;
00016 using namespace Windows::System;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Graphics::Display;
00019
00020 DWriteVerticalText::DWriteVerticalText()
00021 {
00022 }
00023
00024 void DWriteVerticalText::CreateDeviceIndependentResources()
00025 {
00026     DirectXBase::CreateDeviceIndependentResources();
00027
00028     // Set Layout Sample Text
00029     m_readingDirection = ReadingDirectionLeftToRightTopToBottom;
00030     m_text =
00031         L"『世界人権宣言』\r\n"
00032         L"（1948.12.10 第３回国連総会採択）〈前文〉\r\n"
00033         L"\r\n"
00034         L"人類社会のすべての構成員の固有の尊厳と平等で譲ることのできない権利とを承認することは、世界における自由、正義及び平和の基礎であるので、\r\n"
00035         L"\r\n"
00036         L"人権の無視及び軽侮が、人類の良心を踏みにじった野蛮行為をもたらし、言論及び信仰の自由が受けられ、恐怖及び欠乏のない世界の到来が、一般の人々の最高の願望として宣言されたので、\r\n"
00037         L"\r\n"
00038         L"人間が専制と圧迫とに対する最後の手段として反逆に訴えることがないようにするためには、法の支配によって人権を保護することが肝要であるので、\r\n"
00039         L"\r\n"
00040         L"諸国間の友好関係の発展を促進することが肝要であるので、\r\n"
00041         L"\r\n"
00042         L"国際連合の諸国民は、国連憲章において、基本的人権、人間の尊厳及び価値並びに男女の同権についての信念を再確認し、かつ、一層大きな自由のうちで社会的進歩と生活水準の向上とを促進することを決意したので、\r\n"
00043         L"\r\n"
00044         L"加盟国は、国際連合と協力して、人権及び基本的自由の普遍的な尊重及び遵守の促進を達成することを誓約したので、\r\n"
00045         L"\r\n"
00046         L"これらの権利及び自由に対する共通の理解は、この誓約を完全にするためにもっとも重要であるので、\r\n"
00047         L"\r\n"
00048         L"よって、ここに、国連総会は、\r\n"
00049         L"\r\n"
00050         L"\r\n"
00051         L"社会の各個人及び各機関が、この世界人権宣言を常に念頭に置きながら、加盟国自身の人民の間にも、また、加盟国の管轄下にある地域の人民の間にも、これらの権利と自由との尊重を指導及び教育によって促進すること並びにそれらの普遍的措置によって確保することに努力するように、すべての人民とすべての国とが達成すべき共通の基準として、この人権宣言を公布する。\r\n"
00052         L"\r\n"
00053         L"第１条\r\n"
00054         L"すべての人間は、生まれながらにして自由であり、かつ、尊厳と権利と について平等である。人間は、理性と良心とを授けられており、互いに同 胞の精神をもって行動しなければならない。\r\n"
00055         L"\r\n"
00056         L"第２条"
00057         L"すべて人は、人種、皮膚の色、性、言語、宗教、政治上その他の意見、\r\n"
00058         L"\r\n"
00059         L"国民的もしくは社会的出身、財産、門地その他の地位又はこれに類するい\r\n"
00060         L"\r\n"
00061         L"かなる自由による差別をも受けることなく、この宣言に掲げるすべての権\r\n"
00062         L"\r\n"
00063         L"利と自由とを享有することができる。\r\n"
00064         L"\r\n"
00065         L"さらに、個人の属する国又は地域が独立国であると、信託統治地域で\r\n"
00066         L"\r\n"
00067         L"あると、非自治地域であると、又は他のなんらかの主権制限の下にあると\r\n"
00068         L"\r\n"
00069         L"を問わず、その国又は地域の政治上、管轄上又は国際上の地位に基ずくい\r\n"
00070         L"\r\n"
00071         L"かなる差別もしてはならない。\r\n"
00072         L"\r\n"
00073         L"第３条\r\n"
00074         L"すべての人は、生命、自由及び身体の安全に対する権利を有する。\r\n"
00075         L"\r\n"
00076         L"第４条\r\n"
00077         L"何人も、奴隷にされ、又は苦役に服することはない。奴隷制度及び奴隷\r\n"
00078         L"\r\n"
00079         L"売買は、いかなる形においても禁止する。\r\n"
00080         L"\r\n"
00081         L"第５条\r\n"
00082         L"何人も、拷問又は残虐な、非人道的なもしくは屈辱的な取扱もしくは刑\r\n"
00083         L"\r\n"
00084         L"罰を受けることはない。\r\n";
00085
00086     m_fontName                        = L"";
00087     m_localeName                      = L"";
00088     m_textLength                      = 0;
00089     m_fontSize                        = 14;
00090
00091     m_fontName = L"Meiryo UI";
00092     m_localeName = L"ja-jp";
00093     m_readingDirection = ReadingDirectionTopToBottomRightToLeft;
00094
00095     DX::ThrowIfFailed(
00096         m_dwriteFactory->CreateTextFormat(
00097             m_fontName,
00098             nullptr,
00099             DWRITE_FONT_WEIGHT_NORMAL,
00100             DWRITE_FONT_STYLE_NORMAL,
00101             DWRITE_FONT_STRETCH_NORMAL,
00102             m_fontSize,
00103             m_localeName,
00104             &m_textFormat
00105             )
00106         );
00107 }
00108
00109 void DWriteVerticalText::CreateDeviceResources()
00110 {
00111     DirectXBase::CreateDeviceResources();
00112
00113     m_sampleOverlay = ref new SampleOverlay();
00114
00115     m_sampleOverlay->Initialize(
00116         m_d2dDevice.Get(),
00117         m_d2dContext.Get(),
00118         m_wicFactory.Get(),
00119         m_dwriteFactory.Get(),
00120         "DirectWrite vertical text sample"
00121         );
00122
00123     DX::ThrowIfFailed(
00124         m_d2dContext->CreateSolidColorBrush(
00125             D2D1::ColorF(D2D1::ColorF::Black),
00126             &m_blackBrush
00127             )
00128         );
00129 }
00130
00131 void DWriteVerticalText::CreateWindowSizeDependentResources()
00132 {
00133     DirectXBase::CreateWindowSizeDependentResources();
00134
00135     D2D1_SIZE_F size = m_d2dContext->GetSize();
00136
00137     m_flowLayoutSource = new FlowLayoutSource;
00138     m_flowLayoutSink = new FlowLayoutSink(m_dwriteFactory.Get());
00139     m_flowLayout = new FlowLayout(m_dwriteFactory.Get());
00140     m_flowLayout->SetTextFormat(m_textFormat.Get());
00141     m_flowLayout->SetReadingDirection(m_readingDirection);
00142     m_flowLayout->SetReadingDirection(m_readingDirection);
00143
00144     if (m_textLength == 0)
00145     {
00146         m_textLength = static_cast<UINT32>(wcsnlen(m_text, UINT32_MAX));
00147     }
00148
00149     m_flowLayout->SetText(m_text, m_textLength);
00150     m_flowLayout->AnalyzeText();
00151     m_flowLayoutSource->SetSize(size.width, size.height);
00152     m_flowLayoutSource->Reset();
00153     m_flowLayoutSink->Reset();
00154     m_flowLayout->FlowText(m_flowLayoutSource.Get(), m_flowLayoutSink.Get());
00155 }
00156
00157 void DWriteVerticalText::Render()
00158 {
00159     m_d2dContext->BeginDraw();
00160     m_d2dContext->Clear(D2D1::ColorF(D2D1::ColorF::CornflowerBlue));
00161     m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00162
00163     m_flowLayoutSink->DrawGlyphRuns(m_d2dContext.Get(), m_renderingParams.Get(), m_blackBrush.Get());
00164
00165     // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00166     // is lost. It will be handled during the next call to Present.
00167     HRESULT hr = m_d2dContext->EndDraw();
00168     if (hr != D2DERR_RECREATE_TARGET)
00169     {
00170         DX::ThrowIfFailed(hr);
00171     }
00172
00173     m_sampleOverlay->Render();
00174 }
00175
00176 void DWriteVerticalText::Initialize(
00177     _In_ CoreApplicationView^ applicationView
00178     )
00179 {
00180     applicationView->Activated +=
00181         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &DWriteVerticalText::OnActivated);
00182 }
00183
00184 void DWriteVerticalText::SetWindow(
00185     _In_ CoreWindow^ window
00186     )
00187 {
00188     window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
00189
00190     window->SizeChanged +=
00191         ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &DWriteVerticalText::OnWindowSizeChanged);
00192
00193     DisplayProperties::LogicalDpiChanged +=
00194         ref new DisplayPropertiesEventHandler(this, &DWriteVerticalText::OnLogicalDpiChanged);
00195
00196     DisplayProperties::DisplayContentsInvalidated +=
00197         ref new DisplayPropertiesEventHandler(this, &DWriteVerticalText::OnDisplayContentsInvalidated);
00198
00199     DirectXBase::Initialize(window, DisplayProperties::LogicalDpi);
00200 }
00201
00202 void DWriteVerticalText::Load(
00203     _In_ Platform::String^ entryPoint
00204     )
00205 {
00206 }
00207
00208 void DWriteVerticalText::Run()
00209 {
00210     m_window->Activate();
00211
00212     Render();
00213     Present();
00214
00215     m_window->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessUntilQuit);
00216 }
00217
00218 void DWriteVerticalText::Uninitialize()
00219 {
00220 }
00221
00222 void DWriteVerticalText::OnWindowSizeChanged(
00223     _In_ CoreWindow^ sender,
00224     _In_ WindowSizeChangedEventArgs^ args
00225     )
00226 {
00227     UpdateForWindowSizeChange();
00228     m_sampleOverlay->UpdateForWindowSizeChange();
00229     Render();
00230     Present();
00231 }
00232
00233 void DWriteVerticalText::OnLogicalDpiChanged(
00234     _In_ Platform::Object^ sender
00235     )
00236 {
00237     SetDpi(DisplayProperties::LogicalDpi);
00238     Render();
00239     Present();
00240 }
00241
00242 void DWriteVerticalText::OnDisplayContentsInvalidated(
00243     _In_ Platform::Object^ sender
00244     )
00245 {
00246     // Ensure the D3D Device is available for rendering.
00247     ValidateDevice();
00248
00249     Render();
00250     Present();
00251 }
00252
00253 void DWriteVerticalText::OnActivated(
00254     _In_ CoreApplicationView^ applicationView,
00255     _In_ IActivatedEventArgs^ args
00256     )
00257 {
00258     m_window->Activate();
00259 }
00260
00261 IFrameworkView^ DirectXAppSource::CreateView()
00262 {
00263     return ref new DWriteVerticalText();
00264 }
00265
00266 [Platform::MTAThread]
00267 int main(Platform::Array<Platform::String^>^)
00268 {
00269     auto directXAppSource = ref new DirectXAppSource();
00270     CoreApplication::Run(directXAppSource);
00271     return 0;
00272 }
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SimpleController Member List

This is the complete list of members for SimpleController, including all inherited members.
__pad0__ | SimpleController |
CreateDeviceResources() override | SimpleController | [virtual]
CreateWindowSizeDependentResources() override | SimpleController | [virtual]
DrawButtonText(uint16 buttons, const D2D1_RECT_F &loc) | SimpleController | [private]
DrawHeader(const wchar_t *pText, const D2D1_RECT_F &loc) | SimpleController | [private]
DrawText(const wchar_t *pText, const D2D1_RECT_F &loc) | SimpleController | [private]
DrawText(uint32 value, const D2D1_RECT_F &loc) | SimpleController | [private]
DrawText(int16 value, const D2D1_RECT_F &loc) | SimpleController | [private]
DrawText(uint8 value, const D2D1_RECT_F &loc) | SimpleController | [private]
FetchControllerInput() | SimpleController | [private]
m_dataTextFormat | SimpleController | [private]
m_headerTextFormat | SimpleController | [private]
m_isControllerConnected | SimpleController | [private]
m_lastEnumTime | SimpleController | [private]
m_sampleOverlay | SimpleController | [private]
m_textBrush | SimpleController | [private]
m_xinputCaps | SimpleController | [private]
m_xinputState | SimpleController | [private]
Render() override | SimpleController | [virtual]
RenderControllerInput() | SimpleController | [private]
Update(float timeTotal, float timeDelta) | SimpleController |
Generated on Sat Nov 23 2024 16:09:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Thread pool/C++/common/LayoutAwarePage.h Source File

  • Thread pool
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAudio2 audio stream effect/C++/DirectXApp.h Source File

  • XAudio2 audio stream effect

DirectXApp.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 "StreamEffect.h"
00011
00012 ref class DirectXApp : public Windows::ApplicationModel::Core::IFrameworkView
00013 {
00014 internal:
00015     DirectXApp();
00016
00017 public:
00018     // IFrameworkView Methods
00019     virtual void Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00020     virtual void SetWindow(_In_ Windows::UI::Core::CoreWindow^ window);
00021     virtual void Load(_In_ Platform::String^ entryPoint);
00022     virtual void Run();
00023     virtual void Uninitialize();
00024
00025 private:
00026     // Event Handlers
00027     void OnWindowSizeChanged(
00028         _In_ Windows::UI::Core::CoreWindow^ sender,
00029         _In_ Windows::UI::Core::WindowSizeChangedEventArgs^ args
00030         );
00031
00032     void OnVisibilityChanged(
00033         _In_ Windows::UI::Core::CoreWindow^ sender,
00034         _In_ Windows::UI::Core::VisibilityChangedEventArgs^ args
00035         );
00036
00037     void OnLogicalDpiChanged(
00038         _In_ Platform::Object^ sender
00039         );
00040
00041     void OnActivated(
00042         _In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView,
00043         _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^ args
00044         );
00045
00046     void OnSuspending(
00047         _In_ Platform::Object^ sender,
00048         _In_ Windows::ApplicationModel::SuspendingEventArgs^ args
00049         );
00050
00051     void OnResuming(
00052         _In_ Platform::Object^ sender,
00053         _In_ Platform::Object^ args
00054         );
00055
00056     void OnWindowClosed(
00057         _In_ Windows::UI::Core::CoreWindow^ sender,
00058         _In_ Windows::UI::Core::CoreWindowEventArgs^ args
00059         );
00060
00061     StreamEffect^ m_renderer;
00062     bool m_windowClosed;
00063     bool m_windowVisible;
00064 };
00065
00066 ref class DirectXAppSource : Windows::ApplicationModel::Core::IFrameworkViewSource
00067 {
00068 public:
00069     virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00070 };
Generated on Sat Nov 23 2024 16:08:07 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/Photo.h Source File

  • Hilo C++
  • Hilo

Photo.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
00009 #include "IResizable.h"
00010 #include "IPhoto.h"
00011
00012 namespace Hilo
00013 {
00014     interface class IPhotoGroup;
00015     class ExceptionPolicy;
00016
00017     // The Photo class provides data used by XAML image controls.
00018     [Windows::UI::Xaml::Data::Bindable]
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Photo sealed : public IResizable, public IPhoto, public Windows::UI::Xaml::Data::INotifyPropertyChanged
00021     {
00022     internal:
00023         Photo(Windows::Storage::BulkAccess::FileInformation^ file, IPhotoGroup^ photoGroup, std::shared_ptr<ExceptionPolicy> exceptionPolicy);
00024
00025     public:
00026         virtual ~Photo();
00027
00028         virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler^ PropertyChanged;
00029
00030         property IPhotoGroup^ Group
00031         {
00032             virtual IPhotoGroup^ get();
00033         }
00034
00035         property Platform::String^ Name
00036         {
00037             virtual Platform::String^ get();
00038         }
00039
00040         property Platform::String^ Path
00041         {
00042             virtual Platform::String^ get();
00043         }
00044
00045         property Platform::String^ FormattedPath
00046         {
00047             virtual Platform::String^ get();
00048         }
00049
00050         property Platform::String^ FileType
00051         {
00052             virtual Platform::String^ get();
00053         }
00054
00055         property Windows::Foundation::DateTime DateTaken
00056         {
00057             virtual Windows::Foundation::DateTime get();
00058         }
00059
00060         property Platform::String^ FormattedDateTaken
00061         {
00062             virtual Platform::String^ get();
00063         }
00064
00065         property Platform::String^ FormattedTimeTaken
00066         {
00067             virtual Platform::String^ get();
00068         }
00069
00070         property Platform::String^ Resolution
00071         {
00072             virtual Platform::String^ get();
00073         }
00074
00075         property uint64 FileSize
00076         {
00077             virtual uint64 get();
00078         }
00079
00080         property Platform::String^ DisplayType
00081         {
00082             virtual Platform::String^ get();
00083         }
00084
00085         property Windows::UI::Xaml::Media::Imaging::BitmapImage^ Thumbnail
00086         {
00087             virtual Windows::UI::Xaml::Media::Imaging::BitmapImage^ get();
00088         }
00089
00090         property Windows::UI::Xaml::Media::Imaging::BitmapImage^ Image
00091         {
00092             virtual Windows::UI::Xaml::Media::Imaging::BitmapImage^ get();
00093         }
00094
00095         property bool IsInvalidThumbnail
00096         {
00097             virtual bool get();
00098         }
00099
00100         property int ColumnSpan
00101         {
00102             virtual int get();
00103             virtual void set(int value);
00104         }
00105
00106         property int RowSpan
00107         {
00108             virtual int get();
00109             virtual void set(int value);
00110         }
00111
00112         virtual Windows::Foundation::IAsyncOperation<Windows::Storage::Streams::IRandomAccessStreamWithContentType^>^ OpenReadAsync();
00113         virtual void ClearImageData();
00114
00115     internal:
00116         concurrency::task<void> QueryPhotoImageAsync();
00117
00118     private:
00119         Windows::Storage::BulkAccess::FileInformation^ m_fileInfo;
00120         Platform::WeakReference m_weakPhotoGroup;
00121         Windows::UI::Xaml::Media::Imaging::BitmapImage^ m_image;
00122         std::shared_ptr<ExceptionPolicy> m_exceptionPolicy;
00123         Windows::Foundation::EventRegistrationToken m_thumbnailUpdatedEventToken;
00124         Windows::Foundation::EventRegistrationToken m_imageFailedEventToken;
00125         int m_columnSpan;
00126         int m_rowSpan;
00127         bool m_queryPhotoImageAsyncIsRunning;
00128         bool m_isInvalidThumbnail;
00129
00130         void OnThumbnailUpdated(Windows::Storage::BulkAccess::IStorageItemInformation^ sender, Platform::Object^ e);
00131         void OnImageFailedToOpen(Platform::Object^ sender, Windows::UI::Xaml::ExceptionRoutedEventArgs^ e);
00132         void OnPropertyChanged(Platform::String^ propertyName);
00133     };
00134 }
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML personality animations/C++/common/suspensionmanager.h Source File

  • XAML personality animations
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Sharing content source app/C++/pch.h Source File

  • Sharing content source app

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include <sstream>
00021 #include "Common\LayoutAwarePage.h"
00022 #include "Common\SuspensionManager.h"
00023 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Audio Session (WASAPI)/C++/WASAPICapture.h Source File

  • Windows Audio Session (WASAPI)
  • C++

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 //
00012 // WASAPICapture.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 "PlotData.h"
00023
00024 using namespace Microsoft::WRL;
00025 using namespace Windows::Media::Devices;
00026 using namespace Windows::Storage::Streams;
00027
00028 #define AUDIO_FILE_NAME "WASAPIAudioCapture.wav"
00029 #define FLUSH_INTERVAL_SEC 3
00030
00031
00032 #pragma once
00033
00034 namespace SDKSample
00035 {
00036     namespace WASAPIAudio
00037     {
00038         // Primary WASAPI Capture Class
00039         class WASAPICapture :
00040             public RuntimeClass< RuntimeClassFlags< ClassicCom >, FtmBase, IActivateAudioInterfaceCompletionHandler >
00041         {
00042         public:
00043             WASAPICapture();
00044
00045             HRESULT InitializeAudioDeviceAsync();
00046             HRESULT StartCaptureAsync();
00047             HRESULT StopCaptureAsync();
00048             HRESULT FinishCaptureAsync();
00049
00050             DeviceStateChangedEvent^ GetDeviceStateEvent() { return m_DeviceStateChanged; };
00051
00052             METHODASYNCCALLBACK( WASAPICapture, StartCapture, OnStartCapture );
00053             METHODASYNCCALLBACK( WASAPICapture, StopCapture, OnStopCapture );
00054             METHODASYNCCALLBACK( WASAPICapture, SampleReady, OnSampleReady );
00055             METHODASYNCCALLBACK( WASAPICapture, FinishCapture, OnFinishCapture );
00056             METHODASYNCCALLBACK( WASAPICapture, SendScopeData, OnSendScopeData );
00057
00058             // IActivateAudioInterfaceCompletionHandler
00059             STDMETHOD(ActivateCompleted)( IActivateAudioInterfaceAsyncOperation *operation );
00060
00061         private:
00062             ~WASAPICapture();
00063
00064             HRESULT OnStartCapture( IMFAsyncResult* pResult );
00065             HRESULT OnStopCapture( IMFAsyncResult* pResult );
00066             HRESULT OnFinishCapture( IMFAsyncResult* pResult );
00067             HRESULT OnSampleReady( IMFAsyncResult* pResult );
00068             HRESULT OnSendScopeData( IMFAsyncResult* pResult );
00069
00070             HRESULT CreateWAVFile();
00071             HRESULT FixWAVHeader();
00072             HRESULT OnAudioSampleRequested( Platform::Boolean IsSilence = false );
00073             HRESULT InitializeScopeData();
00074             HRESULT ProcessScopeData( BYTE* pData, DWORD cbBytes );
00075
00076         private:
00077             Platform::String^   m_DeviceIdString;
00078             UINT32              m_BufferFrames;
00079             HANDLE              m_SampleReadyEvent;
00080             MFWORKITEM_KEY      m_SampleReadyKey;
00081             CRITICAL_SECTION    m_CritSec;
00082             DWORD               m_dwQueueID;
00083
00084             DWORD               m_cbHeaderSize;
00085             DWORD               m_cbDataSize;
00086             DWORD               m_cbFlushCounter;
00087             BOOL                m_fWriting;
00088
00089             IRandomAccessStream^     m_ContentStream;
00090             IOutputStream^           m_OutputStream;
00091             DataWriter^              m_WAVDataWriter;
00092             WAVEFORMATEX            *m_MixFormat;
00093             IAudioClient            *m_AudioClient;
00094             IAudioCaptureClient     *m_AudioCaptureClient;
00095             IMFAsyncResult          *m_SampleReadyAsyncResult;
00096
00097             DeviceStateChangedEvent^       m_DeviceStateChanged;
00098
00099             Platform::Array<int, 1>^    m_PlotData;
00100             UINT32                      m_cPlotDataMax;
00101             UINT32                      m_cPlotDataFilled;
00102         };
00103     }
00104 }
Generated on Sat Nov 23 2024 16:08:26 for Win8-Examples by doxygen 1.7.1


Win8-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.
__pad0__ | GameTimer |
Active() | GameTimer | [inline]
Active() | GameTimer | [inline]
DeltaTime() | GameTimer |
DeltaTime() | 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 |
PlayingTime() | GameTimer |
PlayingTime(float time) | GameTimer |
Reset() | GameTimer |
Reset() | GameTimer |
Start() | GameTimer |
Start() | GameTimer |
Stop() | GameTimer |
Stop() | GameTimer |
Update() | GameTimer |
Update() | GameTimer |
Generated on Sat Nov 23 2024 16:09:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Direct3DTutorial Member List

This is the complete list of members for Direct3DTutorial, including all inherited members.
__pad0__ | Direct3DTutorial |
CreateDeviceIndependentResources() override | Direct3DTutorial | [virtual]
CreateDeviceResources() override | Direct3DTutorial | [virtual]
CreateWindowSizeDependentResources() override | Direct3DTutorial | [virtual]
m_camera | Direct3DTutorial | [private]
m_constantBuffer | Direct3DTutorial | [private]
m_constantBufferData | Direct3DTutorial | [private]
m_indexBuffer | Direct3DTutorial | [private]
m_indexCount | Direct3DTutorial | [private]
m_inputLayout | Direct3DTutorial | [private]
m_pixelShader | Direct3DTutorial | [private]
m_sampleOverlay | Direct3DTutorial | [private]
m_sampler | Direct3DTutorial | [private]
m_texture | Direct3DTutorial | [private]
m_textureSRV | Direct3DTutorial | [private]
m_vertexBuffer | Direct3DTutorial | [private]
m_vertexShader | Direct3DTutorial | [private]
Render() override | Direct3DTutorial | [virtual]
Update(float timeTotal, float timeDelta) | Direct3DTutorial |
Generated on Sat Nov 23 2024 16:09:11 for Win8-Examples by doxygen 1.7.1


Win8-Examples: HttpClient/C++/HttpRequest.cpp Source File

  • HttpClient

HttpRequest.cpp

Go to the documentation of this file.
00001 //-----------------------------------------------------------------------
00002 //
00003 //  Copyright (C) Microsoft Corporation.  All rights reserved.
00004 //
00005 //
00006 // THIS CODE AND INFORMATION ARE PROVIDED AS-IS WITHOUT WARRANTY OF ANY
00007 // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
00008 // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00009 // PARTICULAR PURPOSE.
00010 //-----------------------------------------------------------------------
00011 #include "pch.h"
00012 #include "HttpRequest.h"
00013 #include <robuffer.h>
00014 #include <shcore.h>
00015
00016 using namespace concurrency;
00017 using namespace Microsoft::WRL;
00018 using namespace Platform;
00019 using namespace std;
00020 using namespace Web;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Storage::Streams;
00023
00024 // Implementation of IXMLHTTPRequest2Callback used when only the complete response is needed.
00025 // When processing chunks of response data as they are received, use HttpRequestBuffersCallback instead.
00026 class HttpRequestStringCallback
00027     : public RuntimeClass<RuntimeClassFlags<ClassicCom>, IXMLHTTPRequest2Callback, FtmBase>
00028 {
00029 public:
00030     HttpRequestStringCallback(IXMLHTTPRequest2* httpRequest,
00031         cancellation_token ct = concurrency::cancellation_token::none()) :
00032         request(httpRequest), cancellationToken(ct)
00033     {
00034         // Register a callback function that aborts the HTTP operation when
00035         // the cancellation token is canceled.
00036         if (cancellationToken != cancellation_token::none())
00037         {
00038             registrationToken = cancellationToken.register_callback([this]()
00039             {
00040                 if (request != nullptr)
00041                 {
00042                     request->Abort();
00043                 }
00044             });
00045         }
00046     }
00047
00048     // Called when the HTTP request is being redirected to a new URL.
00049     IFACEMETHODIMP OnRedirect(IXMLHTTPRequest2*, PCWSTR)
00050     {
00051         return S_OK;
00052     }
00053
00054     // Called when HTTP headers have been received and processed.
00055     IFACEMETHODIMP OnHeadersAvailable(IXMLHTTPRequest2*, DWORD statusCode, PCWSTR reasonPhrase)
00056     {
00057         HRESULT hr = S_OK;
00058
00059         // We must not propagate exceptions back to IXHR2.
00060         try
00061         {
00062             this->statusCode = statusCode;
00063             this->reasonPhrase = reasonPhrase;
00064         }
00065         catch (std::bad_alloc&)
00066         {
00067             hr = E_OUTOFMEMORY;
00068         }
00069
00070         return hr;
00071     }
00072
00073     // Called when a portion of the entity body has been received.
00074     IFACEMETHODIMP OnDataAvailable(IXMLHTTPRequest2*, ISequentialStream*)
00075     {
00076         return S_OK;
00077     }
00078
00079     // Called when the entire entity response has been received.
00080     IFACEMETHODIMP OnResponseReceived(IXMLHTTPRequest2*, ISequentialStream* responseStream)
00081     {
00082         wstring wstr;
00083         HRESULT hr = ReadUtf8StringFromSequentialStream(responseStream, wstr);
00084
00085         // We must not propagate exceptions back to IXHR2.
00086         try
00087         {
00088             completionEvent.set(make_tuple<HRESULT, wstring>(move(hr), move(wstr)));
00089         }
00090         catch (std::bad_alloc&)
00091         {
00092             hr = E_OUTOFMEMORY;
00093         }
00094
00095         return hr;
00096     }
00097
00098     // Simulate the functionality of DataReader.ReadString().
00099     // This is needed because DataReader requires IRandomAccessStream and this
00100     // code has an ISequentialStream that does not have a conversion to IRandomAccessStream like IStream does.
00101     HRESULT ReadUtf8StringFromSequentialStream(ISequentialStream* readStream, wstring& str)
00102     {
00103         // Convert the response to Unicode wstring.
00104         HRESULT hr;
00105
00106         // Holds the response as a Unicode string.
00107         wstringstream ss;
00108
00109         while (true)
00110         {
00111             ULONG cb;
00112             char buffer[4096];
00113
00114             // Read the response as a UTF-8 string.  Since UTF-8 characters are 1-4 bytes long,
00115             // we need to make sure we only read an integral number of characters.  So we'll
00116             // start with 4093 bytes.
00117             hr = readStream->Read(buffer, sizeof(buffer) - 3, &cb);
00118             if (FAILED(hr) || (cb == 0))
00119             {
00120                 break; // Error or no more data to process, exit loop.
00121             }
00122
00123             if (cb == sizeof(buffer) - 3)
00124             {
00125                 ULONG subsequentBytesRead;
00126                 unsigned int i, cl;
00127
00128                 // Find the first byte of the last UTF-8 character in the buffer.
00129                 for (i = cb - 1; (i >= 0) && ((buffer[i] & 0xC0) == 0x80); i--);
00130
00131                 // Calculate the number of subsequent bytes in the UTF-8 character.
00132                 if (((unsigned char)buffer[i]) < 0x80)
00133                 {
00134                     cl = 1;
00135                 }
00136                 else if (((unsigned char)buffer[i]) < 0xE0)
00137                 {
00138                     cl = 2;
00139                 }
00140                 else if (((unsigned char)buffer[i]) < 0xF0)
00141                 {
00142                     cl = 3;
00143                 }
00144                 else
00145                 {
00146                     cl = 4;
00147                 }
00148
00149                 // Read any remaining bytes.
00150                 if (cb < i + cl)
00151                 {
00152                     hr = readStream->Read(buffer + cb, i + cl - cb, &subsequentBytesRead);
00153                     if (FAILED(hr))
00154                     {
00155                         break; // Error, exit loop.
00156                     }
00157                     cb += subsequentBytesRead;
00158                 }
00159             }
00160
00161             // First determine the size required to store the Unicode string.
00162             int const sizeRequired = MultiByteToWideChar(CP_UTF8, 0, buffer, cb, nullptr, 0);
00163             if (sizeRequired == 0)
00164             {
00165                 // Invalid UTF-8.
00166                 hr = HRESULT_FROM_WIN32(GetLastError());
00167                 break;
00168             }
00169             unique_ptr<char16[]> wstr(new(std::nothrow) char16[sizeRequired + 1]);
00170             if (wstr.get() == nullptr)
00171             {
00172                 hr = E_OUTOFMEMORY;
00173                 break;
00174             }
00175
00176             // Convert the string from UTF-8 to UTF-16LE.  This can never fail, since
00177             // the previous call above succeeded.
00178             MultiByteToWideChar(CP_UTF8, 0, buffer, cb, wstr.get(), sizeRequired);
00179             wstr[sizeRequired] = L'\0'; // Terminate the string.
00180             ss << wstr.get(); // Write the string to the stream.
00181         }
00182
00183         str = SUCCEEDED(hr) ? ss.str() : wstring();
00184         return (SUCCEEDED(hr)) ? S_OK : hr; // Don't return S_FALSE.
00185     }
00186
00187     // Called when an error occurs during the HTTP request.
00188     IFACEMETHODIMP OnError(IXMLHTTPRequest2*, HRESULT hrError)
00189     {
00190         HRESULT hr = S_OK;
00191
00192         // We must not propagate exceptions back to IXHR2.
00193         try
00194         {
00195             completionEvent.set(make_tuple<HRESULT, wstring>(move(hrError), wstring()));
00196         }
00197         catch (std::bad_alloc&)
00198         {
00199             hr = E_OUTOFMEMORY;
00200         }
00201
00202         return hr;
00203     }
00204
00205     // Retrieves the completion event for the HTTP operation.
00206     task_completion_event<tuple<HRESULT, wstring>> const& GetCompletionEvent() const
00207     {
00208         return completionEvent;
00209     }
00210
00211     int GetStatusCode() const
00212     {
00213         return statusCode;
00214     }
00215
00216     wstring GetReasonPhrase() const
00217     {
00218         return reasonPhrase;
00219     }
00220
00221 private:
00222     ~HttpRequestStringCallback()
00223     {
00224         // Unregister the callback.
00225         if (cancellationToken != cancellation_token::none())
00226         {
00227             cancellationToken.deregister_callback(registrationToken);
00228         }
00229     }
00230
00231     // Signals that the download operation was canceled.
00232     cancellation_token cancellationToken;
00233
00234     // Used to unregister the cancellation token callback.
00235     cancellation_token_registration registrationToken;
00236
00237     // The IXMLHTTPRequest2 that processes the HTTP request.
00238     ComPtr<IXMLHTTPRequest2> request;
00239
00240     // Task completion event that is set when the
00241     // download operation completes.
00242     task_completion_event<tuple<HRESULT, wstring>> completionEvent;
00243
00244     int statusCode;
00245     wstring reasonPhrase;
00246 };
00247
00248 // Copy bytes from the sequential stream into the buffer provided until
00249 // we reach the end of one or the other.
00250 unsigned int Web::Details::HttpRequestBuffersCallback::ReadData(
00251     _Out_writes_(outputBufferSize) byte* outputBuffer,
00252     unsigned int outputBufferSize)
00253 {
00254     // Lock the data event while doing the read, to ensure that any bytes we don't read will
00255     // result in the correct event getting triggered.
00256     concurrency::critical_section::scoped_lock lock(dataEventLock);
00257
00258     ULONG bytesRead;
00259     CheckHResult(dataStream.Get()->Read(outputBuffer, outputBufferSize, &bytesRead));
00260     if (bytesRead < outputBufferSize)
00261     {
00262         // We need to reset the data event, which we can only do by creating a new one.
00263         dataEvent = task_completion_event<void>();
00264     }
00265
00266     return bytesRead;
00267 }
00268
00269 // Create a task that completes when data is available, in an exception-safe way.
00270 task<void> Web::Details::HttpRequestBuffersCallback::CreateDataTask()
00271 {
00272     concurrency::critical_section::scoped_lock lock(dataEventLock);
00273     return create_task(dataEvent, cancellationToken);
00274 }
00275
00276 HttpRequest::HttpRequest() : responseComplete(true), statusCode(200)
00277 {
00278 }
00279
00280 // Start a download of the specified URI using the specified method.  The returned task produces the
00281 // HTTP response text.  The status code and reason can be read with GetStatusCode() and GetReasonPhrase().
00282 task<wstring> HttpRequest::DownloadAsync(PCWSTR httpMethod, PCWSTR uri, cancellation_token cancellationToken,
00283     PCWSTR contentType, IStream* postStream, uint64 postStreamSizeToSend)
00284 {
00285     // Create an IXMLHTTPRequest2 object.
00286     ComPtr<IXMLHTTPRequest2> xhr;
00287     CheckHResult(CoCreateInstance(CLSID_XmlHttpRequest, nullptr, CLSCTX_INPROC, IID_PPV_ARGS(&xhr)));
00288
00289     // Create callback.
00290     auto stringCallback = Make<HttpRequestStringCallback>(xhr.Get(), cancellationToken);
00291     CheckHResult(stringCallback ? S_OK : E_OUTOFMEMORY);
00292
00293     auto completionTask = create_task(stringCallback->GetCompletionEvent());
00294
00295     // Create a request.
00296     CheckHResult(xhr->Open(httpMethod, uri, stringCallback.Get(), nullptr, nullptr, nullptr, nullptr));
00297
00298     if (postStream != nullptr && contentType != nullptr)
00299     {
00300         CheckHResult(xhr->SetRequestHeader(L"Content-Type", contentType));
00301     }
00302
00303     // Send the request.
00304     CheckHResult(xhr->Send(postStream, postStreamSizeToSend));
00305
00306     // Return a task that completes when the HTTP operation completes.
00307     // We pass the callback to the continuation because the lifetime of the
00308     // callback must exceed the operation to ensure that cancellation
00309     // works correctly.
00310     return completionTask.then([this, stringCallback](tuple<HRESULT, wstring> resultTuple)
00311     {
00312         // If the GET operation failed, throw an Exception.
00313         CheckHResult(std::get<0>(resultTuple));
00314
00315         statusCode = stringCallback->GetStatusCode();
00316         reasonPhrase = stringCallback->GetReasonPhrase();
00317
00318         return std::get<1>(resultTuple);
00319     });
00320 }
00321
00322 // Start an HTTP GET on the specified URI.  The returned task completes once the entire response
00323 // has been received, and the task produces the HTTP response text.  The status code and reason
00324 // can be read with GetStatusCode() and GetReasonPhrase().
00325 task<wstring> HttpRequest::GetAsync(Uri^ uri, cancellation_token cancellationToken)
00326 {
00327     return DownloadAsync(L"GET",
00328                          uri->AbsoluteUri->Data(),
00329                          cancellationToken,
00330                          nullptr,
00331                          nullptr,
00332                          0);
00333 }
00334
00335 void HttpRequest::CreateMemoryStream(IStream **stream)
00336 {
00337     auto randomAccessStream = ref new Windows::Storage::Streams::InMemoryRandomAccessStream();
00338     CheckHResult(CreateStreamOverRandomAccessStream(randomAccessStream, IID_PPV_ARGS(stream)));
00339 }
00340
00341 // Start an HTTP POST on the specified URI, using a string body.  The returned task produces the
00342 // HTTP response text.  The status code and reason can be read with GetStatusCode() and GetReasonPhrase().
00343 task<wstring> HttpRequest::PostAsync(Uri^ uri, const wstring& body, cancellation_token cancellationToken)
00344 {
00345     int length = 0;
00346     ComPtr<IStream> postStream;
00347     CreateMemoryStream(&postStream);
00348
00349     if (body.length() > 0)
00350     {
00351         // Get the required buffer size.
00352         int size = WideCharToMultiByte(CP_UTF8,                         // UTF-8
00353                                        0,                               // Conversion type
00354                                        body.c_str(),                    // Unicode string to convert
00355                                        static_cast<int>(body.length()), // Size
00356                                        nullptr,                         // Output buffer
00357                                        0,                               // Output buffer size
00358                                        nullptr,
00359                                        nullptr);
00360         CheckHResult((size != 0) ? S_OK : HRESULT_FROM_WIN32(GetLastError()));
00361
00362         std::unique_ptr<char[]> tempData(new char[size]);
00363         length = WideCharToMultiByte(CP_UTF8,                         // UTF-8
00364                                      0,                               // Conversion type
00365                                      body.c_str(),                    // Unicode string to convert
00366                                      static_cast<int>(body.length()), // Size
00367                                      tempData.get(),                  // Output buffer
00368                                      size,                            // Output buffer size
00369                                      nullptr,
00370                                      nullptr);
00371         CheckHResult((length != 0) ? S_OK : HRESULT_FROM_WIN32(GetLastError()));
00372         CheckHResult(postStream->Write(tempData.get(), length, nullptr));
00373     }
00374
00375     return DownloadAsync(L"POST",
00376                          uri->AbsoluteUri->Data(),
00377                          cancellationToken,
00378                          L"text/plain;charset=utf-8",
00379                          postStream.Get(),
00380                          length);
00381 }
00382
00383 // Start an HTTP POST on the specified URI, using a stream body.  The returned task produces the
00384 // HTTP response text.  The status code and reason can be read with GetStatusCode() and GetReasonPhrase().
00385 task<wstring> HttpRequest::PostAsync(Uri^ uri, PCWSTR contentType, IStream* postStream,
00386     uint64 postStreamSizeToSend, cancellation_token cancellationToken)
00387 {
00388     return DownloadAsync(L"POST",
00389                          uri->AbsoluteUri->Data(),
00390                          cancellationToken,
00391                          contentType,
00392                          postStream,
00393                          postStreamSizeToSend);
00394 }
00395
00396 // Send a request but don't return the response.  Instead, let the caller read it with ReadAsync().
00397 task<void> HttpRequest::SendAsync(const wstring& httpMethod, Uri^ uri, cancellation_token cancellationToken)
00398 {
00399     // Create an IXMLHTTPRequest2 object.
00400     ComPtr<IXMLHTTPRequest2> xhr;
00401     CheckHResult(CoCreateInstance(CLSID_XmlHttpRequest, nullptr, CLSCTX_INPROC, IID_PPV_ARGS(&xhr)));
00402
00403     // Create callback.
00404     buffersCallback = Make<Web::Details::HttpRequestBuffersCallback>(xhr.Get(), cancellationToken);
00405     CheckHResult(buffersCallback ? S_OK : E_OUTOFMEMORY);
00406
00407     ComPtr<IXMLHTTPRequest2Callback> xhrCallback;
00408     CheckHResult(buffersCallback.As(&xhrCallback));
00409
00410     // Open and send the request.
00411     CheckHResult(xhr->Open(httpMethod.c_str(),
00412                            uri->AbsoluteUri->Data(),
00413                            xhrCallback.Get(),
00414                            nullptr,
00415                            nullptr,
00416                            nullptr,
00417                            nullptr));
00418
00419     responseComplete = false;
00420
00421     CheckHResult(xhr->Send(nullptr, 0));
00422
00423     // Return a task that completes when the HTTP operation completes.
00424     // Since buffersCallback holds a reference on the callback, the lifetime of the callback will exceed
00425     // the operation and ensure that cancellation works correctly.
00426     return buffersCallback->CreateDataTask().then([this]()
00427     {
00428         CheckHResult(buffersCallback->GetError());
00429
00430         statusCode = buffersCallback->GetStatusCode();
00431         reasonPhrase = buffersCallback->GetReasonPhrase();
00432     });
00433 }
00434
00435 // Read a chunk of data from the HTTP response, up to a specified length or until we reach the end
00436 // of the response, and store the value in the provided buffer.  This is useful for large content,
00437 // enabling the streaming of the result.
00438 task<void> HttpRequest::ReadAsync(Windows::Storage::Streams::IBuffer^ readBuffer, unsigned int offsetInBuffer,
00439     unsigned int requestedBytesToRead)
00440 {
00441     if (offsetInBuffer + requestedBytesToRead > readBuffer->Capacity)
00442     {
00443         throw ref new InvalidArgumentException();
00444     }
00445
00446     // Return a task that completes when a read completes.
00447     // We pass the callback to the continuation because the lifetime of the
00448     // callback must exceed the operation to ensure that cancellation
00449     // works correctly.
00450     return buffersCallback->CreateDataTask().then([this, readBuffer, offsetInBuffer, requestedBytesToRead]()
00451     {
00452         CheckHResult(buffersCallback->GetError());
00453
00454         // Get a pointer to the location to copy data into.
00455         ComPtr<IBufferByteAccess> bufferByteAccess;
00456         CheckHResult(reinterpret_cast<IUnknown*>(readBuffer)->QueryInterface(IID_PPV_ARGS(&bufferByteAccess)));
00457         byte* outputBuffer; // Returned internal pointer, do not free this value.
00458         CheckHResult(bufferByteAccess->Buffer(&outputBuffer));
00459
00460         // Copy bytes from the sequential stream into the buffer provided until
00461         // we reach the end of one or the other.
00462         readBuffer->Length = buffersCallback->ReadData(outputBuffer + offsetInBuffer, requestedBytesToRead);
00463         if (buffersCallback->IsResponseReceived() && (readBuffer->Length < requestedBytesToRead))
00464         {
00465             responseComplete = true;
00466         }
00467     });
00468 }
Generated on Sat Nov 23 2024 16:07:58 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::BackgroundTask::BackgroundTaskSample Member List

This is the complete list of members for SDKSample::BackgroundTask::BackgroundTaskSample, including all inherited members.
GetBackgroundTaskStatus(Platform::String^name) | SDKSample::BackgroundTask::BackgroundTaskSample | [static]
InitializeBackgroundTaskStatus() | SDKSample::BackgroundTask::BackgroundTaskSample | [static]
RegisterBackgroundTask(String^taskEntryPoint, String^name, IBackgroundTrigger^trigger, IBackgroundCondition^condition) | SDKSample::BackgroundTask::BackgroundTaskSample | [static]
RegisterServicingCompleteBackgroundTask() | SDKSample::BackgroundTask::BackgroundTaskSample | [static]
SampleBackgroundTaskProgress | SDKSample::BackgroundTask::BackgroundTaskSample | [static]
SampleBackgroundTaskRegistered | SDKSample::BackgroundTask::BackgroundTaskSample | [static]
SampleBackgroundTaskWithConditionProgress | SDKSample::BackgroundTask::BackgroundTaskSample | [static]
SampleBackgroundTaskWithConditionRegistered | SDKSample::BackgroundTask::BackgroundTaskSample | [static]
ServicingCompleteTaskProgress | SDKSample::BackgroundTask::BackgroundTaskSample | [static]
ServicingCompleteTaskRegistered | SDKSample::BackgroundTask::BackgroundTaskSample | [static]
TimeTriggeredTaskProgress | SDKSample::BackgroundTask::BackgroundTaskSample | [static]
TimeTriggeredTaskRegistered | SDKSample::BackgroundTask::BackgroundTaskSample | [static]
UnregisterBackgroundTasks(String^name) | SDKSample::BackgroundTask::BackgroundTaskSample | [static]
UpdateBackgroundTaskStatus(Platform::String^name, bool registered) | SDKSample::BackgroundTask::BackgroundTaskSample | [static]
Generated on Sat Nov 23 2024 16:09:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Proximity/C++/ProximityDeviceScenario.xaml.cpp Source File

  • Proximity

ProximityDeviceScenario.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 // ProximityDeviceScenario.xaml.cpp
00013 // Implementation of the ProximityDeviceScenario class
00014 //
00015
00016
00017 #include "pch.h"
00018 #include "ProximityDeviceScenario.xaml.h"
00019
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Controls;
00022 using namespace Windows::UI::Xaml::Data;
00023 using namespace Windows::UI::Xaml::Navigation;
00024 using namespace Windows::UI::Core;
00025 using namespace Windows::UI::ViewManagement;
00026 using namespace Windows::System;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Networking::Proximity;
00030 using namespace Windows::Storage::Streams;
00031 using namespace Platform;
00032 using namespace ProximityCPP;
00033
00034
00035
00036 ProximityDeviceScenario::ProximityDeviceScenario()
00037 {
00038     InitializeComponent();
00039
00040     m_proximityDevice = ProximityDevice::GetDefault();
00041     if (m_proximityDevice != nullptr)
00042     {
00043         // there is a proximity device, so set up the scenarios
00044         m_publishedMessageId = -1;
00045         m_subscribedMessageId = -1;
00046         ProximityDevice_PublishMessageButton->Click += ref new RoutedEventHandler(this, &ProximityDeviceScenario::ProximityDevice_PublishMessage);
00047         ProximityDevice_SubscribeForMessageButton->Click += ref new RoutedEventHandler(this, &ProximityDeviceScenario::ProximityDevice_SubscribeForMessage);
00048         ProximityDevice_PublishMessageButton->Visibility =  Windows::UI::Xaml::Visibility::Visible;
00049         ProximityDevice_SubscribeForMessageButton->Visibility =  Windows::UI::Xaml::Visibility::Visible;
00050         ProximityDevice_PublishMessageText->Visibility =  Windows::UI::Xaml::Visibility::Visible;
00051     }
00052
00053 }
00054
00055 void ProximityDeviceScenario::ProximityDevice_PublishMessage(Object^ sender, RoutedEventArgs^ e)
00056 {
00057     if (m_publishedMessageId == -1)
00058     {
00059         m_rootPage->NotifyUser("", NotifyType::ErrorMessage);
00060         String^ publishText = ProximityDevice_PublishMessageText->Text;
00061         ProximityDevice_PublishMessageText->Text = ""; // clear the input after publishing.
00062         if (publishText->Length() > 0)
00063         {
00064             m_publishedMessageId = m_proximityDevice->PublishMessage("Windows.SampleMessageType", publishText);
00065             m_rootPage->NotifyUser("Message published, tap another device to transmit.", NotifyType::StatusMessage);
00066         }
00067         else
00068         {
00069             m_rootPage->NotifyUser("Please type a message", NotifyType::ErrorMessage);
00070         }
00071     }
00072     else
00073     {
00074         m_rootPage->NotifyUser("This sample only supports publishing one message at a time.", NotifyType::ErrorMessage);
00075     }
00076 }
00077
00078 void ProximityDeviceScenario::MessageReceived(ProximityDevice^ device, ProximityMessage^ message)
00079 {
00080     m_rootPage->LogInfo("Message received: " + message->DataAsString, ProximityDeviceOutputText);
00081 }
00082
00083 void ProximityDeviceScenario::ProximityDevice_SubscribeForMessage(Object^ sender, RoutedEventArgs^ e)
00084 {
00085     if (m_subscribedMessageId == -1)
00086     {
00087         m_subscribedMessageId = m_proximityDevice->SubscribeForMessage("Windows.SampleMessageType",
00088             ref new MessageReceivedHandler(this, &ProximityDeviceScenario::MessageReceived, CallbackContext::Same));
00089         m_rootPage->NotifyUser("Subscribed for proximity message, enter proximity to receive.", NotifyType::StatusMessage);
00090     }
00091     else
00092     {
00093         m_rootPage->NotifyUser("This sample only supports subscribing for one message at a time.", NotifyType::ErrorMessage);
00094     }
00095 }
00096
00097 /// <summary>
00098 /// Invoked when this page is about to be displayed in a Frame.
00099 /// </summary>
00100 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00101 /// property is typically used to configure the page.</param>
00102 void ProximityDeviceScenario::OnNavigatedTo(NavigationEventArgs^ e)
00103 {
00104     // A pointer back to the main page.  This is needed if you want to call methods in ProximityDeviceScenario such
00105     // as NotifyUser()
00106     m_rootPage = MainPage::Current;
00107     ProximityDevice_PublishMessageText->Text = "Hello World";
00108     if (m_proximityDevice == nullptr)
00109     {
00110         m_rootPage->NotifyUser("No proximity device found", NotifyType::ErrorMessage);
00111     }
00112     m_rootPage->ClearLog(ProximityDeviceOutputText);
00113 }
00114
00115
00116 void ProximityDeviceScenario::OnNavigatingFrom(NavigatingCancelEventArgs^ e)
00117 {
00118     if (m_proximityDevice != nullptr)
00119     {
00120         if (m_publishedMessageId != -1)
00121         {
00122             m_proximityDevice->StopPublishingMessage(m_publishedMessageId);
00123             m_publishedMessageId = -1;
00124         }
00125         if (m_subscribedMessageId != -1)
00126         {
00127             m_proximityDevice->StopSubscribingForMessage(m_subscribedMessageId);
00128             m_subscribedMessageId = 1;
00129         }
00130     }
00131 }
Generated on Sat Nov 23 2024 16:08:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DatagramSocket/C++/App.xaml.cpp Source File

  • DatagramSocket

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "App.xaml.h"
00018 #include "MainPage.xaml.h"
00019
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Controls;
00022 using namespace Windows::ApplicationModel;
00023 using namespace Windows::ApplicationModel::Activation;
00024 using namespace CppSamplesUtils;
00025 using namespace DatagramSocketSample;
00026 using namespace Windows::UI::Xaml::Interop;
00027
00028 App::App()
00029 {
00030     InitializeComponent();
00031     this->Suspending += ref new SuspendingEventHandler(this, &DatagramSocketSample::App::OnSuspending);
00032 }
00033
00034 void App::OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs)
00035 {
00036     auto deferral = pArgs->SuspendingOperation->GetDeferral();
00037     SuspensionManager::StartSaveTask().then([=]()
00038     {
00039         deferral->Complete();
00040     });
00041 }
00042
00043 void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs)
00044 {
00045     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Terminated)
00046     {
00047         SuspensionManager::StartRestoreTask().then([=](concurrency::task<void> restoreTask)
00048         {
00049             try
00050             {
00051                 restoreTask.get();
00052             }
00053             catch (Platform::Exception^)
00054             {
00055                 // If restore fails, the app should proceed as though there was no restored state.
00056             }
00057         });
00058     }
00059     if (Window::Current->Content == nullptr)
00060     {
00061         rootFrame = ref new Frame();
00062         TypeName pageType = { "DatagramSocketSample.MainPage", TypeKind::Custom };
00063         rootFrame->Navigate(pageType);
00064         Window::Current->Content = rootFrame;
00065     }
00066     MainPage^ p = safe_cast<MainPage^>(rootFrame->Content);
00067     p->LaunchArgs = pArgs;
00068     Window::Current->Activate();
00069 }
00070
Generated on Sat Nov 23 2024 16:07:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D post-processing effects/C++/BasicCamera.cpp Source File

  • Direct3D post-processing effects

BasicCamera.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 "BasicCamera.h"
00010
00011 void BasicCamera::GetViewMatrix(_Out_ float4x4 *viewMatrix)
00012 {
00013     *viewMatrix = m_view;
00014 }
00015
00016 void BasicCamera::GetProjectionMatrix(_Out_ float4x4 *projectionMatrix)
00017 {
00018     *projectionMatrix = m_projection;
00019 }
00020
00021 // this method updates the view matrix based on new position and focus coordinates
00022 void BasicCamera::SetViewParameters(
00023     _In_ float3 eyePosition,    // the position of the camera
00024     _In_ float3 lookPosition,   // the point the camera should look at
00025     _In_ float3 up              // the durection vector for up
00026     )
00027 {
00028     m_position = eyePosition;
00029     m_direction = normalize(lookPosition - eyePosition);
00030     float3 zAxis = -m_direction;
00031     float3 xAxis = normalize(cross(up, zAxis));
00032     float3 yAxis = cross(zAxis, xAxis);
00033     float xOffset = -dot(xAxis, m_position);
00034     float yOffset = -dot(yAxis, m_position);
00035     float zOffset = -dot(zAxis, m_position);
00036     m_view = float4x4(
00037         xAxis.x, xAxis.y, xAxis.z, xOffset,
00038         yAxis.x, yAxis.y, yAxis.z, yOffset,
00039         zAxis.x, zAxis.y, zAxis.z, zOffset,
00040         0.0f,    0.0f,    0.0f,    1.0f
00041         );
00042 }
00043     // this method updates the projection matrix based on new parameters
00044 void BasicCamera::SetProjectionParameters(
00045     _In_ float minimumFieldOfView,  // the minimum horizontal or vertical field of view, in degrees
00046     _In_ float aspectRatio,         // the aspect ratio of the projection (width / height)
00047     _In_ float nearPlane,           // depth to map to 0
00048     _In_ float farPlane             // depth to map to 1
00049     )
00050 {
00051     float minScale = 1.0f / tan(minimumFieldOfView * PI_F / 360.0f);
00052     float xScale = 1.0f;
00053     float yScale = 1.0f;
00054     if (aspectRatio < 1.0f)
00055     {
00056         xScale = minScale;
00057         yScale = minScale * aspectRatio;
00058     }
00059     else
00060     {
00061         xScale = minScale / aspectRatio;
00062         yScale = minScale;
00063     }
00064     float zScale = farPlane / (farPlane - nearPlane);
00065     m_projection = float4x4(
00066         xScale, 0.0f,   0.0f,    0.0f,
00067         0.0f,   yScale, 0.0f,    0.0f,
00068         0.0f,   0.0f,   -zScale, -nearPlane*zScale,
00069         0.0f,   0.0f,   -1.0f,   0.0f
00070         );
00071 }
Generated on Sat Nov 23 2024 16:08:07 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File picker contracts/C++/CachedFileUpdater_Remote.xaml.cpp Source File

  • File picker contracts

CachedFileUpdater_Remote.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 // CachedFileUpdater_Remote.xaml.cpp
00013 // Implementation of the CachedFileUpdater_Remote class
00014 //
00015
00016 #include "pch.h"
00017 #include "CachedFileUpdaterPage.xaml.h"
00018 #include "CachedFileUpdater_Remote.xaml.h"
00019 #include "Constants.h"
00020
00021 using namespace SDKSample::FilePickerContracts;
00022
00023 using namespace concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::Foundation;
00027 using namespace Windows::Storage;
00028 using namespace Windows::Storage::Pickers::Provider;
00029 using namespace Windows::Storage::Provider;
00030 using namespace Windows::UI::Core;
00031 using namespace Windows::UI::Popups;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Navigation;
00035
00036 CachedFileUpdater_Remote::CachedFileUpdater_Remote()
00037 {
00038     InitializeComponent();
00039     OverwriteButton->Click += ref new RoutedEventHandler(this, &CachedFileUpdater_Remote::OverwriteButton_Click);
00040     RenameButton->Click += ref new RoutedEventHandler(this, &CachedFileUpdater_Remote::RenameButton_Click);
00041 }
00042
00043 void CachedFileUpdater_Remote::OverwriteButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00044 {
00045     FileUpdateRequest^ fileUpdateRequest = CachedFileUpdaterPage::Current->fileUpdateRequest;
00046     FileUpdateRequestDeferral^ fileUpdateRequestDeferral = CachedFileUpdaterPage::Current->fileUpdateRequestDeferral;
00047
00048     // update the remote version of file...
00049     // Printing the file content
00050     OutputFileAsync(fileUpdateRequest->File);
00051
00052     fileUpdateRequest->Status = FileUpdateStatus::Complete;
00053     fileUpdateRequestDeferral->Complete();
00054
00055     UpdateUI(CachedFileUpdaterPage::Current->cachedFileUpdaterUI->UIStatus);
00056 }
00057
00058 void CachedFileUpdater_Remote::RenameButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00059 {
00060     FileUpdateRequest^ fileUpdateRequest = CachedFileUpdaterPage::Current->fileUpdateRequest;
00061     FileUpdateRequestDeferral^ fileUpdateRequestDeferral = CachedFileUpdaterPage::Current->fileUpdateRequestDeferral;
00062
00063     create_task(fileUpdateRequest->File->CopyAsync(ApplicationData::Current->LocalFolder, fileUpdateRequest->File->Name, NameCollisionOption::GenerateUniqueName)).then([this, fileUpdateRequest, fileUpdateRequestDeferral](StorageFile^ file)
00064     {
00065         CachedFileUpdater::SetUpdateInformation(file, "CachedFile", ReadActivationMode::NotNeeded, WriteActivationMode::AfterWrite, CachedFileOptions::RequireUpdateOnAccess);
00066         fileUpdateRequest->UpdateLocalFile(file);
00067         OutputFileAsync(file);
00068         fileUpdateRequest->Status = FileUpdateStatus::Complete;
00069         fileUpdateRequestDeferral->Complete();
00070         UpdateUI(CachedFileUpdaterPage::Current->cachedFileUpdaterUI->UIStatus);
00071     });
00072
00073 }
00074
00075 void CachedFileUpdater_Remote::OutputFileAsync(StorageFile^ file)
00076 {
00077     create_task(FileIO::ReadTextAsync(file)).then([this, file](String^ fileContent)
00078     {
00079         OutputFileName->Text = L"File Name: " + file->Name;
00080         OutputFileContent->Text = L"File content:\n" + fileContent;
00081     });
00082 }
00083
00084 void CachedFileUpdater_Remote::UpdateUI(UIStatus uiStatus)
00085 {
00086     if (uiStatus == UIStatus::Complete)
00087     {
00088         OverwriteButton->IsEnabled = false;
00089         RenameButton->IsEnabled = false;
00090     }
00091 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Mobile broadband account provisioning/C++/MainPage.xaml.h Source File

  • Mobile broadband account provisioning

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:46 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D and DirectWrite animated text on a path/C++/pch.cpp Source File

  • Direct2D and DirectWrite animated text on a path

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CameraCaptureUI/C++/Constants.h Source File

  • CameraCaptureUI

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"CameraCaptureUI CPP sample");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044
00045
00046 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Configure keys for media/C++/mediabuttons.xaml.cpp Source File

  • Configure keys for media

mediabuttons.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 // mediabuttons.xaml.cpp
00013 // Implementation of the mediabuttons class
00014 //
00015
00016 #include "pch.h"
00017 #include "mediabuttons.xaml.h"
00018
00019 using namespace SDKSample::MediaButtons;
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::Media;
00025 using namespace Windows::UI::Xaml::Data;
00026 using namespace Windows::System;
00027 using namespace Windows::Foundation;
00028 using namespace Platform;
00029 using namespace Windows::Storage::Pickers;
00030 using namespace Windows::Foundation::Collections;
00031 using namespace Concurrency;
00032
00033 mediabuttons::mediabuttons()
00034 {
00035     InitializeComponent();
00036     _dispatcher = Window::Current->Dispatcher;
00037     _wasPlaying = false;
00038     _currentSongIndex = 0;
00039     _playlistCount = 0;
00040     _prevTrackPressedEventToken.Value = 0;
00041     _nextTrackPressedEventToken.Value = 0;
00042     _playlist = ref new Platform::Collections::Vector<Song^>();
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 void mediabuttons::OnNavigatedTo(NavigationEventArgs^ e)
00051 {
00052     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00053     // as NotifyUser()
00054     rootPage = MainPage::Current;
00055
00056     if (IsInitialized)
00057     {
00058       return;
00059     }
00060
00061     PlayButton->Click += ref new RoutedEventHandler(this, &mediabuttons::Play_Click);
00062
00063     MediaControl::PlayPauseTogglePressed += ref new EventHandler<Platform::Object^>(this, &mediabuttons::PlayPause);
00064     MediaControl::PlayPressed += ref new EventHandler<Platform::Object^>(this, &mediabuttons::Play);
00065     MediaControl::StopPressed += ref new EventHandler<Platform::Object^>(this, &mediabuttons::Stop);
00066     MediaControl::PausePressed += ref new EventHandler<Platform::Object^>(this, &mediabuttons::Pause);
00067     MediaControl::FastForwardPressed += ref new EventHandler<Platform::Object^>(this, &mediabuttons::FastForward);
00068     MediaControl::RewindPressed += ref new EventHandler<Platform::Object^>(this, &mediabuttons::Rewind);
00069     MediaControl::ChannelUpPressed += ref new EventHandler<Platform::Object^>(this, &mediabuttons::ChannelUp);
00070     MediaControl::ChannelDownPressed += ref new EventHandler<Platform::Object^>(this, &mediabuttons::ChannelDown);
00071     MediaControl::RecordPressed += ref new EventHandler<Platform::Object^>(this, &mediabuttons::Record);
00072
00073     OutputMediaElement->MediaOpened += ref new RoutedEventHandler(this, &mediabuttons::MediaElement_MediaOpened);
00074     OutputMediaElement->MediaEnded += ref new RoutedEventHandler(this, &mediabuttons::MediaElement_MediaEnded);
00075     OutputMediaElement->CurrentStateChanged += ref new RoutedEventHandler(this, &mediabuttons::MediaElement_CurrentStateChanged);
00076
00077     DisplayStatus("Media Buttons Initialized");
00078     IsInitialized = true;
00079
00080 }
00081
00082 void mediabuttons::SelectFiles_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00083 {
00084     try
00085     {
00086         FileOpenPicker^ picker = ref new FileOpenPicker();
00087         picker->ViewMode = PickerViewMode::List;
00088         picker->SuggestedStartLocation = PickerLocationId::MusicLibrary;
00089         picker->FileTypeFilter->Append(".mp3");
00090         picker->FileTypeFilter->Append(".m4a");
00091         picker->FileTypeFilter->Append(".wma");
00092
00093
00094     create_task(picker->PickMultipleFilesAsync()).then([this](IVectorView<StorageFile^>^ files)
00095     {
00096       if(files->Size > 0)
00097       {
00098         CreatePlaylist(files);
00099         SetCurrentPlayingAsync(_currentSongIndex);
00100       }
00101     });
00102
00103     }
00104     catch(Exception^ ex)
00105     {
00106         rootPage->NotifyUser(ex->ToString(), NotifyType::ErrorMessage);
00107     }
00108 }
00109
00110
00111 void mediabuttons::Play_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00112 {
00113     PlayPause(sender, e);
00114 }
00115
00116
00117 void mediabuttons::SetMediaElementSourceAsync(Song^ song)
00118 {
00119     if (song)
00120     {
00121         create_task(song->File->OpenAsync(FileAccessMode::Read)).then([this, song](Streams::IRandomAccessStream^ stream)
00122     {
00123       OutputMediaElement->SetSource(stream, song->File->ContentType);
00124             MediaControl::ArtistName = song->Artist;
00125             MediaControl::TrackName  = song->Track;
00126     });
00127
00128
00129     }
00130 }
00131
00132
00133 void mediabuttons::CreatePlaylist(IVectorView<StorageFile^>^ files)
00134 {
00135     _playlistCount = files->Size;
00136
00137     if (_prevTrackPressedEventToken.Value != 0)
00138     {
00139         MediaControl::PreviousTrackPressed -= _prevTrackPressedEventToken;
00140         _prevTrackPressedEventToken.Value = 0;
00141     }
00142     if (_nextTrackPressedEventToken.Value != 0)
00143     {
00144         MediaControl::NextTrackPressed -= _nextTrackPressedEventToken;
00145         _nextTrackPressedEventToken.Value = 0;
00146     }
00147
00148     _currentSongIndex = 0;
00149     _playlist->Clear();
00150
00151     if (files->Size > 0)
00152     {
00153         // Application now has read/write access to the picked file(s)
00154         if (files->Size > 1)
00155         {
00156             _nextTrackPressedEventToken = MediaControl::NextTrackPressed += ref new EventHandler<Platform::Object^>(this, &mediabuttons::NextTrack, CallbackContext::Same);
00157         }
00158
00159         // Create the playlist
00160
00161         //for each (StorageFile^ file in files)
00162         std::for_each(begin(files), end(files), [this](StorageFile^ file)
00163         {
00164             Song^ newSong = ref new Song(file);
00165             _playlist->Append(newSong);
00166         });
00167       }
00168
00169     return;
00170 }
00171
00172
00173 void mediabuttons::SetCurrentPlayingAsync(int playlistIndex)
00174 {
00175     _wasPlaying = MediaControl::IsPlaying;
00176
00177     try
00178     {
00179         Song^ currSong = _playlist->GetAt(playlistIndex);
00180         create_task(currSong->File->OpenAsync(FileAccessMode::Read)).then([this, currSong, playlistIndex](Streams::IRandomAccessStream^ stream)
00181         {
00182             OutputMediaElement->SetSource(stream, currSong->File->ContentType);
00183             create_task(currSong->File->Properties->GetMusicPropertiesAsync()).then([this, currSong](Windows::Storage::FileProperties::MusicProperties^ properties)
00184             {
00185                 currSong->Artist  = properties->Artist;
00186                 currSong->Track   = properties->Title;
00187                 MediaControl::ArtistName = currSong->Artist;
00188                 MediaControl::TrackName  = currSong->Track;
00189             });
00190
00191         });
00192
00193     }
00194     catch(Exception^ e)
00195     {
00196         DisplayStatus(GetTimeStampedMessage(e->Message));
00197     }
00198 }
00199
00200
00201 void mediabuttons::DisplayStatus(Platform::String^ text)
00202 {
00203     _dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([=]()
00204     {
00205         rootPage->NotifyUser(text, NotifyType::StatusMessage);
00206     }
00207     , CallbackContext::Any));
00208 }
00209
00210
00211 Platform::String^ mediabuttons::GetTimeStampedMessage(Platform::String^ EventCalled)
00212 {
00213     Platform::String^ message;
00214     Windows::Foundation::DateTime timestamp = Windows::Foundation::DateTime();
00215
00216     Windows::Globalization::DateTimeFormatting::DateTimeFormatter^ formatter = ref new Windows::Globalization::DateTimeFormatting::DateTimeFormatter("longtime");
00217     Windows::Globalization::Calendar^ calendar = ref new Windows::Globalization::Calendar();
00218     calendar->SetToNow();
00219
00220     message = EventCalled + "   " + formatter->Format(calendar->GetDateTime());
00221
00222     return message;
00223 }
00224
00225
00226 void mediabuttons::MediaElement_MediaEnded(Object^ sender, RoutedEventArgs^ e)
00227 {
00228     if (_currentSongIndex < _playlistCount - 1)
00229     {
00230         _currentSongIndex++;
00231
00232         SetCurrentPlayingAsync(_currentSongIndex);
00233
00234         if (_wasPlaying)
00235         {
00236             OutputMediaElement->Play();
00237         }
00238     }
00239 }
00240
00241
00242 void mediabuttons::MediaElement_MediaOpened(Object^ sender, RoutedEventArgs^ e)
00243 {
00244     if (_wasPlaying)
00245     {
00246         OutputMediaElement->Play();
00247     }
00248 }
00249
00250
00251 void mediabuttons::MediaElement_CurrentStateChanged(Object^ sender, RoutedEventArgs^ e)
00252 {
00253     if (OutputMediaElement->CurrentState == Media::MediaElementState::Playing)
00254     {
00255         MediaControl::IsPlaying = true;
00256         PlayButton->Content = "Pause";
00257     }
00258     else
00259     {
00260         MediaControl::IsPlaying = false;
00261         PlayButton->Content = "Play";
00262     }
00263 }
00264
00265
00266 void mediabuttons::PlayPause(Object^ sender, Object^ e)
00267 {
00268     if (MediaControl::IsPlaying)
00269     {
00270         _dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([=]()
00271         {
00272             OutputMediaElement->Pause();
00273         }
00274         , CallbackContext::Any));
00275         DisplayStatus(GetTimeStampedMessage("Play/Pause Pressed - Pause"));
00276     }
00277     else
00278     {
00279         _dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([=]()
00280         {
00281             OutputMediaElement->Play();
00282         }
00283         , CallbackContext::Any));
00284         DisplayStatus(GetTimeStampedMessage("Play/Pause Pressed - Play"));
00285     }
00286 }
00287
00288
00289 void mediabuttons::Play(Object^ sender, Object^ e)
00290 {
00291     _dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([=]()
00292     {
00293         OutputMediaElement->Play();
00294     }
00295     , CallbackContext::Any));
00296     DisplayStatus(GetTimeStampedMessage("Play Pressed"));
00297 }
00298
00299
00300 void mediabuttons::Stop(Object^ sender, Object^ e)
00301 {
00302     _dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([=]()
00303     {
00304         OutputMediaElement->Stop();
00305     }
00306     , CallbackContext::Any));
00307     DisplayStatus(GetTimeStampedMessage("Stop Pressed"));
00308 }
00309
00310
00311 void mediabuttons::Pause(Object^ sender, Object^ e)
00312 {
00313     _dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([=]()
00314     {
00315         OutputMediaElement->Pause();
00316     }
00317     , CallbackContext::Any));
00318     DisplayStatus(GetTimeStampedMessage("Pause Pressed"));
00319 }
00320
00321
00322 void mediabuttons::NextTrack(Object^ sender, Object^ e)
00323 {
00324     DisplayStatus(GetTimeStampedMessage("Next Track Pressed"));
00325
00326     if (_currentSongIndex < (_playlistCount - 1))
00327     {
00328         _currentSongIndex++;
00329
00330         SetCurrentPlayingAsync(_currentSongIndex);
00331
00332         if (_currentSongIndex > 0)
00333         {
00334             if (_prevTrackPressedEventToken.Value == 0)
00335             {
00336                 _prevTrackPressedEventToken = MediaControl::PreviousTrackPressed += ref new EventHandler<Platform::Object^>(this, &mediabuttons::PrevTrack, CallbackContext::Same);
00337             }
00338         }
00339         if (_currentSongIndex == (_playlistCount - 1))
00340         {
00341             if (_nextTrackPressedEventToken.Value != 0)
00342             {
00343                 MediaControl::NextTrackPressed -= _nextTrackPressedEventToken;
00344                 _nextTrackPressedEventToken.Value = 0;
00345             }
00346         }
00347     }
00348 }
00349
00350
00351 void mediabuttons::PrevTrack(Object^ sender, Object^ e)
00352 {
00353     DisplayStatus(GetTimeStampedMessage("Prev Track Pressed"));
00354     if (_currentSongIndex > 0)
00355     {
00356         if (_currentSongIndex == (_playlistCount - 1))
00357         {
00358             if (_nextTrackPressedEventToken.Value == 0)
00359             {
00360                 _nextTrackPressedEventToken = MediaControl::NextTrackPressed += ref new EventHandler<Platform::Object^>(this, &mediabuttons::NextTrack, CallbackContext::Same);
00361             }
00362         }
00363
00364     _currentSongIndex--;
00365     SetCurrentPlayingAsync(_currentSongIndex);
00366
00367     if (_currentSongIndex == 0)
00368         {
00369             MediaControl::PreviousTrackPressed -= _prevTrackPressedEventToken;
00370             _prevTrackPressedEventToken.Value = 0;
00371         }
00372     }
00373 }
00374
00375
00376 void mediabuttons::FastForward(Object^ sender, Object^ e)
00377 {
00378     // Handle the fastforward event.  The fastforward event is a repeating event.
00379     // If the user holds down the button more events will be fired. We will just
00380     // display something on the screen.
00381     DisplayStatus(GetTimeStampedMessage("Fast Forward Pressed"));
00382 }
00383
00384
00385 void mediabuttons::Rewind(Object^ sender, Object^ e)
00386 {
00387     // Handle the rewind event.  The rewind event is a repeating event.
00388     // If the user holds down the button more events will be fired. We will just
00389     // display something on the screen.
00390     DisplayStatus(GetTimeStampedMessage("Rewind Pressed"));
00391 }
00392
00393
00394 void mediabuttons::ChannelUp(Object^ sender, Object^ e)
00395 {
00396     // Handle the channelup event.  The channelup event is a repeating event.
00397     // If the user holds down the button more events will be fired. We will just
00398     // display something on the screen.
00399     DisplayStatus(GetTimeStampedMessage("Channel Up Pressed"));
00400 }
00401
00402
00403 void mediabuttons::ChannelDown(Object^ sender, Object^ e)
00404 {
00405     // Handle the channeldown event.  The channeldown event is a repeating event.
00406     // If the user holds down the button more events will be fired. We will just
00407     // display something on the screen.
00408     DisplayStatus(GetTimeStampedMessage("Channel Down Pressed"));
00409 }
00410
00411
00412 void mediabuttons::Record(Object^ sender, Object^ e)
00413 {
00414     // Handle the Previous Track event.  We will just display something on the screen.
00415     DisplayStatus(GetTimeStampedMessage("Record Pressed"));
00416 }
Generated on Sat Nov 23 2024 16:07:59 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media Server client/C++/pch.cpp Source File

  • Media Server client

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/MediaExtensions/Grayscale/Grayscale.h Source File

  • Media extensions
  • MediaExtensions
  • Grayscale

Grayscale.h

Go to the documentation of this file.
00001 // Defines the transform class.
00002 //
00003 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00004 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00005 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00006 // PARTICULAR PURPOSE.
00007 //
00008 // Copyright (c) Microsoft Corporation. All rights reserved.
00009
00010 #ifndef GRAYSCALE_H
00011 #define GRAYSCALE_H
00012
00013 #include <new>
00014 #include <mfapi.h>
00015 #include <mftransform.h>
00016 #include <mfidl.h>
00017 #include <mferror.h>
00018 #include <strsafe.h>
00019 #include <assert.h>
00020
00021 // Note: The Direct2D helper library is included for its 2D matrix operations.
00022 #include <D2d1helper.h>
00023
00024 #include <wrl\implements.h>
00025 #include <wrl\module.h>
00026 #include <windows.media.h>
00027
00028 #include "GrayscaleTransform.h"
00029
00030 // CLSID of the MFT.
00031 DEFINE_GUID(CLSID_GrayscaleMFT,
00032 0x2f3dbc05, 0xc011, 0x4a8f, 0xb2, 0x64, 0xe4, 0x2e, 0x35, 0xc6, 0x7b, 0xf4);
00033
00034 //
00035 // * IMPORTANT: If you implement your own MFT, create a new GUID for the CLSID. *
00036 //
00037
00038
00039 // Configuration attributes
00040
00041 // {7BBBB051-133B-41F5-B6AA-5AFF9B33A2CB}
00042 DEFINE_GUID(MFT_GRAYSCALE_DESTINATION_RECT,
00043 0x7bbbb051, 0x133b, 0x41f5, 0xb6, 0xaa, 0x5a, 0xff, 0x9b, 0x33, 0xa2, 0xcb);
00044
00045
00046 // {14782342-93E8-4565-872C-D9A2973D5CBF}
00047 DEFINE_GUID(MFT_GRAYSCALE_SATURATION,
00048 0x14782342, 0x93e8, 0x4565, 0x87, 0x2c, 0xd9, 0xa2, 0x97, 0x3d, 0x5c, 0xbf);
00049
00050 // {E0BADE5D-E4B9-4689-9DBA-E2F00D9CED0E}
00051 DEFINE_GUID(MFT_GRAYSCALE_CHROMA_ROTATION,
00052 0xe0bade5d, 0xe4b9, 0x4689, 0x9d, 0xba, 0xe2, 0xf0, 0xd, 0x9c, 0xed, 0xe);
00053
00054
00055 template <class T> void SafeRelease(T **ppT)
00056 {
00057     if (*ppT)
00058     {
00059         (*ppT)->Release();
00060         *ppT = NULL;
00061     }
00062 }
00063
00064 // Function pointer for the function that transforms the image.
00065 typedef void (*IMAGE_TRANSFORM_FN)(
00066     const D2D1::Matrix3x2F& mat,             // Chroma transform matrix.
00067     const D2D_RECT_U&       rcDest,          // Destination rectangle for the transformation.
00068     BYTE*                   pDest,           // Destination buffer.
00069     LONG                    lDestStride,     // Destination stride.
00070     const BYTE*             pSrc,            // Source buffer.
00071     LONG                    lSrcStride,      // Source stride.
00072     DWORD                   dwWidthInPixels, // Image width in pixels.
00073     DWORD                   dwHeightInPixels // Image height in pixels.
00074     );
00075
00076 // CGrayscale class:
00077 // Implements a grayscale video effect.
00078
00079 class CGrayscale
00080     : public Microsoft::WRL::RuntimeClass<
00081            Microsoft::WRL::RuntimeClassFlags< Microsoft::WRL::RuntimeClassType::WinRtClassicComMix >,
00082            ABI::Windows::Media::IMediaExtension,
00083            IMFTransform >
00084 {
00085     InspectableClass(RuntimeClass_GrayscaleTransform_GrayscaleEffect, BaseTrust)
00086
00087 public:
00088     CGrayscale();
00089
00090     ~CGrayscale();
00091
00092     STDMETHOD(RuntimeClassInitialize)();
00093
00094     // IMediaExtension
00095     STDMETHODIMP SetProperties(ABI::Windows::Foundation::Collections::IPropertySet *pConfiguration);
00096
00097     // IMFTransform
00098     STDMETHODIMP GetStreamLimits(
00099         DWORD   *pdwInputMinimum,
00100         DWORD   *pdwInputMaximum,
00101         DWORD   *pdwOutputMinimum,
00102         DWORD   *pdwOutputMaximum
00103     );
00104
00105     STDMETHODIMP GetStreamCount(
00106         DWORD   *pcInputStreams,
00107         DWORD   *pcOutputStreams
00108     );
00109
00110     STDMETHODIMP GetStreamIDs(
00111         DWORD   dwInputIDArraySize,
00112         DWORD   *pdwInputIDs,
00113         DWORD   dwOutputIDArraySize,
00114         DWORD   *pdwOutputIDs
00115     );
00116
00117     STDMETHODIMP GetInputStreamInfo(
00118         DWORD                     dwInputStreamID,
00119         MFT_INPUT_STREAM_INFO *   pStreamInfo
00120     );
00121
00122     STDMETHODIMP GetOutputStreamInfo(
00123         DWORD                     dwOutputStreamID,
00124         MFT_OUTPUT_STREAM_INFO *  pStreamInfo
00125     );
00126
00127     STDMETHODIMP GetAttributes(IMFAttributes** pAttributes);
00128
00129     STDMETHODIMP GetInputStreamAttributes(
00130         DWORD           dwInputStreamID,
00131         IMFAttributes   **ppAttributes
00132     );
00133
00134     STDMETHODIMP GetOutputStreamAttributes(
00135         DWORD           dwOutputStreamID,
00136         IMFAttributes   **ppAttributes
00137     );
00138
00139     STDMETHODIMP DeleteInputStream(DWORD dwStreamID);
00140
00141     STDMETHODIMP AddInputStreams(
00142         DWORD   cStreams,
00143         DWORD   *adwStreamIDs
00144     );
00145
00146     STDMETHODIMP GetInputAvailableType(
00147         DWORD           dwInputStreamID,
00148         DWORD           dwTypeIndex, // 0-based
00149         IMFMediaType    **ppType
00150     );
00151
00152     STDMETHODIMP GetOutputAvailableType(
00153         DWORD           dwOutputStreamID,
00154         DWORD           dwTypeIndex, // 0-based
00155         IMFMediaType    **ppType
00156     );
00157
00158     STDMETHODIMP SetInputType(
00159         DWORD           dwInputStreamID,
00160         IMFMediaType    *pType,
00161         DWORD           dwFlags
00162     );
00163
00164     STDMETHODIMP SetOutputType(
00165         DWORD           dwOutputStreamID,
00166         IMFMediaType    *pType,
00167         DWORD           dwFlags
00168     );
00169
00170     STDMETHODIMP GetInputCurrentType(
00171         DWORD           dwInputStreamID,
00172         IMFMediaType    **ppType
00173     );
00174
00175     STDMETHODIMP GetOutputCurrentType(
00176         DWORD           dwOutputStreamID,
00177         IMFMediaType    **ppType
00178     );
00179
00180     STDMETHODIMP GetInputStatus(
00181         DWORD           dwInputStreamID,
00182         DWORD           *pdwFlags
00183     );
00184
00185     STDMETHODIMP GetOutputStatus(DWORD *pdwFlags);
00186
00187     STDMETHODIMP SetOutputBounds(
00188         LONGLONG        hnsLowerBound,
00189         LONGLONG        hnsUpperBound
00190     );
00191
00192     STDMETHODIMP ProcessEvent(
00193         DWORD              dwInputStreamID,
00194         IMFMediaEvent      *pEvent
00195     );
00196
00197     STDMETHODIMP ProcessMessage(
00198         MFT_MESSAGE_TYPE    eMessage,
00199         ULONG_PTR           ulParam
00200     );
00201
00202     STDMETHODIMP ProcessInput(
00203         DWORD               dwInputStreamID,
00204         IMFSample           *pSample,
00205         DWORD               dwFlags
00206     );
00207
00208     STDMETHODIMP ProcessOutput(
00209         DWORD                   dwFlags,
00210         DWORD                   cOutputBufferCount,
00211         MFT_OUTPUT_DATA_BUFFER  *pOutputSamples, // one per stream
00212         DWORD                   *pdwStatus
00213     );
00214
00215
00216 private:
00217     // HasPendingOutput: Returns TRUE if the MFT is holding an input sample.
00218     BOOL HasPendingOutput() const { return m_pSample != NULL; }
00219
00220     // IsValidInputStream: Returns TRUE if dwInputStreamID is a valid input stream identifier.
00221     BOOL IsValidInputStream(DWORD dwInputStreamID) const
00222     {
00223         return dwInputStreamID == 0;
00224     }
00225
00226     // IsValidOutputStream: Returns TRUE if dwOutputStreamID is a valid output stream identifier.
00227     BOOL IsValidOutputStream(DWORD dwOutputStreamID) const
00228     {
00229         return dwOutputStreamID == 0;
00230     }
00231
00232     HRESULT OnGetPartialType(DWORD dwTypeIndex, IMFMediaType **ppmt);
00233     HRESULT OnCheckInputType(IMFMediaType *pmt);
00234     HRESULT OnCheckOutputType(IMFMediaType *pmt);
00235     HRESULT OnCheckMediaType(IMFMediaType *pmt);
00236     void    OnSetInputType(IMFMediaType *pmt);
00237     void    OnSetOutputType(IMFMediaType *pmt);
00238     HRESULT BeginStreaming();
00239     HRESULT EndStreaming();
00240     HRESULT OnProcessOutput(IMFMediaBuffer *pIn, IMFMediaBuffer *pOut);
00241     HRESULT OnFlush();
00242     HRESULT UpdateFormatInfo();
00243
00244     CRITICAL_SECTION            m_critSec;
00245
00246     // Transformation parameters
00247     D2D1::Matrix3x2F            m_transform;                // Chroma transform matrix.
00248     D2D_RECT_U                  m_rcDest;                   // Destination rectangle for the effect.
00249
00250     // Streaming
00251     bool                        m_bStreamingInitialized;
00252     IMFSample                   *m_pSample;                 // Input sample.
00253     IMFMediaType                *m_pInputType;              // Input media type.
00254     IMFMediaType                *m_pOutputType;             // Output media type.
00255
00256     // Fomat information
00257     UINT32                      m_imageWidthInPixels;
00258     UINT32                      m_imageHeightInPixels;
00259     DWORD                       m_cbImageSize;              // Image size, in bytes.
00260
00261     IMFAttributes               *m_pAttributes;
00262
00263     // Image transform function. (Changes based on the media type.)
00264     IMAGE_TRANSFORM_FN          m_pTransformFn;
00265 };
00266 #endif
Generated on Sat Nov 23 2024 16:08:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D magazine app/C++/Design.cpp Source File

  • Direct2D magazine app

Design.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
00010 using namespace Windows::Data::Xml::Dom;
00011
00012 Design::Design() :
00013     Element(),
00014     m_pageSize()
00015 {
00016 }
00017
00018 bool Design::Initialize(
00019     _In_ Document^ document,
00020     _In_ XmlElement^ xmlElement
00021     )
00022 {
00023     if (!Element::Initialize(document, xmlElement))
00024     {
00025         return false;
00026     }
00027
00028     Platform::String^ value = xmlElement->GetAttribute("page-width");
00029
00030     if (value != nullptr)
00031     {
00032         m_pageSize.width = static_cast<float>(_wtof(value->Data()));
00033     }
00034
00035     value = xmlElement->GetAttribute("page-height");
00036
00037     if (value != nullptr)
00038     {
00039         m_pageSize.height = static_cast<float>(_wtof(value->Data()));
00040     }
00041
00042     return true;
00043 }
00044
00045 bool Design::AcceptChildNode(
00046     _In_ Document^ document,
00047     _In_ IXmlNode^ childXmlNode
00048     )
00049 {
00050     if (childXmlNode->NodeType == NodeType::ElementNode)
00051     {
00052         XmlElement^ xmlElement = dynamic_cast<XmlElement^>(childXmlNode);
00053
00054         Element^ child = nullptr;
00055         Platform::String^ elementName = xmlElement->TagName;
00056
00057         if (elementName != nullptr)
00058         {
00059             if (elementName == "page-roll")
00060             {
00061                 child = Element::Create<PageRoll>(document, childXmlNode);
00062             }
00063         }
00064
00065         if (child == nullptr)
00066         {
00067             return false;
00068         }
00069
00070         AddChild(child);
00071     }
00072
00073     return true;
00074 }
Generated on Sat Nov 23 2024 16:08:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DirectX::HDRColorA Member List

This is the complete list of members for DirectX::HDRColorA, including all inherited members.
a | DirectX::HDRColorA |
b | DirectX::HDRColorA |
Clamp(_In_ float fMin, _In_ float fMax) | DirectX::HDRColorA | [inline]
g | DirectX::HDRColorA |
HDRColorA() | DirectX::HDRColorA | [inline]
HDRColorA(float _r, float _g, float _b, float _a) | DirectX::HDRColorA | [inline]
HDRColorA(const HDRColorA &c) | DirectX::HDRColorA | [inline]
HDRColorA(const LDRColorA &c) | DirectX::HDRColorA | [inline]
operator*(_In_ float f) const | DirectX::HDRColorA | [inline]
operator*(_In_ const HDRColorA &c) const | DirectX::HDRColorA | [inline]
operator*=(_In_ float f) | DirectX::HDRColorA | [inline]
operator+(_In_ const HDRColorA &c) const | DirectX::HDRColorA | [inline]
operator+=(_In_ const HDRColorA &c) | DirectX::HDRColorA | [inline]
operator-(_In_ const HDRColorA &c) const | DirectX::HDRColorA | [inline]
operator-=(_In_ const HDRColorA &c) | DirectX::HDRColorA | [inline]
operator/(_In_ float f) const | DirectX::HDRColorA | [inline]
operator/=(_In_ float f) | DirectX::HDRColorA | [inline]
operator=(_In_ const LDRColorA &c) | DirectX::HDRColorA | [inline]
r | DirectX::HDRColorA |
ToLDRColorA() const | DirectX::HDRColorA | [inline]
Generated on Sat Nov 23 2024 16:09:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/ScenarioList.xaml.cpp Source File

  • Media extensions

ScenarioList.xaml.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 //
00009 // ScenarioList.xaml.cpp
00010 // Implementation of the ScenarioList class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioList.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace MediaExtensionsCPP;
00018
00019 using namespace Platform;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Graphics::Display;
00023 using namespace Windows::UI::ViewManagement;
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 using namespace Windows::UI::Xaml::Interop;
00032
00033 ScenarioList::ScenarioList()
00034 {
00035     InitializeComponent();
00036 }
00037
00038 ScenarioList::~ScenarioList()
00039 {
00040 }
00041
00042 void ScenarioList::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00043 {
00044     if (Scenarios->SelectedItem != nullptr)
00045     {
00046         rootPage->NotifyUser("", NotifyType::StatusMessage);
00047
00048         ListBoxItem^ selectedListBoxItem = dynamic_cast<ListBoxItem^>(Scenarios->SelectedItem);
00049         SuspensionManager::SessionState()->Insert("SelectedScenario", selectedListBoxItem->Name);
00050
00051         if (rootPage->InputFrame != nullptr && rootPage->OutputFrame != nullptr)
00052         {
00053             //Load the input and output pages for the current scenario into their respective frames.
00054             TypeName inputPage = { "MediaExtensionsCPP" + "." + "ScenarioInput" + ((Scenarios->SelectedIndex + 1).ToString()), TypeKind::Custom };
00055             TypeName outputPage = { "MediaExtensionsCPP" + "." + "ScenarioOutput" + ((Scenarios->SelectedIndex + 1).ToString()), TypeKind::Custom };
00056             rootPage->DoNavigation(inputPage, rootPage->InputFrame);
00057             rootPage->DoNavigation(outputPage, rootPage->OutputFrame);
00058         }
00059     }
00060 }
00061
00062 void ScenarioList::OnNavigatedTo(NavigationEventArgs^ e)
00063 {
00064     rootPage = dynamic_cast<MainPage^>(e->Parameter);
00065
00066     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &ScenarioList::Scenarios_SelectionChanged);
00067     ListBoxItem^ startingScenario = nullptr;
00068
00069     auto ps = SuspensionManager::SessionState();
00070     if (ps->HasKey("SelectedScenario"))
00071     {
00072         PropertyValue^ pv;
00073         String^ item = dynamic_cast<String^>(ps->Lookup("SelectedScenario"));
00074         startingScenario = dynamic_cast<ListBoxItem^>(this->FindName(item));
00075     }
00076
00077     Scenarios->SelectedItem = startingScenario != nullptr ? startingScenario : Scenario1;
00078 }
Generated on Sat Nov 23 2024 16:07:57 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Removable storage/C++/pch.h Source File

  • Removable storage

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "Constants.h"
00023 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Calendar details and math/C++/DisplayCalendarData.xaml.cpp Source File

  • Calendar details and math

DisplayCalendarData.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 // DisplayCalendarData.xaml.cpp
00013 // Implementation of the DisplayCalendarData class
00014 //
00015
00016 #include "pch.h"
00017 #include "DisplayCalendarData.xaml.h"
00018
00019 using namespace SDKSample::CalendarSample;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024 using namespace Platform;
00025 using namespace Windows::Foundation;
00026 using namespace Windows::Foundation::Collections;
00027 using namespace Windows::Globalization;
00028
00029 DisplayCalendarData::DisplayCalendarData()
00030 {
00031     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 void DisplayCalendarData::OnNavigatedTo(NavigationEventArgs^ e)
00040 {
00041     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00042     // as NotifyUser()
00043     rootPage = MainPage::Current;
00044 }
00045
00046 void SDKSample::CalendarSample::DisplayCalendarData::Display_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00047 {
00048     // This scenario uses the Windows.Globalization.Calendar class to display the parts of a date.
00049
00050     // Store results here
00051     String^ results;
00052
00053     // Array languages used by the test
00054     auto ja = ref new Platform::Collections::Vector<String^>();
00055   ja->Append("ja-JP");
00056   auto he = ref new Platform::Collections::Vector<String^>();
00057   he->Append("he-IL");
00058
00059   // Create a calendar based on the current user.
00060   Calendar^ cal1 = ref new Calendar();
00061
00062   // Create a calendar using Japanese language and Japanese calendar.
00063   Calendar^ cal2 = ref new Calendar(ja, CalendarIdentifiers::Japanese, ClockIdentifiers::TwelveHour);
00064
00065   // Create a calendar using Hebrew language and Hebrew calendar.
00066   Calendar^ cal3 = ref new Calendar(he, CalendarIdentifiers::Hebrew, ClockIdentifiers::TwentyFourHour);
00067
00068   // Obtain the date parts using the default calendar system.
00069   String^ calItems1 =
00070         "User's default calendar: " + cal1->GetCalendarSystem() + "\n" +
00071     "Name of Month: " + cal1->MonthAsSoloString() + "\n" +
00072     "Day of Month: " + cal1->DayAsPaddedString(2) + "\n" +
00073     "Day of Week: " + cal1->DayOfWeekAsString() + "\n" +
00074     "Year: " + cal1->YearAsString();
00075
00076   // Obtain the date parts using the Japanese calendar system.
00077   String^ calItems2 =
00078         "Calendar system: " + cal2->GetCalendarSystem() + "\n" +
00079     "Name of Month: " + cal2->MonthAsSoloString() + "\n" +
00080     "Day of Month: " + cal2->DayAsPaddedString(2) + "\n" +
00081     "Day of Week: " + cal2->DayOfWeekAsString() + "\n" +
00082     "Year: " + cal2->YearAsString();
00083
00084   // Obtain the date parts using the Hebrew calendar system.
00085   String^ calItems3 =
00086         "Calendar system: " + cal3->GetCalendarSystem() + "\n" +
00087     "Name of Month: " + cal3->MonthAsSoloString() + "\n" +
00088     "Day of Month: " + cal3->DayAsPaddedString(2) + "\n" +
00089     "Day of Week: " + cal3->DayOfWeekAsString() + "\n" +
00090     "Year: " + cal3->YearAsString();
00091
00092   // Generate the results.
00093   results = calItems1 + "\n\n" + calItems2 + "\n\n" + calItems3;
00094
00095     // Display the results
00096     rootPage->NotifyUser(results, NotifyType::StatusMessage);
00097 }
Generated on Sat Nov 23 2024 16:07:58 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Web authentication broker/C++/Constants.h Source File

  • Web authentication broker

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"Web Authentication");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044
00045
00046 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Certificate enrollment/C++/common/suspensionmanager.cpp Source File

  • Certificate enrollment
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::TileContent::TileNotificationBase Member List

This is the complete list of members for NotificationsExtensions::TileContent::TileNotificationBase, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
Branding | NotificationsExtensions::TileContent::TileNotificationBase |
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
GetContent() | NotificationsExtensions::NotificationBase | [pure virtual]
GetContent() | NotificationsExtensions::NotificationBase | [pure virtual]
GetContent() | NotificationsExtensions::NotificationBase | [pure virtual]
GetContent() | NotificationsExtensions::NotificationBase | [pure virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
m_Branding | NotificationsExtensions::TileContent::TileNotificationBase | [private]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextFields | NotificationsExtensions::NotificationBase |
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:43 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DXGI swap chain rotation/C++/BasicLoader.cpp Source File

  • DXGI swap chain rotation

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 Sat Nov 23 2024 16:08:08 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D convolve matrix effect/C++/ConvolveMatrixEffect.h Source File

  • Direct2D convolve matrix effect

ConvolveMatrixEffect.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 "DirectXBase.h"
00011 #include "SampleOverlay.h"
00012 #include "ConvolutionKernels.h"
00013
00014 ref class ConvolveMatrixEffect : public DirectXBase, public Windows::ApplicationModel::Core::IFrameworkView
00015 {
00016 internal:
00017     ConvolveMatrixEffect();
00018
00019     // DirectXBase Methods
00020     virtual void CreateDeviceIndependentResources() override;
00021     virtual void CreateDeviceResources() override;
00022     virtual void CreateWindowSizeDependentResources() override;
00023     virtual void Render() override;
00024
00025 public:
00026     // IFrameworkView Methods
00027     virtual void Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00028     virtual void SetWindow(_In_ Windows::UI::Core::CoreWindow^ window);
00029     virtual void Load(_In_ Platform::String^ entryPoint);
00030     virtual void Run();
00031     virtual void Uninitialize();
00032
00033 private:
00034     // Event Handlers
00035     void OnWindowSizeChanged(
00036         _In_ Windows::UI::Core::CoreWindow^ sender,
00037         _In_ Windows::UI::Core::WindowSizeChangedEventArgs^ args
00038         );
00039
00040     void OnLogicalDpiChanged(
00041         _In_ Platform::Object^ sender
00042         );
00043
00044     void OnDisplayContentsInvalidated(
00045         _In_ Platform::Object^ sender
00046         );
00047
00048     void OnActivated(
00049         _In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView,
00050         _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^ args
00051         );
00052
00053     void OnSuspending(
00054         _In_ Platform::Object^ sender,
00055         _In_ Windows::ApplicationModel::SuspendingEventArgs^ args
00056         );
00057
00058     void OnResuming(
00059         _In_ Platform::Object^ sender,
00060         _In_ Platform::Object^ args
00061         );
00062
00063     void OnPointerPressed(
00064         _In_ Windows::UI::Core::CoreWindow^ sender,
00065         _In_ Windows::UI::Core::PointerEventArgs^ args
00066         );
00067
00068     void OnPointerMoved(
00069         _In_ Windows::UI::Core::CoreWindow^ sender,
00070         _In_ Windows::UI::Core::PointerEventArgs^ args
00071         );
00072
00073     void OnPointerReleased(
00074         _In_ Windows::UI::Core::CoreWindow^ sender,
00075         _In_ Windows::UI::Core::PointerEventArgs^ args
00076         );
00077
00078     void OnHolding(
00079         _In_ Windows::UI::Input::GestureRecognizer^ sender,
00080         _In_ Windows::UI::Input::HoldingEventArgs^ args
00081         );
00082
00083     void ShowMenu(
00084         Windows::Foundation::Point position
00085         );
00086
00087     void SwitchKernel(_In_ Windows::UI::Popups::IUICommand^ command);
00088
00089     SampleOverlay^                                          m_sampleOverlay;
00090     Platform::Agile<Windows::UI::Input::GestureRecognizer>  m_gestureRecognizer;
00091
00092     KernelSelection                                         m_selectedKernel;
00093     D2D1_SIZE_U                                             m_bitmapPixelSize;
00094     D2D1_SIZE_F                                             m_imageSize;
00095
00096     Microsoft::WRL::ComPtr<IWICFormatConverter>             m_wicConvertedSource;
00097     Microsoft::WRL::ComPtr<ID2D1Effect>                     m_bitmapSourceEffect;
00098     Microsoft::WRL::ComPtr<ID2D1Effect>                     m_convolveMatrixEffect;
00099 };
00100
00101 ref class DirectXAppSource : Windows::ApplicationModel::Core::IFrameworkViewSource
00102 {
00103 public:
00104     virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00105 };
Generated on Sat Nov 23 2024 16:08:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX marble maze game/C++/BasicLoader.cpp Source File

  • DirectX marble maze game

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 Sat Nov 23 2024 16:08:07 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Context menu/C++/common/suspensionmanager.h Source File

  • Context menu
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML FlipView control/C++/pch.cpp Source File

  • XAML FlipView control

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D-Direct2D interop/C++/BasicCamera.h Source File

  • Direct3D-Direct2D interop

BasicCamera.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 camera class.
00011 ref class BasicCamera
00012 {
00013
00014 private:
00015     float3 m_position;      // the position of the camera
00016     float3 m_direction;     // the unit vector of the viewing direction
00017     float4x4 m_view;        // view matrix
00018     float4x4 m_projection;  // projection matrix
00019
00020 internal:
00021     void GetViewMatrix(_Out_ float4x4 *viewMatrix);
00022     void GetProjectionMatrix(_Out_ float4x4 *projectionMatrix);
00023
00024     // this method updates the view matrix based on new position and focus coordinates
00025     void SetViewParameters(
00026         _In_ float3 eyePosition,    // the position of the camera
00027         _In_ float3 lookPosition,   // the point the camera should look at
00028         _In_ float3 up              // the durection vector for up
00029         );
00030
00031     // this method updates the projection matrix based on new parameters
00032     void SetProjectionParameters(
00033         _In_ float minimumFieldOfView,  // the minimum horizontal or vertical field of view, in degrees
00034         _In_ float aspectRatio,         // the aspect ratio of the projection (width / height)
00035         _In_ float nearPlane,           // depth to map to 0
00036         _In_ float farPlane             // depth to map to 1
00037         );
00038 };
Generated on Sat Nov 23 2024 16:08:07 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/HubPhotoGroup.cpp Source File

  • Hilo C++
  • Hilo

HubPhotoGroup.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 #include "HubPhotoGroup.h"
00009 #include "TaskExceptionsExtensions.h"
00010 #include "IPhoto.h"
00011 #include "IResizable.h"
00012 #include "Repository.h"
00013
00014 using namespace concurrency;
00015 using namespace Hilo;
00016 using namespace std;
00017 using namespace Platform;
00018 using namespace Platform::Collections;
00019 using namespace Windows::Foundation::Collections;
00020
00021 const unsigned int MaxNumberOfPictures = 6;
00022
00023 HubPhotoGroup::HubPhotoGroup(String^ title, String^ emptyTitle, shared_ptr<Repository> repository, shared_ptr<ExceptionPolicy> exceptionPolicy) :
00024     m_title(title), m_emptyTitle(emptyTitle), m_retrievedPhotos(false), m_repository(repository), m_exceptionPolicy(exceptionPolicy),
00025     m_receivedChangeWhileRunning(false), m_runningQuery(false), m_hasFileUpdateTask(false), m_lastFileChangeTime(0ull)
00026 {
00027     auto wr = Platform::WeakReference(this);
00028     function<void()> callback = [wr] {
00029         auto vm = wr.Resolve<HubPhotoGroup>();
00030         if (nullptr != vm)
00031         {
00032             vm->OnDataChanged();
00033         }
00034     };
00035     m_repository->AddObserver(callback, PageType::Hub);
00036 }
00037
00038 HubPhotoGroup::~HubPhotoGroup()
00039 {
00040     if (nullptr != m_repository)
00041     {
00042         m_repository->RemoveObserver(PageType::Hub);
00043     }
00044 }
00045
00046 #pragma region Regulate File Update Events
00047 // To prevent UI flicker, the HubPhotoGroup limits the frequency of update events
00048 // that occur when file system changes require the hub photo group to update the displayed items.
00049
00050 // This is minimum allowed time in milliseconds between successive file system change notifications.
00051 const ULONGLONG EVENTSPACING = 30000ul;
00052
00053 // This is the handler that is invoked whenever the file system notifies the hub photo group of a change in the
00054 // previously submitted query. The handler propagates updates at a maximum rate of one for each EVENTSPACING/1000 seconds.
00055 void HubPhotoGroup::OnDataChanged()
00056 {
00057     assert(IsMainThread());
00058
00059     auto currentTime = GetTickCount64();
00060
00061     if (m_hasFileUpdateTask)
00062     {
00063         // An update is already scheduled to occur. Ignore the current change notification.
00064     }
00065     else if (m_lastFileChangeTime == 0ull || currentTime > (m_lastFileChangeTime + EVENTSPACING))
00066     {
00067         // If it's the first change, or more than EVENTSPACING/1000 seconds have elapsed since the last update, observe the change immediately.
00068         m_lastFileChangeTime = currentTime;
00069         ObserveFileChange();
00070     }
00071     else
00072     {
00073         // Otherwise, schedule the update to occur EVENTSPACING/1000 seconds from the previous update.
00074         auto timeSinceUpdate = (currentTime > m_lastFileChangeTime ? currentTime - m_lastFileChangeTime : 0ul);
00075         unsigned int timeToWait = (timeSinceUpdate < EVENTSPACING ? EVENTSPACING - (unsigned int)timeSinceUpdate : EVENTSPACING);
00076         m_lastFileChangeTime = currentTime + timeToWait;
00077         m_hasFileUpdateTask = true;
00078
00079         // Use weak reference to avoid inadvertently extending object lifetime.
00080         auto weakThis = Platform::WeakReference(this);
00081
00082         // Observe the update after waiting the specified amount of time.
00083         create_task([timeToWait]() {
00084             assert(IsBackgroundThread());
00085             ::wait(timeToWait);
00086         }).then([weakThis]() {
00087             assert(IsMainThread());
00088             auto obj = weakThis.Resolve<HubPhotoGroup>();
00089             if (nullptr != obj)
00090             {
00091                 obj->ObserveFileChange();
00092                 obj->m_hasFileUpdateTask = false;
00093             }
00094         }, task_continuation_context::use_current()).then(ObserveException<void>(m_exceptionPolicy));
00095     }
00096 }
00097 #pragma endregion
00098
00099 void HubPhotoGroup::OnPropertyChanged(String^ propertyName)
00100 {
00101     assert(IsMainThread());
00102     PropertyChanged(this, ref new Windows::UI::Xaml::Data::PropertyChangedEventArgs(propertyName));
00103 }
00104
00105 IObservableVector<IPhoto^>^ HubPhotoGroup::Items::get()
00106 {
00107     assert(IsMainThread());
00108     if (m_photos == nullptr)
00109     {
00110         OnDataChanged();
00111     }
00112     return m_photos;
00113 }
00114
00115 String^ HubPhotoGroup::Title::get()
00116 {
00117     if (!m_retrievedPhotos)
00118     {
00119         return "";
00120     }
00121
00122     if (m_photos->Size == 0)
00123     {
00124         return m_emptyTitle;
00125     }
00126     return m_title;
00127 }
00128
00129 task<void> HubPhotoGroup::QueryPhotosAsync()
00130 {
00131     // only for unit testing
00132     if (m_photos == nullptr)
00133     {
00134         m_photos = ref new Vector<IPhoto^>();
00135     }
00136
00137     auto t = m_repository->GetPhotosForPictureHubGroupAsync(this, MaxNumberOfPictures);
00138     return t.then([this](IVectorView<IPhoto^>^ photos)
00139     {
00140         assert(IsMainThread());
00141         m_retrievedPhotos = true;
00142         m_photos->Clear();
00143         bool firstPhoto = true;
00144         for (auto photo : photos)
00145         {
00146             if (firstPhoto)
00147             {
00148                 IResizable^ resizable = dynamic_cast<IResizable^>(photo);
00149                 if (nullptr != resizable)
00150                 {
00151                     resizable->ColumnSpan = 2;
00152                     resizable->RowSpan = 2;
00153                 }
00154                 firstPhoto = false;
00155             }
00156             m_photos->Append(photo);
00157         }
00158     });
00159 }
00160
00161 void HubPhotoGroup::ObserveFileChange()
00162 {
00163     assert(IsMainThread());
00164     if (m_runningQuery)
00165     {
00166         m_receivedChangeWhileRunning = true;
00167     }
00168
00169     if (!m_runningQuery)
00170     {
00171         if (m_photos == nullptr)
00172         {
00173             m_photos = ref new Vector<IPhoto^>();
00174         }
00175         m_runningQuery = true;
00176         QueryPhotosAsync().then([this]
00177         {
00178             assert(IsMainThread());
00179             if (!m_receivedChangeWhileRunning)
00180             {
00181                 OnPropertyChanged("Items");
00182                 OnPropertyChanged("Title");
00183             }
00184             m_runningQuery = false;
00185             if (m_receivedChangeWhileRunning)
00186             {
00187                 m_receivedChangeWhileRunning = false;
00188                 OnDataChanged();
00189             }
00190         }).then(ObserveException<void>(m_exceptionPolicy));
00191
00192     }
00193 }
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playlist/C++/Remove.xaml.cpp Source File

  • Playlist

Remove.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 // Remove.xaml.cpp
00013 // Implementation of the Remove class
00014 //
00015
00016 #include "pch.h"
00017 #include "Remove.xaml.h"
00018
00019 using namespace SDKSample::Playlists;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 Remove::Remove()
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 Remove::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 Remove::PickPlaylistButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00043 {
00044     // Make sure app is unsnapped before invoking the file picker
00045     if(!MainPage::EnsureUnsnapped())
00046     {
00047         OutputStatus->Text = "Unable to unsnap the app.";
00048         return;
00049     }
00050
00051     // Pick a file, load it as a playlist, then remove the last item in the playlist.
00052     MainPage::PickPlaylist().then([this](task<Playlist^> playlistTask)
00053     {
00054         try
00055         {
00056             MainPage::playlist = playlistTask.get();
00057
00058             if (MainPage::playlist->Files->Size > 0)
00059             {
00060                 // Remove the last item.
00061                 MainPage::playlist->Files->RemoveAtEnd();
00062                 task<void>(MainPage::playlist->SaveAsync()).then([this]()
00063                 {
00064                     OutputStatus->Text = "The last item in the playlist was removed.";
00065                 });
00066             }
00067             else
00068             {
00069                 OutputStatus->Text = "No items in playlist.";
00070             }
00071         }
00072         catch (NullReferenceException^ ex)
00073         {
00074             OutputStatus->Text = "No playlist picked.";
00075         }
00076         catch(AccessDeniedException^ ex)
00077         {
00078             OutputStatus->Text = "Access is denied, cannot load playlist.";
00079         }
00080     });
00081 }
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

MoveLookController Member List

This is the complete list of members for MoveLookController, including all inherited members.
__pad0__ | MoveLookController |
Active() | MoveLookController |
Active(_In_ bool active) | MoveLookController |
Active() | MoveLookController |
Active(_In_ bool active) | MoveLookController |
args | MoveLookController | [private]
AutoFire() | MoveLookController |
AutoFire(_In_ bool AutoFire) | MoveLookController |
AutoFire() | MoveLookController |
AutoFire(_In_ bool AutoFire) | MoveLookController |
GetLookPoint() | MoveLookController | [private]
GetPosition() | MoveLookController | [private]
Initialize(_In_ Windows::UI::Core::CoreWindow^window) | MoveLookController |
Initialize(_In_ Windows::UI::Core::CoreWindow^window) | MoveLookController | [private]
Initialize(_In_ Windows::UI::Core::CoreWindow^window) | MoveLookController |
IsFiring() | MoveLookController |
IsFiring() | MoveLookController |
IsPauseRequested() | MoveLookController |
IsPauseRequested() | MoveLookController |
IsPressComplete() | MoveLookController |
IsPressComplete() | MoveLookController |
LoadInternalState(_In_ Windows::Foundation::Collections::IPropertySet^state) | MoveLookController | [private]
LookDirection() | MoveLookController |
LookDirection() | MoveLookController |
m_autoFire | MoveLookController | [private]
m_back | MoveLookController | [private]
m_buttonInUse | MoveLookController | [private]
m_buttonLowerRight | MoveLookController | [private]
m_buttonPointerID | MoveLookController | [private]
m_buttonPressed | MoveLookController | [private]
m_buttonUpperLeft | MoveLookController | [private]
m_down | MoveLookController | [private]
m_fireInUse | MoveLookController | [private]
m_fireLastPoint | MoveLookController | [private]
m_fireLowerRight | MoveLookController | [private]
m_firePointerID | MoveLookController | [private]
m_firePressed | MoveLookController | [private]
m_fireUpperLeft | MoveLookController | [private]
m_forward | MoveLookController | [private]
m_isControllerConnected | MoveLookController | [private]
m_left | MoveLookController | [private]
m_lookInUse | MoveLookController | [private]
m_lookLastDelta | MoveLookController | [private]
m_lookLastDelta | MoveLookController | [private]
m_lookLastPoint | MoveLookController | [private]
m_lookLastPoint | MoveLookController | [private]
m_lookPointerID | MoveLookController | [private]
m_mouseInUse | MoveLookController | [private]
m_mouseLastPoint | MoveLookController | [private]
m_mouseLeftInUse | MoveLookController | [private]
m_mouseLookInUse | MoveLookController | [private]
m_mouseLookPointerID | MoveLookController | [private]
m_mousePointerID | MoveLookController | [private]
m_mouseRightInUse | MoveLookController | [private]
m_moveCommand | MoveLookController | [private]
m_moveCommand | MoveLookController | [private]
m_moveFirstDown | MoveLookController | [private]
m_moveFirstDown | MoveLookController | [private]
m_moveInUse | MoveLookController | [private]
m_moveLowerRight | MoveLookController | [private]
m_movePointerID | MoveLookController | [private]
m_movePointerPosition | MoveLookController | [private]
m_movePointerPosition | MoveLookController | [private]
m_moveUpperLeft | MoveLookController | [private]
m_pause | MoveLookController | [private]
m_pausePressed | MoveLookController | [private]
m_pitch | MoveLookController | [private]
m_position | MoveLookController | [private]
m_right | MoveLookController | [private]
m_state | MoveLookController | [private]
m_up | MoveLookController | [private]
m_velocity | MoveLookController | [private]
m_xinputCaps | MoveLookController | [private]
m_xinputStartButtonInUse | MoveLookController | [private]
m_xinputState | MoveLookController | [private]
m_xinputTriggerInUse | MoveLookController | [private]
m_yaw | MoveLookController | [private]
OnKeyDown(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::KeyEventArgs^args) | MoveLookController | [protected]
OnKeyDown(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::KeyEventArgs^args) | MoveLookController | [private]
OnKeyDown(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::KeyEventArgs^args) | MoveLookController | [protected]
OnKeyUp(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::KeyEventArgs^args) | MoveLookController | [protected]
OnKeyUp(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::KeyEventArgs^args) | MoveLookController | [private]
OnKeyUp(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::KeyEventArgs^args) | MoveLookController | [protected]
OnMouseMoved(_In_ Windows::Devices::Input::MouseDevice^mouseDevice, _In_ Windows::Devices::Input::MouseEventArgs^args) | MoveLookController | [protected]
OnMouseMoved(_In_ Windows::Devices::Input::MouseDevice^mouseDevice, _In_ Windows::Devices::Input::MouseEventArgs^args) | MoveLookController | [private]
OnMouseMoved(_In_ Windows::Devices::Input::MouseDevice^mouseDevice, _In_ Windows::Devices::Input::MouseEventArgs^args) | MoveLookController | [protected]
OnPointerExited(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | MoveLookController | [protected]
OnPointerExited(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | MoveLookController | [protected]
OnPointerMoved(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | MoveLookController | [protected]
OnPointerMoved(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | MoveLookController | [private]
OnPointerMoved(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | MoveLookController | [protected]
OnPointerPressed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | MoveLookController | [protected]
OnPointerPressed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | MoveLookController | [protected]
OnPointerReleased(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | MoveLookController | [protected]
OnPointerReleased(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | MoveLookController | [private]
OnPointerReleased(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | MoveLookController | [protected]
Pitch() | MoveLookController |
Pitch(_In_ float pitch) | MoveLookController |
Pitch() | MoveLookController |
Pitch(_In_ float pitch) | MoveLookController |
ResetState() | MoveLookController | [private]
ResetState() | MoveLookController | [private]
SaveInternalState(_In_ Windows::Foundation::Collections::IPropertySet^state) | MoveLookController | [private]
SaveInternalValue(_In_ Windows::Foundation::Collections::IPropertySet^state, _In_ Platform::String^key, _In_ Platform::Object^value) | MoveLookController | [private]
SetFireRect(_In_ DirectX::XMFLOAT2 upperLeft, _In_ DirectX::XMFLOAT2 lowerRight) | MoveLookController |
SetFireRect(_In_ DirectX::XMFLOAT2 upperLeft, _In_ DirectX::XMFLOAT2 lowerRight) | MoveLookController |
SetMoveRect(_In_ DirectX::XMFLOAT2 upperLeft, _In_ DirectX::XMFLOAT2 lowerRight) | MoveLookController |
SetMoveRect(_In_ DirectX::XMFLOAT2 upperLeft, _In_ DirectX::XMFLOAT2 lowerRight) | MoveLookController |
SetOrientation(_In_ float pitch, _In_ float yaw) | MoveLookController | [private]
SetPosition(_In_ float3 pos) | MoveLookController | [private]
Update() | MoveLookController |
Update(Windows::UI::Core::CoreWindow^window) | MoveLookController | [private]
Update() | MoveLookController |
UpdateGameController() | MoveLookController | [private]
UpdateGameController() | MoveLookController | [private]
Velocity() | MoveLookController |
Velocity() | MoveLookController |
WaitForPress(_In_ DirectX::XMFLOAT2 UpperLeft, _In_ DirectX::XMFLOAT2 LowerRight) | MoveLookController |
WaitForPress() | MoveLookController |
WaitForPress(_In_ DirectX::XMFLOAT2 UpperLeft, _In_ DirectX::XMFLOAT2 LowerRight) | MoveLookController |
WaitForPress() | MoveLookController |
Yaw() | MoveLookController |
Yaw(_In_ float yaw) | MoveLookController |
Yaw() | MoveLookController |
Yaw(_In_ float yaw) | MoveLookController |
Generated on Sat Nov 23 2024 16:09:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Folder enumeration/C++/pch.h Source File

  • Folder enumeration

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Audio Session (WASAPI)/C++/WASAPIRenderer.h Source File

  • Windows Audio Session (WASAPI)
  • C++

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         // User Configurable Arguments for Scenario
00037         struct DEVICEPROPS
00038         {
00039             Platform::Boolean       IsHWOffload;
00040             Platform::Boolean       IsTonePlayback;
00041             Platform::Boolean       IsBackground;
00042             REFERENCE_TIME          hnsBufferDuration;
00043             DWORD                   Frequency;
00044             IRandomAccessStream^    ContentStream;
00045         };
00046
00047         // Primary WASAPI Renderering Class
00048         class WASAPIRenderer :
00049             public RuntimeClass< RuntimeClassFlags< ClassicCom >, FtmBase, IActivateAudioInterfaceCompletionHandler >
00050         {
00051         public:
00052             WASAPIRenderer();
00053
00054             HRESULT SetProperties( DEVICEPROPS props );
00055             HRESULT InitializeAudioDeviceAsync();
00056             HRESULT StartPlaybackAsync();
00057             HRESULT StopPlaybackAsync();
00058             HRESULT PausePlaybackAsync();
00059
00060             HRESULT SetVolumeOnSession( UINT32 volume );
00061             DeviceStateChangedEvent^ GetDeviceStateEvent() { return m_DeviceStateChanged; };
00062
00063             METHODASYNCCALLBACK( WASAPIRenderer, StartPlayback, OnStartPlayback );
00064             METHODASYNCCALLBACK( WASAPIRenderer, StopPlayback, OnStopPlayback );
00065             METHODASYNCCALLBACK( WASAPIRenderer, PausePlayback, OnPausePlayback );
00066             METHODASYNCCALLBACK( WASAPIRenderer, SampleReady, OnSampleReady );
00067
00068             // IActivateAudioInterfaceCompletionHandler
00069             STDMETHOD(ActivateCompleted)( IActivateAudioInterfaceAsyncOperation *operation );
00070
00071         private:
00072             ~WASAPIRenderer();
00073
00074             HRESULT OnStartPlayback( IMFAsyncResult* pResult );
00075             HRESULT OnStopPlayback( IMFAsyncResult* pResult );
00076             HRESULT OnPausePlayback( IMFAsyncResult* pResult );
00077             HRESULT OnSampleReady( IMFAsyncResult* pResult );
00078
00079             HRESULT ConfigureDeviceInternal();
00080             HRESULT ValidateBufferValue();
00081             HRESULT OnAudioSampleRequested( Platform::Boolean IsSilence = false );
00082             HRESULT ConfigureSource();
00083             UINT32 GetBufferFramesPerPeriod();
00084
00085             HRESULT GetToneSample( UINT32 FramesAvailable );
00086             HRESULT GetMFSample( UINT32 FramesAvailable );
00087
00088         private:
00089             Platform::String^   m_DeviceIdString;
00090             UINT32              m_BufferFrames;
00091             HANDLE              m_SampleReadyEvent;
00092             MFWORKITEM_KEY      m_SampleReadyKey;
00093             CRITICAL_SECTION    m_CritSec;
00094
00095             WAVEFORMATEX           *m_MixFormat;
00096             IAudioClient2          *m_AudioClient;
00097             IAudioRenderClient     *m_AudioRenderClient;
00098             IMFAsyncResult         *m_SampleReadyAsyncResult;
00099
00100             DeviceStateChangedEvent^       m_DeviceStateChanged;
00101             DEVICEPROPS                    m_DeviceProps;
00102
00103             ToneSampleGenerator    *m_ToneSource;
00104             MFSampleGenerator      *m_MFSource;
00105         };
00106     }
00107 }
00108
Generated on Sat Nov 23 2024 16:08:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/pch.h Source File

  • Direct3D resource loading

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 <d3d11_1.h>
00012 #include <d2d1_1.h>
00013 #include <d2d1effects.h>
00014 #include <dwrite_1.h>
00015 #include <wincodec.h>
00016 #include <agile.h>
00017 #include "BasicMath.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML images/C++/pch.h Source File

  • XAML images

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <string>
00019 #include <collection.h>
00020 #include <ppltasks.h>
00021 #include "Common\LayoutAwarePage.h"
00022 #include "Common\SuspensionManager.h"
00023 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX touch input/C++/DirectXBase.cpp Source File

  • DirectX touch input

DirectXBase.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 "DirectXBase.h"
00010
00011 using namespace Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::Graphics::Display;
00015 using namespace D2D1;
00016
00017 // Constructor.
00018 DirectXBase::DirectXBase() :
00019     m_windowSizeChangeInProgress(false),
00020     m_dpi(-1.0f)
00021 {
00022 }
00023
00024 // Initialize the DirectX resources required to run.
00025 void DirectXBase::Initialize(CoreWindow^ window, float dpi)
00026 {
00027     m_window = window;
00028
00029     CreateDeviceIndependentResources();
00030     CreateDeviceResources();
00031     SetDpi(dpi);
00032 }
00033
00034 // Recreate all device resources and set them back to the current state.
00035 void DirectXBase::HandleDeviceLost()
00036 {
00037     // Reset these member variables to ensure that SetDpi recreates all resources.
00038     float dpi = m_dpi;
00039     m_dpi = -1.0f;
00040     m_windowBounds.Width = 0;
00041     m_windowBounds.Height = 0;
00042     m_swapChain = nullptr;
00043
00044     CreateDeviceResources();
00045     SetDpi(dpi);
00046 }
00047
00048 // These are the resources required independent of the device.
00049 void DirectXBase::CreateDeviceIndependentResources()
00050 {
00051     D2D1_FACTORY_OPTIONS options;
00052     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00053
00054 #if defined(_DEBUG)
00055     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00056     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00057 #endif
00058
00059     DX::ThrowIfFailed(
00060         D2D1CreateFactory(
00061             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00062             __uuidof(ID2D1Factory1),
00063             &options,
00064             &m_d2dFactory
00065             )
00066         );
00067
00068     DX::ThrowIfFailed(
00069         DWriteCreateFactory(
00070             DWRITE_FACTORY_TYPE_SHARED,
00071             __uuidof(IDWriteFactory),
00072             &m_dwriteFactory
00073             )
00074         );
00075
00076     DX::ThrowIfFailed(
00077         CoCreateInstance(
00078             CLSID_WICImagingFactory,
00079             nullptr,
00080             CLSCTX_INPROC_SERVER,
00081             IID_PPV_ARGS(&m_wicFactory)
00082             )
00083         );
00084 }
00085
00086 // These are the resources that depend on the device.
00087 void DirectXBase::CreateDeviceResources()
00088 {
00089     // This flag adds support for surfaces with a different color channel ordering
00090     // than the API default. It is required for compatibility with Direct2D.
00091     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00092     ComPtr<IDXGIDevice> dxgiDevice;
00093
00094 #if defined(_DEBUG)
00095     // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00096     creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00097 #endif
00098
00099     // This array defines the set of DirectX hardware feature levels this app will support.
00100     // Note the ordering should be preserved.
00101     // Don't forget to declare your application's minimum required feature level in its
00102     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00103     D3D_FEATURE_LEVEL featureLevels[] =
00104     {
00105         D3D_FEATURE_LEVEL_11_1,
00106         D3D_FEATURE_LEVEL_11_0,
00107         D3D_FEATURE_LEVEL_10_1,
00108         D3D_FEATURE_LEVEL_10_0,
00109         D3D_FEATURE_LEVEL_9_3,
00110         D3D_FEATURE_LEVEL_9_2,
00111         D3D_FEATURE_LEVEL_9_1
00112     };
00113
00114     // Create the Direct3D 11 API device object and a corresponding context.
00115     ComPtr<ID3D11Device> device;
00116     ComPtr<ID3D11DeviceContext> context;
00117     DX::ThrowIfFailed(
00118         D3D11CreateDevice(
00119             nullptr,                    // Specify nullptr to use the default adapter.
00120             D3D_DRIVER_TYPE_HARDWARE,
00121             0,
00122             creationFlags,              // Set debug and Direct2D compatibility flags.
00123             featureLevels,              // List of feature levels this app can support.
00124             ARRAYSIZE(featureLevels),
00125             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Metro style apps.
00126             &device,                    // Returns the Direct3D device created.
00127             &m_featureLevel,            // Returns feature level of device created.
00128             &context                    // Returns the device immediate context.
00129             )
00130         );
00131
00132     // Get the Direct3D 11.1 API device and context interfaces.
00133     DX::ThrowIfFailed(
00134         device.As(&m_d3dDevice)
00135         );
00136
00137     DX::ThrowIfFailed(
00138         context.As(&m_d3dContext)
00139         );
00140
00141     // Get the underlying DXGI device of the Direct3D device.
00142     DX::ThrowIfFailed(
00143         m_d3dDevice.As(&dxgiDevice)
00144         );
00145
00146     // Create the Direct2D device object and a corresponding context.
00147     DX::ThrowIfFailed(
00148         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00149         );
00150
00151     DX::ThrowIfFailed(
00152         m_d2dDevice->CreateDeviceContext(
00153             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00154             &m_d2dContext
00155             )
00156         );
00157 }
00158
00159 // Helps track the DPI in the helper class.
00160 // This is called in the dpiChanged event handler in the view class.
00161 void DirectXBase::SetDpi(float dpi)
00162 {
00163     if (dpi != m_dpi)
00164     {
00165         // Save the DPI of this display in our class.
00166         m_dpi = dpi;
00167
00168         // Update Direct2D's stored DPI.
00169         m_d2dContext->SetDpi(m_dpi, m_dpi);
00170
00171         // Often a DPI change implies a window size change. In some cases Windows will issue
00172         // both a size changed event and a DPI changed event. In this case, the resulting bounds
00173         // will not change, and the window resize code will only be executed once.
00174         UpdateForWindowSizeChange();
00175     }
00176 }
00177
00178 // This routine is called in the event handler for the view SizeChanged event.
00179 void DirectXBase::UpdateForWindowSizeChange()
00180 {
00181     // Only handle window size changed if there is no pending DPI change.
00182     if (m_dpi != DisplayProperties::LogicalDpi)
00183     {
00184         return;
00185     }
00186
00187     if (m_window->Bounds.Width  != m_windowBounds.Width ||
00188         m_window->Bounds.Height != m_windowBounds.Height)
00189     {
00190         m_d2dContext->SetTarget(nullptr);
00191         m_d2dTargetBitmap = nullptr;
00192         m_d3dRenderTargetView = nullptr;
00193         m_d3dDepthStencilView = nullptr;
00194         m_windowSizeChangeInProgress = true;
00195         CreateWindowSizeDependentResources();
00196     }
00197 }
00198
00199 // Allocate all memory resources that change on a window SizeChanged event.
00200 void DirectXBase::CreateWindowSizeDependentResources()
00201 {
00202     // Store the window bounds so the next time we get a SizeChanged event we can
00203     // avoid rebuilding everything if the size is identical.
00204     m_windowBounds = m_window->Bounds;
00205
00206     if (m_swapChain != nullptr)
00207     {
00208         // If the swap chain already exists, resize it.
00209         HRESULT hr = m_swapChain->ResizeBuffers(2, 0, 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0);
00210
00211         if (hr == DXGI_ERROR_DEVICE_REMOVED)
00212         {
00213             // If the device was removed for any reason, a new device and swapchain will need to be created.
00214             HandleDeviceLost();
00215
00216             // Everything is set up now. Do not continue execution of this method.
00217             return;
00218         }
00219         else
00220         {
00221             DX::ThrowIfFailed(hr);
00222         }
00223     }
00224     else
00225     {
00226         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00227         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00228         swapChainDesc.Width = 0;                                     // Use automatic sizing.
00229         swapChainDesc.Height = 0;
00230         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;           // This is the most common swap chain format.
00231         swapChainDesc.Stereo = false;
00232         swapChainDesc.SampleDesc.Count = 1;                          // Don't use multi-sampling.
00233         swapChainDesc.SampleDesc.Quality = 0;
00234         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00235         swapChainDesc.BufferCount = 2;                               // Use double-buffering to minimize latency.
00236         swapChainDesc.Scaling = DXGI_SCALING_NONE;
00237         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Metro style apps must use this SwapEffect.
00238         swapChainDesc.Flags = 0;
00239
00240         ComPtr<IDXGIDevice1> dxgiDevice;
00241         DX::ThrowIfFailed(
00242             m_d3dDevice.As(&dxgiDevice)
00243             );
00244
00245         ComPtr<IDXGIAdapter> dxgiAdapter;
00246         DX::ThrowIfFailed(
00247             dxgiDevice->GetAdapter(&dxgiAdapter)
00248             );
00249
00250         ComPtr<IDXGIFactory2> dxgiFactory;
00251         DX::ThrowIfFailed(
00252             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00253             );
00254
00255         CoreWindow^ window = m_window.Get();
00256         DX::ThrowIfFailed(
00257             dxgiFactory->CreateSwapChainForCoreWindow(
00258                 m_d3dDevice.Get(),
00259                 reinterpret_cast<IUnknown*>(window),
00260                 &swapChainDesc,
00261                 nullptr,
00262                 &m_swapChain
00263                 )
00264             );
00265
00266         // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
00267         // ensures that the application will only render after each VSync, minimizing power consumption.
00268         DX::ThrowIfFailed(
00269             dxgiDevice->SetMaximumFrameLatency(1)
00270             );
00271     }
00272
00273     // Create a Direct3D render target view of the swap chain back buffer.
00274     ComPtr<ID3D11Texture2D> backBuffer;
00275     DX::ThrowIfFailed(
00276         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00277         );
00278
00279     DX::ThrowIfFailed(
00280         m_d3dDevice->CreateRenderTargetView(
00281             backBuffer.Get(),
00282             nullptr,
00283             &m_d3dRenderTargetView
00284             )
00285         );
00286
00287     // Cache the rendertarget dimensions in our helper class for convenient use.
00288     D3D11_TEXTURE2D_DESC backBufferDesc = {0};
00289     backBuffer->GetDesc(&backBufferDesc);
00290     m_renderTargetSize.Width  = static_cast<float>(backBufferDesc.Width);
00291     m_renderTargetSize.Height = static_cast<float>(backBufferDesc.Height);
00292
00293     // Create a depth stencil view for use with 3D rendering if needed.
00294     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00295         DXGI_FORMAT_D24_UNORM_S8_UINT,
00296         backBufferDesc.Width,
00297         backBufferDesc.Height,
00298         1,
00299         1,
00300         D3D11_BIND_DEPTH_STENCIL
00301         );
00302
00303     ComPtr<ID3D11Texture2D> depthStencil;
00304     DX::ThrowIfFailed(
00305         m_d3dDevice->CreateTexture2D(
00306             &depthStencilDesc,
00307             nullptr,
00308             &depthStencil
00309             )
00310         );
00311
00312     auto viewDesc = CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D);
00313     DX::ThrowIfFailed(
00314         m_d3dDevice->CreateDepthStencilView(
00315             depthStencil.Get(),
00316             &viewDesc,
00317             &m_d3dDepthStencilView
00318             )
00319         );
00320
00321     // Set the 3D rendering viewport to target the entire window.
00322     CD3D11_VIEWPORT viewport(
00323         0.0f,
00324         0.0f,
00325         static_cast<float>(backBufferDesc.Width),
00326         static_cast<float>(backBufferDesc.Height)
00327         );
00328
00329     m_d3dContext->RSSetViewports(1, &viewport);
00330
00331     // Create a Direct2D target bitmap associated with the
00332     // swap chain back buffer and set it as the current target.
00333     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00334         BitmapProperties1(
00335             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00336             PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00337             m_dpi,
00338             m_dpi
00339             );
00340
00341     ComPtr<IDXGISurface> dxgiBackBuffer;
00342     DX::ThrowIfFailed(
00343         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00344         );
00345
00346     DX::ThrowIfFailed(
00347         m_d2dContext->CreateBitmapFromDxgiSurface(
00348             dxgiBackBuffer.Get(),
00349             &bitmapProperties,
00350             &m_d2dTargetBitmap
00351             )
00352         );
00353
00354     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00355
00356     // Grayscale text anti-aliasing is recommended for all Metro style apps.
00357     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00358 }
00359
00360 // Method to deliver the final image to the display.
00361 void DirectXBase::Present()
00362 {
00363     // The application may optionally specify "dirty" or "scroll" rects to improve efficiency
00364     // in certain scenarios.  In this sample, however, we do not utilize those features.
00365     DXGI_PRESENT_PARAMETERS parameters = {0};
00366     parameters.DirtyRectsCount = 0;
00367     parameters.pDirtyRects = nullptr;
00368     parameters.pScrollRect = nullptr;
00369     parameters.pScrollOffset = nullptr;
00370
00371     // The first argument instructs DXGI to block until VSync, putting the application
00372     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00373     // frames that will never be displayed to the screen.
00374     HRESULT hr = m_swapChain->Present1(1, 0, &parameters);
00375
00376     // Discard the contents of the render target.
00377     // This is a valid operation only when the existing contents will be entirely
00378     // overwritten. If dirty or scroll rects are used, this call should be removed.
00379     m_d3dContext->DiscardView(m_d3dRenderTargetView.Get());
00380
00381     // Discard the contents of the depth stencil.
00382     m_d3dContext->DiscardView(m_d3dDepthStencilView.Get());
00383
00384     // If the device was removed either by a disconnect or a driver upgrade, we
00385     // must recreate all device resources.
00386     if (hr == DXGI_ERROR_DEVICE_REMOVED)
00387     {
00388         HandleDeviceLost();
00389     }
00390     else
00391     {
00392         DX::ThrowIfFailed(hr);
00393     }
00394
00395     if (m_windowSizeChangeInProgress)
00396     {
00397         // A window size change has been initiated and the app has just completed presenting
00398         // the first frame with the new size. Notify the resize manager so we can short
00399         // circuit any resize animation and prevent unnecessary delays.
00400         CoreWindowResizeManager::GetForCurrentView()->NotifyLayoutCompleted();
00401         m_windowSizeChangeInProgress = false;
00402     }
00403 }
00404
00405 void DirectXBase::ValidateDevice()
00406 {
00407     // The D3D Device is no longer valid if the default adapter changes or if
00408     // the device has been removed.
00409
00410     // First, get the information for the adapter related to the current device.
00411
00412     ComPtr<IDXGIDevice1> dxgiDevice;
00413     ComPtr<IDXGIAdapter> deviceAdapter;
00414     DXGI_ADAPTER_DESC deviceDesc;
00415     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00416     DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter));
00417     DX::ThrowIfFailed(deviceAdapter->GetDesc(&deviceDesc));
00418
00419     // Next, get the information for the default adapter.
00420
00421     ComPtr<IDXGIFactory2> dxgiFactory;
00422     ComPtr<IDXGIAdapter1> currentAdapter;
00423     DXGI_ADAPTER_DESC currentDesc;
00424     DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)));
00425     DX::ThrowIfFailed(dxgiFactory->EnumAdapters1(0, &currentAdapter));
00426     DX::ThrowIfFailed(currentAdapter->GetDesc(&currentDesc));
00427
00428     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00429     // a new D3D device must be created.
00430
00431     if ((deviceDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart) ||
00432         (deviceDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart) ||
00433         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00434     {
00435         // Release references to resources related to the old device.
00436         dxgiDevice = nullptr;
00437         deviceAdapter = nullptr;
00438
00439         // Create a new device and swap chain.
00440         HandleDeviceLost();
00441     }
00442 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Message dialog/C++/CancelCommand.xaml.cpp Source File

  • Message dialog

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 SDKSample::MessageDialogSample;
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 SDKSample::MessageDialogSample::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 Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D tutorial/C++/Lesson5.Components/DirectXBase.cpp Source File

  • Direct3D tutorial
  • Lesson5.Components

DirectXBase.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 "DirectXBase.h"
00010
00011 using namespace Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::Graphics::Display;
00015 using namespace D2D1;
00016
00017 // Constructor.
00018 DirectXBase::DirectXBase() :
00019     m_windowSizeChangeInProgress(false),
00020     m_dpi(-1.0f)
00021 {
00022 }
00023
00024 // Initialize the DirectX resources required to run.
00025 void DirectXBase::Initialize(CoreWindow^ window, float dpi)
00026 {
00027     m_window = window;
00028
00029     CreateDeviceIndependentResources();
00030     CreateDeviceResources();
00031     SetDpi(dpi);
00032 }
00033
00034 // Recreate all device resources and set them back to the current state.
00035 void DirectXBase::HandleDeviceLost()
00036 {
00037     // Reset these member variables to ensure that SetDpi recreates all resources.
00038     float dpi = m_dpi;
00039     m_dpi = -1.0f;
00040     m_windowBounds.Width = 0;
00041     m_windowBounds.Height = 0;
00042     m_swapChain = nullptr;
00043
00044     CreateDeviceResources();
00045     SetDpi(dpi);
00046 }
00047
00048 // These are the resources required independent of the device.
00049 void DirectXBase::CreateDeviceIndependentResources()
00050 {
00051     D2D1_FACTORY_OPTIONS options;
00052     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00053
00054 #if defined(_DEBUG)
00055     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00056     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00057 #endif
00058
00059     DX::ThrowIfFailed(
00060         D2D1CreateFactory(
00061             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00062             __uuidof(ID2D1Factory1),
00063             &options,
00064             &m_d2dFactory
00065             )
00066         );
00067
00068     DX::ThrowIfFailed(
00069         DWriteCreateFactory(
00070             DWRITE_FACTORY_TYPE_SHARED,
00071             __uuidof(IDWriteFactory),
00072             &m_dwriteFactory
00073             )
00074         );
00075
00076     DX::ThrowIfFailed(
00077         CoCreateInstance(
00078             CLSID_WICImagingFactory,
00079             nullptr,
00080             CLSCTX_INPROC_SERVER,
00081             IID_PPV_ARGS(&m_wicFactory)
00082             )
00083         );
00084 }
00085
00086 // These are the resources that depend on the device.
00087 void DirectXBase::CreateDeviceResources()
00088 {
00089     // This flag adds support for surfaces with a different color channel ordering
00090     // than the API default. It is required for compatibility with Direct2D.
00091     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00092     ComPtr<IDXGIDevice> dxgiDevice;
00093
00094 #if defined(_DEBUG)
00095     // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00096     creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00097 #endif
00098
00099     // This array defines the set of DirectX hardware feature levels this app will support.
00100     // Note the ordering should be preserved.
00101     // Don't forget to declare your application's minimum required feature level in its
00102     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00103     D3D_FEATURE_LEVEL featureLevels[] =
00104     {
00105         D3D_FEATURE_LEVEL_11_1,
00106         D3D_FEATURE_LEVEL_11_0,
00107         D3D_FEATURE_LEVEL_10_1,
00108         D3D_FEATURE_LEVEL_10_0,
00109         D3D_FEATURE_LEVEL_9_3,
00110         D3D_FEATURE_LEVEL_9_2,
00111         D3D_FEATURE_LEVEL_9_1
00112     };
00113
00114     // Create the Direct3D 11 API device object and a corresponding context.
00115     ComPtr<ID3D11Device> device;
00116     ComPtr<ID3D11DeviceContext> context;
00117     DX::ThrowIfFailed(
00118         D3D11CreateDevice(
00119             nullptr,                    // Specify nullptr to use the default adapter.
00120             D3D_DRIVER_TYPE_HARDWARE,
00121             0,
00122             creationFlags,              // Set debug and Direct2D compatibility flags.
00123             featureLevels,              // List of feature levels this app can support.
00124             ARRAYSIZE(featureLevels),
00125             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Store apps.
00126             &device,                    // Returns the Direct3D device created.
00127             &m_featureLevel,            // Returns feature level of device created.
00128             &context                    // Returns the device immediate context.
00129             )
00130         );
00131
00132     // Get the Direct3D 11.1 API device and context interfaces.
00133     DX::ThrowIfFailed(
00134         device.As(&m_d3dDevice)
00135         );
00136
00137     DX::ThrowIfFailed(
00138         context.As(&m_d3dContext)
00139         );
00140
00141     // Get the underlying DXGI device of the Direct3D device.
00142     DX::ThrowIfFailed(
00143         m_d3dDevice.As(&dxgiDevice)
00144         );
00145
00146     // Create the Direct2D device object and a corresponding context.
00147     DX::ThrowIfFailed(
00148         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00149         );
00150
00151     DX::ThrowIfFailed(
00152         m_d2dDevice->CreateDeviceContext(
00153             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00154             &m_d2dContext
00155             )
00156         );
00157 }
00158
00159 // Helps track the DPI in the helper class.
00160 // This is called in the dpiChanged event handler in the view class.
00161 void DirectXBase::SetDpi(float dpi)
00162 {
00163     if (dpi != m_dpi)
00164     {
00165         // Save the DPI of this display in our class.
00166         m_dpi = dpi;
00167
00168         // Update Direct2D's stored DPI.
00169         m_d2dContext->SetDpi(m_dpi, m_dpi);
00170
00171         // Often a DPI change implies a window size change. In some cases Windows will issue
00172         // both a size changed event and a DPI changed event. In this case, the resulting bounds
00173         // will not change, and the window resize code will only be executed once.
00174         UpdateForWindowSizeChange();
00175     }
00176 }
00177
00178 // This routine is called in the event handler for the view SizeChanged event.
00179 void DirectXBase::UpdateForWindowSizeChange()
00180 {
00181     // Only handle window size changed if there is no pending DPI change.
00182     if (m_dpi != DisplayProperties::LogicalDpi)
00183     {
00184         return;
00185     }
00186
00187     if (m_window->Bounds.Width  != m_windowBounds.Width ||
00188         m_window->Bounds.Height != m_windowBounds.Height)
00189     {
00190         m_d2dContext->SetTarget(nullptr);
00191         m_d2dTargetBitmap = nullptr;
00192         m_d3dRenderTargetView = nullptr;
00193         m_d3dDepthStencilView = nullptr;
00194         m_windowSizeChangeInProgress = true;
00195         CreateWindowSizeDependentResources();
00196     }
00197 }
00198
00199 // Allocate all memory resources that change on a window SizeChanged event.
00200 void DirectXBase::CreateWindowSizeDependentResources()
00201 {
00202     // Store the window bounds so the next time we get a SizeChanged event we can
00203     // avoid rebuilding everything if the size is identical.
00204     m_windowBounds = m_window->Bounds;
00205
00206     if (m_swapChain != nullptr)
00207     {
00208         // If the swap chain already exists, resize it.
00209         HRESULT hr = m_swapChain->ResizeBuffers(2, 0, 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0);
00210
00211         if (hr == DXGI_ERROR_DEVICE_REMOVED)
00212         {
00213             // If the device was removed for any reason, a new device and swapchain will need to be created.
00214             HandleDeviceLost();
00215
00216             // Everything is set up now. Do not continue execution of this method.
00217             return;
00218         }
00219         else
00220         {
00221             DX::ThrowIfFailed(hr);
00222         }
00223     }
00224     else
00225     {
00226         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00227         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00228         swapChainDesc.Width = 0;                                     // Use automatic sizing.
00229         swapChainDesc.Height = 0;
00230         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;           // This is the most common swap chain format.
00231         swapChainDesc.Stereo = false;
00232         swapChainDesc.SampleDesc.Count = 1;                          // Don't use multi-sampling.
00233         swapChainDesc.SampleDesc.Quality = 0;
00234         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00235         swapChainDesc.BufferCount = 2;                               // Use double-buffering to minimize latency.
00236         swapChainDesc.Scaling = DXGI_SCALING_NONE;
00237         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Windows Store apps must use this SwapEffect.
00238         swapChainDesc.Flags = 0;
00239
00240         ComPtr<IDXGIDevice1> dxgiDevice;
00241         DX::ThrowIfFailed(
00242             m_d3dDevice.As(&dxgiDevice)
00243             );
00244
00245         ComPtr<IDXGIAdapter> dxgiAdapter;
00246         DX::ThrowIfFailed(
00247             dxgiDevice->GetAdapter(&dxgiAdapter)
00248             );
00249
00250         ComPtr<IDXGIFactory2> dxgiFactory;
00251         DX::ThrowIfFailed(
00252             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00253             );
00254
00255         CoreWindow^ window = m_window.Get();
00256         DX::ThrowIfFailed(
00257             dxgiFactory->CreateSwapChainForCoreWindow(
00258                 m_d3dDevice.Get(),
00259                 reinterpret_cast<IUnknown*>(window),
00260                 &swapChainDesc,
00261                 nullptr,
00262                 &m_swapChain
00263                 )
00264             );
00265
00266         // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
00267         // ensures that the application will only render after each VSync, minimizing power consumption.
00268         DX::ThrowIfFailed(
00269             dxgiDevice->SetMaximumFrameLatency(1)
00270             );
00271     }
00272
00273     // Create a Direct3D render target view of the swap chain back buffer.
00274     ComPtr<ID3D11Texture2D> backBuffer;
00275     DX::ThrowIfFailed(
00276         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00277         );
00278
00279     DX::ThrowIfFailed(
00280         m_d3dDevice->CreateRenderTargetView(
00281             backBuffer.Get(),
00282             nullptr,
00283             &m_d3dRenderTargetView
00284             )
00285         );
00286
00287     // Cache the rendertarget dimensions in our helper class for convenient use.
00288     D3D11_TEXTURE2D_DESC backBufferDesc = {0};
00289     backBuffer->GetDesc(&backBufferDesc);
00290     m_renderTargetSize.Width  = static_cast<float>(backBufferDesc.Width);
00291     m_renderTargetSize.Height = static_cast<float>(backBufferDesc.Height);
00292
00293     // Create a depth stencil view for use with 3D rendering if needed.
00294     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00295         DXGI_FORMAT_D24_UNORM_S8_UINT,
00296         backBufferDesc.Width,
00297         backBufferDesc.Height,
00298         1,
00299         1,
00300         D3D11_BIND_DEPTH_STENCIL
00301         );
00302
00303     ComPtr<ID3D11Texture2D> depthStencil;
00304     DX::ThrowIfFailed(
00305         m_d3dDevice->CreateTexture2D(
00306             &depthStencilDesc,
00307             nullptr,
00308             &depthStencil
00309             )
00310         );
00311
00312     auto viewDesc = CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D);
00313     DX::ThrowIfFailed(
00314         m_d3dDevice->CreateDepthStencilView(
00315             depthStencil.Get(),
00316             &viewDesc,
00317             &m_d3dDepthStencilView
00318             )
00319         );
00320
00321     // Set the 3D rendering viewport to target the entire window.
00322     CD3D11_VIEWPORT viewport(
00323         0.0f,
00324         0.0f,
00325         static_cast<float>(backBufferDesc.Width),
00326         static_cast<float>(backBufferDesc.Height)
00327         );
00328
00329     m_d3dContext->RSSetViewports(1, &viewport);
00330
00331     // Create a Direct2D target bitmap associated with the
00332     // swap chain back buffer and set it as the current target.
00333     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00334         BitmapProperties1(
00335             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00336             PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00337             m_dpi,
00338             m_dpi
00339             );
00340
00341     ComPtr<IDXGISurface> dxgiBackBuffer;
00342     DX::ThrowIfFailed(
00343         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00344         );
00345
00346     DX::ThrowIfFailed(
00347         m_d2dContext->CreateBitmapFromDxgiSurface(
00348             dxgiBackBuffer.Get(),
00349             &bitmapProperties,
00350             &m_d2dTargetBitmap
00351             )
00352         );
00353
00354     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00355
00356     // Grayscale text anti-aliasing is recommended for all Windows Store apps.
00357     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00358 }
00359
00360 // Method to deliver the final image to the display.
00361 void DirectXBase::Present()
00362 {
00363     // The application may optionally specify "dirty" or "scroll" rects to improve efficiency
00364     // in certain scenarios.  In this sample, however, we do not utilize those features.
00365     DXGI_PRESENT_PARAMETERS parameters = {0};
00366     parameters.DirtyRectsCount = 0;
00367     parameters.pDirtyRects = nullptr;
00368     parameters.pScrollRect = nullptr;
00369     parameters.pScrollOffset = nullptr;
00370
00371     // The first argument instructs DXGI to block until VSync, putting the application
00372     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00373     // frames that will never be displayed to the screen.
00374     HRESULT hr = m_swapChain->Present1(1, 0, &parameters);
00375
00376     // Discard the contents of the render target.
00377     // This is a valid operation only when the existing contents will be entirely
00378     // overwritten. If dirty or scroll rects are used, this call should be removed.
00379     m_d3dContext->DiscardView(m_d3dRenderTargetView.Get());
00380
00381     // Discard the contents of the depth stencil.
00382     m_d3dContext->DiscardView(m_d3dDepthStencilView.Get());
00383
00384     // If the device was removed either by a disconnect or a driver upgrade, we
00385     // must recreate all device resources.
00386     if (hr == DXGI_ERROR_DEVICE_REMOVED)
00387     {
00388         HandleDeviceLost();
00389     }
00390     else
00391     {
00392         DX::ThrowIfFailed(hr);
00393     }
00394
00395     if (m_windowSizeChangeInProgress)
00396     {
00397         // A window size change has been initiated and the app has just completed presenting
00398         // the first frame with the new size. Notify the resize manager so we can short
00399         // circuit any resize animation and prevent unnecessary delays.
00400         CoreWindowResizeManager::GetForCurrentView()->NotifyLayoutCompleted();
00401         m_windowSizeChangeInProgress = false;
00402     }
00403 }
00404
00405 void DirectXBase::ValidateDevice()
00406 {
00407     // The D3D Device is no longer valid if the default adapter changes or if
00408     // the device has been removed.
00409
00410     // First, get the information for the adapter related to the current device.
00411
00412     ComPtr<IDXGIDevice1> dxgiDevice;
00413     ComPtr<IDXGIAdapter> deviceAdapter;
00414     DXGI_ADAPTER_DESC deviceDesc;
00415     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00416     DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter));
00417     DX::ThrowIfFailed(deviceAdapter->GetDesc(&deviceDesc));
00418
00419     // Next, get the information for the default adapter.
00420
00421     ComPtr<IDXGIFactory2> dxgiFactory;
00422     ComPtr<IDXGIAdapter1> currentAdapter;
00423     DXGI_ADAPTER_DESC currentDesc;
00424     DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)));
00425     DX::ThrowIfFailed(dxgiFactory->EnumAdapters1(0, &currentAdapter));
00426     DX::ThrowIfFailed(currentAdapter->GetDesc(&currentDesc));
00427
00428     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00429     // a new D3D device must be created.
00430
00431     if ((deviceDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart) ||
00432         (deviceDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart) ||
00433         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00434     {
00435         // Release references to resources related to the old device.
00436         dxgiDevice = nullptr;
00437         deviceAdapter = nullptr;
00438
00439         // Create a new device and swap chain.
00440         HandleDeviceLost();
00441     }
00442 }
Generated on Sat Nov 23 2024 16:08:02 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Print/C++/ScenarioInput6.xaml.h Source File

  • Print

ScenarioInput6.xaml.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 //
00009 // ScenarioInput6.xaml.h
00010 // Declaration of the ScenarioInput6 class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioInput6.g.h"
00017 #include "MainPage.xaml.h"
00018
00019
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Printing;
00022
00023 namespace PrintSample
00024 {
00025     /// <summary>
00026     /// Photo size options
00027     /// </summary>
00028     enum PhotoSize : byte
00029     {
00030         psFullPage,
00031         ps4x6,
00032         ps5x7,
00033         ps8x10
00034     };
00035
00036     /// <summary>
00037     /// Photo scaling options
00038     /// </summary>
00039     enum Scaling : byte
00040     {
00041         sShrinkToFit,
00042         sCrop
00043     };
00044
00045     /// <summary>
00046     /// Printable page description
00047     /// </summary>
00048     public value class PageDescription
00049     {
00050     public:
00051         Size    Margin;
00052         Size    PageSize;
00053         Size    ViewablePageSize;
00054         Size    PictureViewSize;
00055         bool    IsContentCropped;
00056
00057         friend bool operator == (PageDescription pageDescriptiopn1, PageDescription pageDescription2)
00058         {
00059             // Detect if PageSize changed
00060             bool equal = (std::abs(pageDescriptiopn1.PageSize.Width - pageDescription2.PageSize.Width) < FLT_EPSILON) &&
00061                          (std::abs(pageDescriptiopn1.PageSize.Height - pageDescription2.PageSize.Height) < FLT_EPSILON);
00062
00063             // Detect if ViewablePageSize changed
00064             if (equal)
00065             {
00066                 equal = (std::abs(pageDescriptiopn1.ViewablePageSize.Width - pageDescription2.ViewablePageSize.Width) < FLT_EPSILON) &&
00067                         (std::abs(pageDescriptiopn1.ViewablePageSize.Height - pageDescription2.ViewablePageSize.Height) < FLT_EPSILON);
00068             }
00069
00070             // Detect if PictureViewSize changed
00071             if (equal)
00072             {
00073                 equal = (std::abs(pageDescriptiopn1.PictureViewSize.Width - pageDescription2.PictureViewSize.Width) < FLT_EPSILON) &&
00074                         (std::abs(pageDescriptiopn1.PictureViewSize.Height - pageDescription2.PictureViewSize.Height) < FLT_EPSILON);
00075             }
00076
00077             // Detect if cropping changed
00078             if (equal)
00079             {
00080                 equal = pageDescriptiopn1.IsContentCropped == pageDescription2.IsContentCropped;
00081             }
00082
00083             return equal;
00084         }
00085
00086         friend bool operator != (PageDescription pageDescriptiopn1, PageDescription pageDescription2)
00087         {
00088             return !(pageDescriptiopn1 == pageDescription2);
00089         }
00090     };
00091
00092     /// <summary>
00093     /// Photo printing scenario
00094     /// </summary>
00095     [Windows::Foundation::Metadata::WebHostHidden]
00096     public ref class ScenarioInput6 sealed
00097     {
00098     public:
00099         ScenarioInput6();
00100
00101     private:
00102
00103         // Scenario specific constants.
00104
00105         /// <summary>
00106         /// The app's number of photos.
00107         /// </summary>
00108         static const int NumberOfPhotos = 9;
00109
00110         /// <summary>
00111         /// Constant for 96 DPI
00112         /// </summary>
00113         static const int DPI96 = 96;
00114
00115         /// <summary>
00116         /// A map of UIElements used to store the print preview pages.
00117         /// </summary>
00118         std::map<int,UIElement^>                            m_pageCollection;
00119
00120         /// <summary>
00121         /// Synchronization object used to secure access to the page collection and the visual root(printingRoot).
00122         /// </summary>
00123         concurrency::critical_section                       m_csPrintSync;
00124
00125         /// <summary>
00126         /// Current size settings for the image.
00127         /// </summary>
00128         PhotoSize                                           m_photoSize;
00129
00130         /// <summary>
00131         /// Current scale settings for the image.
00132         /// </summary>
00133         Scaling                                             m_photoScale;
00134
00135         /// <summary>
00136         /// The current printer's page description used to create the content (size, margins, printable area).
00137         /// </summary>
00138         PageDescription                                     m_currentPageDescription;
00139
00140         /// <summary>
00141         /// A request "number" used to describe a Paginate - GetPreviewPage session.
00142         /// It is used by GetPreviewPage to determine, before calling SetPreviewPage, if the page content is out of date.
00143         /// Flow:
00144         /// Paginate will increment the request count and all subsequent GetPreviewPage calls will store a local copy and verify it before calling SetPreviewPage.
00145         /// If another Paginate event is triggered while some GetPreviewPage workers are still executing asynchronously
00146         /// their results will be discarded(ignored) because their request number is expired (the photo page description changed).
00147         /// </summary>
00148         LONGLONG                                            m_requestCount;
00149
00150     protected:
00151
00152         /// <summary>
00153         /// Option change event handler
00154         /// </summary>
00155         /// <param name="sender">The print task option details for which an option changed.</param>
00156         /// <param name="args">The event arguments containing the id of the option changed.</param>
00157         void PrintDetailedOptionsOptionChanged(Windows::Graphics::Printing::OptionDetails::PrintTaskOptionDetails^ sender,
00158                                                Windows::Graphics::Printing::OptionDetails::PrintTaskOptionChangedEventArgs^ args);
00159
00160         /// <summary>
00161         /// This is the event handler for PrintManager.PrintTaskRequested.
00162         /// In order to ensure a good user experience, the system requires that the app handle the PrintTaskRequested event within the time specified
00163         /// by PrintTaskRequestedEventArgs->Request->Deadline.
00164         /// Therefore, we use this handler to only create the print task.
00165         /// The print settings customization can be done when the print document source is requested.
00166         /// </summary>
00167         /// <param name="sender">The print manager for which a print task request was made.</param>
00168         /// <param name="e">The print taks request associated arguments.</param>
00169         virtual void PrintTaskRequested(Windows::Graphics::Printing::PrintManager^ sender, Windows::Graphics::Printing::PrintTaskRequestedEventArgs^ e) override;
00170
00171         /// <summary>
00172         /// Helper function used to triger a preview refresh
00173         /// </summary>
00174         void RefreshPreview();
00175
00176         /// <summary>
00177         /// This is the event handler for Pagination.
00178         /// </summary>
00179         /// <param name="sender">The document for which pagination occurs.</param>
00180         /// <param name="e">The pagination event arguments containing the print options.</param>
00181         virtual void CreatePrintPreviewPages(Object^ sender, PaginateEventArgs^ e) override;
00182
00183         /// <summary>
00184         /// This is the event handler for PrintDocument.GetPrintPreviewPage. It provides a specific print preview page,
00185         /// in the form of an UIElement, to an instance of PrintDocument.
00186         /// PrintDocument subsequently converts the UIElement into a page that the Windows print system can deal with.
00187         /// </summary>
00188         /// <param name="sender">The print document.</param>
00189         /// <param name="e">Arguments containing the preview requested page.</param>
00190         virtual void GetPrintPreviewPage(Object^ sender, GetPreviewPageEventArgs^ e) override;
00191
00192         /// <summary>
00193         /// This is the event handler for PrintDocument.AddPages. It provides all pages to be printed, in the form of
00194         /// UIElements, to an instance of PrintDocument. PrintDocument subsequently converts the UIElements
00195         /// into a pages that the Windows print system can deal with.
00196         /// </summary>
00197         /// <param name="sender">The print document.</param>
00198         /// <param name="e">Add page event arguments containing a print task options reference</param>
00199         virtual void AddPrintPages(Object^ sender, AddPagesEventArgs^ e) override;
00200
00201         /// <summary>
00202         /// Helper function that clears the page collection and also the pages attached to the "visual root".
00203         /// </summary>
00204         void ClearPageCollection();
00205
00206 private:
00207         /// <summary>
00208         /// Generic swap of 2 values
00209         /// </summary>
00210         /// <typeparam name="T">typename</typeparam>
00211         /// <param name="v1">Value 1</param>
00212         /// <param name="v2">Value 2</param>
00213         template<class T> static void Swap(T& v1, T& v2);
00214
00215         /// <summary>
00216         /// Generates a page containing a photo.
00217         /// The image will be rotated if detected that there is a gain from that regarding size (try to maximize photo size).
00218         /// </summary>
00219         /// <param name="photoNumber">The photo number.</param>
00220         /// <param name="pageDescription">The description of the printer page.</param>
00221         /// <returns>A task that will produce the page.</returns>
00222         concurrency::task<UIElement^> ScenarioInput6::GeneratePage(int photoNumber, PageDescription pageDescription);
00223
00224         /// <summary>
00225         /// Loads an image from an uri source and performs a rotation based on the print target aspect.
00226         /// </summary>
00227         /// <param name="source">The location of the image.</param>
00228         /// <param name="landscape">A flag that indicates if the target(printer page) is in landscape mode.</param>
00229         concurrency::task<Windows::UI::Xaml::Media::Imaging::WriteableBitmap^> LoadBitmap(Windows::Foundation::Uri^ source, bool landscape);
00230
00231     public:
00232         virtual void OnNavigatedTo(NavigationEventArgs^ e) override;
00233         virtual void OnNavigatedFrom(NavigationEventArgs^ e) override;
00234     };
00235 }
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML images/C++/Scenario3.xaml.cpp Source File

  • XAML images

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 SDKSample::Images;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 Scenario3::Scenario3()
00026 {
00027     InitializeComponent();
00028 }
00029
00030 // Invoked when this page is about to be displayed in a Frame.
00031 void Scenario3::OnNavigatedTo(NavigationEventArgs^ e)
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     rootPage = MainPage::Current;
00036 }
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Real-time communication/C#,C++/App.xaml.cs Source File

  • Real-time communication
  • C#,C++

App.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.ApplicationModel;
00012 using Windows.ApplicationModel.Activation;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Navigation;
00016 using SDKTemplate;
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// Provides application-specific behavior to supplement the default Application class.
00022     /// </summary>
00023     sealed partial class App : Application
00024     {
00025         public LaunchActivatedEventArgs LaunchArgs;
00026
00027         /// <summary>
00028         /// Initializes the singleton application object.  This is the first line of authored code
00029         /// executed, and as such is the logical equivalent of main() or WinMain().
00030         /// </summary>
00031         public App()
00032         {
00033             this.InitializeComponent();
00034             this.Suspending += new SuspendingEventHandler(OnSuspending);
00035         }
00036
00037         async void OnSuspending(object sender, SuspendingEventArgs args)
00038         {
00039             SuspendingDeferral deferral = args.SuspendingOperation.GetDeferral();
00040             await SuspensionManager.SaveAsync();
00041             deferral.Complete();
00042         }
00043
00044         /// <summary>
00045         /// Invoked when the application is launched normally by the end user.  Other entry points
00046         /// will be used when the application is launched to open a specific file, to display
00047         /// search results, and so forth.
00048         /// </summary>
00049         /// <param name="args">Details about the launch request and process.</param>
00050         async protected override void OnLaunched(LaunchActivatedEventArgs args)
00051         {
00052             this.LaunchArgs = args;
00053
00054             Frame rootFrame = null;
00055             if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
00056             {
00057                 // Do an asynchronous restore
00058                 await SuspensionManager.RestoreAsync();
00059             }
00060             if (Window.Current.Content == null)
00061             {
00062                 rootFrame = new Frame();
00063                 rootFrame.Navigate(typeof(MainPage));
00064                 Window.Current.Content = rootFrame;
00065             }
00066             Window.Current.Activate();
00067         }
00068     }
00069 }
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D sprite/C++/DirectXApp.cpp Source File

  • Direct3D sprite

DirectXApp.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 "DirectXApp.h"
00010 #include "BasicTimer.h"
00011
00012 using namespace Windows::ApplicationModel;
00013 using namespace Windows::ApplicationModel::Core;
00014 using namespace Windows::ApplicationModel::Activation;
00015 using namespace Windows::UI::Core;
00016 using namespace Windows::UI::Input;
00017 using namespace Windows::System;
00018 using namespace Windows::Storage;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::Graphics::Display;
00022
00023 DirectXApp::DirectXApp() :
00024     m_windowClosed(false),
00025     m_windowVisible(true)
00026 {
00027 }
00028
00029 void DirectXApp::Initialize(
00030     _In_ CoreApplicationView^ applicationView
00031     )
00032 {
00033     applicationView->Activated +=
00034         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &DirectXApp::OnActivated);
00035
00036     m_renderer = ref new SimpleSprites();
00037 }
00038
00039 void DirectXApp::SetWindow(
00040     _In_ CoreWindow^ window
00041     )
00042 {
00043     window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
00044
00045     window->SizeChanged +=
00046         ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &DirectXApp::OnWindowSizeChanged);
00047
00048     window->VisibilityChanged +=
00049         ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &DirectXApp::OnVisibilityChanged);
00050
00051     window->Closed +=
00052         ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &DirectXApp::OnWindowClosed);
00053
00054     DisplayProperties::LogicalDpiChanged +=
00055         ref new DisplayPropertiesEventHandler(this, &DirectXApp::OnLogicalDpiChanged);
00056
00057     window->PointerPressed +=
00058         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &DirectXApp::OnPointerPressed);
00059
00060     window->PointerReleased +=
00061         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &DirectXApp::OnPointerReleased);
00062
00063     window->PointerMoved +=
00064         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &DirectXApp::OnPointerMoved);
00065
00066     m_renderer->Initialize(window, DisplayProperties::LogicalDpi);
00067 }
00068
00069 void DirectXApp::Load(
00070     _In_ Platform::String^ entryPoint
00071     )
00072 {
00073 }
00074
00075 void DirectXApp::Run()
00076 {
00077     BasicTimer^ timer = ref new BasicTimer();
00078
00079     while (!m_windowClosed)
00080     {
00081         if (m_windowVisible)
00082         {
00083             timer->Update();
00084             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
00085             m_renderer->Update(timer->Total, timer->Delta);
00086             m_renderer->Render();
00087             m_renderer->Present(); // This call is synchronized to the display frame rate.
00088         }
00089         else
00090         {
00091             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
00092         }
00093     }
00094 }
00095
00096 void DirectXApp::Uninitialize()
00097 {
00098 }
00099
00100 void DirectXApp::OnWindowSizeChanged(
00101     _In_ CoreWindow^ sender,
00102     _In_ WindowSizeChangedEventArgs^ args
00103     )
00104 {
00105     m_renderer->UpdateForWindowSizeChange();
00106 }
00107
00108 void DirectXApp::OnWindowClosed(
00109     _In_ CoreWindow^ sender,
00110     _In_ CoreWindowEventArgs^ args
00111     )
00112 {
00113     m_windowClosed = true;
00114 }
00115
00116 void DirectXApp::OnVisibilityChanged(
00117     _In_ CoreWindow^ sender,
00118     _In_ VisibilityChangedEventArgs^ args
00119     )
00120 {
00121     m_windowVisible = args->Visible;
00122 }
00123
00124 void DirectXApp::OnLogicalDpiChanged(
00125     _In_ Platform::Object^ sender
00126     )
00127 {
00128     m_renderer->SetDpi(DisplayProperties::LogicalDpi);
00129 }
00130
00131 void DirectXApp::OnActivated(
00132     _In_ CoreApplicationView^ applicationView,
00133     _In_ IActivatedEventArgs^ args
00134     )
00135 {
00136     CoreWindow::GetForCurrentThread()->Activate();
00137 }
00138
00139 void DirectXApp::OnPointerPressed(
00140     _In_ Windows::UI::Core::CoreWindow^ sender,
00141     _In_ Windows::UI::Core::PointerEventArgs^ args
00142     )
00143 {
00144     m_renderer->AddRepulsor(
00145         args->CurrentPoint->PointerId,
00146         float2(
00147             args->CurrentPoint->Position.X,
00148             args->CurrentPoint->Position.Y
00149             )
00150         );
00151 }
00152
00153 void DirectXApp::OnPointerReleased(
00154     _In_ Windows::UI::Core::CoreWindow^ sender,
00155     _In_ Windows::UI::Core::PointerEventArgs^ args
00156     )
00157 {
00158     m_renderer->RemoveRepulsor(args->CurrentPoint->PointerId);
00159 }
00160
00161 void DirectXApp::OnPointerMoved(
00162     _In_ Windows::UI::Core::CoreWindow^ sender,
00163     _In_ Windows::UI::Core::PointerEventArgs^ args
00164     )
00165 {
00166     if (args->CurrentPoint->IsInContact)
00167     {
00168         m_renderer->MoveRepulsor(
00169             args->CurrentPoint->PointerId,
00170             float2(
00171                 args->CurrentPoint->Position.X,
00172                 args->CurrentPoint->Position.Y
00173                 )
00174             );
00175     }
00176 }
00177
00178 IFrameworkView^ DirectXAppSource::CreateView()
00179 {
00180     return ref new DirectXApp();
00181 }
00182
00183 [Platform::MTAThread]
00184 int main(Platform::Array<Platform::String^>^)
00185 {
00186     auto directXAppSource = ref new DirectXAppSource();
00187     CoreApplication::Run(directXAppSource);
00188     return 0;
00189 }
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Hilo::FileSystemRepository Member List

This is the complete list of members for Hilo::FileSystemRepository, including all inherited members.
AddObserver(const std::function< void()> callback, PageType pageType) | Hilo::FileSystemRepository | [virtual]
CreateFileQuery(Windows::Storage::Search::IStorageFolderQueryOperations^folder, Platform::String^query, Windows::Storage::Search::IndexerOption option=Windows::Storage::Search::IndexerOption::UseIndexerWhenAvailable) | Hilo::FileSystemRepository | [inline, private]
FileSystemRepository(std::shared_ptr< ExceptionPolicy > exceptionPolicy) | Hilo::FileSystemRepository |
GetDateTimeForYearFolderAsync(Windows::Storage::Search::IStorageFolderQueryOperations^folderQuery, std::shared_ptr< ExceptionPolicy > exceptionPolicy) | Hilo::FileSystemRepository | [private]
GetFolderPhotoCountAsync(Windows::Storage::Search::IStorageFolderQueryOperations^folderQuery) | Hilo::FileSystemRepository | [virtual]
GetMonthGroupedPhotosWithCacheAsync(std::shared_ptr< Hilo::PhotoCache > photoCache, concurrency::cancellation_token token) | Hilo::FileSystemRepository | [virtual]
Hilo::Repository::GetMonthGroupedPhotosWithCacheAsync(std::shared_ptr< PhotoCache > photoCache, concurrency::cancellation_token token)=0 | Hilo::Repository | [pure virtual]
GetPhotoDataForMonthGroup(IPhotoGroup^photoGroup, Windows::Storage::Search::IStorageFolderQueryOperations^folderQuery, unsigned int maxNumberOfItems) | Hilo::FileSystemRepository | [virtual]
GetPhotosForDateRangeQueryAsync(Platform::String^dateRangeQuery) | Hilo::FileSystemRepository | [virtual]
GetPhotosForPictureHubGroupAsync(IPhotoGroup^photoGroup, unsigned int maxNumberOfItem) | Hilo::FileSystemRepository | [virtual]
GetPhotoStorageFilesAsync(Platform::String^query, unsigned int maxNumberOfItems=25) | Hilo::FileSystemRepository | [inline, virtual]
GetSinglePhotoAsync(Platform::String^photoPath) | Hilo::FileSystemRepository | [virtual]
GetYearGroupedMonthsAsync(concurrency::cancellation_token token) | Hilo::FileSystemRepository | [virtual]
HasPhotosInRangeAsync(Platform::String^dateRangeQuery, Windows::Storage::Search::IStorageFolderQueryOperations^folderQuery) | Hilo::FileSystemRepository | [virtual]
m_allPhotosQueryChange | Hilo::FileSystemRepository | [private]
m_exceptionPolicy | Hilo::FileSystemRepository | [private]
m_hubViewModelCallback | Hilo::FileSystemRepository | [private]
m_imageBrowserViewModelCallback | Hilo::FileSystemRepository | [private]
m_imageViewModelCallback | Hilo::FileSystemRepository | [private]
m_monthQueryChange | Hilo::FileSystemRepository | [private]
m_pictureHubGroupQueryChange | Hilo::FileSystemRepository | [private]
NotifyAllObservers() | Hilo::FileSystemRepository | [virtual]
RemoveObserver(PageType pageType) | Hilo::FileSystemRepository | [virtual]
Generated on Sat Nov 23 2024 16:09:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX marble maze game/C++/BasicTimer.h Source File

  • DirectX marble maze game

BasicTimer.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 timer class used to drive the render loop of the actively-animated
00011 // DirectX SDK samples. Uses the QueryPerformanceCounter function to retrieve
00012 // high-resolution timing information.
00013 ref class BasicTimer
00014 {
00015 private:
00016     LARGE_INTEGER m_frequency;
00017     LARGE_INTEGER m_currentTime;
00018     LARGE_INTEGER m_startTime;
00019     LARGE_INTEGER m_lastTime;
00020     float m_total;
00021     float m_delta;
00022
00023 internal:
00024     BasicTimer();
00025     void Reset();
00026     void Update();
00027     property float Total
00028     {
00029         float get();
00030     }
00031     property float Delta
00032     {
00033         float get();
00034     }
00035 };
Generated on Sat Nov 23 2024 16:08:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: User domain name/C++/common/LayoutAwarePage.h Source File

  • User domain name
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DxgiRotation Member List

This is the complete list of members for DxgiRotation, including all inherited members.
__pad0__ | DxgiRotation |
CreateDeviceResources() override | DxgiRotation | [virtual]
CreateWindowSizeDependentResources() override | DxgiRotation | [virtual]
m_Camera | DxgiRotation | [private]
m_constantBuffer | DxgiRotation | [private]
m_constantBufferData | DxgiRotation | [private]
m_indexBuffer | DxgiRotation | [private]
m_indexCount | DxgiRotation | [private]
m_inputLayout | DxgiRotation | [private]
m_pixelShader | DxgiRotation | [private]
m_referenceBitmap | DxgiRotation | [private]
m_referenceBitmapSource | DxgiRotation | [private]
m_sampleOverlay | DxgiRotation | [private]
m_sampler | DxgiRotation | [private]
m_textBrush | DxgiRotation | [private]
m_textFormat | DxgiRotation | [private]
m_textLayout | DxgiRotation | [private]
m_texture | DxgiRotation | [private]
m_textureSRV | DxgiRotation | [private]
m_vertexBuffer | DxgiRotation | [private]
m_vertexShader | DxgiRotation | [private]
Render() override | DxgiRotation | [virtual]
Update(float TimeTotal, float TimeDelta) | DxgiRotation |
Generated on Sat Nov 23 2024 16:09:12 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML user and custom controls/C++/Constants.cpp Source File

  • XAML user and custom controls

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
00021     { "Using a custom UserControl", "SDKSample.UserAndCustomControls.Scenario1" },
00022     { "Creating a custom control", "SDKSample.UserAndCustomControls.Scenario2" },
00023     { "DependencyProperty", "SDKSample.UserAndCustomControls.Scenario3" },
00024   { "Distributing your control", "SDKSample.UserAndCustomControls.Scenario4" }
00025 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Splash screen/C++/common/suspensionmanager.cpp Source File

  • Splash screen
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:37 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML two-dimensional transforms/C++/common/suspensionmanager.cpp Source File

  • XAML two-dimensional transforms
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Removable storage/C++/S2_SendToStorage.xaml.cpp Source File

  • Removable storage

S2_SendToStorage.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 // S2_SendToStorage.xaml.cpp
00013 // Implementation of the S2_SendToStorage class
00014 //
00015
00016 #include "pch.h"
00017 #include "S2_SendToStorage.xaml.h"
00018
00019 using namespace SDKSample::RemovableStorageCPP;
00020
00021 using namespace concurrency;
00022 using namespace Platform;
00023 using namespace Platform::Collections;
00024 using namespace Windows::Devices::Enumeration;
00025 using namespace Windows::Devices::Portable;
00026 using namespace Windows::Foundation::Collections;
00027 using namespace Windows::Storage;
00028 using namespace Windows::Storage::Pickers;
00029 using namespace Windows::UI::Core;
00030 using namespace Windows::UI::Xaml;
00031 using namespace Windows::UI::Xaml::Controls;
00032 using namespace Windows::UI::Xaml::Navigation;
00033
00034 S2_SendToStorage::S2_SendToStorage() : rootPage(MainPage::Current)
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 S2_SendToStorage::OnNavigatedTo(NavigationEventArgs^ e)
00045 {
00046     DeviceSelector->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00047 }
00048
00049 /// <summary>
00050 /// This is the click handler for the 'Send Image' button.
00051 /// </summary>
00052 /// <param name="sender"></param>
00053 /// <param name="e"></param>
00054 void S2_SendToStorage::SendImage_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00055 {
00056     ShowDeviceSelectorAsync();
00057 }
00058
00059 /// <summary>
00060 /// Enumerates all storages and populates the device selection list.
00061 /// </summary>
00062 void S2_SendToStorage::ShowDeviceSelectorAsync()
00063 {
00064     _deviceInfoCollection = nullptr;
00065
00066     // Find all storage devices using Windows.Devices.Enumeration
00067     create_task(DeviceInformation::FindAllAsync(StorageDevice::GetDeviceSelector())).then([this] (DeviceInformationCollection^ deviceInfoCollection)
00068     {
00069         _deviceInfoCollection = deviceInfoCollection;
00070         if (_deviceInfoCollection->Size > 0)
00071         {
00072             auto items = ref new Vector<String^>();
00073             std::for_each(begin(_deviceInfoCollection), end(_deviceInfoCollection), [items](IDeviceInformation^ deviceInfo)
00074             {
00075                 items->Append(ref new String(deviceInfo->Name->Begin()));
00076             });
00077             cvs->Source = items;
00078             DeviceSelector->Visibility = Windows::UI::Xaml::Visibility::Visible;
00079         }
00080         else
00081         {
00082             rootPage->NotifyUser("No removable storages were found. Please attach a removable storage to the system (e.g. a camera or camera memory)", NotifyType::StatusMessage);
00083         }
00084     });
00085 }
00086
00087 /// <summary>
00088 /// This is the tapped handler for the device selection list. It runs the scenario
00089 /// for the selected storage.
00090 /// </summary>
00091 /// <param name="sender"></param>
00092 /// <param name="e"></param>
00093 void S2_SendToStorage::DeviceList_Tapped(Platform::Object^ sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^ e)
00094 {
00095     DeviceSelector->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00096     if (_deviceInfoCollection == nullptr)
00097     {
00098         return; // not yet populated
00099     }
00100
00101     auto deviceInfo = _deviceInfoCollection->GetAt(DeviceList->SelectedIndex);
00102     SendImageFileToStorageAsync(deviceInfo);
00103 }
00104
00105 /// <summary>
00106 /// Sends a user-selected image file to the storage referenced by the device information element.
00107 /// </summary>
00108 /// <param name="deviceInfoElement">Contains information about a selected device.</param>
00109 void S2_SendToStorage::SendImageFileToStorageAsync(DeviceInformation^ deviceInfoElement)
00110 {
00111     // Verify that we are currently not snapped, or that we can unsnap to open the file picker
00112     auto currentState = Windows::UI::ViewManagement::ApplicationView::Value;
00113     if (currentState == Windows::UI::ViewManagement::ApplicationViewState::Snapped && !Windows::UI::ViewManagement::ApplicationView::TryUnsnap())
00114     {
00115         rootPage->NotifyUser("Could not unsnap (required to launch the file open picker). Please unsnap this app before proceeding", NotifyType::ErrorMessage);
00116         return;
00117     }
00118
00119     // Launch the picker to select an image file
00120     auto picker = ref new FileOpenPicker();
00121     picker->FileTypeFilter->Append(".jpg");
00122     picker->FileTypeFilter->Append(".png");
00123     picker->FileTypeFilter->Append(".gif");
00124     picker->SuggestedStartLocation = PickerLocationId::PicturesLibrary;
00125
00126     create_task(picker->PickSingleFileAsync()).then([this, deviceInfoElement] (StorageFile^ sourceFile)
00127     {
00128         if (sourceFile != nullptr)
00129         {
00130             // Convert the selected device information element to a StorageFolder
00131             auto storage = StorageDevice::FromId(deviceInfoElement->Id);
00132             auto storageName = deviceInfoElement->Name;
00133
00134             rootPage->NotifyUser("Copying image: " + sourceFile->Name + " to " + storageName + " ...", NotifyType::StatusMessage);
00135             CopyFileToFolderOnStorageAsync(sourceFile, storage);
00136         }
00137         else
00138         {
00139             rootPage->NotifyUser("No file was selected", NotifyType::StatusMessage);
00140         }
00141     });
00142 }
00143
00144 /// <summary>
00145 /// Copies a file to the first folder on a storage.
00146 /// </summary>
00147 /// <param name="sourceFile"></param>
00148 /// <param name="storage"></param>
00149 void S2_SendToStorage::CopyFileToFolderOnStorageAsync(StorageFile^ sourceFile, StorageFolder^ storage)
00150 {
00151     auto storageName = storage->Name;
00152
00153     // Construct a folder search to find sub-folders under the current storage.
00154     // The default (shallow) query should be sufficient in finding the first level of sub-folders.
00155     // If the first level of sub-folders are not writable, a deep query + recursive copy may be needed.
00156     create_task(storage->GetFoldersAsync()).then([this, sourceFile, storageName] (IVectorView<StorageFolder^>^ folders)
00157     {
00158         if (folders->Size > 0)
00159         {
00160             auto destinationFolder = folders->GetAt(0);
00161             auto destinationFolderName = destinationFolder->Name;
00162             rootPage->NotifyUser("Trying the first folder on storage: " + destinationFolderName + "...", NotifyType::StatusMessage);
00163
00164             // The following CopyAsync task is nested (instead of chained) with the containing GetFoldersAsync task because we only call it when a sub-folder is present.
00165             create_task(sourceFile->CopyAsync(destinationFolder, sourceFile->Name, NameCollisionOption::GenerateUniqueName)).then([this, storageName, destinationFolderName] (task<StorageFile^> thisTask)
00166             {
00167                 try
00168                 {
00169                     auto newFile = thisTask.get();
00170                     rootPage->NotifyUser("Image " + newFile->Name + " created on " + storageName, NotifyType::StatusMessage);
00171                 }
00172                 catch (Exception^ e) // Catching all exceptions because different removable storages can exhibit different error behavior on CopyAsync
00173                 {
00174                     rootPage->NotifyUser("Caught exception while copying the image to the first sub-folder: " + destinationFolderName + ", " + storageName + " may not allow sending files to its top level folders. Error: " + e->Message, NotifyType::ErrorMessage);
00175                 }
00176             });
00177         }
00178         else
00179         {
00180             rootPage->NotifyUser("No sub-folders found on " + storageName + " to copy to", NotifyType::StatusMessage);
00181         }
00182     });
00183 }
Generated on Sat Nov 23 2024 16:08:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: HttpClient/C++/Scenario3.xaml.h Source File

  • HttpClient

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 "HttpRequest.h"
00022
00023 namespace SDKSample
00024 {
00025     namespace HttpClientSample
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 Scenario3 sealed
00032         {
00033         public:
00034             Scenario3();
00035
00036         protected:
00037             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00038
00039         private:
00040             MainPage^ rootPage;
00041             Web::HttpRequest httpRequest;
00042             concurrency::cancellation_token_source cancellationTokenSource;
00043             void Start_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00044             void Cancel_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00045             void DisplayTextResult(const std::wstring& response, Windows::UI::Xaml::Controls::TextBox^ output);
00046         };
00047     }
00048 }
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

CustomDeviceAccess::DeviceListEntry Member List

This is the complete list of members for CustomDeviceAccess::DeviceListEntry, including all inherited members.
Device | CustomDeviceAccess::DeviceListEntry |
DeviceListEntry(Windows.Devices.Enumeration.DeviceInformation DeviceInterface) | CustomDeviceAccess::DeviceListEntry | [inline]
Id | CustomDeviceAccess::DeviceListEntry |
InstanceId | CustomDeviceAccess::DeviceListEntry |
Matched | CustomDeviceAccess::DeviceListEntry |
Generated on Sat Nov 23 2024 16:09:37 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media Play To/C++/MainPage.xaml.h Source File

  • Media Play To

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:46 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/texconv/BC4BC5.cpp Source File

  • Direct3D resource loading
  • texconv

BC4BC5.cpp

Go to the documentation of this file.
00001 //-------------------------------------------------------------------------------------
00002 // BC4BC5.cpp
00003 //
00004 // Block-compression (BC) functionality for BC4 and BC5 (DirectX 10 texture compression)
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 #include "directxtexp.h"
00015
00016 #include "BC.h"
00017
00018 #pragma warning(disable : 4201)
00019
00020 namespace DirectX
00021 {
00022
00023 //------------------------------------------------------------------------------------
00024 // Constants
00025 //------------------------------------------------------------------------------------
00026
00027 // Because these are used in SAL annotations, they need to remain macros rather than const values
00028 #define BLOCK_LEN 4
00029     // length of each block in texel
00030
00031 #define BLOCK_SIZE (BLOCK_LEN * BLOCK_LEN)
00032     // total texels in a 4x4 block.
00033
00034 //------------------------------------------------------------------------------------
00035 // Structures
00036 //-------------------------------------------------------------------------------------
00037
00038 // BC4U/BC5U
00039 struct BC4_UNORM
00040 {
00041     float R(size_t uOffset) const
00042     {
00043         size_t uIndex = GetIndex(uOffset);
00044         return DecodeFromIndex(uIndex);
00045     }
00046
00047     float DecodeFromIndex(size_t uIndex) const
00048     {
00049         if (uIndex == 0)
00050             return red_0 / 255.0f;
00051         if (uIndex == 1)
00052             return red_1 / 255.0f;
00053         float fred_0 = red_0 / 255.0f;
00054         float fred_1 = red_1 / 255.0f;
00055         if (red_0 > red_1)
00056         {
00057             uIndex -= 1;
00058             return (fred_0 * (7-uIndex) + fred_1 * uIndex) / 7.0f;
00059         }
00060         else
00061         {
00062             if (uIndex == 6)
00063                 return 0.0f;
00064             if (uIndex == 7)
00065                 return 1.0f;
00066             uIndex -= 1;
00067             return (fred_0 * (5-uIndex) + fred_1 * uIndex) / 5.0f;
00068         }
00069     }
00070
00071     size_t GetIndex(size_t uOffset) const
00072     {
00073         return (size_t) ((data >> (3*uOffset + 16)) & 0x07);
00074     }
00075
00076     void SetIndex(size_t uOffset, size_t uIndex)
00077     {
00078         data &= ~((uint64_t) 0x07 << (3*uOffset + 16));
00079         data |= ((uint64_t) uIndex << (3*uOffset + 16));
00080     }
00081
00082     union
00083     {
00084         struct
00085         {
00086             uint8_t red_0;
00087             uint8_t red_1;
00088             uint8_t indices[6];
00089         };
00090         uint64_t data;
00091     };
00092 };
00093
00094 // BC4S/BC5S
00095 struct BC4_SNORM
00096 {
00097     float R(size_t uOffset) const
00098     {
00099         size_t uIndex = GetIndex(uOffset);
00100         return DecodeFromIndex(uIndex);
00101     }
00102
00103     float DecodeFromIndex(size_t uIndex) const
00104     {
00105         int8_t sred_0 = (red_0 == -128)? -127 : red_0;
00106         int8_t sred_1 = (red_1 == -128)? -127 : red_1;
00107
00108         if (uIndex == 0)
00109             return sred_0 / 127.0f;
00110         if (uIndex == 1)
00111             return sred_1 / 127.0f;
00112         float fred_0 = sred_0 / 127.0f;
00113         float fred_1 = sred_1 / 127.0f;
00114         if (red_0 > red_1)
00115         {
00116             uIndex -= 1;
00117             return (fred_0 * (7-uIndex) + fred_1 * uIndex) / 7.0f;
00118         }
00119         else
00120         {
00121             if (uIndex == 6)
00122                 return -1.0f;
00123             if (uIndex == 7)
00124                 return 1.0f;
00125             uIndex -= 1;
00126             return (fred_0 * (5-uIndex) + fred_1 * uIndex) / 5.0f;
00127         }
00128     }
00129
00130     size_t GetIndex(size_t uOffset) const
00131     {
00132         return (size_t) ((data >> (3*uOffset + 16)) & 0x07);
00133     }
00134
00135     void SetIndex(size_t uOffset, size_t uIndex)
00136     {
00137         data &= ~((uint64_t) 0x07 << (3*uOffset + 16));
00138         data |= ((uint64_t) uIndex << (3*uOffset + 16));
00139     }
00140
00141     union
00142     {
00143         struct
00144         {
00145             int8_t red_0;
00146             int8_t red_1;
00147             uint8_t indices[6];
00148         };
00149         uint64_t data;
00150     };
00151 };
00152
00153
00154 //-------------------------------------------------------------------------------------
00155 // Convert a floating point value to an 8-bit SNORM
00156 //-------------------------------------------------------------------------------------
00157 static void inline FloatToSNorm( _In_ float fVal, _Out_ int8_t *piSNorm )
00158 {
00159     const uint32_t dwMostNeg = ( 1 << ( 8 * sizeof( int8_t ) - 1 ) );
00160
00161     if( _isnan( fVal ) )
00162         fVal = 0;
00163     else
00164         if( fVal > 1 )
00165             fVal = 1; // Clamp to 1
00166         else
00167             if( fVal < -1 )
00168                 fVal = -1;  // Clamp to -1
00169
00170     fVal = fVal * (int8_t) ( dwMostNeg - 1 );
00171
00172     if( fVal >= 0 )
00173         fVal += .5f;
00174     else
00175         fVal -= .5f;
00176
00177     *piSNorm = (int8_t) (fVal);
00178 }
00179
00180
00181 //------------------------------------------------------------------------------
00182 static void FindEndPointsBC4U( _In_reads_(BLOCK_SIZE) const float theTexelsU[], _Out_ uint8_t &endpointU_0, _Out_ uint8_t &endpointU_1)
00183 {
00184     // The boundary of codec for signed/unsigned format
00185     float MIN_NORM;
00186     float MAX_NORM = 1.0f;
00187     int8_t iStart, iEnd;
00188     size_t i;
00189
00190     MIN_NORM = 0.0f;
00191
00192     // Find max/min of input texels
00193     float fBlockMax = theTexelsU[0];
00194     float fBlockMin = theTexelsU[0];
00195     for (i = 0; i < BLOCK_SIZE; ++i)
00196     {
00197         if (theTexelsU[i]<fBlockMin)
00198         {
00199             fBlockMin = theTexelsU[i];
00200         }
00201         else if (theTexelsU[i]>fBlockMax)
00202         {
00203             fBlockMax = theTexelsU[i];
00204         }
00205     }
00206
00207     //  If there are boundary values in input texels, Should use 4 block-codec to guarantee
00208     //  the exact code of the boundary values.
00209     bool bUsing4BlockCodec = ( MIN_NORM == fBlockMin || MAX_NORM == fBlockMax );
00210
00211     // Using Optimize
00212     float fStart, fEnd;
00213
00214     if (!bUsing4BlockCodec)
00215     {
00216         OptimizeAlpha<false>(&fStart, &fEnd, theTexelsU, 8);
00217
00218         iStart = (uint8_t) (fStart * 255.0f);
00219         iEnd   = (uint8_t) (fEnd   * 255.0f);
00220
00221         endpointU_0 = iEnd;
00222         endpointU_1 = iStart;
00223     }
00224     else
00225     {
00226         OptimizeAlpha<false>(&fStart, &fEnd, theTexelsU, 6);
00227
00228         iStart = (uint8_t) (fStart * 255.0f);
00229         iEnd   = (uint8_t) (fEnd   * 255.0f);
00230
00231         endpointU_1 = iEnd;
00232         endpointU_0 = iStart;
00233     }
00234 }
00235
00236 static void FindEndPointsBC4S(_In_reads_(BLOCK_SIZE) const float theTexelsU[], _Out_ int8_t &endpointU_0, _Out_ int8_t &endpointU_1)
00237 {
00238     //  The boundary of codec for signed/unsigned format
00239     float MIN_NORM;
00240     float MAX_NORM = 1.0f;
00241     int8_t iStart, iEnd;
00242     size_t i;
00243
00244     MIN_NORM = -1.0f;
00245
00246     // Find max/min of input texels
00247     float fBlockMax = theTexelsU[0];
00248     float fBlockMin = theTexelsU[0];
00249     for (i = 0; i < BLOCK_SIZE; ++i)
00250     {
00251         if (theTexelsU[i]<fBlockMin)
00252         {
00253             fBlockMin = theTexelsU[i];
00254         }
00255         else if (theTexelsU[i]>fBlockMax)
00256         {
00257             fBlockMax = theTexelsU[i];
00258         }
00259     }
00260
00261     //  If there are boundary values in input texels, Should use 4 block-codec to guarantee
00262     //  the exact code of the boundary values.
00263     bool bUsing4BlockCodec = ( MIN_NORM == fBlockMin || MAX_NORM == fBlockMax );
00264
00265     // Using Optimize
00266     float fStart, fEnd;
00267
00268     if (!bUsing4BlockCodec)
00269     {
00270         OptimizeAlpha<true>(&fStart, &fEnd, theTexelsU, 8);
00271
00272         FloatToSNorm(fStart, &iStart);
00273         FloatToSNorm(fEnd, &iEnd);
00274
00275         endpointU_0 = iEnd;
00276         endpointU_1 = iStart;
00277     }
00278     else
00279     {
00280         OptimizeAlpha<true>(&fStart, &fEnd, theTexelsU, 6);
00281
00282         FloatToSNorm(fStart, &iStart);
00283         FloatToSNorm(fEnd, &iEnd);
00284
00285         endpointU_1 = iEnd;
00286         endpointU_0 = iStart;
00287     }
00288 }
00289
00290
00291 //------------------------------------------------------------------------------
00292 static inline void FindEndPointsBC5U( _In_reads_(BLOCK_SIZE) const float theTexelsU[], _In_reads_(BLOCK_SIZE) const float theTexelsV[],
00293                                       _Out_ uint8_t &endpointU_0, _Out_ uint8_t &endpointU_1, _Out_ uint8_t &endpointV_0, _Out_ uint8_t &endpointV_1)
00294 {
00295     //Encoding the U and V channel by BC4 codec separately.
00296     FindEndPointsBC4U( theTexelsU, endpointU_0, endpointU_1);
00297     FindEndPointsBC4U( theTexelsV, endpointV_0, endpointV_1);
00298 }
00299
00300 static inline void FindEndPointsBC5S( _In_reads_(BLOCK_SIZE) const float theTexelsU[], _In_reads_(BLOCK_SIZE) const float theTexelsV[],
00301                                       _Out_ int8_t &endpointU_0, _Out_ int8_t &endpointU_1, _Out_ int8_t &endpointV_0, _Out_ int8_t &endpointV_1)
00302 {
00303     //Encoding the U and V channel by BC4 codec separately.
00304     FindEndPointsBC4S( theTexelsU, endpointU_0, endpointU_1);
00305     FindEndPointsBC4S( theTexelsV, endpointV_0, endpointV_1);
00306 }
00307
00308
00309 //------------------------------------------------------------------------------
00310 static void FindClosestUNORM(_Inout_ BC4_UNORM* pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const float theTexelsU[])
00311 {
00312     float rGradient[8];
00313     int i;
00314     for (i = 0; i < 8; ++i)
00315     {
00316         rGradient[i] = pBC->DecodeFromIndex(i);
00317     }
00318     for (i = 0; i < NUM_PIXELS_PER_BLOCK; ++i)
00319     {
00320         size_t uBestIndex = 0;
00321         float fBestDelta = 100000;
00322         for (size_t uIndex = 0; uIndex < 8; uIndex++)
00323         {
00324             float fCurrentDelta = fabsf(rGradient[uIndex]-theTexelsU[i]);
00325             if (fCurrentDelta < fBestDelta)
00326             {
00327                 uBestIndex = uIndex;
00328                 fBestDelta = fCurrentDelta;
00329             }
00330         }
00331         pBC->SetIndex(i, uBestIndex);
00332     }
00333 }
00334
00335 static void FindClosestSNORM(_Inout_ BC4_SNORM* pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const float theTexelsU[])
00336 {
00337     float rGradient[8];
00338     int i;
00339     for (i = 0; i < 8; ++i)
00340     {
00341         rGradient[i] = pBC->DecodeFromIndex(i);
00342     }
00343     for (i = 0; i < NUM_PIXELS_PER_BLOCK; ++i)
00344     {
00345         size_t uBestIndex = 0;
00346         float fBestDelta = 100000;
00347         for (size_t uIndex = 0; uIndex < 8; uIndex++)
00348         {
00349             float fCurrentDelta = fabsf(rGradient[uIndex]-theTexelsU[i]);
00350             if (fCurrentDelta < fBestDelta)
00351             {
00352                 uBestIndex = uIndex;
00353                 fBestDelta = fCurrentDelta;
00354             }
00355         }
00356         pBC->SetIndex(i, uBestIndex);
00357     }
00358 }
00359
00360
00361 //=====================================================================================
00362 // Entry points
00363 //=====================================================================================
00364
00365 //-------------------------------------------------------------------------------------
00366 // BC4 Compression
00367 //-------------------------------------------------------------------------------------
00368 _Use_decl_annotations_
00369 void D3DXDecodeBC4U( XMVECTOR *pColor, const uint8_t *pBC )
00370 {
00371     assert( pColor && pBC );
00372     static_assert( sizeof(BC4_UNORM) == 8, "BC4_UNORM should be 8 bytes" );
00373
00374     const BC4_UNORM * pBC4 = reinterpret_cast<const BC4_UNORM*>(pBC);
00375
00376     for (size_t i = 0; i < NUM_PIXELS_PER_BLOCK; ++i)
00377     {
00378         pColor[i] = XMVectorSet( pBC4->R(i), 0, 0, 1.0f);
00379     }
00380 }
00381
00382 _Use_decl_annotations_
00383 void D3DXDecodeBC4S(XMVECTOR *pColor, const uint8_t *pBC)
00384 {
00385     assert( pColor && pBC );
00386     static_assert( sizeof(BC4_SNORM) == 8, "BC4_SNORM should be 8 bytes" );
00387
00388     const BC4_SNORM * pBC4 = reinterpret_cast<const BC4_SNORM*>(pBC);
00389
00390     for (size_t i = 0; i < NUM_PIXELS_PER_BLOCK; ++i)
00391     {
00392         pColor[i] = XMVectorSet( pBC4->R(i), 0, 0, 1.0f);
00393     }
00394 }
00395
00396 _Use_decl_annotations_
00397 void D3DXEncodeBC4U( uint8_t *pBC, const XMVECTOR *pColor, DWORD flags )
00398 {
00399     UNREFERENCED_PARAMETER( flags );
00400
00401     assert( pBC && pColor );
00402     static_assert( sizeof(BC4_UNORM) == 8, "BC4_UNORM should be 8 bytes" );
00403
00404     memset(pBC, 0, sizeof(BC4_UNORM));
00405     BC4_UNORM * pBC4 = reinterpret_cast<BC4_UNORM*>(pBC);
00406     float theTexelsU[NUM_PIXELS_PER_BLOCK];
00407
00408     for (size_t i = 0; i < NUM_PIXELS_PER_BLOCK; ++i)
00409     {
00410         theTexelsU[i] = XMVectorGetX( pColor[i] );
00411     }
00412
00413     FindEndPointsBC4U(theTexelsU, pBC4->red_0, pBC4->red_1);
00414     FindClosestUNORM(pBC4, theTexelsU);
00415 }
00416
00417 _Use_decl_annotations_
00418 void D3DXEncodeBC4S( uint8_t *pBC, const XMVECTOR *pColor, DWORD flags )
00419 {
00420     UNREFERENCED_PARAMETER( flags );
00421
00422     assert( pBC && pColor );
00423     static_assert( sizeof(BC4_SNORM) == 8, "BC4_SNORM should be 8 bytes" );
00424
00425     memset(pBC, 0, sizeof(BC4_UNORM));
00426     BC4_SNORM * pBC4 = reinterpret_cast<BC4_SNORM*>(pBC);
00427     float theTexelsU[NUM_PIXELS_PER_BLOCK];
00428
00429     for (size_t i = 0; i < NUM_PIXELS_PER_BLOCK; ++i)
00430     {
00431         theTexelsU[i] = XMVectorGetX( pColor[i] );
00432     }
00433
00434     FindEndPointsBC4S(theTexelsU, pBC4->red_0, pBC4->red_1);
00435     FindClosestSNORM(pBC4, theTexelsU);
00436 }
00437
00438
00439 //-------------------------------------------------------------------------------------
00440 // BC5 Compression
00441 //-------------------------------------------------------------------------------------
00442 _Use_decl_annotations_
00443 void D3DXDecodeBC5U(XMVECTOR *pColor, const uint8_t *pBC)
00444 {
00445     assert( pColor && pBC );
00446     static_assert( sizeof(BC4_UNORM) == 8, "BC4_UNORM should be 8 bytes" );
00447
00448     const BC4_UNORM * pBCR = reinterpret_cast<const BC4_UNORM*>(pBC);
00449     const BC4_UNORM * pBCG = reinterpret_cast<const BC4_UNORM*>(pBC+sizeof(BC4_UNORM));
00450
00451     for (size_t i = 0; i < NUM_PIXELS_PER_BLOCK; ++i)
00452     {
00453         pColor[i] = XMVectorSet(pBCR->R(i), pBCG->R(i), 0, 1.0f);
00454     }
00455 }
00456
00457 _Use_decl_annotations_
00458 void D3DXDecodeBC5S(XMVECTOR *pColor, const uint8_t *pBC)
00459 {
00460     assert( pColor && pBC );
00461     static_assert( sizeof(BC4_SNORM) == 8, "BC4_SNORM should be 8 bytes" );
00462
00463     const BC4_SNORM * pBCR = reinterpret_cast<const BC4_SNORM*>(pBC);
00464     const BC4_SNORM * pBCG = reinterpret_cast<const BC4_SNORM*>(pBC+sizeof(BC4_SNORM));
00465
00466     for (size_t i = 0; i < NUM_PIXELS_PER_BLOCK; ++i)
00467     {
00468         pColor[i] = XMVectorSet(pBCR->R(i), pBCG->R(i), 0, 1.0f);
00469     }
00470 }
00471
00472 _Use_decl_annotations_
00473 void D3DXEncodeBC5U( uint8_t *pBC, const XMVECTOR *pColor, DWORD flags )
00474 {
00475     UNREFERENCED_PARAMETER( flags );
00476
00477     assert( pBC && pColor );
00478     static_assert( sizeof(BC4_UNORM) == 8, "BC4_UNORM should be 8 bytes" );
00479
00480     memset(pBC, 0, sizeof(BC4_UNORM)*2);
00481     BC4_UNORM * pBCR = reinterpret_cast<BC4_UNORM*>(pBC);
00482     BC4_UNORM * pBCG = reinterpret_cast<BC4_UNORM*>(pBC+sizeof(BC4_UNORM));
00483     float theTexelsU[NUM_PIXELS_PER_BLOCK];
00484     float theTexelsV[NUM_PIXELS_PER_BLOCK];
00485
00486     for (size_t i = 0; i < NUM_PIXELS_PER_BLOCK; ++i)
00487     {
00488         XMFLOAT4A clr;
00489         XMStoreFloat4A( &clr, pColor[i] );
00490         theTexelsU[i] = clr.x;
00491         theTexelsV[i] = clr.y;
00492     }
00493
00494     FindEndPointsBC5U(
00495         theTexelsU,
00496         theTexelsV,
00497         pBCR->red_0,
00498         pBCR->red_1,
00499         pBCG->red_0,
00500         pBCG->red_1);
00501
00502     FindClosestUNORM(pBCR, theTexelsU);
00503     FindClosestUNORM(pBCG, theTexelsV);
00504 }
00505
00506 _Use_decl_annotations_
00507 void D3DXEncodeBC5S( uint8_t *pBC, const XMVECTOR *pColor, DWORD flags )
00508 {
00509     UNREFERENCED_PARAMETER( flags );
00510
00511     assert( pBC && pColor );
00512     static_assert( sizeof(BC4_SNORM) == 8, "BC4_SNORM should be 8 bytes" );
00513
00514     memset(pBC, 0, sizeof(BC4_UNORM)*2);
00515     BC4_SNORM * pBCR = reinterpret_cast<BC4_SNORM*>(pBC);
00516     BC4_SNORM * pBCG = reinterpret_cast<BC4_SNORM*>(pBC+sizeof(BC4_SNORM));
00517     float theTexelsU[NUM_PIXELS_PER_BLOCK];
00518     float theTexelsV[NUM_PIXELS_PER_BLOCK];
00519
00520     for (size_t i = 0; i < NUM_PIXELS_PER_BLOCK; ++i)
00521     {
00522         XMFLOAT4A clr;
00523         XMStoreFloat4A( &clr, pColor[i] );
00524         theTexelsU[i] = clr.x;
00525         theTexelsV[i] = clr.y;
00526     }
00527
00528     FindEndPointsBC5S(
00529         theTexelsU,
00530         theTexelsV,
00531         pBCR->red_0,
00532         pBCR->red_1,
00533         pBCG->red_0,
00534         pBCG->red_1);
00535
00536     FindClosestSNORM(pBCR, theTexelsU);
00537     FindClosestSNORM(pBCG, theTexelsV);
00538 }
00539
00540 } // namespace
Generated on Sat Nov 23 2024 16:08:11 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D-Direct2D interop/C++/DDSTextureLoader.h Source File

  • Direct3D-Direct2D interop

DDSTextureLoader.h

Go to the documentation of this file.
00001 //--------------------------------------------------------------------------------------
00002 // File: DDSTextureLoader.h
00003 //
00004 // Function for loading a DDS texture and creating a Direct3D 11 runtime resource for it
00005 //
00006 // Note this function is 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
00018 #pragma once
00019
00020 void CreateDDSTextureFromMemory(
00021     _In_ ID3D11Device* d3dDevice,
00022     _In_reads_bytes_(ddsDataSize) const byte* ddsData,
00023     _In_ size_t ddsDataSize,
00024     _Out_opt_ ID3D11Resource** texture,
00025     _Out_opt_ ID3D11ShaderResourceView** textureView,
00026     _In_ size_t maxsize = 0
00027     );
Generated on Sat Nov 23 2024 16:08:11 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Design Member List

This is the complete list of members for Design, including all inherited members.
__pad0__ | Design |
AcceptChildNode(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^childXmlNode) override | Design | [virtual]
AddChild(_In_ Element^element) | Element |
AddSibling(_In_ Element^element) | Element |
BindResource(_In_ Element^rootElement) | Element | [virtual]
Create(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^xmlNode) | Element | [static]
Draw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
GetFirstChild() | Element | [inline]
GetName() | Element | [inline]
GetNextSibling() | Element | [inline]
GetOpacity() | Element | [inline, virtual]
GetPageSize() | Design | [inline]
GetParent() | Element | [inline]
GetSize() | Element | [inline]
Initialize(_In_ Document^document, _In_ Windows::Data::Xml::Dom::XmlElement^xmlElement) override | Design | [virtual]
m_pageSize | Design | [private]
Measure(_In_ Document^document, D2D1_SIZE_F const &parentSize, _Out_ D2D1_RECT_F *bounds) | Element | [virtual]
PrepareToDraw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
ReleaseParent() | Element | [virtual]
Generated on Sat Nov 23 2024 16:09:11 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Touch hit testing/C++/SampleOverlay.h Source File

  • Input Touch hit testing

SampleOverlay.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 "DirectXSample.h"
00011
00012 // This class is responsible for initializing and rendering the title overlay visible
00013 // at the top of the DirectX SDK samples.
00014 ref class SampleOverlay
00015 {
00016 internal:
00017     SampleOverlay();
00018
00019     void Initialize(
00020         _In_ ID2D1Device*         d2dDevice,
00021         _In_ ID2D1DeviceContext*  d2dContext,
00022         _In_ IWICImagingFactory*  wicFactory,
00023         _In_ IDWriteFactory*      dwriteFactory,
00024         _In_ Platform::String^    caption
00025         );
00026
00027     void ResetDirectXResources();
00028
00029     void UpdateForWindowSizeChange();
00030
00031     void Render();
00032
00033     float GetTitleHeightInDips();
00034
00035 private:
00036
00037     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00038     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00039     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00040     Microsoft::WRL::ComPtr<IDWriteFactory>          m_dwriteFactory;
00041     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_whiteBrush;
00042     Microsoft::WRL::ComPtr<ID2D1DrawingStateBlock>  m_stateBlock;
00043
00044     Microsoft::WRL::ComPtr<IWICImagingFactory>      m_wicFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Bitmap>             m_logoBitmap;
00046     Microsoft::WRL::ComPtr<IDWriteTextLayout>       m_textLayout;
00047
00048     UINT                                            m_idIncrement;
00049     bool                                            m_drawOverlay;
00050     Platform::String^                               m_sampleName;
00051     float                                           m_padding;
00052     float                                           m_textVerticalOffset;
00053     D2D1_SIZE_F                                     m_logoSize;
00054     float                                           m_overlayWidth;
00055 };
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML high contrast style/C++/TargetButton.xaml.cpp Source File

  • XAML high contrast style

TargetButton.xaml.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // TargetButton.xaml.cpp
00003 // Implementation of the TargetButton class
00004 //
00005
00006 #include "pch.h"
00007 #include "TargetButton.xaml.h"
00008
00009 using namespace SDKSample::HighContrast;
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 TargetButton::TargetButton()
00025 {
00026   InitializeComponent();
00027 }
00028
00029 /// <summary>
00030 /// Invoked when this page is about to be displayed in a Frame.
00031 /// </summary>
00032 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00033 /// property is typically used to configure the page.</param>
00034 void TargetButton::OnNavigatedTo(NavigationEventArgs^ e)
00035 {
00036   (void) e; // Unused parameter
00037 }
00038
00039 void TargetButton::OnApplyTemplate()
00040 {
00041            Windows::UI::Xaml::Controls::Button::OnApplyTemplate();
00042
00043             // Apply correct coloring when in High Contrast
00044
00045             Windows::UI::ViewManagement::AccessibilitySettings^ accessibilitySettings = ref new Windows::UI::ViewManagement::AccessibilitySettings;
00046             if (!(accessibilitySettings->HighContrast) /*Off*/)
00047             {
00048                 // Use default colors
00049
00050                 Background = ref new SolidColorBrush(Windows::UI::Colors::Red);
00051                 BorderBrush = ref new SolidColorBrush(Windows::UI::Colors::Black);
00052
00053         Circle4->Fill = ref new SolidColorBrush(Windows::UI::Colors::Blue);
00054                 Circle3->Fill = ref new SolidColorBrush(Windows::UI::Colors::Green);
00055                 Circle2->Fill = ref new SolidColorBrush(Windows::UI::Colors::Yellow);
00056                 Circle1->Fill = ref new SolidColorBrush(Windows::UI::Colors::White);
00057
00058                 Circle4->Stroke = ref new SolidColorBrush(Windows::UI::Colors::Black);
00059         Circle3->Stroke = ref new SolidColorBrush(Windows::UI::Colors::Black);
00060         Circle2->Stroke = ref new SolidColorBrush(Windows::UI::Colors::Black);
00061         Circle1->Stroke = ref new SolidColorBrush(Windows::UI::Colors::Black);
00062             }
00063             else
00064             {
00065                 // Use High Contrast Colors
00066
00067                 Windows::UI::ViewManagement::UISettings^ uiSettings = ref new Windows::UI::ViewManagement::UISettings;
00068
00069         Platform::String^ strBlackScheme = "High Contrast Black";
00070         Platform::String^ strWhiteScheme = "High Contrast White";
00071
00072         if(accessibilitySettings->HighContrastScheme->Equals(strBlackScheme))
00073         {
00074            Background = ref new SolidColorBrush(Windows::UI::Colors::Black);
00075            Circle4->Fill  = ref new SolidColorBrush(Windows::UI::Colors::Black);
00076            Circle3->Fill = ref new SolidColorBrush(Windows::UI::Colors::Black);
00077            Circle2->Fill = ref new SolidColorBrush(Windows::UI::Colors::Black);
00078            Circle1->Fill = ref new SolidColorBrush(Windows::UI::Colors::Black);
00079
00080            BorderBrush = ref new SolidColorBrush(Windows::UI::Colors::White);
00081            Circle4->Stroke  = ref new SolidColorBrush(Windows::UI::Colors::White);
00082            Circle3->Stroke = ref new SolidColorBrush(Windows::UI::Colors::White);
00083            Circle2->Stroke = ref new SolidColorBrush(Windows::UI::Colors::White);
00084            Circle1->Stroke = ref new SolidColorBrush(Windows::UI::Colors::White);
00085         }
00086         else if(accessibilitySettings->HighContrastScheme->Equals(strWhiteScheme))
00087         {
00088            Background = ref new SolidColorBrush(Windows::UI::Colors::White);
00089            Circle4->Fill  = ref new SolidColorBrush(Windows::UI::Colors::White);
00090            Circle3->Fill = ref new SolidColorBrush(Windows::UI::Colors::White);
00091            Circle2->Fill = ref new SolidColorBrush(Windows::UI::Colors::White);
00092            Circle1->Fill = ref new SolidColorBrush(Windows::UI::Colors::White);
00093
00094            BorderBrush = ref new SolidColorBrush(Windows::UI::Colors::Black);
00095            Circle4->Stroke  = ref new SolidColorBrush(Windows::UI::Colors::Black);
00096            Circle3->Stroke = ref new SolidColorBrush(Windows::UI::Colors::Black);
00097            Circle2->Stroke = ref new SolidColorBrush(Windows::UI::Colors::Black);
00098            Circle1->Stroke = ref new SolidColorBrush(Windows::UI::Colors::Black);
00099         }
00100         else
00101         {
00102               Background = ref new SolidColorBrush(uiSettings->UIElementColor( Windows::UI::ViewManagement::UIElementType::ButtonFace));
00103                         BorderBrush = ref new SolidColorBrush(uiSettings->UIElementColor( Windows::UI::ViewManagement::UIElementType::ButtonText));
00104                         Circle4->Fill = ref new SolidColorBrush(uiSettings->UIElementColor(Windows::UI::ViewManagement::UIElementType::Hotlight));
00105                         Circle3->Fill = ref new SolidColorBrush(uiSettings->UIElementColor(Windows::UI::ViewManagement::UIElementType::Hotlight));
00106                         Circle2->Fill  = ref new SolidColorBrush(uiSettings->UIElementColor(Windows::UI::ViewManagement::UIElementType::Hotlight));
00107                         Circle1->Fill = ref new SolidColorBrush(uiSettings->UIElementColor(Windows::UI::ViewManagement::UIElementType::Hotlight));
00108
00109             Circle4->Stroke = ref new SolidColorBrush(uiSettings->UIElementColor(Windows::UI::ViewManagement::UIElementType::HighlightText));
00110                         Circle3->Stroke = ref new SolidColorBrush(uiSettings->UIElementColor(Windows::UI::ViewManagement::UIElementType::HighlightText));
00111                         Circle2->Stroke  = ref new SolidColorBrush(uiSettings->UIElementColor(Windows::UI::ViewManagement::UIElementType::HighlightText));
00112                         Circle1->Stroke = ref new SolidColorBrush(uiSettings->UIElementColor(Windows::UI::ViewManagement::UIElementType::HighlightText));
00113         }
00114
00115             }
00116         }
Generated on Sat Nov 23 2024 16:08:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

ContactPicker::sealed::SampleContact Member List

This is the complete list of members for ContactPicker::sealed::SampleContact, including all inherited members.
Address | ContactPicker::sealed::SampleContact
City | ContactPicker::sealed::SampleContact
HomeEmail | ContactPicker::sealed::SampleContact
HomePhone | ContactPicker::sealed::SampleContact
Id | ContactPicker::sealed::SampleContact
MobilePhone | ContactPicker::sealed::SampleContact
Name | ContactPicker::sealed::SampleContact
State | ContactPicker::sealed::SampleContact
Street | ContactPicker::sealed::SampleContact
WorkEmail | ContactPicker::sealed::SampleContact
WorkPhone | ContactPicker::sealed::SampleContact
ZipCode | ContactPicker::sealed::SampleContact
Generated on Sat Nov 23 2024 16:09:36 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Audio Session (WASAPI)/C++/App.xaml.cpp Source File

  • Windows Audio Session (WASAPI)
  • C++

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:28 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D tutorial/C++/Lesson5.Components/DirectXApp.cpp Source File

  • Direct3D tutorial
  • Lesson5.Components

DirectXApp.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 "DirectXApp.h"
00010 #include "BasicTimer.h"
00011
00012 using namespace Windows::ApplicationModel;
00013 using namespace Windows::ApplicationModel::Core;
00014 using namespace Windows::ApplicationModel::Activation;
00015 using namespace Windows::UI::Core;
00016 using namespace Windows::System;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Graphics::Display;
00019
00020 DirectXApp::DirectXApp() :
00021     m_windowClosed(false),
00022     m_windowVisible(true)
00023 {
00024 }
00025
00026 void DirectXApp::Initialize(
00027     _In_ CoreApplicationView^ applicationView
00028     )
00029 {
00030     applicationView->Activated +=
00031         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &DirectXApp::OnActivated);
00032
00033     m_renderer = ref new Direct3DTutorial();
00034 }
00035
00036 void DirectXApp::SetWindow(
00037     _In_ CoreWindow^ window
00038     )
00039 {
00040     window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
00041
00042     window->SizeChanged +=
00043         ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &DirectXApp::OnWindowSizeChanged);
00044
00045     window->VisibilityChanged +=
00046         ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &DirectXApp::OnVisibilityChanged);
00047
00048     window->Closed +=
00049         ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &DirectXApp::OnWindowClosed);
00050
00051     DisplayProperties::LogicalDpiChanged +=
00052         ref new DisplayPropertiesEventHandler(this, &DirectXApp::OnLogicalDpiChanged);
00053
00054     m_renderer->Initialize(window, DisplayProperties::LogicalDpi);
00055 }
00056
00057 void DirectXApp::Load(
00058     _In_ Platform::String^ entryPoint
00059     )
00060 {
00061 }
00062
00063 void DirectXApp::Run()
00064 {
00065     BasicTimer^ timer = ref new BasicTimer();
00066
00067     while (!m_windowClosed)
00068     {
00069         if (m_windowVisible)
00070         {
00071             timer->Update();
00072             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
00073             m_renderer->Update(timer->Total, timer->Delta);
00074             m_renderer->Render();
00075             m_renderer->Present(); // This call is synchronized to the display frame rate.
00076         }
00077         else
00078         {
00079             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
00080         }
00081     }
00082 }
00083
00084 void DirectXApp::Uninitialize()
00085 {
00086 }
00087
00088 void DirectXApp::OnWindowSizeChanged(
00089     _In_ CoreWindow^ sender,
00090     _In_ WindowSizeChangedEventArgs^ args
00091     )
00092 {
00093     m_renderer->UpdateForWindowSizeChange();
00094 }
00095
00096 void DirectXApp::OnVisibilityChanged(
00097     _In_ CoreWindow^ sender,
00098     _In_ VisibilityChangedEventArgs^ args
00099     )
00100 {
00101     m_windowVisible = args->Visible;
00102 }
00103
00104 void DirectXApp::OnWindowClosed(
00105     _In_ CoreWindow^ sender,
00106     _In_ CoreWindowEventArgs^ args
00107     )
00108 {
00109     m_windowClosed = true;
00110 }
00111
00112 void DirectXApp::OnLogicalDpiChanged(
00113     _In_ Platform::Object^ sender
00114     )
00115 {
00116     m_renderer->SetDpi(DisplayProperties::LogicalDpi);
00117 }
00118
00119 void DirectXApp::OnActivated(
00120     _In_ CoreApplicationView^ applicationView,
00121     _In_ IActivatedEventArgs^ args
00122     )
00123 {
00124     CoreWindow::GetForCurrentThread()->Activate();
00125 }
00126
00127 IFrameworkView^ DirectXAppSource::CreateView()
00128 {
00129     return ref new DirectXApp();
00130 }
00131
00132 [Platform::MTAThread]
00133 int main(Platform::Array<Platform::String^>^)
00134 {
00135     auto directXAppSource = ref new DirectXAppSource();
00136     CoreApplication::Run(directXAppSource);
00137     return 0;
00138 }
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DatagramSocket/C++/App.xaml.h Source File

  • DatagramSocket

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace DatagramSocketSample
00023 {
00024     [Windows::Foundation::Metadata::WebHostHidden]
00025     ref class App sealed
00026     {
00027     internal:
00028         App();
00029     public:
00030         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00031         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Accelerometer sensor/C++/pch.cpp Source File

  • Accelerometer sensor

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 Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CryptoWinRT/C++/Scenario1.xaml.cpp Source File

  • CryptoWinRT

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::CryptoWinRT;
00020
00021 using namespace Platform;
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::Navigation;
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 void SDKSample::CryptoWinRT::Scenario1::RunSample_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00046 {
00047     Scenario1Text->Text = "";
00048     IBuffer^ buffer;
00049
00050     // Initialize example data.
00051     Array<byte>^ ByteArray = ref new Array<byte>(12);
00052     for(UINT32 i = 0; i < ByteArray->Length; i++)
00053         ByteArray[i] = i;
00054
00055     String^ base64String = "uiwyeroiugfyqcajkds897945234==";
00056     String^ hexString = "30313233";
00057     String^ inputString = "Input string";
00058
00059     // Generate random bytes.
00060     buffer = CryptographicBuffer::GenerateRandom(32);
00061     Scenario1Text->Text += "GenerateRandom\n";
00062     Scenario1Text->Text += "  Buffer: " + CryptographicBuffer::EncodeToHexString(buffer) + "\n\n";
00063
00064     // Convert from a byte array.
00065     buffer = CryptographicBuffer::CreateFromByteArray(ByteArray);
00066     Scenario1Text->Text += "CreateFromByteArray\n";
00067     Scenario1Text->Text += "  Buffer: " + CryptographicBuffer::EncodeToHexString(buffer) + "\n\n";
00068
00069     // Decode a Base64 encoded string to binary.
00070     buffer = CryptographicBuffer::DecodeFromBase64String(base64String);
00071     Scenario1Text->Text += "DecodeFromBase64String\n";
00072     Scenario1Text->Text += "  Base64 String: " + base64String + "\n";
00073     Scenario1Text->Text += "  Buffer:        " + CryptographicBuffer::EncodeToHexString(buffer) + "\n\n";
00074
00075     // Decode a hexadecimal string to binary.
00076     buffer = CryptographicBuffer::DecodeFromHexString(hexString);
00077     Scenario1Text->Text += "DecodeFromHexString\n";
00078     Scenario1Text->Text += "  Hex String: " + hexString + "\n";
00079     Scenario1Text->Text += "  Buffer:     " + CryptographicBuffer::EncodeToHexString(buffer) + "\n\n";
00080
00081     // Convert a string to UTF16BE binary data.
00082     buffer = CryptographicBuffer::ConvertStringToBinary(inputString, BinaryStringEncoding::Utf16BE);
00083     Scenario1Text->Text += "ConvertStringToBinary (Utf16BE)\n";
00084     Scenario1Text->Text += "  String: " + inputString + "\n";
00085     Scenario1Text->Text += "  Buffer: " + CryptographicBuffer::EncodeToHexString(buffer) + "\n\n";
00086
00087     // Convert a string to UTF16LE binary data.
00088     buffer = CryptographicBuffer::ConvertStringToBinary(inputString, BinaryStringEncoding::Utf16LE);
00089     Scenario1Text->Text += "ConvertStringToBinary (Utf16LE)\n";
00090     Scenario1Text->Text += "  String: " + inputString + "\n";
00091     Scenario1Text->Text += "  Buffer: " + CryptographicBuffer::EncodeToHexString(buffer) + "\n\n";
00092
00093     // Convert a string to UTF8 binary data.
00094     buffer = CryptographicBuffer::ConvertStringToBinary(inputString, BinaryStringEncoding::Utf8);
00095     Scenario1Text->Text += "ConvertStringToBinary (Utf8)\n";
00096     Scenario1Text->Text += "  String: " + inputString + "\n";
00097     Scenario1Text->Text += "  Buffer: " + CryptographicBuffer::EncodeToHexString(buffer) + "\n\n";
00098
00099     // Decode from a Base64 encoded string.
00100     buffer = CryptographicBuffer::DecodeFromBase64String(base64String);
00101     Scenario1Text->Text += "DecodeFromBase64String \n";
00102     Scenario1Text->Text += "  String: " + base64String + "\n";
00103     Scenario1Text->Text += "  Buffer (Hex): " + CryptographicBuffer::EncodeToHexString(buffer) + "\n\n";
00104     Scenario1Text->Text += "  Buffer (Base64): " + CryptographicBuffer::EncodeToBase64String(buffer) + "\n\n";
00105
00106     // Decode from a hexadecimal encoded string.
00107     buffer = CryptographicBuffer::DecodeFromHexString(hexString);
00108     Scenario1Text->Text += "DecodeFromHexString \n";
00109     Scenario1Text->Text += "  String: " + hexString + "\n";
00110     Scenario1Text->Text += "  Buffer: " + CryptographicBuffer::EncodeToHexString(buffer) + "\n\n";
00111 }
Generated on Sat Nov 23 2024 16:07:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playlist/C++/Clear.xaml.cpp Source File

  • Playlist

Clear.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 // Clear.xaml.cpp
00013 // Implementation of the Clear class
00014 //
00015
00016 #include "pch.h"
00017 #include "Clear.xaml.h"
00018
00019 using namespace SDKSample::Playlists;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 Clear::Clear()
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 Clear::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 Clear::PickPlaylistButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00043 {
00044     // Make sure app is unsnapped before invoking the file picker
00045     if(!MainPage::EnsureUnsnapped())
00046     {
00047         OutputStatus->Text = "Unable to unsnap the app.";
00048         return;
00049     }
00050
00051     MainPage::PickPlaylist().then([this](task<Playlist^> playlistTask)
00052     {
00053         try
00054         {
00055             MainPage::playlist = playlistTask.get();
00056
00057             if (MainPage::playlist != nullptr)
00058             {
00059                 // Clear playlist.
00060                 MainPage::playlist->Files->Clear();
00061                 task<void>(MainPage::playlist->SaveAsync()).then([this]()
00062                 {
00063                     OutputStatus->Text = "Playlist cleared.";
00064                 });
00065             }
00066         }
00067         catch (NullReferenceException^ ex)
00068         {
00069             OutputStatus->Text = "No playlist picked.";
00070         }
00071         catch(AccessDeniedException^ ex)
00072         {
00073             OutputStatus->Text = "Access is denied, cannot load playlist.";
00074         }
00075     });
00076 }
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: StreamSocket/C++/sample-utils/CppSamplesUtils.h Source File

  • StreamSocket
  • sample-utils

CppSamplesUtils.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 <string>
00014 #include <sstream>
00015 #include <algorithm>
00016 #include <collection.h>
00017 #include <ppltasks.h>
00018
00019 namespace CppSamplesUtils
00020 {
00021     namespace Details
00022     {
00023         static Windows::Foundation::Collections::PropertySet^ sessionState = nullptr;
00024         static Platform::String^ sessionStateFileName = ref new Platform::String(L"_cppSessionState.xml");
00025
00026         concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file);
00027         concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file);
00028     }
00029
00030     class SuspensionManager
00031     {
00032     public:
00033         static Windows::Foundation::Collections::PropertySet^ SessionState()
00034         {
00035             using namespace Windows::Foundation::Collections;
00036             using namespace Details;
00037
00038             if (sessionState == nullptr)
00039             {
00040                 sessionState = ref new PropertySet();
00041             }
00042             return sessionState;
00043         }
00044
00045         static concurrency::task<void> StartRestoreTask()
00046         {
00047             using namespace Windows::Foundation;
00048             using namespace Windows::Storage;
00049             using namespace Windows::Storage::Streams;
00050             using namespace Details;
00051
00052             auto state = SessionState();
00053             state->Clear();
00054
00055             concurrency::task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFileName));
00056             return getFileTask.then([=](StorageFile^ file)
00057             {
00058                 return DeserializeSessionState(file);
00059             });
00060         }
00061
00062         static concurrency::task<void> StartSaveTask()
00063         {
00064             using namespace Windows::Foundation;
00065             using namespace Windows::Storage;
00066             using namespace Windows::Storage::Streams;
00067             using namespace Details;
00068
00069             concurrency::task<StorageFile^> createFileTask(ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFileName, CreationCollisionOption::ReplaceExisting));
00070             return createFileTask.then([=](StorageFile^ file)
00071             {
00072                 return SerializeSessionState(file);
00073             });
00074         }
00075     };
00076
00077     namespace Details
00078     {
00079         template <class T>
00080         inline Platform::String^ ToString(T value)
00081         {
00082             std::wstringstream wss;
00083             wss << value;
00084             return ref new Platform::String(wss.str().c_str());
00085         }
00086
00087         template <class T>
00088         inline T FromStringTo(Platform::String^ str)
00089         {
00090             std::wistringstream wiss(str->Data());
00091             T value = 0;
00092             wiss >> value;
00093             return value;
00094         }
00095
00096         template <class T>
00097         inline T FromHexStringTo(Platform::String^ str)
00098         {
00099             std::wistringstream wiss(str->Data());
00100             T value = 0;
00101             wiss >> std::hex >> value;
00102             return value;
00103         }
00104
00105         template <>
00106         inline Platform::Guid FromStringTo<Platform::Guid>(Platform::String^ str)
00107         {
00108             using namespace Platform;
00109
00110             if (str->Length() != 38)
00111             {
00112                 throw ref new InvalidArgumentException;
00113             }
00114             std::wstring ws(str->Data());
00115             if (ws[0] != L'{' || ws[37] != L'}' || ws[9] != L'-' || ws[14] != L'-' || ws[19] != L'-' || ws[24] != L'-')
00116             {
00117                 throw ref new InvalidArgumentException;
00118             }
00119             ws[0] = ws[37] = ws[9] = ws[14] = ws[19] =ws[24] = L' ';
00120             std::wistringstream wiss(ws);
00121             unsigned int a = 0;
00122             unsigned short b = 0;
00123             unsigned short c = 0;
00124             unsigned short d = 0;
00125             unsigned long long e = 0;
00126             static_assert(sizeof(d) == sizeof(char) * 2, "sizeof(d) == sizeof(char) * 2");
00127             static_assert(sizeof(e) == sizeof(char) * 8, "sizeof(e) == sizeof(char) * 8");
00128             wiss >> std::hex >> a >> b >> c >> d >> e;
00129             unsigned char *ad = (unsigned char*)(&d);
00130             unsigned char *ae = (unsigned char*)(&e);
00131             return Platform::Guid(a, b, c, ad[1], ad[0], ae[5], ae[4], ae[3], ae[2], ae[1], ae[0]);
00132         }
00133
00134         inline Platform::Object^ ConvertStringToObject(Windows::Foundation::PropertyType type, Platform::String^ str)
00135         {
00136             using namespace Platform;
00137             using namespace Windows::Foundation;
00138
00139             if (type == PropertyType::String)
00140             {
00141                 return PropertyValue::CreateString(str);
00142             }
00143
00144             switch (type)
00145             {
00146             case PropertyType::UInt8:
00147                 return PropertyValue::CreateUInt8((unsigned char)FromStringTo<unsigned short>(str));
00148             case PropertyType::UInt16:
00149                 return PropertyValue::CreateUInt16(FromStringTo<unsigned short>(str));
00150             case PropertyType::UInt32:
00151                 return PropertyValue::CreateUInt32(FromStringTo<unsigned int>(str));
00152             case PropertyType::UInt64:
00153                 return PropertyValue::CreateUInt64(FromStringTo<unsigned long long>(str));
00154             case PropertyType::Int16:
00155                 return PropertyValue::CreateInt16(FromStringTo<short>(str));
00156             case PropertyType::Int32:
00157                 return PropertyValue::CreateInt32(FromStringTo<int>(str));
00158             case PropertyType::Int64:
00159                 return PropertyValue::CreateInt64(FromStringTo<long long>(str));
00160             case PropertyType::Single:
00161                 return PropertyValue::CreateSingle(FromStringTo<float>(str));
00162             case PropertyType::Double:
00163                 return PropertyValue::CreateDouble(FromStringTo<double>(str));
00164             case PropertyType::Boolean:
00165                 return PropertyValue::CreateBoolean(FromStringTo<bool>(str));
00166             case PropertyType::Char16:
00167                 return PropertyValue::CreateChar16(str->Data()[0]);
00168             case PropertyType::Guid:
00169                 return PropertyValue::CreateGuid(FromStringTo<Guid>(str));
00170             default:
00171                 throw ref new Platform::InvalidCastException;
00172             }
00173         }
00174
00175         inline Platform::String^ ConvertPropertyValueToString(Windows::Foundation::IPropertyValue^ pv)
00176         {
00177             using namespace Platform;
00178             using namespace Windows::Foundation;
00179
00180             String^ valueString;
00181
00182             switch (pv->Type)
00183             {
00184             case PropertyType::String:
00185                 valueString = pv->GetString();
00186                 break;
00187
00188             case PropertyType::UInt8:
00189             case PropertyType::UInt16:
00190             case PropertyType::UInt32:
00191             case PropertyType::UInt64:
00192                 valueString = ToString(pv->GetUInt64());
00193                 break;
00194
00195             case PropertyType::Int16:
00196             case PropertyType::Int32:
00197             case PropertyType::Int64:
00198                 valueString = ToString(pv->GetInt64());
00199                 break;
00200
00201             case PropertyType::Single:
00202                 valueString = ToString(pv->GetSingle());
00203                 break;
00204
00205             case PropertyType::Double:
00206                 valueString = ToString(pv->GetDouble());
00207                 break;
00208
00209             case PropertyType::Boolean:
00210                 valueString = ToString(pv->GetBoolean());
00211                 break;
00212
00213             case PropertyType::Char16:
00214                 wchar_t buffer[2];
00215                 buffer[0] = pv->GetChar16();
00216                 buffer[1] = 0;
00217                 valueString = ref new String(buffer);
00218                 break;
00219
00220             case PropertyType::Guid:
00221                 valueString = pv->GetGuid().ToString();
00222                 break;
00223
00224             default:
00225                 throw ref new InvalidCastException;
00226             }
00227
00228             return valueString;
00229         }
00230
00231         inline Windows::Data::Xml::Dom::XmlElement^ CreateXmlElementFromObject(Windows::Data::Xml::Dom::XmlDocument^ doc, Platform::String^ name, Platform::Object^ value)
00232         {
00233             using namespace Platform;
00234             using namespace Windows::Foundation;
00235             using namespace Windows::Data::Xml::Dom;
00236
00237             XmlElement^ element = doc->CreateElement("item");
00238             element->SetAttribute("name", name);
00239
00240             IPropertyValue^ pv = (IPropertyValue^)value;
00241             element->SetAttribute("type", ToString((int)pv->Type));
00242             element->SetAttribute("value", ConvertPropertyValueToString(pv));
00243
00244             return element;
00245         }
00246
00247         inline concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file)
00248         {
00249             using namespace Windows::Data::Xml::Dom;
00250             using namespace Windows::Foundation;
00251             namespace WFC = Windows::Foundation::Collections;
00252             typedef Windows::Foundation::Collections::IKeyValuePair<Platform::String^, Platform::Object^> KVPair;
00253
00254             XmlDocument^ doc = ref new XmlDocument;
00255             doc->AppendChild(doc->CreateElement("items"));
00256             auto sessionState = SuspensionManager::SessionState();
00257
00258             std::for_each(WFC::begin(sessionState), WFC::end(sessionState), [doc](KVPair^ item)
00259             {
00260                 doc->DocumentElement->AppendChild(CreateXmlElementFromObject(doc, item->Key, item->Value));
00261             });
00262
00263             return concurrency::task<void>(doc->SaveToFileAsync(file));
00264         }
00265
00266         inline Windows::Foundation::PropertyType PropertyTypeFromString(Platform::String^ str)
00267         {
00268             int value = FromStringTo<int>(str);
00269             return (Windows::Foundation::PropertyType)value;
00270         }
00271
00272         inline concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file)
00273         {
00274             using namespace Platform;
00275             using namespace Windows::Foundation;
00276             using namespace Windows::Data::Xml::Dom;
00277             namespace WFC = Windows::Foundation::Collections;
00278
00279             concurrency::task<XmlDocument^> loadFileTask(XmlDocument::LoadFromFileAsync(file));
00280             return loadFileTask.then([=](concurrency::task<XmlDocument^> docTask)
00281             {
00282                 try
00283                 {
00284                     auto doc = docTask.get();
00285                     auto items = doc->SelectNodes("/items/item");
00286                     auto sessionState = SuspensionManager::SessionState();
00287
00288                     std::for_each(WFC::begin(items), WFC::end(items), [sessionState](IXmlNode^ node)
00289                     {
00290                         auto element = (IXmlElement^)node;
00291                         String^ name = element->GetAttribute("name");
00292                         String^ value = element->GetAttribute("value");
00293                         PropertyType type = PropertyTypeFromString(element->GetAttribute("type"));
00294
00295                         Object^ valueObject = ConvertStringToObject(type, value);
00296                         sessionState->Insert(name, valueObject);
00297                     });
00298
00299                 }
00300                 catch (Platform::Exception^)
00301                 {
00302                     // Restoring is best effort
00303                 }
00304             });
00305         }
00306     } // namespace Details
00307 } // namespace CppSamplesUtils
Generated on Sat Nov 23 2024 16:07:54 for Win8-Examples by doxygen 1.7.1


Win8-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]
_Acquires_lock_(m_criticalSection) void Lock() | CritSec | [inline]
_Acquires_lock_(m_criticalSection) void Lock() | CritSec | [inline]
_Releases_lock_(m_criticalSection) void Unlock() | CritSec | [inline]
_Releases_lock_(m_criticalSection) void Unlock() | CritSec | [inline]
_Releases_lock_(m_criticalSection) void Unlock() | CritSec | [inline]
CritSec() | CritSec | [inline]
CritSec() | CritSec | [inline]
CritSec() | CritSec | [inline]
m_criticalSection | CritSec |
~CritSec() | CritSec | [inline]
~CritSec() | CritSec | [inline]
~CritSec() | CritSec | [inline]
Generated on Sat Nov 23 2024 16:09:10 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Association launching/C++/ReceiveUriInput.xaml.h Source File

  • Association launching

ReceiveUriInput.xaml.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 // ReceiveUriInput.xaml.h
00009 // Declaration of the ReceiveUriInput class.
00010 //
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "ReceiveUriInput.g.h"
00016 #include "MainPage.xaml.h"
00017
00018 using namespace Windows::UI::Xaml;
00019
00020 namespace AssociationLaunching
00021 {
00022   [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class ReceiveUriInput sealed
00024     {
00025     public:
00026         ReceiveUriInput();
00027
00028     protected:
00029         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030
00031     private:
00032         ~ReceiveUriInput();
00033         MainPage^ rootPage;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:57 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D sprite/C++/DirectXBase.cpp Source File

  • Direct3D sprite

DirectXBase.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 "DirectXBase.h"
00010
00011 using namespace Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::Graphics::Display;
00015 using namespace D2D1;
00016
00017 // Constructor.
00018 DirectXBase::DirectXBase() :
00019     m_windowSizeChangeInProgress(false),
00020     m_dpi(-1.0f)
00021 {
00022 }
00023
00024 // Initialize the DirectX resources required to run.
00025 void DirectXBase::Initialize(CoreWindow^ window, float dpi)
00026 {
00027     m_window = window;
00028
00029     CreateDeviceIndependentResources();
00030     CreateDeviceResources();
00031     SetDpi(dpi);
00032 }
00033
00034 // Recreate all device resources and set them back to the current state.
00035 void DirectXBase::HandleDeviceLost()
00036 {
00037     // Reset these member variables to ensure that SetDpi recreates all resources.
00038     float dpi = m_dpi;
00039     m_dpi = -1.0f;
00040     m_windowBounds.Width = 0;
00041     m_windowBounds.Height = 0;
00042     m_swapChain = nullptr;
00043
00044     CreateDeviceResources();
00045     SetDpi(dpi);
00046 }
00047
00048 // These are the resources required independent of the device.
00049 void DirectXBase::CreateDeviceIndependentResources()
00050 {
00051     D2D1_FACTORY_OPTIONS options;
00052     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00053
00054 #if defined(_DEBUG)
00055     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00056     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00057 #endif
00058
00059     DX::ThrowIfFailed(
00060         D2D1CreateFactory(
00061             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00062             __uuidof(ID2D1Factory1),
00063             &options,
00064             &m_d2dFactory
00065             )
00066         );
00067
00068     DX::ThrowIfFailed(
00069         DWriteCreateFactory(
00070             DWRITE_FACTORY_TYPE_SHARED,
00071             __uuidof(IDWriteFactory),
00072             &m_dwriteFactory
00073             )
00074         );
00075
00076     DX::ThrowIfFailed(
00077         CoCreateInstance(
00078             CLSID_WICImagingFactory,
00079             nullptr,
00080             CLSCTX_INPROC_SERVER,
00081             IID_PPV_ARGS(&m_wicFactory)
00082             )
00083         );
00084 }
00085
00086 // These are the resources that depend on the device.
00087 void DirectXBase::CreateDeviceResources()
00088 {
00089     // This flag adds support for surfaces with a different color channel ordering
00090     // than the API default. It is required for compatibility with Direct2D.
00091     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00092     ComPtr<IDXGIDevice> dxgiDevice;
00093
00094 #if defined(_DEBUG)
00095     // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00096     creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00097 #endif
00098
00099     // This array defines the set of DirectX hardware feature levels this app will support.
00100     // Note the ordering should be preserved.
00101     // Don't forget to declare your application's minimum required feature level in its
00102     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00103     D3D_FEATURE_LEVEL featureLevels[] =
00104     {
00105         D3D_FEATURE_LEVEL_11_1,
00106         D3D_FEATURE_LEVEL_11_0,
00107         D3D_FEATURE_LEVEL_10_1,
00108         D3D_FEATURE_LEVEL_10_0,
00109         D3D_FEATURE_LEVEL_9_3,
00110         D3D_FEATURE_LEVEL_9_2,
00111         D3D_FEATURE_LEVEL_9_1
00112     };
00113
00114     // Create the Direct3D 11 API device object and a corresponding context.
00115     ComPtr<ID3D11Device> device;
00116     ComPtr<ID3D11DeviceContext> context;
00117     DX::ThrowIfFailed(
00118         D3D11CreateDevice(
00119             nullptr,                    // Specify nullptr to use the default adapter.
00120             D3D_DRIVER_TYPE_HARDWARE,
00121             0,
00122             creationFlags,              // Set debug and Direct2D compatibility flags.
00123             featureLevels,              // List of feature levels this app can support.
00124             ARRAYSIZE(featureLevels),
00125             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Metro style apps.
00126             &device,                    // Returns the Direct3D device created.
00127             &m_featureLevel,            // Returns feature level of device created.
00128             &context                    // Returns the device immediate context.
00129             )
00130         );
00131
00132     // Get the Direct3D 11.1 API device and context interfaces.
00133     DX::ThrowIfFailed(
00134         device.As(&m_d3dDevice)
00135         );
00136
00137     DX::ThrowIfFailed(
00138         context.As(&m_d3dContext)
00139         );
00140
00141     // Get the underlying DXGI device of the Direct3D device.
00142     DX::ThrowIfFailed(
00143         m_d3dDevice.As(&dxgiDevice)
00144         );
00145
00146     // Create the Direct2D device object and a corresponding context.
00147     DX::ThrowIfFailed(
00148         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00149         );
00150
00151     DX::ThrowIfFailed(
00152         m_d2dDevice->CreateDeviceContext(
00153             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00154             &m_d2dContext
00155             )
00156         );
00157 }
00158
00159 // Helps track the DPI in the helper class.
00160 // This is called in the dpiChanged event handler in the view class.
00161 void DirectXBase::SetDpi(float dpi)
00162 {
00163     if (dpi != m_dpi)
00164     {
00165         // Save the DPI of this display in our class.
00166         m_dpi = dpi;
00167
00168         // Update Direct2D's stored DPI.
00169         m_d2dContext->SetDpi(m_dpi, m_dpi);
00170
00171         // Often a DPI change implies a window size change. In some cases Windows will issue
00172         // both a size changed event and a DPI changed event. In this case, the resulting bounds
00173         // will not change, and the window resize code will only be executed once.
00174         UpdateForWindowSizeChange();
00175     }
00176 }
00177
00178 // This routine is called in the event handler for the view SizeChanged event.
00179 void DirectXBase::UpdateForWindowSizeChange()
00180 {
00181     // Only handle window size changed if there is no pending DPI change.
00182     if (m_dpi != DisplayProperties::LogicalDpi)
00183     {
00184         return;
00185     }
00186
00187     if (m_window->Bounds.Width  != m_windowBounds.Width ||
00188         m_window->Bounds.Height != m_windowBounds.Height)
00189     {
00190         m_d2dContext->SetTarget(nullptr);
00191         m_d2dTargetBitmap = nullptr;
00192         m_d3dRenderTargetView = nullptr;
00193         m_d3dDepthStencilView = nullptr;
00194         m_windowSizeChangeInProgress = true;
00195         CreateWindowSizeDependentResources();
00196     }
00197 }
00198
00199 // Allocate all memory resources that change on a window SizeChanged event.
00200 void DirectXBase::CreateWindowSizeDependentResources()
00201 {
00202     // Store the window bounds so the next time we get a SizeChanged event we can
00203     // avoid rebuilding everything if the size is identical.
00204     m_windowBounds = m_window->Bounds;
00205
00206     if (m_swapChain != nullptr)
00207     {
00208         // If the swap chain already exists, resize it.
00209         HRESULT hr = m_swapChain->ResizeBuffers(2, 0, 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0);
00210
00211         if (hr == DXGI_ERROR_DEVICE_REMOVED)
00212         {
00213             // If the device was removed for any reason, a new device and swapchain will need to be created.
00214             HandleDeviceLost();
00215
00216             // Everything is set up now. Do not continue execution of this method.
00217             return;
00218         }
00219         else
00220         {
00221             DX::ThrowIfFailed(hr);
00222         }
00223     }
00224     else
00225     {
00226         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00227         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00228         swapChainDesc.Width = 0;                                     // Use automatic sizing.
00229         swapChainDesc.Height = 0;
00230         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;           // This is the most common swap chain format.
00231         swapChainDesc.Stereo = false;
00232         swapChainDesc.SampleDesc.Count = 1;                          // Don't use multi-sampling.
00233         swapChainDesc.SampleDesc.Quality = 0;
00234         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00235         swapChainDesc.BufferCount = 2;                               // Use double-buffering to minimize latency.
00236         swapChainDesc.Scaling = DXGI_SCALING_NONE;
00237         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Metro style apps must use this SwapEffect.
00238         swapChainDesc.Flags = 0;
00239
00240         ComPtr<IDXGIDevice1> dxgiDevice;
00241         DX::ThrowIfFailed(
00242             m_d3dDevice.As(&dxgiDevice)
00243             );
00244
00245         ComPtr<IDXGIAdapter> dxgiAdapter;
00246         DX::ThrowIfFailed(
00247             dxgiDevice->GetAdapter(&dxgiAdapter)
00248             );
00249
00250         ComPtr<IDXGIFactory2> dxgiFactory;
00251         DX::ThrowIfFailed(
00252             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00253             );
00254
00255         CoreWindow^ window = m_window.Get();
00256         DX::ThrowIfFailed(
00257             dxgiFactory->CreateSwapChainForCoreWindow(
00258                 m_d3dDevice.Get(),
00259                 reinterpret_cast<IUnknown*>(window),
00260                 &swapChainDesc,
00261                 nullptr,
00262                 &m_swapChain
00263                 )
00264             );
00265
00266         // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
00267         // ensures that the application will only render after each VSync, minimizing power consumption.
00268         DX::ThrowIfFailed(
00269             dxgiDevice->SetMaximumFrameLatency(1)
00270             );
00271     }
00272
00273     // Create a Direct3D render target view of the swap chain back buffer.
00274     ComPtr<ID3D11Texture2D> backBuffer;
00275     DX::ThrowIfFailed(
00276         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00277         );
00278
00279     DX::ThrowIfFailed(
00280         m_d3dDevice->CreateRenderTargetView(
00281             backBuffer.Get(),
00282             nullptr,
00283             &m_d3dRenderTargetView
00284             )
00285         );
00286
00287     // Cache the rendertarget dimensions in our helper class for convenient use.
00288     D3D11_TEXTURE2D_DESC backBufferDesc = {0};
00289     backBuffer->GetDesc(&backBufferDesc);
00290     m_renderTargetSize.Width  = static_cast<float>(backBufferDesc.Width);
00291     m_renderTargetSize.Height = static_cast<float>(backBufferDesc.Height);
00292
00293     // Create a depth stencil view for use with 3D rendering if needed.
00294     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00295         DXGI_FORMAT_D24_UNORM_S8_UINT,
00296         backBufferDesc.Width,
00297         backBufferDesc.Height,
00298         1,
00299         1,
00300         D3D11_BIND_DEPTH_STENCIL
00301         );
00302
00303     ComPtr<ID3D11Texture2D> depthStencil;
00304     DX::ThrowIfFailed(
00305         m_d3dDevice->CreateTexture2D(
00306             &depthStencilDesc,
00307             nullptr,
00308             &depthStencil
00309             )
00310         );
00311
00312     auto viewDesc = CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D);
00313     DX::ThrowIfFailed(
00314         m_d3dDevice->CreateDepthStencilView(
00315             depthStencil.Get(),
00316             &viewDesc,
00317             &m_d3dDepthStencilView
00318             )
00319         );
00320
00321     // Set the 3D rendering viewport to target the entire window.
00322     CD3D11_VIEWPORT viewport(
00323         0.0f,
00324         0.0f,
00325         static_cast<float>(backBufferDesc.Width),
00326         static_cast<float>(backBufferDesc.Height)
00327         );
00328
00329     m_d3dContext->RSSetViewports(1, &viewport);
00330
00331     // Create a Direct2D target bitmap associated with the
00332     // swap chain back buffer and set it as the current target.
00333     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00334         BitmapProperties1(
00335             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00336             PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00337             m_dpi,
00338             m_dpi
00339             );
00340
00341     ComPtr<IDXGISurface> dxgiBackBuffer;
00342     DX::ThrowIfFailed(
00343         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00344         );
00345
00346     DX::ThrowIfFailed(
00347         m_d2dContext->CreateBitmapFromDxgiSurface(
00348             dxgiBackBuffer.Get(),
00349             &bitmapProperties,
00350             &m_d2dTargetBitmap
00351             )
00352         );
00353
00354     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00355
00356     // Grayscale text anti-aliasing is recommended for all Metro style apps.
00357     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00358 }
00359
00360 // Method to deliver the final image to the display.
00361 void DirectXBase::Present()
00362 {
00363     // The application may optionally specify "dirty" or "scroll" rects to improve efficiency
00364     // in certain scenarios.  In this sample, however, we do not utilize those features.
00365     DXGI_PRESENT_PARAMETERS parameters = {0};
00366     parameters.DirtyRectsCount = 0;
00367     parameters.pDirtyRects = nullptr;
00368     parameters.pScrollRect = nullptr;
00369     parameters.pScrollOffset = nullptr;
00370
00371     // The first argument instructs DXGI to block until VSync, putting the application
00372     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00373     // frames that will never be displayed to the screen.
00374     HRESULT hr = m_swapChain->Present1(1, 0, &parameters);
00375
00376     // Discard the contents of the render target.
00377     // This is a valid operation only when the existing contents will be entirely
00378     // overwritten. If dirty or scroll rects are used, this call should be removed.
00379     m_d3dContext->DiscardView(m_d3dRenderTargetView.Get());
00380
00381     // Discard the contents of the depth stencil.
00382     m_d3dContext->DiscardView(m_d3dDepthStencilView.Get());
00383
00384     // If the device was removed either by a disconnect or a driver upgrade, we
00385     // must recreate all device resources.
00386     if (hr == DXGI_ERROR_DEVICE_REMOVED)
00387     {
00388         HandleDeviceLost();
00389     }
00390     else
00391     {
00392         DX::ThrowIfFailed(hr);
00393     }
00394
00395     if (m_windowSizeChangeInProgress)
00396     {
00397         // A window size change has been initiated and the app has just completed presenting
00398         // the first frame with the new size. Notify the resize manager so we can short
00399         // circuit any resize animation and prevent unnecessary delays.
00400         CoreWindowResizeManager::GetForCurrentView()->NotifyLayoutCompleted();
00401         m_windowSizeChangeInProgress = false;
00402     }
00403 }
00404
00405 void DirectXBase::ValidateDevice()
00406 {
00407     // The D3D Device is no longer valid if the default adapter changes or if
00408     // the device has been removed.
00409
00410     // First, get the information for the adapter related to the current device.
00411
00412     ComPtr<IDXGIDevice1> dxgiDevice;
00413     ComPtr<IDXGIAdapter> deviceAdapter;
00414     DXGI_ADAPTER_DESC deviceDesc;
00415     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00416     DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter));
00417     DX::ThrowIfFailed(deviceAdapter->GetDesc(&deviceDesc));
00418
00419     // Next, get the information for the default adapter.
00420
00421     ComPtr<IDXGIFactory2> dxgiFactory;
00422     ComPtr<IDXGIAdapter1> currentAdapter;
00423     DXGI_ADAPTER_DESC currentDesc;
00424     DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)));
00425     DX::ThrowIfFailed(dxgiFactory->EnumAdapters1(0, &currentAdapter));
00426     DX::ThrowIfFailed(currentAdapter->GetDesc(&currentDesc));
00427
00428     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00429     // a new D3D device must be created.
00430
00431     if ((deviceDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart) ||
00432         (deviceDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart) ||
00433         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00434     {
00435         // Release references to resources related to the old device.
00436         dxgiDevice = nullptr;
00437         deviceAdapter = nullptr;
00438
00439         // Create a new device and swap chain.
00440         HandleDeviceLost();
00441     }
00442 }
Generated on Sat Nov 23 2024 16:08:02 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DirectXFractal Member List

This is the complete list of members for DirectXFractal, including all inherited members.
__pad0__ | DirectXFractal |
CreateDeviceIndependentResources() override | DirectXFractal | [virtual]
CreateDeviceResources() override | DirectXFractal | [virtual]
CreateWindowSizeDependentResources() override | DirectXFractal | [virtual]
DetermineFractalTechnique() | DirectXFractal | [private]
HandleDeviceLost() override | DirectXFractal | [virtual]
HandleViewManipulation(float dRotation, float dScale, float dX, float dY) | DirectXFractal |
LoadInternalState(_In_ Windows::Foundation::Collections::IPropertySet^state) | DirectXFractal |
m_bufferHeight | DirectXFractal | [private]
m_bufferInfoCB | DirectXFractal | [private]
m_bufferWidth | DirectXFractal | [private]
m_complete | DirectXFractal | [private]
m_completedIterations | DirectXFractal | [private]
m_computeCB | DirectXFractal | [private]
m_directComputeCS | DirectXFractal | [private]
m_downSampleRatio | DirectXFractal | [private]
m_drawRectCB | DirectXFractal | [private]
m_fastGenerate | DirectXFractal | [private]
m_finalPS | DirectXFractal | [private]
m_finalRTV | DirectXFractal | [private]
m_finalSRV | DirectXFractal | [private]
m_gradient | DirectXFractal | [private]
m_indexBuffer | DirectXFractal | [private]
m_indexCount | DirectXFractal | [private]
m_initialPS | DirectXFractal | [private]
m_inputLayout | DirectXFractal | [private]
m_linearSampler | DirectXFractal | [private]
m_movingThrottle | DirectXFractal | [private]
m_numIterationsPerFrame | DirectXFractal | [private]
m_pointSampler | DirectXFractal | [private]
m_renderBufferPS | DirectXFractal | [private]
m_renderTexturePS | DirectXFractal | [private]
m_sampleOverlay | DirectXFractal | [private]
m_singlePassPS | DirectXFractal | [private]
m_stepPS | DirectXFractal | [private]
m_technique | DirectXFractal | [private]
m_tempRTV | DirectXFractal | [private]
m_tempSRV | DirectXFractal | [private]
m_tempUAV | DirectXFractal | [private]
m_transform | DirectXFractal | [private]
m_useDoubles | DirectXFractal | [private]
m_useUnormTextures | DirectXFractal | [private]
m_vertexBuffer | DirectXFractal | [private]
m_vertexShader | DirectXFractal | [private]
Render() override | DirectXFractal | [virtual]
RoundUpTo16(int value) | DirectXFractal | [private]
SaveInternalState(_In_ Windows::Foundation::Collections::IPropertySet^state) | DirectXFractal |
SaveInternalValue(_In_ Windows::Foundation::Collections::IPropertySet^state, _In_ Platform::String^key, _In_ Platform::Object^value) | DirectXFractal | [private]
Update(float timeTotal, float timeDelta) | DirectXFractal |
Generated on Sat Nov 23 2024 16:09:11 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

ContentImageSource Member List

This is the complete list of members for ContentImageSource, including all inherited members.
AddRef() override | ContentImageSource | [virtual]
ContentImageSource(_In_ Element^content, _In_ Document^document, bool isOpaque) | ContentImageSource |
Draw(RECT const &drawingBounds) | ContentImageSource | [private]
GetImageSize() | ContentImageSource |
GetImageSource() | ContentImageSource |
Initialize() | ContentImageSource | [private]
m_content | ContentImageSource | [private]
m_contentSize | ContentImageSource | [private]
m_document | ContentImageSource | [private]
m_imageSource | ContentImageSource | [private]
m_imageSourceNative | ContentImageSource | [private]
m_isOpaque | ContentImageSource | [private]
m_refCount | ContentImageSource | [private]
Measure(_Out_ SIZE *contentSize) | ContentImageSource | [private]
QueryInterface(REFIID uuid, _Outptr_ void **object) override | ContentImageSource | [virtual]
Release() override | ContentImageSource | [virtual]
UpdateContent(_In_ Element^content) | ContentImageSource |
UpdatesNeeded() override | ContentImageSource | [virtual]
Generated on Sat Nov 23 2024 16:09:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Hilo::ObservableQuery Member List

This is the complete list of members for Hilo::ObservableQuery, including all inherited members.
AddObserver(const std::function< void()> callback, PageType pageType)=0 | Hilo::ObservableQuery | [pure virtual]
RemoveObserver(PageType pageType)=0 | Hilo::ObservableQuery | [pure virtual]
Generated on Sat Nov 23 2024 16:09:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Network information/C++/pch.cpp Source File

  • Network information

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C#,C++/MediaExtensions/Mpeg1Decoder/dll.cpp Source File

  • Media extensions
  • C#,C++
  • MediaExtensions
  • Mpeg1Decoder

dll.cpp

Go to the documentation of this file.
00001 //////////////////////////////////////////////////////////////////////////
00002 //
00003 // dllmain.cpp
00004 //
00005 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00007 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00008 // PARTICULAR PURPOSE.
00009 //
00010 // Copyright (c) Microsoft Corporation. All rights reserved.
00011 //
00012 //////////////////////////////////////////////////////////////////////////
00013
00014 #include <wrl\module.h>
00015 #include "Decoder.h"
00016
00017 using namespace Microsoft::WRL;
00018
00019 namespace Microsoft { namespace Samples {
00020     ActivatableClass(CDecoder);
00021 }}
00022
00023 BOOL WINAPI DllMain( _In_ HINSTANCE hInstance, _In_ DWORD dwReason, _In_opt_ LPVOID lpReserved )
00024 {
00025     if( DLL_PROCESS_ATTACH == dwReason )
00026     {
00027         //
00028         //  Don't need per-thread callbacks
00029         //
00030         DisableThreadLibraryCalls( hInstance );
00031
00032         Module<InProc>::GetModule().Create();
00033     }
00034     else if( DLL_PROCESS_DETACH == dwReason )
00035     {
00036         Module<InProc>::GetModule().Terminate();
00037     }
00038
00039     return TRUE;
00040 }
00041
00042 HRESULT WINAPI DllGetActivationFactory( _In_ HSTRING activatibleClassId, _Outptr_ IActivationFactory** factory )
00043 {
00044     auto &module = Microsoft::WRL::Module< Microsoft::WRL::InProc >::GetModule();
00045     return module.GetActivationFactory( activatibleClassId, factory );
00046 }
00047
00048 HRESULT WINAPI DllCanUnloadNow()
00049 {
00050     auto &module = Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule();
00051     return (module.Terminate()) ? S_OK : S_FALSE;
00052 }
00053
00054 STDAPI DllGetClassObject( _In_ REFCLSID rclsid, _In_ REFIID riid, _Outptr_ LPVOID FAR* ppv )
00055 {
00056     auto &module = Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule();
00057     return module.GetClassObject( rclsid, riid, ppv );
00058 }
Generated on Sat Nov 23 2024 16:08:21 for Win8-Examples by doxygen 1.7.1


Win8-Examples: UI contrast and settings/C++/MainPage.xaml.h Source File

  • UI contrast and settings

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/MediaExtensions/Mpeg1Source/MPEG1Src.cpp Source File

  • Media extensions
  • MediaExtensions
  • Mpeg1Source

MPEG1Src.cpp

Go to the documentation of this file.
00001 //////////////////////////////////////////////////////////////////////////
00002 //
00003 // CMPEG1Source.h
00004 // Implements the MPEG-1 media source object.
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
00016 #include "MPEG1Src.h"
00017
00018 //-------------------------------------------------------------------
00019 //
00020 // Notes:
00021 // This sample contains an MPEG-1 source.
00022 //
00023 // - The source parses MPEG-1 systems-layer streams and generates
00024 //   samples that contain MPEG-1 payloads.
00025 // - The source does not support files that contain a raw MPEG-1
00026 //   video or audio stream.
00027 // - The source does not support seeking.
00028 //
00029 //-------------------------------------------------------------------
00030
00031 #pragma warning( push )
00032 #pragma warning( disable : 4355 )  // 'this' used in base member initializer list
00033
00034 HRESULT CreateVideoMediaType(const MPEG1VideoSeqHeader& videoSeqHdr, IMFMediaType **ppType);
00035 HRESULT CreateAudioMediaType(const MPEG1AudioFrameHeader& audioHeader, IMFMediaType **ppType);
00036 HRESULT GetStreamMajorType(IMFStreamDescriptor *pSD, GUID *pguidMajorType);
00037 BOOL    SampleRequestMatch(SourceOp *pOp1, SourceOp *pOp2);
00038
00039
00040 /* Public class methods */
00041
00042 //-------------------------------------------------------------------
00043 // Name: CreateInstance
00044 // Static method to create an instance of the source.
00045 //
00046 // ppSource:    Receives a ref-counted pointer to the source.
00047 //-------------------------------------------------------------------
00048
00049 HRESULT CMPEG1Source::CreateInstance(CMPEG1Source **ppSource)
00050 {
00051     if (ppSource == NULL)
00052     {
00053         return E_POINTER;
00054     }
00055
00056     HRESULT hr = S_OK;
00057     CMPEG1Source *pSource = new (std::nothrow) CMPEG1Source(hr);
00058     if (pSource == NULL)
00059     {
00060         return E_OUTOFMEMORY;
00061     }
00062
00063     if (SUCCEEDED(hr))
00064     {
00065         *ppSource = pSource;
00066         (*ppSource)->AddRef();
00067     }
00068
00069     SafeRelease(&pSource);
00070     return hr;
00071 }
00072
00073
00074 //-------------------------------------------------------------------
00075 // IUnknown methods
00076 //-------------------------------------------------------------------
00077
00078 HRESULT CMPEG1Source::QueryInterface(REFIID riid, void** ppv)
00079 {
00080     if (ppv == nullptr)
00081     {
00082         return E_POINTER;
00083     }
00084
00085     HRESULT hr = E_NOINTERFACE;
00086     if (riid == IID_IUnknown ||
00087         riid == IID_IMFMediaEventGenerator ||
00088         riid == IID_IMFMediaSource)
00089     {
00090         (*ppv) = static_cast<IMFMediaSource *>(this);
00091         AddRef();
00092         hr = S_OK;
00093     }
00094     else if (riid == IID_IMFGetService)
00095     {
00096         (*ppv) = static_cast<IMFGetService*>(this);
00097         AddRef();
00098         hr = S_OK;
00099     }
00100     else if (riid == IID_IMFRateControl)
00101     {
00102         (*ppv) = static_cast<IMFRateControl*>(this);
00103         AddRef();
00104         hr = S_OK;
00105     }
00106
00107     return hr;
00108 }
00109
00110 ULONG CMPEG1Source::AddRef()
00111 {
00112     return _InterlockedIncrement(&m_cRef);
00113 }
00114
00115 ULONG CMPEG1Source::Release()
00116 {
00117     LONG cRef = _InterlockedDecrement(&m_cRef);
00118     if (cRef == 0)
00119     {
00120         delete this;
00121     }
00122     return cRef;
00123 }
00124
00125 //-------------------------------------------------------------------
00126 // IMFMediaEventGenerator methods
00127 //
00128 // All of the IMFMediaEventGenerator methods do the following:
00129 // 1. Check for shutdown status.
00130 // 2. Call the event queue helper object.
00131 //-------------------------------------------------------------------
00132
00133 HRESULT CMPEG1Source::BeginGetEvent(IMFAsyncCallback* pCallback,IUnknown* punkState)
00134 {
00135     HRESULT hr = S_OK;
00136
00137     EnterCriticalSection(&m_critSec);
00138
00139     hr = CheckShutdown();
00140
00141     if (SUCCEEDED(hr))
00142     {
00143         hr = m_pEventQueue->BeginGetEvent(pCallback, punkState);
00144     }
00145
00146     LeaveCriticalSection(&m_critSec);
00147     return hr;
00148 }
00149
00150 HRESULT CMPEG1Source::EndGetEvent(IMFAsyncResult* pResult, IMFMediaEvent** ppEvent)
00151 {
00152     HRESULT hr = S_OK;
00153
00154     EnterCriticalSection(&m_critSec);
00155
00156     hr = CheckShutdown();
00157
00158     if (SUCCEEDED(hr))
00159     {
00160         hr = m_pEventQueue->EndGetEvent(pResult, ppEvent);
00161     }
00162
00163     LeaveCriticalSection(&m_critSec);
00164     return hr;
00165 }
00166
00167 HRESULT CMPEG1Source::GetEvent(DWORD dwFlags, IMFMediaEvent** ppEvent)
00168 {
00169     // NOTE:
00170     // GetEvent can block indefinitely, so we don't hold the critical
00171     // section. Therefore we need to use a local copy of the event queue
00172     // pointer, to make sure the pointer remains valid.
00173
00174     HRESULT hr = S_OK;
00175
00176     IMFMediaEventQueue *pQueue = NULL;
00177
00178     EnterCriticalSection(&m_critSec);
00179
00180     // Check shutdown
00181     hr = CheckShutdown();
00182
00183     // Cache a local pointer to the queue.
00184     if (SUCCEEDED(hr))
00185     {
00186         pQueue = m_pEventQueue;
00187         pQueue->AddRef();
00188     }
00189
00190     LeaveCriticalSection(&m_critSec);
00191
00192     // Use the local pointer to call GetEvent.
00193     if (SUCCEEDED(hr))
00194     {
00195         hr = pQueue->GetEvent(dwFlags, ppEvent);
00196     }
00197
00198     SafeRelease(&pQueue);
00199     return hr;
00200 }
00201
00202 HRESULT CMPEG1Source::QueueEvent(MediaEventType met, REFGUID guidExtendedType, HRESULT hrStatus, const PROPVARIANT* pvValue)
00203 {
00204     HRESULT hr = S_OK;
00205
00206     EnterCriticalSection(&m_critSec);
00207
00208     hr = CheckShutdown();
00209
00210     if (SUCCEEDED(hr))
00211     {
00212         hr = m_pEventQueue->QueueEventParamVar(met, guidExtendedType, hrStatus, pvValue);
00213     }
00214
00215     LeaveCriticalSection(&m_critSec);
00216
00217     return hr;
00218 }
00219
00220 //-------------------------------------------------------------------
00221 // IMFMediaSource methods
00222 //-------------------------------------------------------------------
00223
00224
00225 //-------------------------------------------------------------------
00226 // CreatePresentationDescriptor
00227 // Returns a shallow copy of the source's presentation descriptor.
00228 //-------------------------------------------------------------------
00229
00230 HRESULT CMPEG1Source::CreatePresentationDescriptor(
00231     IMFPresentationDescriptor** ppPresentationDescriptor
00232     )
00233 {
00234     if (ppPresentationDescriptor == NULL)
00235     {
00236         return E_POINTER;
00237     }
00238
00239     HRESULT hr = S_OK;
00240
00241     EnterCriticalSection(&m_critSec);
00242
00243     // Fail if the source is shut down.
00244     hr = CheckShutdown();
00245
00246     // Fail if the source was not initialized yet.
00247     if (SUCCEEDED(hr))
00248     {
00249         hr = IsInitialized();
00250     }
00251
00252     // Do we have a valid presentation descriptor?
00253     if (SUCCEEDED(hr))
00254     {
00255         if (m_pPresentationDescriptor == NULL)
00256         {
00257             hr = MF_E_NOT_INITIALIZED;
00258         }
00259     }
00260
00261     // Clone our presentation descriptor.
00262     if (SUCCEEDED(hr))
00263     {
00264         hr = m_pPresentationDescriptor->Clone(ppPresentationDescriptor);
00265     }
00266
00267     LeaveCriticalSection(&m_critSec);
00268     return hr;
00269 }
00270
00271
00272 //-------------------------------------------------------------------
00273 // GetCharacteristics
00274 // Returns capabilities flags.
00275 //-------------------------------------------------------------------
00276
00277 HRESULT CMPEG1Source::GetCharacteristics(DWORD* pdwCharacteristics)
00278 {
00279     if (pdwCharacteristics == NULL)
00280     {
00281         return E_POINTER;
00282     }
00283
00284     HRESULT hr = S_OK;
00285
00286     EnterCriticalSection(&m_critSec);
00287
00288     hr = CheckShutdown();
00289
00290     if (SUCCEEDED(hr))
00291     {
00292         *pdwCharacteristics =  MFMEDIASOURCE_CAN_PAUSE;
00293     }
00294
00295     // NOTE: This sample does not implement seeking, so we do not
00296     // include the MFMEDIASOURCE_CAN_SEEK flag.
00297
00298     LeaveCriticalSection(&m_critSec);
00299     return hr;
00300 }
00301
00302
00303 //-------------------------------------------------------------------
00304 // Pause
00305 // Pauses the source.
00306 //-------------------------------------------------------------------
00307
00308 HRESULT CMPEG1Source::Pause()
00309 {
00310     EnterCriticalSection(&m_critSec);
00311
00312     HRESULT hr = S_OK;
00313
00314     // Fail if the source is shut down.
00315     hr = CheckShutdown();
00316
00317     // Queue the operation.
00318     if (SUCCEEDED(hr))
00319     {
00320         hr = QueueAsyncOperation(SourceOp::OP_PAUSE);
00321     }
00322
00323     LeaveCriticalSection(&m_critSec);
00324     return hr;
00325 }
00326
00327 //-------------------------------------------------------------------
00328 // Shutdown
00329 // Shuts down the source and releases all resources.
00330 //-------------------------------------------------------------------
00331
00332 HRESULT CMPEG1Source::Shutdown()
00333 {
00334     EnterCriticalSection(&m_critSec);
00335
00336     HRESULT hr = S_OK;
00337
00338     CMPEG1Stream *pStream = NULL;
00339
00340     hr = CheckShutdown();
00341
00342     if (SUCCEEDED(hr))
00343     {
00344         // Shut down the stream objects.
00345
00346         for (DWORD i = 0; i < m_streams.GetCount(); i++)
00347         {
00348             (void)m_streams[i]->Shutdown();
00349         }
00350
00351         // Shut down the event queue.
00352         if (m_pEventQueue)
00353         {
00354             (void)m_pEventQueue->Shutdown();
00355         }
00356
00357         // Release objects.
00358
00359         SafeRelease(&m_pEventQueue);
00360         SafeRelease(&m_pPresentationDescriptor);
00361         SafeRelease(&m_pBeginOpenResult);
00362         SafeRelease(&m_pByteStream);
00363         SafeRelease(&m_pCurrentOp);
00364
00365         CoTaskMemFree(m_pHeader);
00366         m_pHeader = NULL;
00367
00368         delete m_pParser;
00369         m_pParser = NULL;
00370
00371         // Set the state.
00372         m_state = STATE_SHUTDOWN;
00373     }
00374
00375     LeaveCriticalSection(&m_critSec);
00376     return hr;
00377 }
00378
00379
00380 //-------------------------------------------------------------------
00381 // Start
00382 // Starts or seeks the media source.
00383 //-------------------------------------------------------------------
00384
00385 HRESULT CMPEG1Source::Start(
00386         IMFPresentationDescriptor* pPresentationDescriptor,
00387         const GUID* pguidTimeFormat,
00388         const PROPVARIANT* pvarStartPos
00389     )
00390 {
00391
00392     HRESULT hr = S_OK;
00393     SourceOp *pAsyncOp = NULL;
00394
00395     // Check parameters.
00396
00397     // Start position and presentation descriptor cannot be NULL.
00398     if (pvarStartPos == NULL || pPresentationDescriptor == NULL)
00399     {
00400         return E_INVALIDARG;
00401     }
00402
00403     // Check the time format.
00404     if ((pguidTimeFormat != NULL) && (*pguidTimeFormat != GUID_NULL))
00405     {
00406         // Unrecognized time format GUID.
00407         return MF_E_UNSUPPORTED_TIME_FORMAT;
00408     }
00409
00410     // Check the data type of the start position.
00411     if ((pvarStartPos->vt != VT_I8) && (pvarStartPos->vt != VT_EMPTY))
00412     {
00413         return MF_E_UNSUPPORTED_TIME_FORMAT;
00414     }
00415
00416     EnterCriticalSection(&m_critSec);
00417
00418     // Check if this is a seek request. This sample does not support seeking.
00419
00420     if (pvarStartPos->vt == VT_I8)
00421     {
00422         // If the current state is STOPPED, then position 0 is valid.
00423         // Otherwise, the start position must be VT_EMPTY (current position).
00424
00425         if ((m_state != STATE_STOPPED) || (pvarStartPos->hVal.QuadPart != 0))
00426         {
00427             hr = MF_E_INVALIDREQUEST;
00428             goto done;
00429         }
00430     }
00431
00432     // Fail if the source is shut down.
00433     hr = CheckShutdown();
00434     if (FAILED(hr))
00435     {
00436         goto done;
00437     }
00438
00439     // Fail if the source was not initialized yet.
00440     hr = IsInitialized();
00441     if (FAILED(hr))
00442     {
00443         goto done;
00444     }
00445
00446     // Perform a sanity check on the caller's presentation descriptor.
00447     hr = ValidatePresentationDescriptor(pPresentationDescriptor);
00448     if (FAILED(hr))
00449     {
00450         goto done;
00451     }
00452
00453     // The operation looks OK. Complete the operation asynchronously.
00454
00455     hr = SourceOp::CreateStartOp(pPresentationDescriptor, &pAsyncOp);
00456     if (FAILED(hr))
00457     {
00458         goto done;
00459     }
00460
00461     hr = pAsyncOp->SetData(*pvarStartPos);
00462     if (FAILED(hr))
00463     {
00464         goto done;
00465     }
00466
00467     hr = QueueOperation(pAsyncOp);
00468
00469 done:
00470     SafeRelease(&pAsyncOp);
00471     LeaveCriticalSection(&m_critSec);
00472     return hr;
00473 }
00474
00475
00476 //-------------------------------------------------------------------
00477 // Stop
00478 // Stops the media source.
00479 //-------------------------------------------------------------------
00480
00481 HRESULT CMPEG1Source::Stop()
00482 {
00483     EnterCriticalSection(&m_critSec);
00484
00485     HRESULT hr = S_OK;
00486
00487     // Fail if the source is shut down.
00488     hr = CheckShutdown();
00489
00490     // Fail if the source was not initialized yet.
00491     if (SUCCEEDED(hr))
00492     {
00493         hr = IsInitialized();
00494     }
00495
00496     // Queue the operation.
00497     if (SUCCEEDED(hr))
00498     {
00499         hr = QueueAsyncOperation(SourceOp::OP_STOP);
00500     }
00501
00502     LeaveCriticalSection(&m_critSec);
00503     return hr;
00504 }
00505
00506 //-------------------------------------------------------------------
00507 // IMFMediaSource methods
00508 //-------------------------------------------------------------------
00509
00510 //-------------------------------------------------------------------
00511 // GetService
00512 // Returns a service
00513 //-------------------------------------------------------------------
00514
00515 HRESULT CMPEG1Source::GetService( _In_ REFGUID guidService, _In_ REFIID riid, _Out_opt_ LPVOID *ppvObject)
00516 {
00517     HRESULT hr = MF_E_UNSUPPORTED_SERVICE;
00518
00519     if (ppvObject == nullptr)
00520     {
00521         return E_POINTER;
00522     }
00523
00524     if (guidService == MF_RATE_CONTROL_SERVICE)
00525     {
00526         hr = QueryInterface(riid, ppvObject);
00527     }
00528
00529     return hr;
00530 }
00531
00532 //-------------------------------------------------------------------
00533 // IMFRateControl methods
00534 //-------------------------------------------------------------------
00535
00536 //-------------------------------------------------------------------
00537 // SetRate
00538 // Sets a rate on the source. Only supported rates are 0 and 1.
00539 //-------------------------------------------------------------------
00540
00541 HRESULT CMPEG1Source::SetRate(BOOL fThin, float flRate)
00542 {
00543     if (fThin)
00544     {
00545         return MF_E_THINNING_UNSUPPORTED;
00546     }
00547     if (!IsRateSupported(flRate, &flRate))
00548     {
00549         return MF_E_UNSUPPORTED_RATE;
00550     }
00551
00552     EnterCriticalSection(&m_critSec);
00553     HRESULT hr = S_OK;
00554     SourceOp *pAsyncOp = nullptr;
00555
00556     if (flRate == m_flRate)
00557     {
00558         goto done;
00559     }
00560
00561     hr = SourceOp::CreateSetRateOp(fThin, flRate, &pAsyncOp);
00562
00563     if (SUCCEEDED(hr))
00564     {
00565         // Queue asynchronous stop
00566         hr = QueueOperation(pAsyncOp);
00567     }
00568
00569 done:
00570     SafeRelease(&pAsyncOp);
00571     LeaveCriticalSection(&m_critSec);
00572     return hr;
00573 }
00574
00575 //-------------------------------------------------------------------
00576 // GetRate
00577 // Returns a current rate.
00578 //-------------------------------------------------------------------
00579
00580 HRESULT CMPEG1Source::GetRate(_Inout_opt_ BOOL *pfThin, _Inout_opt_ float *pflRate)
00581 {
00582     if (pfThin == nullptr || pflRate == nullptr)
00583     {
00584         return E_INVALIDARG;
00585     }
00586
00587     EnterCriticalSection(&m_critSec);
00588     *pfThin = FALSE;
00589     *pflRate = m_flRate;
00590     LeaveCriticalSection(&m_critSec);
00591
00592     return S_OK;
00593 }
00594
00595
00596 //-------------------------------------------------------------------
00597 // Public non-interface methods
00598 //-------------------------------------------------------------------
00599
00600 //-------------------------------------------------------------------
00601 // BeginOpen
00602 // Begins reading the byte stream to initialize the source.
00603 // Called by the byte-stream handler when it creates the source.
00604 //
00605 // This method is asynchronous. When the operation completes,
00606 // the callback is invoked and the byte-stream handler calls
00607 // EndOpen.
00608 //
00609 // pStream: Pointer to the byte stream for the MPEG-1 stream.
00610 // pCB: Pointer to the byte-stream handler's callback.
00611 // pState: State object for the async callback. (Can be NULL.)
00612 //
00613 // Note: The source reads enough data to find one packet header
00614 // for each audio or video stream. This enables the source to
00615 // create a presentation descriptor that describes the format of
00616 // each stream. The source queues the packets that it reads during
00617 // BeginOpen.
00618 //-------------------------------------------------------------------
00619
00620 HRESULT CMPEG1Source::BeginOpen(IMFByteStream *pStream, IMFAsyncCallback *pCB, IUnknown *pState)
00621 {
00622     if (pStream == NULL || pCB == NULL)
00623     {
00624         return E_POINTER;
00625     }
00626
00627     if (m_state != STATE_INVALID)
00628     {
00629         return MF_E_INVALIDREQUEST;
00630     }
00631
00632     HRESULT hr = S_OK;
00633     DWORD dwCaps = 0;
00634
00635     EnterCriticalSection(&m_critSec);
00636
00637     // Cache the byte-stream pointer.
00638     m_pByteStream = pStream;
00639     m_pByteStream->AddRef();
00640
00641     // Validate the capabilities of the byte stream.
00642     // The byte stream must be readable and seekable.
00643     hr = pStream->GetCapabilities(&dwCaps);
00644
00645     if (SUCCEEDED(hr))
00646     {
00647         if ((dwCaps & MFBYTESTREAM_IS_SEEKABLE) == 0)
00648         {
00649             hr = MF_E_BYTESTREAM_NOT_SEEKABLE;
00650         }
00651         else if ((dwCaps & MFBYTESTREAM_IS_READABLE) == 0)
00652         {
00653             hr = E_FAIL;
00654         }
00655     }
00656
00657     // Reserve space in the read buffer.
00658     if (SUCCEEDED(hr))
00659     {
00660         hr = m_ReadBuffer.Initalize(INITIAL_BUFFER_SIZE);
00661     }
00662
00663     // Create the MPEG-1 parser.
00664     if (SUCCEEDED(hr))
00665     {
00666         m_pParser = new (std::nothrow) Parser();
00667         if (m_pParser == NULL)
00668         {
00669             hr = E_OUTOFMEMORY;
00670         }
00671     }
00672
00673     // Create an async result object. We'll use it later to invoke the callback.
00674     if (SUCCEEDED(hr))
00675     {
00676         hr = MFCreateAsyncResult(NULL, pCB, pState, &m_pBeginOpenResult);
00677     }
00678
00679     // Start reading data from the stream.
00680     if (SUCCEEDED(hr))
00681     {
00682         hr = RequestData(READ_SIZE);
00683     }
00684
00685     // At this point, we now guarantee to invoke the callback.
00686     if (SUCCEEDED(hr))
00687     {
00688         m_state = STATE_OPENING;
00689     }
00690
00691     LeaveCriticalSection(&m_critSec);
00692     return hr;
00693 }
00694
00695
00696 //-------------------------------------------------------------------
00697 // EndOpen
00698 // Completes the BeginOpen operation.
00699 // Called by the byte-stream handler when it creates the source.
00700 //-------------------------------------------------------------------
00701
00702 HRESULT CMPEG1Source::EndOpen(IMFAsyncResult *pResult)
00703 {
00704     EnterCriticalSection(&m_critSec);
00705
00706     HRESULT hr = S_OK;
00707
00708     hr = pResult->GetStatus();
00709
00710     if (FAILED(hr))
00711     {
00712         // The source is not designed to recover after failing to open.
00713         // Switch to shut-down state.
00714         Shutdown();
00715     }
00716     LeaveCriticalSection(&m_critSec);
00717     return hr;
00718 }
00719
00720
00721
00722 //-------------------------------------------------------------------
00723 // OnByteStreamRead
00724 // Called when an asynchronous read completes.
00725 //
00726 // Read requests are issued in the RequestData() method.
00727 //-------------------------------------------------------------------
00728
00729 HRESULT CMPEG1Source::OnByteStreamRead(IMFAsyncResult *pResult)
00730 {
00731     EnterCriticalSection(&m_critSec);
00732
00733     HRESULT hr = S_OK;
00734     DWORD cbRead = 0;
00735
00736     IUnknown *pState = NULL;
00737
00738     if (m_state == STATE_SHUTDOWN)
00739     {
00740         // If we are shut down, then we've already released the
00741         // byte stream. Nothing to do.
00742         LeaveCriticalSection(&m_critSec);
00743         return S_OK;
00744     }
00745
00746     // Get the state object. This is either NULL or the most
00747     // recent OP_REQUEST_DATA operation.
00748     (void)pResult->GetState(&pState);
00749
00750     // Complete the read opertation.
00751     hr = m_pByteStream->EndRead(pResult, &cbRead);
00752
00753     // If the source stops and restarts in rapid succession, there is
00754     // a chance this is a "stale" read request, initiated before the
00755     // stop/restart.
00756
00757     // To ensure that we don't deliver stale data, we store the
00758     // OP_REQUEST_DATA operation as a state object in pResult, and compare
00759     // this against the current value of m_cRestartCounter.
00760
00761     // If they don't match, we discard the data.
00762
00763     // NOTE: During BeginOpen, pState is NULL
00764
00765     if (SUCCEEDED(hr))
00766     {
00767         if ((pState == NULL) || ( ((SourceOp*)pState)->Data().ulVal == m_cRestartCounter) )
00768         {
00769             // This data is OK to parse.
00770
00771             if (cbRead == 0)
00772             {
00773                 // There is no more data in the stream. Signal end-of-stream.
00774                 hr = EndOfMPEGStream();
00775             }
00776             else
00777             {
00778                 // Update the end-position of the read buffer.
00779                 hr = m_ReadBuffer.MoveEnd(cbRead);
00780
00781                 // Parse the new data.
00782                 if (SUCCEEDED(hr))
00783                 {
00784                     hr = ParseData();
00785                 }
00786             }
00787         }
00788     }
00789
00790     if (FAILED(hr))
00791     {
00792         StreamingError(hr);
00793     }
00794     SafeRelease(&pState);
00795     LeaveCriticalSection(&m_critSec);
00796     return hr;
00797 }
00798
00799
00800
00801 /* Private methods */
00802
00803 CMPEG1Source::CMPEG1Source(HRESULT& hr) :
00804     OpQueue(m_critSec),
00805     m_cRef(1),
00806     m_pEventQueue(NULL),
00807     m_pPresentationDescriptor(NULL),
00808     m_pBeginOpenResult(NULL),
00809     m_pParser(NULL),
00810     m_pByteStream(NULL),
00811     m_pHeader(NULL),
00812     m_state(STATE_INVALID),
00813     m_pCurrentOp(NULL),
00814     m_pSampleRequest(NULL),
00815     m_cRestartCounter(0),
00816     m_OnByteStreamRead(this, &CMPEG1Source::OnByteStreamRead),
00817     m_flRate(1.0f)
00818 {
00819     auto module = ::Microsoft::WRL::GetModuleBase();
00820     if (module != nullptr)
00821     {
00822         module->IncrementObjectCount();
00823     }
00824
00825   InitializeCriticalSectionEx(&m_critSec, 3000, 0);
00826
00827     // Create the media event queue.
00828     hr = MFCreateEventQueue(&m_pEventQueue);
00829 }
00830
00831 CMPEG1Source::~CMPEG1Source()
00832 {
00833     if (m_state != STATE_SHUTDOWN)
00834     {
00835         Shutdown();
00836     }
00837
00838     DeleteCriticalSection(&m_critSec);
00839
00840   auto module = ::Microsoft::WRL::GetModuleBase();
00841     if (module != nullptr)
00842     {
00843         module->DecrementObjectCount();
00844     }
00845 }
00846
00847
00848 //-------------------------------------------------------------------
00849 // CompleteOpen
00850 //
00851 // Completes the asynchronous BeginOpen operation.
00852 //
00853 // hrStatus: Status of the BeginOpen operation.
00854 //-------------------------------------------------------------------
00855
00856 HRESULT CMPEG1Source::CompleteOpen(HRESULT hrStatus)
00857 {
00858     HRESULT hr = S_OK;
00859
00860     if (m_pBeginOpenResult)
00861     {
00862         hr = m_pBeginOpenResult->SetStatus(hrStatus);
00863         if (SUCCEEDED(hr))
00864         {
00865             hr = MFInvokeCallback(m_pBeginOpenResult);
00866         }
00867     }
00868
00869     SafeRelease(&m_pBeginOpenResult);
00870     return hr;
00871 }
00872
00873
00874 //-------------------------------------------------------------------
00875 // IsInitialized:
00876 // Returns S_OK if the source is correctly initialized with an
00877 // MPEG-1 byte stream. Otherwise, returns MF_E_NOT_INITIALIZED.
00878 //-------------------------------------------------------------------
00879
00880 HRESULT CMPEG1Source::IsInitialized() const
00881 {
00882     if (m_state == STATE_OPENING || m_state == STATE_INVALID)
00883     {
00884         return MF_E_NOT_INITIALIZED;
00885     }
00886     else
00887     {
00888         return S_OK;
00889     }
00890 }
00891
00892
00893 //-------------------------------------------------------------------
00894 // IsStreamTypeSupported:
00895 // Returns TRUE if the source supports the specified MPEG-1 stream
00896 // type.
00897 //-------------------------------------------------------------------
00898
00899 BOOL CMPEG1Source::IsStreamTypeSupported(StreamType type) const
00900 {
00901     // We support audio and video streams.
00902     return (type == StreamType_Video || type == StreamType_Audio);
00903 }
00904
00905 //-------------------------------------------------------------------
00906 // IsStreamActive:
00907 // Returns TRUE if the source should deliver a payload, whose type
00908 // is indicated by the specified packet header.
00909 //
00910 // Note: This method does not test the started/paused/stopped state
00911 //       of the source.
00912 //-------------------------------------------------------------------
00913
00914 BOOL CMPEG1Source::IsStreamActive(const MPEG1PacketHeader& packetHdr)
00915 {
00916     if (m_state == STATE_OPENING)
00917     {
00918         // The source is still opening.
00919         // Deliver payloads for every supported stream type.
00920         return IsStreamTypeSupported(packetHdr.type);
00921     }
00922     else
00923     {
00924         // The source is already opened. Check if the stream is active.
00925         CMPEG1Stream *pStream = m_streams.Find(packetHdr.stream_id);
00926
00927         if (pStream == NULL)
00928         {
00929             return FALSE;
00930         }
00931         else
00932         {
00933             return pStream->IsActive();
00934         }
00935     }
00936 }
00937
00938
00939 //-------------------------------------------------------------------
00940 // InitPresentationDescriptor
00941 //
00942 // Creates the source's presentation descriptor, if possible.
00943 //
00944 // During the BeginOpen operation, the source reads packets looking
00945 // for headers for each stream. This enables the source to create the
00946 // presentation descriptor, which describes the stream formats.
00947 //
00948 // This method tests whether the source has seen enough packets
00949 // to create the PD. If so, it invokes the callback to complete
00950 // the BeginOpen operation.
00951 //-------------------------------------------------------------------
00952
00953 HRESULT CMPEG1Source::InitPresentationDescriptor()
00954 {
00955     HRESULT hr = S_OK;
00956     DWORD cStreams = 0;
00957
00958     assert(m_pPresentationDescriptor == NULL);
00959     assert(m_state == STATE_OPENING);
00960
00961     if (m_pHeader == NULL)
00962     {
00963         return E_FAIL;
00964     }
00965
00966     // Get the number of streams, as declared in the MPEG-1 header, skipping
00967     // any streams with an unsupported format.
00968     for (DWORD i = 0; i < m_pHeader->cStreams; i++)
00969     {
00970         if (IsStreamTypeSupported(m_pHeader->streams[i].type))
00971         {
00972             cStreams++;
00973         }
00974     }
00975
00976     // How many streams do we actually have?
00977     if (cStreams > m_streams.GetCount())
00978     {
00979         // Keep reading data until we have seen a packet for each stream.
00980         return S_OK;
00981     }
00982
00983     // We should never create a stream we don't support.
00984     assert(cStreams == m_streams.GetCount());
00985
00986     // Ready to create the presentation descriptor.
00987
00988     // Create an array of IMFStreamDescriptor pointers.
00989     IMFStreamDescriptor **ppSD =
00990             new (std::nothrow) IMFStreamDescriptor*[cStreams];
00991
00992     if (ppSD == NULL)
00993     {
00994         hr = E_OUTOFMEMORY;
00995         goto done;
00996     }
00997
00998     ZeroMemory(ppSD, cStreams * sizeof(IMFStreamDescriptor*));
00999
01000     // Fill the array by getting the stream descriptors from the streams.
01001     for (DWORD i = 0; i < cStreams; i++)
01002     {
01003         hr = m_streams[i]->GetStreamDescriptor(&ppSD[i]);
01004         if (FAILED(hr))
01005         {
01006             goto done;
01007         }
01008     }
01009
01010     // Create the presentation descriptor.
01011     hr = MFCreatePresentationDescriptor(cStreams, ppSD,
01012         &m_pPresentationDescriptor);
01013
01014     if (FAILED(hr))
01015     {
01016         goto done;
01017     }
01018
01019     // Select the first video stream (if any).
01020     for (DWORD i = 0; i < cStreams; i++)
01021     {
01022         GUID majorType = GUID_NULL;
01023
01024         hr = GetStreamMajorType(ppSD[i], &majorType);
01025         if (FAILED(hr))
01026         {
01027             goto done;
01028         }
01029
01030         hr = m_pPresentationDescriptor->SelectStream(i);
01031         if (FAILED(hr))
01032         {
01033             goto done;
01034         }
01035     }
01036
01037     // Switch state from "opening" to stopped.
01038     m_state = STATE_STOPPED;
01039
01040     // Invoke the async callback to complete the BeginOpen operation.
01041     hr = CompleteOpen(S_OK);
01042
01043 done:
01044     // clean up:
01045     if (ppSD)
01046     {
01047         for (DWORD i = 0; i < cStreams; i++)
01048         {
01049             SafeRelease(&ppSD[i]);
01050         }
01051         delete [] ppSD;
01052     }
01053     return hr;
01054 }
01055
01056
01057 //-------------------------------------------------------------------
01058 // QueueAsyncOperation
01059 // Queue an asynchronous operation.
01060 //
01061 // OpType: Type of operation to queue.
01062 //
01063 // Note: If the SourceOp object requires additional information, call
01064 // OpQueue<SourceOp>::QueueOperation, which takes a SourceOp pointer.
01065 //-------------------------------------------------------------------
01066
01067 HRESULT CMPEG1Source::QueueAsyncOperation(SourceOp::Operation OpType)
01068 {
01069     HRESULT hr = S_OK;
01070     SourceOp *pOp = NULL;
01071
01072     hr = SourceOp::CreateOp(OpType, &pOp);
01073
01074     if (SUCCEEDED(hr))
01075     {
01076         hr = QueueOperation(pOp);
01077     }
01078
01079     SafeRelease(&pOp);
01080     return hr;
01081 }
01082
01083 //-------------------------------------------------------------------
01084 // BeginAsyncOp
01085 //
01086 // Starts an asynchronous operation. Called by the source at the
01087 // begining of any asynchronous operation.
01088 //-------------------------------------------------------------------
01089
01090 HRESULT CMPEG1Source::BeginAsyncOp(SourceOp *pOp)
01091 {
01092     // At this point, the current operation should be NULL (the
01093     // previous operation is NULL) and the new operation (pOp)
01094     // must not be NULL.
01095
01096     if (pOp == NULL || m_pCurrentOp != NULL)
01097     {
01098         assert(FALSE);
01099         return E_FAIL;
01100     }
01101
01102     // Store the new operation as the current operation.
01103
01104     m_pCurrentOp = pOp;
01105     m_pCurrentOp->AddRef();
01106
01107     return S_OK;
01108 }
01109
01110 //-------------------------------------------------------------------
01111 // CompleteAsyncOp
01112 //
01113 // Completes an asynchronous operation. Called by the source at the
01114 // end of any asynchronous operation.
01115 //-------------------------------------------------------------------
01116
01117 HRESULT CMPEG1Source::CompleteAsyncOp(SourceOp *pOp)
01118 {
01119     HRESULT hr = S_OK;
01120
01121     // At this point, the current operation (m_pCurrentOp)
01122     // must match the operation that is ending (pOp).
01123
01124     if (pOp == NULL || m_pCurrentOp == NULL)
01125     {
01126         assert(FALSE);
01127         return E_FAIL;
01128     }
01129
01130     if (m_pCurrentOp != pOp)
01131     {
01132         assert(FALSE);
01133         return E_FAIL;
01134     }
01135
01136     // Release the current operation.
01137     SafeRelease(&m_pCurrentOp);
01138
01139     // Process the next operation on the queue.
01140     hr = ProcessQueue();
01141
01142     return hr;
01143 }
01144
01145 //-------------------------------------------------------------------
01146 // DispatchOperation
01147 //
01148 // Performs the asynchronous operation indicated by pOp.
01149 //
01150 // NOTE:
01151 // This method implements the pure-virtual OpQueue::DispatchOperation
01152 // method. It is always called from a work-queue thread.
01153 //-------------------------------------------------------------------
01154
01155 HRESULT CMPEG1Source::DispatchOperation(SourceOp *pOp)
01156 {
01157     EnterCriticalSection(&m_critSec);
01158
01159     HRESULT hr = S_OK;
01160
01161     if (m_state == STATE_SHUTDOWN)
01162     {
01163         LeaveCriticalSection(&m_critSec);
01164
01165         return S_OK; // Already shut down, ignore the request.
01166     }
01167
01168     switch (pOp->Op())
01169     {
01170
01171     // IMFMediaSource methods:
01172
01173     case SourceOp::OP_START:
01174         hr = DoStart((StartOp*)pOp);
01175         break;
01176
01177     case SourceOp::OP_STOP:
01178         hr = DoStop(pOp);
01179         break;
01180
01181     case SourceOp::OP_PAUSE:
01182         hr = DoPause(pOp);
01183         break;
01184
01185     case SourceOp::OP_SETRATE:
01186         hr = DoSetRate(pOp);
01187         break;
01188
01189     // Operations requested by the streams:
01190
01191     case SourceOp::OP_REQUEST_DATA:
01192         hr = OnStreamRequestSample(pOp);
01193         break;
01194
01195     case SourceOp::OP_END_OF_STREAM:
01196         hr = OnEndOfStream(pOp);
01197         break;
01198
01199     default:
01200         hr = E_UNEXPECTED;
01201     }
01202
01203     if (FAILED(hr))
01204     {
01205         StreamingError(hr);
01206     }
01207
01208     LeaveCriticalSection(&m_critSec);
01209     return hr;
01210 }
01211
01212
01213 //-------------------------------------------------------------------
01214 // ValidateOperation
01215 //
01216 // Checks whether the source can perform the operation indicated
01217 // by pOp at this time.
01218 //
01219 // If the source cannot perform the operation now, the method
01220 // returns MF_E_NOTACCEPTING.
01221 //
01222 // NOTE:
01223 // Implements the pure-virtual OpQueue::ValidateOperation method.
01224 //-------------------------------------------------------------------
01225
01226 HRESULT CMPEG1Source::ValidateOperation(SourceOp *pOp)
01227 {
01228     if (m_pCurrentOp != NULL)
01229     {
01230         return MF_E_NOTACCEPTING;
01231     }
01232     return S_OK;
01233 }
01234
01235
01236
01237 //-------------------------------------------------------------------
01238 // DoStart
01239 // Perform an async start operation (IMFMediaSource::Start)
01240 //
01241 // pOp: Contains the start parameters.
01242 //
01243 // Note: This sample currently does not implement seeking, and the
01244 // Start() method fails if the caller requests a seek.
01245 //-------------------------------------------------------------------
01246
01247 HRESULT CMPEG1Source::DoStart(StartOp *pOp)
01248 {
01249     assert(pOp->Op() == SourceOp::OP_START);
01250
01251     IMFPresentationDescriptor *pPD = NULL;
01252     IMFMediaEvent  *pEvent = NULL;
01253
01254     HRESULT     hr = S_OK;
01255     LONGLONG    llStartOffset = 0;
01256     BOOL        bRestartFromCurrentPosition = FALSE;
01257     BOOL        bSentEvents = FALSE;
01258
01259     hr = BeginAsyncOp(pOp);
01260
01261     // Get the presentation descriptor from the SourceOp object.
01262     // This is the PD that the caller passed into the Start() method.
01263     // The PD has already been validated.
01264     if (SUCCEEDED(hr))
01265     {
01266         hr = pOp->GetPresentationDescriptor(&pPD);
01267     }
01268     // Because this sample does not support seeking, the start
01269     // position must be 0 (from stopped) or "current position."
01270
01271     // If the sample supported seeking, we would need to get the
01272     // start position from the PROPVARIANT data contained in pOp.
01273
01274     if (SUCCEEDED(hr))
01275     {
01276         // Select/deselect streams, based on what the caller set in the PD.
01277         // This method also sends the MENewStream/MEUpdatedStream events.
01278         hr = SelectStreams(pPD, pOp->Data());
01279     }
01280
01281     if (SUCCEEDED(hr))
01282     {
01283         m_state = STATE_STARTED;
01284
01285         // Queue the "started" event. The event data is the start position.
01286         hr = m_pEventQueue->QueueEventParamVar(
01287             MESourceStarted,
01288             GUID_NULL,
01289             S_OK,
01290             &pOp->Data()
01291             );
01292     }
01293
01294     if (FAILED(hr))
01295     {
01296         // Failure. Send the error code to the application.
01297
01298         // Note: It's possible that QueueEvent itself failed, in which case it
01299         // is likely to fail again. But there is no good way to recover in
01300         // that case.
01301
01302         (void)m_pEventQueue->QueueEventParamVar(
01303             MESourceStarted, GUID_NULL, hr, NULL);
01304     }
01305
01306     CompleteAsyncOp(pOp);
01307
01308     SafeRelease(&pEvent);
01309     SafeRelease(&pPD);
01310     return hr;
01311 }
01312
01313
01314 //-------------------------------------------------------------------
01315 // DoStop
01316 // Perform an async stop operation (IMFMediaSource::Stop)
01317 //-------------------------------------------------------------------
01318
01319 HRESULT CMPEG1Source::DoStop(SourceOp *pOp)
01320 {
01321     HRESULT hr = S_OK;
01322     QWORD qwCurrentPosition = 0;
01323
01324     hr = BeginAsyncOp(pOp);
01325
01326     // Stop the active streams.
01327     if (SUCCEEDED(hr))
01328     {
01329         for (DWORD i = 0; i < m_streams.GetCount(); i++)
01330         {
01331             if (m_streams[i]->IsActive())
01332             {
01333                 hr = m_streams[i]->Stop();
01334             }
01335             if (FAILED(hr))
01336             {
01337                 break;
01338             }
01339         }
01340     }
01341
01342     // Seek to the start of the file. If we restart after stopping,
01343     // we will start from the beginning of the file again.
01344     if (SUCCEEDED(hr))
01345     {
01346         hr = m_pByteStream->Seek(
01347             msoBegin,
01348             0,
01349             MFBYTESTREAM_SEEK_FLAG_CANCEL_PENDING_IO,
01350             &qwCurrentPosition
01351             );
01352     }
01353
01354     // Increment the counter that tracks "stale" read requests.
01355     if (SUCCEEDED(hr))
01356     {
01357         ++m_cRestartCounter; // This counter is allowed to overflow.
01358     }
01359
01360     SafeRelease(&m_pSampleRequest);
01361
01362     m_state = STATE_STOPPED;
01363
01364     // Send the "stopped" event. This might include a failure code.
01365     (void)m_pEventQueue->QueueEventParamVar(MESourceStopped, GUID_NULL, hr, NULL);
01366
01367     CompleteAsyncOp(pOp);
01368
01369     return hr;
01370 }
01371
01372
01373 //-------------------------------------------------------------------
01374 // DoPause
01375 // Perform an async pause operation (IMFMediaSource::Pause)
01376 //-------------------------------------------------------------------
01377
01378 HRESULT CMPEG1Source::DoPause(SourceOp *pOp)
01379 {
01380     HRESULT hr = S_OK;
01381
01382     hr = BeginAsyncOp(pOp);
01383
01384     // Pause is only allowed while running.
01385     if (SUCCEEDED(hr))
01386     {
01387         if (m_state != STATE_STARTED)
01388         {
01389             hr = MF_E_INVALID_STATE_TRANSITION;
01390         }
01391     }
01392
01393     // Pause the active streams.
01394     if (SUCCEEDED(hr))
01395     {
01396         for (DWORD i = 0; i < m_streams.GetCount(); i++)
01397         {
01398             if (m_streams[i]->IsActive())
01399             {
01400                 hr = m_streams[i]->Pause();
01401             }
01402             if (FAILED(hr))
01403             {
01404                 break;
01405             }
01406         }
01407     }
01408
01409     m_state = STATE_PAUSED;
01410
01411
01412     // Send the "paused" event. This might include a failure code.
01413     (void)m_pEventQueue->QueueEventParamVar(MESourcePaused, GUID_NULL, hr, NULL);
01414
01415     CompleteAsyncOp(pOp);
01416
01417     return hr;
01418 }
01419
01420 //-------------------------------------------------------------------
01421 // DoSetRate
01422 // Perform an async set rate operation (IMFRateControl::SetRate)
01423 //-------------------------------------------------------------------
01424
01425 HRESULT CMPEG1Source::DoSetRate(SourceOp *pOp)
01426 {
01427     HRESULT hr = S_OK;
01428     SetRateOp *pSetRateOp = static_cast<SetRateOp*>(pOp);
01429
01430     hr = BeginAsyncOp(pOp);
01431
01432     // Set rate on active streams.
01433     if (SUCCEEDED(hr))
01434     {
01435         for (DWORD i = 0; i < m_streams.GetCount(); i++)
01436         {
01437             if (m_streams[i]->IsActive())
01438             {
01439                 hr = m_streams[i]->SetRate(pSetRateOp->GetRate());
01440             }
01441             if (FAILED(hr))
01442             {
01443                 break;
01444             }
01445         }
01446     }
01447
01448     if (SUCCEEDED(hr))
01449     {
01450         m_flRate = pSetRateOp->GetRate();
01451     }
01452
01453     // Send the "rate changted" event. This might include a failure code.
01454     (void)m_pEventQueue->QueueEventParamVar(MESourceRateChanged, GUID_NULL, hr, NULL);
01455
01456     CompleteAsyncOp(pOp);
01457
01458     return hr;
01459 }
01460
01461 //-------------------------------------------------------------------
01462 // StreamRequestSample
01463 // Called by streams when they need more data.
01464 //
01465 // Note: This is an async operation. The stream requests more data
01466 // by queueing an OP_REQUEST_DATA operation.
01467 //-------------------------------------------------------------------
01468
01469 HRESULT CMPEG1Source::OnStreamRequestSample(SourceOp *pOp)
01470 {
01471     HRESULT hr = S_OK;
01472
01473     hr = BeginAsyncOp(pOp);
01474
01475     // Ignore this request if we are already handling an earlier request.
01476     // (In that case m_pSampleRequest will be non-NULL.)
01477
01478     if (SUCCEEDED(hr))
01479     {
01480         if (m_pSampleRequest == NULL)
01481         {
01482             // Add the request counter as data to the operation.
01483             // This counter tracks whether a read request becomes "stale."
01484
01485             PROPVARIANT var;
01486             var.vt = VT_UI4;
01487             var.ulVal = m_cRestartCounter;
01488
01489             hr = pOp->SetData(var);
01490
01491             if (SUCCEEDED(hr))
01492             {
01493                 // Store this while the request is pending.
01494                 m_pSampleRequest = pOp;
01495                 m_pSampleRequest->AddRef();
01496
01497                 // Try to parse data - this will invoke a read request if needed.
01498                 ParseData();
01499             }
01500         }
01501
01502         CompleteAsyncOp(pOp);
01503     }
01504
01505     return hr;
01506 }
01507
01508
01509 //-------------------------------------------------------------------
01510 // OnEndOfStream
01511 // Called by each stream when it sends the last sample in the stream.
01512 //
01513 // Note: When the media source reaches the end of the MPEG-1 stream,
01514 // it calls EndOfStream on each stream object. The streams might have
01515 // data still in their queues. As each stream empties its queue, it
01516 // notifies the source through an async OP_END_OF_STREAM operation.
01517 //
01518 // When every stream notifies the source, the source can send the
01519 // "end-of-presentation" event.
01520 //-------------------------------------------------------------------
01521
01522 HRESULT CMPEG1Source::OnEndOfStream(SourceOp *pOp)
01523 {
01524     HRESULT hr = S_OK;
01525
01526     hr = BeginAsyncOp(pOp);
01527
01528     // Decrement the count of end-of-stream notifications.
01529     if (SUCCEEDED(hr))
01530     {
01531         --m_cPendingEOS;
01532         if (m_cPendingEOS == 0)
01533         {
01534             // No more streams. Send the end-of-presentation event.
01535             hr = m_pEventQueue->QueueEventParamVar(MEEndOfPresentation, GUID_NULL, S_OK, NULL);
01536         }
01537
01538     }
01539
01540     if (SUCCEEDED(hr))
01541     {
01542         hr = CompleteAsyncOp(pOp);
01543     }
01544
01545     return hr;
01546 }
01547
01548
01549
01550 //-------------------------------------------------------------------
01551 // SelectStreams
01552 // Called during START operations to select and deselect streams.
01553 //-------------------------------------------------------------------
01554
01555 HRESULT CMPEG1Source::SelectStreams(
01556     IMFPresentationDescriptor *pPD,   // Presentation descriptor.
01557     const PROPVARIANT varStart        // New start position.
01558     )
01559 {
01560     HRESULT hr = S_OK;
01561     BOOL    fSelected = FALSE;
01562     BOOL    fWasSelected = FALSE;
01563     DWORD   stream_id = 0;
01564
01565     IMFStreamDescriptor *pSD = NULL;
01566
01567     CMPEG1Stream *pStream = NULL; // Not add-ref'd
01568
01569     // Reset the pending EOS count.
01570     m_cPendingEOS = 0;
01571
01572     // Loop throught the stream descriptors to find which streams are active.
01573     for (DWORD i = 0; i < m_streams.GetCount(); i++)
01574     {
01575         hr = pPD->GetStreamDescriptorByIndex(i, &fSelected, &pSD);
01576         if (FAILED(hr))
01577         {
01578             goto done;
01579         }
01580
01581         hr = pSD->GetStreamIdentifier(&stream_id);
01582         if (FAILED(hr))
01583         {
01584             goto done;
01585         }
01586
01587         pStream = m_streams.Find((BYTE)stream_id);
01588         if (pStream == NULL)
01589         {
01590             hr = E_INVALIDARG;
01591             goto done;
01592         }
01593
01594         // Was the stream active already?
01595         fWasSelected = pStream->IsActive();
01596
01597         // Activate or deactivate the stream.
01598         hr = pStream->Activate(fSelected);
01599         if (FAILED(hr))
01600         {
01601             goto done;
01602         }
01603
01604         if (fSelected)
01605         {
01606             m_cPendingEOS++;
01607
01608             // If the stream was previously selected, send an "updated stream"
01609             // event. Otherwise, send a "new stream" event.
01610             MediaEventType met = fWasSelected ? MEUpdatedStream : MENewStream;
01611
01612             hr = m_pEventQueue->QueueEventParamUnk(met, GUID_NULL, hr, pStream);
01613             if (FAILED(hr))
01614             {
01615                 goto done;
01616             }
01617
01618             // Start the stream. The stream will send the appropriate event.
01619             hr = pStream->Start(varStart);
01620             if (FAILED(hr))
01621             {
01622                 goto done;
01623             }
01624         }
01625         SafeRelease(&pSD);
01626     }
01627
01628 done:
01629     SafeRelease(&pSD);
01630     return hr;
01631 }
01632
01633
01634 //-------------------------------------------------------------------
01635 // RequestData
01636 // Request the next batch of data.
01637 //
01638 // cbRequest: Amount of data to read, in bytes.
01639 //-------------------------------------------------------------------
01640
01641 HRESULT CMPEG1Source::RequestData(DWORD cbRequest)
01642 {
01643     HRESULT hr = S_OK;
01644
01645     // Reserve a sufficient read buffer.
01646     hr = m_ReadBuffer.Reserve(cbRequest);
01647
01648     // Submit the async read request.
01649     // When it completes, our OnByteStreamRead method will be invoked.
01650
01651     if (SUCCEEDED(hr))
01652     {
01653         hr = m_pByteStream->BeginRead(
01654             m_ReadBuffer.DataPtr() + m_ReadBuffer.DataSize(),
01655             cbRequest,
01656             &m_OnByteStreamRead,
01657             m_pSampleRequest
01658             );
01659     }
01660
01661     return hr;
01662 }
01663
01664
01665 //-------------------------------------------------------------------
01666 // ParseData
01667 // Parses the next batch of data.
01668 //-------------------------------------------------------------------
01669
01670 HRESULT CMPEG1Source::ParseData()
01671 {
01672     HRESULT hr = S_OK;
01673
01674     DWORD cbNextRequest = 0;
01675     BOOL  bNeedMoreData = FALSE;
01676
01677     // Keep processing data until
01678     // (a) All streams have enough samples, or
01679     // (b) The parser needs more data in the buffer.
01680
01681     while ( StreamsNeedData() )
01682     {
01683         DWORD cbAte = 0;    // How much data we consumed from the read buffer.
01684
01685         // Check if we got the first system header.
01686         if (m_pHeader == NULL && m_pParser->HasSystemHeader())
01687         {
01688             hr = m_pParser->GetSystemHeader(&m_pHeader);
01689
01690             if (FAILED(hr)) { break; }
01691         }
01692
01693         if (m_pParser->IsEndOfStream())
01694         {
01695             // The parser reached the end of the MPEG-1 stream. Notify the streams.
01696             hr = EndOfMPEGStream();
01697         }
01698         else if (m_pParser->HasPacket())
01699         {
01700             // The parser reached the start of a new packet.
01701             hr = ReadPayload(&cbAte, &cbNextRequest);
01702         }
01703         else
01704         {
01705             // Parse more data.
01706             hr = m_pParser->ParseBytes(m_ReadBuffer.DataPtr(), m_ReadBuffer.DataSize(), &cbAte);
01707         }
01708
01709         // Parser::ParseBytes() or ReadPayload can return S_FALSE, meaning "Need more data"
01710         if (hr == S_FALSE)
01711         {
01712             bNeedMoreData = TRUE;
01713         }
01714
01715         if (FAILED(hr)) { break; }
01716
01717         // Advance the start of the read buffer by the amount consumed.
01718         hr = m_ReadBuffer.MoveStart(cbAte);
01719
01720         if (FAILED(hr)) { break; }
01721
01722         // If we need more data, start an async read operation.
01723         if (bNeedMoreData)
01724         {
01725             hr = RequestData( max(READ_SIZE, cbNextRequest) );
01726
01727             // Break from the loop because we need to wait for the async read to complete.
01728             break;
01729         }
01730     }
01731
01732     // Flag our state. If a stream requests more data while we are waiting for an async
01733     // read to complete, we can ignore the stream's request, because the request will be
01734     // dispatched as soon as we get more data.
01735
01736     if (SUCCEEDED(hr))
01737     {
01738         if (!bNeedMoreData)
01739         {
01740             SafeRelease(&m_pSampleRequest);
01741         }
01742     }
01743
01744     return hr;
01745 }
01746
01747 //-------------------------------------------------------------------
01748 // ReadPayload
01749 // Read the next MPEG-1 payload.
01750 //
01751 // When this method is called:
01752 // - The read position has reached the beginning of a payload.
01753 // - We have the packet header, but not necessarily the entire payload.
01754 //-------------------------------------------------------------------
01755
01756 HRESULT CMPEG1Source::ReadPayload(DWORD *pcbAte, DWORD *pcbNextRequest)
01757 {
01758     assert(m_pParser != NULL);
01759     assert(m_pParser->HasPacket());
01760
01761     HRESULT hr = S_OK;
01762
01763     DWORD cbPayloadRead = 0;
01764     DWORD cbPayloadUnread = 0;
01765
01766     // At this point, the read buffer might be larger or smaller than the payload.
01767     // Calculate which portion of the payload has been read.
01768     if (m_pParser->PayloadSize() > m_ReadBuffer.DataSize())
01769     {
01770         cbPayloadUnread = m_pParser->PayloadSize() - m_ReadBuffer.DataSize();
01771     }
01772
01773     cbPayloadRead = m_pParser->PayloadSize() - cbPayloadUnread;
01774
01775     // Do we need to deliver this payload?
01776     if ( !IsStreamActive(m_pParser->PacketHeader()) )
01777     {
01778         QWORD qwCurrentPosition = 0;
01779
01780         // Skip this payload. Seek past the unread portion of the payload.
01781         hr = m_pByteStream->Seek(
01782             msoCurrent,
01783             cbPayloadUnread,
01784             MFBYTESTREAM_SEEK_FLAG_CANCEL_PENDING_IO,
01785             &qwCurrentPosition
01786             );
01787
01788         // Advance the data buffer to the end of payload, or the portion
01789         // that has been read.
01790
01791         if (SUCCEEDED(hr))
01792         {
01793             *pcbAte = cbPayloadRead;
01794
01795             // Tell the parser that we are done with this packet.
01796             m_pParser->ClearPacket();
01797         }
01798
01799     }
01800     else if (cbPayloadUnread > 0)
01801     {
01802         // Some portion of this payload has not been read. Schedule a read.
01803         *pcbNextRequest = cbPayloadUnread;
01804
01805         *pcbAte = 0;
01806
01807         hr = S_FALSE; // Need more data.
01808     }
01809     else
01810     {
01811         // The entire payload is in the data buffer. Deliver the packet.
01812         hr = DeliverPayload();
01813
01814         if (SUCCEEDED(hr))
01815         {
01816             *pcbAte = cbPayloadRead;
01817
01818             // Tell the parser that we are done with this packet.
01819             m_pParser->ClearPacket();
01820         }
01821     }
01822
01823     return hr;
01824 }
01825
01826 //-------------------------------------------------------------------
01827 // EndOfMPEGStream:
01828 // Called when the parser reaches the end of the MPEG1 stream.
01829 //-------------------------------------------------------------------
01830
01831 HRESULT CMPEG1Source::EndOfMPEGStream()
01832 {
01833     // Notify the streams. The streams might have pending samples.
01834     // When each stream delivers the last sample, it will send the
01835     // end-of-stream event to the pipeline and then notify the
01836     // source.
01837
01838     // When every stream is done, the source sends the end-of-
01839     // presentation event.
01840
01841     HRESULT hr = S_OK;
01842
01843     for (DWORD i = 0; i < m_streams.GetCount(); i++)
01844     {
01845         if (m_streams[i]->IsActive())
01846         {
01847             hr = m_streams[i]->EndOfStream();
01848         }
01849         if (FAILED(hr))
01850         {
01851             break;
01852         }
01853     }
01854
01855     return hr;
01856 }
01857
01858
01859
01860 //-------------------------------------------------------------------
01861 // StreamsNeedData:
01862 // Returns TRUE if any streams need more data.
01863 //-------------------------------------------------------------------
01864
01865 BOOL CMPEG1Source::StreamsNeedData() const
01866 {
01867     BOOL bNeedData = FALSE;
01868
01869     switch (m_state)
01870     {
01871     case STATE_OPENING:
01872         // While opening, we always need data (until we get enough
01873         // to complete the open operation).
01874         return TRUE;
01875
01876     case STATE_SHUTDOWN:
01877         // While shut down, we never need data.
01878         return FALSE;
01879
01880     default:
01881         // If none of the above, ask the streams.
01882         for (DWORD i = 0; i < m_streams.GetCount(); i++)
01883         {
01884             if (m_streams[i]->NeedsData())
01885             {
01886                 bNeedData = TRUE;
01887                 break;
01888             }
01889         }
01890         return bNeedData;
01891     }
01892 }
01893
01894
01895 //-------------------------------------------------------------------
01896 // DeliverPayload:
01897 // Delivers an MPEG-1 payload.
01898 //-------------------------------------------------------------------
01899
01900 HRESULT CMPEG1Source::DeliverPayload()
01901 {
01902     // When this method is called, the read buffer contains a complete
01903     // payload, and the payload belongs to a stream whose type we support.
01904
01905     assert(m_pParser->HasPacket());
01906
01907     HRESULT             hr = S_OK;
01908     MPEG1PacketHeader   packetHdr;
01909     CMPEG1Stream        *pStream = NULL;    // not AddRef'd
01910
01911     IMFMediaBuffer      *pBuffer = NULL;
01912     IMFSample           *pSample = NULL;
01913     BYTE                *pData = NULL;      // Pointer to the IMFMediaBuffer data.
01914
01915     packetHdr = m_pParser->PacketHeader();
01916
01917     if (packetHdr.cbPayload > m_ReadBuffer.DataSize())
01918     {
01919         assert(FALSE);
01920         hr = E_UNEXPECTED;
01921     }
01922
01923     // If we are still opening the file, then we might need to create this stream.
01924     if (SUCCEEDED(hr))
01925     {
01926         if (m_state == STATE_OPENING)
01927         {
01928             hr = CreateStream(packetHdr);
01929         }
01930     }
01931
01932     if (SUCCEEDED(hr))
01933     {
01934         pStream = m_streams.Find(packetHdr.stream_id);
01935         assert(pStream != NULL);
01936     }
01937
01938     // Create a media buffer for the payload.
01939     if (SUCCEEDED(hr))
01940     {
01941         hr = MFCreateMemoryBuffer(packetHdr.cbPayload, &pBuffer);
01942     }
01943
01944     if (SUCCEEDED(hr))
01945     {
01946         hr = pBuffer->Lock(&pData, NULL, NULL);
01947     }
01948
01949     if (SUCCEEDED(hr))
01950     {
01951         CopyMemory(pData, m_ReadBuffer.DataPtr(), packetHdr.cbPayload);
01952     }
01953
01954     if (SUCCEEDED(hr))
01955     {
01956         hr = pBuffer->Unlock();
01957     }
01958
01959     if (SUCCEEDED(hr))
01960     {
01961         hr = pBuffer->SetCurrentLength(packetHdr.cbPayload);
01962     }
01963
01964     // Create a sample to hold the buffer.
01965     if (SUCCEEDED(hr))
01966     {
01967         hr = MFCreateSample(&pSample);
01968     }
01969     if (SUCCEEDED(hr))
01970     {
01971         hr = pSample->AddBuffer(pBuffer);
01972     }
01973
01974     // Time stamp the sample.
01975     if (SUCCEEDED(hr))
01976     {
01977         if (packetHdr.bHasPTS)
01978         {
01979             LONGLONG hnsStart = packetHdr.PTS * 10000 / 90;
01980
01981             hr = pSample->SetSampleTime(hnsStart);
01982         }
01983     }
01984
01985     // Deliver the payload to the stream.
01986     if (SUCCEEDED(hr))
01987     {
01988         hr = pStream->DeliverPayload(pSample);
01989     }
01990
01991     // If the open operation is still pending, check if we're done.
01992     if (SUCCEEDED(hr))
01993     {
01994         if (m_state == STATE_OPENING)
01995         {
01996             hr = InitPresentationDescriptor();
01997         }
01998     }
01999
02000     SafeRelease(&pBuffer);
02001     SafeRelease(&pSample);
02002     return hr;
02003 }
02004
02005
02006
02007 //-------------------------------------------------------------------
02008 // CreateStream:
02009 // Creates a media stream, based on a packet header.
02010 //-------------------------------------------------------------------
02011
02012 HRESULT CMPEG1Source::CreateStream(const MPEG1PacketHeader& packetHdr)
02013 {
02014     // We validate the stream type before calling this method.
02015     assert(IsStreamTypeSupported(packetHdr.type));
02016
02017
02018     // First see if the stream already exists.
02019     if ( m_streams.Find(packetHdr.stream_id) != NULL )
02020     {
02021         // The stream already exists. Nothing to do.
02022         return S_OK;
02023     }
02024
02025     HRESULT hr = S_OK;
02026     DWORD cbAte = 0;
02027     BYTE *pPayload = NULL;
02028
02029     IMFMediaType *pType = NULL;
02030     IMFStreamDescriptor *pSD = NULL;
02031     CMPEG1Stream *pStream = NULL;
02032     IMFMediaTypeHandler *pHandler = NULL;
02033
02034     MPEG1VideoSeqHeader videoSeqHdr;
02035     MPEG1AudioFrameHeader audioFrameHeader;
02036
02037     // Get a pointer to the start of the payload.
02038     pPayload = m_ReadBuffer.DataPtr();
02039
02040     // Create a media type, based on the packet type (audio/video)
02041     switch (packetHdr.type)
02042     {
02043     case StreamType_Video:
02044         // Video: Read the sequence header and use it to create a media type.
02045         hr = ReadVideoSequenceHeader(pPayload, packetHdr.cbPayload, videoSeqHdr, &cbAte);
02046         if (SUCCEEDED(hr))
02047         {
02048             hr = CreateVideoMediaType(videoSeqHdr, &pType);
02049         }
02050         break;
02051
02052     case StreamType_Audio:
02053         // Audio: Read the frame header and use it to create a media type.
02054         hr = ReadAudioFrameHeader(pPayload, packetHdr.cbPayload, audioFrameHeader, &cbAte);
02055         if (SUCCEEDED(hr))
02056         {
02057             hr = CreateAudioMediaType(audioFrameHeader, &pType);
02058         }
02059         break;
02060
02061     default:
02062         assert(false); // If this case occurs, then IsStreamTypeSupported() is wrong.
02063         hr = E_UNEXPECTED;
02064     }
02065
02066     if (SUCCEEDED(hr))
02067     {
02068         // Create the stream descriptor from the media type.
02069         hr = MFCreateStreamDescriptor(packetHdr.stream_id, 1, &pType, &pSD);
02070     }
02071
02072     // Set the default media type on the stream handler.
02073     if (SUCCEEDED(hr))
02074     {
02075         hr = pSD->GetMediaTypeHandler(&pHandler);
02076     }
02077     if (SUCCEEDED(hr))
02078     {
02079         hr = pHandler->SetCurrentMediaType(pType);
02080     }
02081
02082     // Create the new stream.
02083     if (SUCCEEDED(hr))
02084     {
02085         pStream = new (std::nothrow) CMPEG1Stream(this, pSD, hr);
02086         if (pStream == NULL)
02087         {
02088             hr = E_OUTOFMEMORY;
02089         }
02090     }
02091
02092     // Add the stream to the array.
02093     if (SUCCEEDED(hr))
02094     {
02095         hr = m_streams.AddStream(packetHdr.stream_id, pStream);
02096     }
02097
02098     SafeRelease(&pSD);
02099     SafeRelease(&pStream);
02100     return hr;
02101 }
02102
02103
02104 //-------------------------------------------------------------------
02105 // ValidatePresentationDescriptor:
02106 // Validates the presentation descriptor that the caller specifies
02107 // in IMFMediaSource::Start().
02108 //
02109 // Note: This method performs a basic sanity check on the PD. It is
02110 // not intended to be a thorough validation.
02111 //-------------------------------------------------------------------
02112
02113 HRESULT CMPEG1Source::ValidatePresentationDescriptor(IMFPresentationDescriptor *pPD)
02114 {
02115     HRESULT hr = S_OK;
02116     BOOL fSelected = FALSE;
02117     DWORD cStreams = 0;
02118
02119     IMFStreamDescriptor *pSD = NULL;
02120
02121     if (m_pHeader == NULL)
02122     {
02123         return E_UNEXPECTED;
02124     }
02125
02126     // The caller's PD must have the same number of streams as ours.
02127     hr = pPD->GetStreamDescriptorCount(&cStreams);
02128
02129     if (SUCCEEDED(hr))
02130     {
02131         if (cStreams != m_pHeader->cStreams)
02132         {
02133             hr = E_INVALIDARG;
02134         }
02135     }
02136
02137     // The caller must select at least one stream.
02138     if (SUCCEEDED(hr))
02139     {
02140         for (DWORD i = 0; i < cStreams; i++)
02141         {
02142             hr = pPD->GetStreamDescriptorByIndex(i, &fSelected, &pSD);
02143             if (FAILED(hr))
02144             {
02145                 break;
02146             }
02147             if (fSelected)
02148             {
02149                 break;
02150             }
02151             SafeRelease(&pSD);
02152         }
02153     }
02154
02155     if (SUCCEEDED(hr))
02156     {
02157         if (!fSelected)
02158         {
02159             hr = E_INVALIDARG;
02160         }
02161     }
02162
02163     SafeRelease(&pSD);
02164     return hr;
02165 }
02166
02167
02168 //-------------------------------------------------------------------
02169 // StreamingError:
02170 // Handles an error that occurs duing an asynchronous operation.
02171 //
02172 // hr: Error code of the operation that failed.
02173 //-------------------------------------------------------------------
02174
02175 void CMPEG1Source::StreamingError(HRESULT hr)
02176 {
02177     if (m_state == STATE_OPENING)
02178     {
02179         // An error happened during BeginOpen.
02180         // Invoke the callback with the status code.
02181
02182         CompleteOpen(hr);
02183     }
02184     else if (m_state != STATE_SHUTDOWN)
02185     {
02186         // An error occurred during streaming. Send the MEError event
02187         // to notify the pipeline.
02188
02189         QueueEvent(MEError, GUID_NULL, hr, NULL);
02190     }
02191 }
02192
02193 BOOL CMPEG1Source::IsRateSupported(float flRate, float *pflAdjustedRate)
02194 {
02195     if (flRate < 0.00001f && flRate > -0.00001f)
02196     {
02197         *pflAdjustedRate = 0.0f;
02198         return TRUE;
02199     }
02200     else if(flRate < 1.0001f && flRate > 0.9999f)
02201     {
02202         *pflAdjustedRate = 1.0f;
02203         return TRUE;
02204     }
02205     return FALSE;
02206 }
02207
02208
02209 /* SourceOp class */
02210
02211
02212 //-------------------------------------------------------------------
02213 // CreateOp
02214 // Static method to create a SourceOp instance.
02215 //
02216 // op: Specifies the async operation.
02217 // ppOp: Receives a pointer to the SourceOp object.
02218 //-------------------------------------------------------------------
02219
02220 HRESULT SourceOp::CreateOp(SourceOp::Operation op, SourceOp **ppOp)
02221 {
02222     if (ppOp == NULL)
02223     {
02224         return E_POINTER;
02225     }
02226
02227     SourceOp *pOp = new (std::nothrow) SourceOp(op);
02228     if (pOp  == NULL)
02229     {
02230         return E_OUTOFMEMORY;
02231     }
02232     *ppOp = pOp;
02233
02234     return S_OK;
02235 }
02236
02237 //-------------------------------------------------------------------
02238 // CreateStartOp:
02239 // Static method to create a SourceOp instance for the Start()
02240 // operation.
02241 //
02242 // pPD: Presentation descriptor from the caller.
02243 // ppOp: Receives a pointer to the SourceOp object.
02244 //-------------------------------------------------------------------
02245
02246 HRESULT SourceOp::CreateStartOp(IMFPresentationDescriptor *pPD, SourceOp **ppOp)
02247 {
02248     if (ppOp == NULL)
02249     {
02250         return E_POINTER;
02251     }
02252
02253     SourceOp *pOp = new (std::nothrow) StartOp(pPD);
02254     if (pOp == NULL)
02255     {
02256         return E_OUTOFMEMORY;
02257     }
02258
02259     *ppOp = pOp;
02260     return S_OK;
02261 }
02262
02263 //-------------------------------------------------------------------
02264 // CreateSetRateOp:
02265 // Static method to create a SourceOp instance for the SetRate()
02266 // operation.
02267 //
02268 // fThin: TRUE - thinning is on, FALSE otherwise
02269 // flRate: New rate
02270 // ppOp: Receives a pointer to the SourceOp object.
02271 //-------------------------------------------------------------------
02272
02273 HRESULT SourceOp::CreateSetRateOp(BOOL fThin, float flRate, SourceOp **ppOp)
02274 {
02275     if (ppOp == NULL)
02276     {
02277         return E_POINTER;
02278     }
02279
02280     SourceOp *pOp = new (std::nothrow) SetRateOp(fThin, flRate);
02281     if (pOp == NULL)
02282     {
02283         return E_OUTOFMEMORY;
02284     }
02285
02286     *ppOp = pOp;
02287     return S_OK;
02288 }
02289
02290 ULONG SourceOp::AddRef()
02291 {
02292     return _InterlockedIncrement(&m_cRef);
02293 }
02294
02295 ULONG SourceOp::Release()
02296 {
02297     LONG cRef = _InterlockedDecrement(&m_cRef);
02298     if (cRef == 0)
02299     {
02300         delete this;
02301     }
02302     return cRef;
02303 }
02304
02305 HRESULT SourceOp::QueryInterface(REFIID riid, void** ppv)
02306 {
02307     if (ppv == nullptr)
02308     {
02309         return E_POINTER;
02310     }
02311
02312     HRESULT hr = E_NOINTERFACE;
02313     if (riid == IID_IUnknown)
02314     {
02315         (*ppv) = static_cast<IUnknown *>(this);
02316         AddRef();
02317         hr = S_OK;
02318     }
02319
02320     return hr;
02321 }
02322
02323 SourceOp::SourceOp(Operation op) : m_cRef(1), m_op(op)
02324 {
02325     ZeroMemory(&m_data, sizeof(m_data));
02326 }
02327
02328 SourceOp::~SourceOp()
02329 {
02330     PropVariantClear(&m_data);
02331 }
02332
02333 HRESULT SourceOp::SetData(const PROPVARIANT& var)
02334 {
02335     return PropVariantCopy(&m_data, &var);
02336 }
02337
02338
02339 StartOp::StartOp(IMFPresentationDescriptor *pPD) : SourceOp(SourceOp::OP_START), m_pPD(pPD)
02340 {
02341     if (m_pPD)
02342     {
02343         m_pPD->AddRef();
02344     }
02345 }
02346
02347 StartOp::~StartOp()
02348 {
02349     SafeRelease(&m_pPD);
02350 }
02351
02352
02353 HRESULT StartOp::GetPresentationDescriptor(IMFPresentationDescriptor **ppPD)
02354 {
02355     if (ppPD == NULL)
02356     {
02357         return E_POINTER;
02358     }
02359     if (m_pPD == NULL)
02360     {
02361         return MF_E_INVALIDREQUEST;
02362     }
02363     *ppPD = m_pPD;
02364     (*ppPD)->AddRef();
02365     return S_OK;
02366 }
02367
02368 SetRateOp::SetRateOp(BOOL fThin, float flRate)
02369 : SourceOp(SourceOp::OP_SETRATE)
02370 , m_fThin(fThin)
02371 , m_flRate(flRate)
02372 {
02373 }
02374
02375 SetRateOp::~SetRateOp()
02376 {
02377 }
02378
02379 /*  Static functions */
02380
02381
02382 //-------------------------------------------------------------------
02383 // CreateVideoMediaType:
02384 // Create a media type from an MPEG-1 video sequence header.
02385 //-------------------------------------------------------------------
02386
02387 HRESULT CreateVideoMediaType(const MPEG1VideoSeqHeader& videoSeqHdr, IMFMediaType **ppType)
02388 {
02389     HRESULT hr = S_OK;
02390
02391     IMFMediaType *pType = NULL;
02392
02393     hr = MFCreateMediaType(&pType);
02394
02395     if (SUCCEEDED(hr))
02396     {
02397         hr = pType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video);
02398     }
02399
02400     // Subtype = MPEG-1 payload
02401     if (SUCCEEDED(hr))
02402     {
02403         hr = pType->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_MPG1);
02404     }
02405
02406     // Format details.
02407     if (SUCCEEDED(hr))
02408     {
02409         // Frame size
02410
02411         hr = MFSetAttributeSize(
02412             pType,
02413             MF_MT_FRAME_SIZE,
02414             videoSeqHdr.width,
02415             videoSeqHdr.height
02416             );
02417     }
02418     if (SUCCEEDED(hr))
02419     {
02420         // Frame rate
02421
02422         hr = MFSetAttributeRatio(
02423             pType,
02424             MF_MT_FRAME_RATE,
02425             videoSeqHdr.frameRate.Numerator,
02426             videoSeqHdr.frameRate.Denominator
02427             );
02428     }
02429     if (SUCCEEDED(hr))
02430     {
02431         // Pixel aspect ratio
02432
02433         hr = MFSetAttributeRatio(
02434             pType,
02435             MF_MT_PIXEL_ASPECT_RATIO,
02436             videoSeqHdr.pixelAspectRatio.Numerator,
02437             videoSeqHdr.pixelAspectRatio.Denominator
02438             );
02439     }
02440     if (SUCCEEDED(hr))
02441     {
02442         // Average bit rate
02443
02444         hr = pType->SetUINT32(MF_MT_AVG_BITRATE, videoSeqHdr.bitRate);
02445     }
02446     if (SUCCEEDED(hr))
02447     {
02448
02449         // Interlacing (progressive frames)
02450
02451         hr = pType->SetUINT32(MF_MT_INTERLACE_MODE, (UINT32)MFVideoInterlace_Progressive);
02452     }
02453     if (SUCCEEDED(hr))
02454     {
02455         // Sequence header.
02456
02457         hr = pType->SetBlob(
02458             MF_MT_MPEG_SEQUENCE_HEADER,
02459             videoSeqHdr.header,             // Byte array
02460             videoSeqHdr.cbHeader            // Size
02461             );
02462     }
02463
02464     if (SUCCEEDED(hr))
02465     {
02466         *ppType = pType;
02467         (*ppType)->AddRef();
02468     }
02469
02470     SafeRelease(&pType);
02471     return hr;
02472 }
02473
02474
02475 //-------------------------------------------------------------------
02476 // CreateAudioMediaType:
02477 // Create a media type from an MPEG-1 audio frame header.
02478 //
02479 // Note: This function fills in an MPEG1WAVEFORMAT structure and then
02480 // converts the structure to a Media Foundation media type
02481 // (IMFMediaType). This is somewhat roundabout but it guarantees
02482 // that the type can be converted back to an MPEG1WAVEFORMAT by the
02483 // decoder if need be.
02484 //
02485 // The WAVEFORMATEX portion of the MPEG1WAVEFORMAT structure is
02486 // converted into attributes on the IMFMediaType object. The rest of
02487 // the struct is stored in the MF_MT_USER_DATA attribute.
02488 //-------------------------------------------------------------------
02489
02490 HRESULT CreateAudioMediaType(const MPEG1AudioFrameHeader& audioHeader, IMFMediaType **ppType)
02491 {
02492     HRESULT hr = S_OK;
02493     IMFMediaType *pType = NULL;
02494
02495     MPEG1WAVEFORMAT format;
02496     ZeroMemory(&format, sizeof(format));
02497
02498     format.wfx.wFormatTag = WAVE_FORMAT_MPEG;
02499     format.wfx.nChannels = audioHeader.nChannels;
02500     format.wfx.nSamplesPerSec = audioHeader.dwSamplesPerSec;
02501     if (audioHeader.dwBitRate > 0)
02502     {
02503         format.wfx.nAvgBytesPerSec = (audioHeader.dwBitRate * 1000) / 8;
02504     }
02505     format.wfx.nBlockAlign = audioHeader.nBlockAlign;
02506     format.wfx.wBitsPerSample = 0; // Not used.
02507     format.wfx.cbSize = sizeof(MPEG1WAVEFORMAT) - sizeof(WAVEFORMATEX);
02508
02509     // MPEG-1 audio layer.
02510     switch (audioHeader.layer)
02511     {
02512     case MPEG1_Audio_Layer1:
02513         format.fwHeadLayer = ACM_MPEG_LAYER1;
02514         break;
02515
02516     case MPEG1_Audio_Layer2:
02517         format.fwHeadLayer = ACM_MPEG_LAYER2;
02518         break;
02519
02520     case MPEG1_Audio_Layer3:
02521         format.fwHeadLayer = ACM_MPEG_LAYER3;
02522         break;
02523     };
02524
02525     format.dwHeadBitrate = audioHeader.dwBitRate * 1000;
02526
02527     // Mode
02528     switch (audioHeader.mode)
02529     {
02530     case MPEG1_Audio_Stereo:
02531         format.fwHeadMode = ACM_MPEG_STEREO;
02532         break;
02533
02534     case MPEG1_Audio_JointStereo:
02535         format.fwHeadMode = ACM_MPEG_JOINTSTEREO;
02536         break;
02537
02538     case MPEG1_Audio_DualChannel:
02539         format.fwHeadMode = ACM_MPEG_DUALCHANNEL;
02540         break;
02541
02542     case MPEG1_Audio_SingleChannel:
02543         format.fwHeadMode = ACM_MPEG_SINGLECHANNEL;
02544         break;
02545     };
02546
02547     if (audioHeader.mode == ACM_MPEG_JOINTSTEREO)
02548     {
02549         // Convert the 'mode_extension' field to the correct MPEG1WAVEFORMAT value.
02550         if (audioHeader.modeExtension <= 0x03)
02551         {
02552             format.fwHeadModeExt = 0x01 << audioHeader.modeExtension;
02553         }
02554     }
02555
02556     // Convert the 'emphasis' field to the correct MPEG1WAVEFORMAT value.
02557     if (audioHeader.emphasis <= 0x03)
02558     {
02559         format.wHeadEmphasis = audioHeader.emphasis + 1;
02560     }
02561
02562     // The flags translate directly.
02563     format.fwHeadFlags = audioHeader.wFlags;
02564     // Add the "MPEG-1" flag, although it's somewhat redundant.
02565     format.fwHeadFlags |= ACM_MPEG_ID_MPEG1;
02566
02567     // Use the structure to initialize the Media Foundation media type.
02568     hr = MFCreateMediaType(&pType);
02569     if (SUCCEEDED(hr))
02570     {
02571         hr = MFInitMediaTypeFromWaveFormatEx(pType, (const WAVEFORMATEX*)&format, sizeof(format));
02572     }
02573
02574     if (SUCCEEDED(hr))
02575     {
02576         *ppType = pType;
02577         (*ppType)->AddRef();
02578     }
02579
02580     SafeRelease(&pType);
02581     return hr;
02582 }
02583
02584 // Get the major media type from a stream descriptor.
02585 HRESULT GetStreamMajorType(IMFStreamDescriptor *pSD, GUID *pguidMajorType)
02586 {
02587     if (pSD == NULL) { return E_POINTER; }
02588     if (pguidMajorType == NULL) { return E_POINTER; }
02589
02590     HRESULT hr = S_OK;
02591     IMFMediaTypeHandler *pHandler = NULL;
02592
02593     hr = pSD->GetMediaTypeHandler(&pHandler);
02594     if (SUCCEEDED(hr))
02595     {
02596         hr = pHandler->GetMajorType(pguidMajorType);
02597     }
02598     SafeRelease(&pHandler);
02599     return hr;
02600 }
02601
02602
02603 BOOL SampleRequestMatch(SourceOp *pOp1, SourceOp *pOp2)
02604 {
02605     if ((pOp1 == NULL) && (pOp2 == NULL))
02606     {
02607         return TRUE;
02608     }
02609     else if ((pOp1 == NULL) || (pOp2 == NULL))
02610     {
02611         return FALSE;
02612     }
02613     else
02614     {
02615         return (pOp1->Data().ulVal == pOp2->Data().ulVal);
02616     }
02617 }
02618
02619 #pragma warning( pop )
Generated on Sat Nov 23 2024 16:08:21 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/Level5.cpp Source File

  • DirectX 3D shooting game

Level5.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 "Level5.h"
00010 #include "Cylinder.h"
00011 #include "Animate.h"
00012
00013 using namespace DirectX;
00014
00015 //----------------------------------------------------------------------
00016
00017 Level5::Level5()
00018 {
00019     m_timeLimit = 30.0f;
00020     m_objective = "Hit each of the moving targets while avoiding the obstacles before time runs out.";
00021 }
00022
00023 //----------------------------------------------------------------------
00024
00025 void Level5::Initialize(std::vector<GameObject^> objects)
00026 {
00027     Level3::Initialize(objects);
00028
00029     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     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     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.begin(); object != objects.end(); object++)
00056     {
00057         if (Cylinder^ obstacle = dynamic_cast<Cylinder^>(*object))
00058         {
00059             if (obstacleCount < 5)
00060             {
00061                 obstacle->Active(true);
00062                 obstacle->Position(obstacleStartPosition[obstacleCount]);
00063                 obstacle->AnimatePosition(
00064                     ref new AnimateLinePosition(
00065                         obstacleStartPosition[obstacleCount],
00066                         obstacleEndPosition[obstacleCount],
00067                         10.0,
00068                         false
00069                         )
00070                     );
00071                 obstacle->AnimatePosition()->Start(obstacleStartTime[obstacleCount]);
00072                 obstacleCount ++;
00073             }
00074         }
00075     }
00076 }
00077
00078 //----------------------------------------------------------------------
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Sharing content target app/C++/common/LayoutAwarePage.h Source File

  • Sharing content target app
  • common

LayoutAwarePage.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 #include <collection.h>
00015
00016 namespace ShareTarget
00017 {
00018     namespace Common
00019     {
00020         /// <summary>
00021         /// Typical implementation of Page that provides several important conveniences: application
00022         /// view state to visual state mapping, GoBack and GoHome event handlers, and a default view
00023         /// model.
00024         /// </summary>
00025         [Windows::Foundation::Metadata::WebHostHidden]
00026         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00027         {
00028         internal:
00029             LayoutAwarePage();
00030
00031         public:
00032             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00033             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00034             void InvalidateVisualState();
00035             property bool UseFilledStateForNarrowWindow
00036             {
00037                 bool get();
00038                 void set(bool value);
00039             }
00040             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Object^>^ DefaultViewModel
00041             {
00042                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Object^>^ get();
00043             }
00044
00045         protected:
00046             virtual void GoHome(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             virtual void GoBack(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00049
00050         private:
00051             bool _useFilledStateForNarrowWindow;
00052             Platform::Collections::Map<Platform::String^, Object^>^ _defaultViewModel;
00053             Windows::Foundation::EventRegistrationToken _windowSizeEventToken;
00054             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00055             void WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00056         };
00057     }
00058 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: UI Automation core window provider/C++/TriColorWindow.h Source File

  • UI Automation core window provider

TriColorWindow.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 // Main window for the TriColor sample provider
00009 #pragma once
00010
00011 #include "DirectXBase.h"
00012
00013 #using "UiaCoreWindowProvider.winmd"
00014
00015 // The main window for the target provider
00016 // Implemented on top of ICoreWindow interface
00017
00018 // The C4691 warning can ignored given that the UiaCoreWindowProvider::Framework::Rect and Point data types referenced below
00019 // are contained in the InternalInterfaces_w.winmd file being regenerated during the build from the InternalInterfaces.idl,
00020 // (which has the Rect and Point data types in the UiaCoreWindowProvider.Framework namespace.)
00021 #pragma warning(push)
00022 #pragma warning(disable: 4691)
00023
00024 ref class CTriColorWindow sealed:
00025         public DirectXBase,
00026         public Windows::ApplicationModel::Core::IFrameworkView,
00027         public UiaCoreWindowProvider::ITriColorControlInternal
00028 {
00029 public:
00030     CTriColorWindow();
00031
00032     // DirectXBase Methods
00033     virtual void CreateDeviceIndependentResources() override;
00034     virtual void CreateDeviceResources() override;
00035     virtual void CreateWindowSizeDependentResources() override;
00036     virtual void Render() override;
00037
00038     // IFrameworkView Methods
00039     virtual void Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00040     virtual void SetWindow(_In_ Windows::UI::Core::CoreWindow^ window);
00041     virtual void Load(_In_ Platform::String^ entryPoint);
00042     virtual void Run();
00043     virtual void Uninitialize();
00044
00045     // ITriColorControlInternal
00046     virtual property UiaCoreWindowProvider::TriColorValue ControlValue
00047     {
00048         UiaCoreWindowProvider::TriColorValue get();
00049         void set(_In_ UiaCoreWindowProvider::TriColorValue value);
00050     }
00051     virtual property short HasFocus
00052     {
00053         short get();
00054     }
00055     virtual property Windows::Foundation::Rect ControlRect
00056     {
00057         Windows::Foundation::Rect get();
00058     }
00059     virtual Windows::Foundation::Rect RectFromValue(_In_ UiaCoreWindowProvider::TriColorValue value);
00060     virtual UiaCoreWindowProvider::TriColorValue ValueFromPoint(_In_ Windows::Foundation::Point pt);
00061     virtual Platform::Object ^GetAppWindowProvider();
00062     virtual Platform::Object ^GetTriColorControlProvider();
00063     virtual Platform::Object ^GetTriColorFragmentProvider(_In_ UiaCoreWindowProvider::TriColorValue value);
00064
00065 private:
00066
00067     ~CTriColorWindow();
00068
00069     void OnWindowSizeChanged(
00070         _In_ Windows::UI::Core::CoreWindow^ sender,
00071         _In_ Windows::UI::Core::WindowSizeChangedEventArgs^ args
00072         );
00073
00074     void OnLogicalDpiChanged(
00075         _In_ Platform::Object^ sender
00076         );
00077
00078     void OnDisplayContentsInvalidated(
00079         _In_ Platform::Object^ sender
00080         );
00081
00082     void OnActivated(
00083         _In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView,
00084         _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^ args
00085         );
00086
00087     void OnSuspending(
00088         _In_ Platform::Object^ sender,
00089         _In_ Windows::ApplicationModel::SuspendingEventArgs^ args
00090         );
00091
00092     void OnResuming(
00093         _In_ Platform::Object^ sender,
00094         _In_ Platform::Object^ args
00095         );
00096
00097     void OnKeyDown(
00098         _In_ Windows::UI::Core::CoreWindow^ sender,
00099         _In_ Windows::UI::Core::KeyEventArgs^ e
00100         );
00101
00102     void OnPointerReleased(
00103         _In_ Windows::UI::Core::CoreWindow^ sender,
00104         _In_ Windows::UI::Core::PointerEventArgs^ e
00105         );
00106
00107     void OnWindowActivated(
00108         _In_ Windows::UI::Core::CoreWindow^ sender,
00109         _In_ Windows::UI::Core::WindowActivatedEventArgs^ e
00110         );
00111
00112     void OnWindowClosed(
00113         _In_ Windows::UI::Core::CoreWindow^ sender,
00114         _In_ Windows::UI::Core::CoreWindowEventArgs^ e
00115         );
00116
00117     void OnAutomationProviderRequested(
00118         _In_ Windows::UI::Core::CoreWindow^ sender,
00119         _In_ Windows::UI::Core::AutomationProviderRequestedEventArgs ^e
00120         );
00121
00122     void OnHighContrastChanged(
00123         _In_ Windows::UI::ViewManagement::AccessibilitySettings^ sender,
00124         _In_ Platform::Object^ e
00125         );
00126
00127     void CreateThemeSpecificResources();
00128     void DiscardThemeSpecificResources();
00129
00130     void EnsureAppWindowProviderCreated();
00131     void EnsureControlProviderCreated();
00132     void EnsureFragmentProviderCreated(_In_ UiaCoreWindowProvider::TriColorValue value);
00133
00134     Windows::Foundation::Rect GetRedRect();
00135     Windows::Foundation::Rect GetYellowRect();
00136     Windows::Foundation::Rect GetGreenRect();
00137     HRESULT ValueFromPoint(_In_ Windows::Foundation::Point pt, _Out_ UiaCoreWindowProvider::TriColorValue * value);
00138     void SetValue(_In_ UiaCoreWindowProvider::TriColorValue newValue);
00139     static bool PointInRect(_In_ Windows::Foundation::Rect rect, _In_ Windows::Foundation::Point pt);
00140
00141 private:
00142
00143     Windows::UI::ViewManagement::AccessibilitySettings^ m_accSettings;
00144     Windows::UI::ViewManagement::UISettings^ m_uiSettings;
00145
00146     Platform::Object^ m_appWindowProvider;
00147     Platform::Object^ m_controlProvider;
00148     Platform::Object^ m_redProvider;
00149     Platform::Object^ m_yellowProvider;
00150     Platform::Object^ m_greenProvider;
00151
00152     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> m_windowTextBrush;
00153     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> m_blackBrush;
00154     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> m_whiteBrush;
00155     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> m_redBrush;
00156     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> m_yellowBrush;
00157     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> m_greenBrush;
00158     Microsoft::WRL::ComPtr<IDWriteTextFormat> m_titleFormat;
00159     Microsoft::WRL::ComPtr<IDWriteTextFormat> m_labelFormat;
00160
00161     Windows::Foundation::Rect m_controlRect;
00162     UiaCoreWindowProvider::TriColorValue m_value;
00163     bool m_activated;
00164 };
00165
00166 #pragma warning(pop)
00167
00168 // A factory to create TriColorWindow objects.
00169 ref class CTriColorWindowFactory : public Windows::ApplicationModel::Core::IFrameworkViewSource
00170 {
00171 public:
00172     virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00173 };
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX marble maze game/C++/DDSTextureLoader.h Source File

  • DirectX marble maze game

DDSTextureLoader.h

Go to the documentation of this file.
00001 //--------------------------------------------------------------------------------------
00002 // File: DDSTextureLoader.h
00003 //
00004 // Function for loading a DDS texture and creating a Direct3D 11 runtime resource for it
00005 //
00006 // Note this function is 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
00018 #pragma once
00019
00020 void CreateDDSTextureFromMemory(
00021     _In_ ID3D11Device* d3dDevice,
00022     _In_reads_bytes_(ddsDataSize) const byte* ddsData,
00023     _In_ size_t ddsDataSize,
00024     _Out_opt_ ID3D11Resource** texture,
00025     _Out_opt_ ID3D11ShaderResourceView** textureView,
00026     _In_ size_t maxsize = 0
00027     );
Generated on Sat Nov 23 2024 16:08:11 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text display/C++/Common/LayoutAwarePage.h Source File

  • XAML text display
  • Common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: PlayToReceiver/C++/MainPage.xaml.cpp Source File

  • PlayToReceiver

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:43 for Win8-Examples by doxygen 1.7.1


Win8-Examples: OrientationSensor/C++/Scenario1.xaml.h Source File

  • OrientationSensor

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 SDKSample
00023 {
00024     namespace OrientationSensorCPP
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 Scenario1 sealed
00031         {
00032         public:
00033             Scenario1();
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             MainPage^ rootPage;
00041             Windows::Devices::Sensors::OrientationSensor^ sensor;
00042             Windows::Foundation::EventRegistrationToken visibilityToken;
00043             Windows::Foundation::EventRegistrationToken readingToken;
00044             uint32 desiredReportInterval;
00045
00046             void VisibilityChanged(Platform::Object^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ e);
00047             void ReadingChanged(Windows::Devices::Sensors::OrientationSensor^ sender, Windows::Devices::Sensors::OrientationSensorReadingChangedEventArgs^ 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     }
00052 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text editing/C++/Common/LayoutAwarePage.h Source File

  • XAML text editing
  • Common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: User domain name/C++/pch.cpp Source File

  • User domain name

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: LightSensor/C++/MainPage.xaml.cpp Source File

  • LightSensor

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:42 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Hilo::CalendarExtensions Member List

This is the complete list of members for Hilo::CalendarExtensions, including all inherited members.
CreateMonthRangeFromDate(const Windows::Foundation::DateTime date) | Hilo::CalendarExtensions | [static]
CreateMonthRangeFromDate(Windows::Globalization::Calendar^cal) | Hilo::CalendarExtensions | [private, static]
CreateMonthRangeFromYearAndMonth(int year, int month) | Hilo::CalendarExtensions | [static]
GetAqsFormattedDate(const Windows::Foundation::DateTime date) | Hilo::CalendarExtensions | [private, static]
GetCalendar() | Hilo::CalendarExtensions | [private, static]
GetLocalizedAbbreviatedMonthName(int year, int month) | Hilo::CalendarExtensions | [static]
GetLocalizedMonthAndYear(const Windows::Foundation::DateTime date) | Hilo::CalendarExtensions | [static]
GetLocalizedYear(const Windows::Foundation::DateTime yearDate) | Hilo::CalendarExtensions | [static]
GetNumberOfMonthsInYear(const Windows::Foundation::DateTime yearDate) | Hilo::CalendarExtensions | [static]
GetNumericYear(const Windows::Foundation::DateTime yearDate) | Hilo::CalendarExtensions | [static]
ResolvedGeographicRegion() | Hilo::CalendarExtensions | [static]
ResolvedLanguage() | Hilo::CalendarExtensions | [static]
WriteLocalizedYearAndMonth(const Windows::Foundation::DateTime date, int &yearResult, int &monthResult) | Hilo::CalendarExtensions | [static]
Generated on Sat Nov 23 2024 16:09:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D tutorial/C++/Lesson3.Cubes/pch.h Source File

  • Direct3D tutorial
  • Lesson3.Cubes

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 <d3d11_1.h>
00012 #include <agile.h>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/Animate.cpp Source File

  • DirectX 3D shooting game

Animate.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 "Animate.h"
00010
00011 using namespace DirectX;
00012
00013 //----------------------------------------------------------------------
00014
00015 Animate::Animate():
00016     m_continuous(false),
00017     m_startTime(0.0f),
00018     m_duration(10.0f)
00019 {
00020 }
00021
00022 //----------------------------------------------------------------------
00023
00024 float Animate::Start()
00025 {
00026     return m_startTime;
00027 }
00028
00029 //----------------------------------------------------------------------
00030
00031 void Animate::Start(_In_ float start)
00032 {
00033     m_startTime = start;
00034 }
00035
00036 //----------------------------------------------------------------------
00037
00038 float Animate::Duration()
00039 {
00040     return m_duration;
00041 }
00042
00043 //----------------------------------------------------------------------
00044
00045 void Animate::Duration(_In_ float duration)
00046 {
00047     m_duration = duration;
00048 }
00049
00050 //----------------------------------------------------------------------
00051
00052 bool Animate::Continuous()
00053 {
00054     return m_continuous;
00055 }
00056
00057 //----------------------------------------------------------------------
00058
00059 void Animate::Continuous(_In_ bool continuous)
00060 {
00061     m_continuous = continuous;
00062 }
00063
00064 //----------------------------------------------------------------------
00065
00066 AnimateLinePosition::AnimateLinePosition(
00067     _In_ XMFLOAT3 startPosition,
00068     _In_ XMFLOAT3 endPosition,
00069     _In_ float duration,
00070     _In_ bool continuous)
00071 {
00072     m_startPosition = startPosition;
00073     m_endPosition = endPosition;
00074     m_duration = duration;
00075     m_continuous = continuous;
00076
00077     m_length = XMVectorGetX(
00078         XMVector3Length(XMLoadFloat3(&endPosition) - XMLoadFloat3(&startPosition))
00079         );
00080 }
00081
00082 //----------------------------------------------------------------------
00083
00084 XMFLOAT3 AnimateLinePosition::Evaluate(_In_ float t)
00085 {
00086     if (t <= m_startTime)
00087     {
00088         return m_startPosition;
00089     }
00090
00091     if ((t >= (m_startTime + m_duration)) && !m_continuous)
00092     {
00093         return m_endPosition;
00094     }
00095
00096     float startTime = m_startTime;
00097     if (m_continuous)
00098     {
00099         // For continuous operation move the start time forward to
00100         // eliminate previous iterations.
00101         startTime += ((int)((t - m_startTime) / m_duration)) * m_duration;
00102     }
00103
00104     float u = (t - startTime) / m_duration;
00105     XMFLOAT3 currentPosition;
00106     currentPosition.x = m_startPosition.x + (m_endPosition.x - m_startPosition.x)*u;
00107     currentPosition.y = m_startPosition.y + (m_endPosition.y - m_startPosition.y)*u;
00108     currentPosition.z = m_startPosition.z + (m_endPosition.z - m_startPosition.z)*u;
00109
00110     return currentPosition;
00111 }
00112
00113 //----------------------------------------------------------------------
00114
00115 AnimateLineListPosition::AnimateLineListPosition(
00116     _In_ unsigned int count,
00117     _In_reads_(count) XMFLOAT3 position[],
00118     _In_ float duration,
00119     _In_ bool continuous)
00120 {
00121     m_duration = duration;
00122     m_continuous = continuous;
00123     m_count = count;
00124
00125     std::vector<LineSegment> segment(m_count);
00126     m_segment = segment;
00127     m_totalLength = 0.0f;
00128
00129     m_segment[0].position = position[0];
00130     for (unsigned int i = 1; i < count; i++)
00131     {
00132         m_segment[i].position = position[i];
00133         m_segment[i - 1].length = XMVectorGetX(
00134             XMVector3Length(
00135                 XMLoadFloat3(&m_segment[i].position) -
00136                 XMLoadFloat3(&m_segment[i - 1].position)
00137                 )
00138             );
00139         m_totalLength += m_segment[i - 1].length;
00140     }
00141
00142     // Parameterize the segments to ensure uniform evaluation along the path.
00143     float u = 0.0f;
00144     for (unsigned int i = 0; i < (count - 1); i++)
00145     {
00146         m_segment[i].uStart = u;
00147         m_segment[i].uLength = (m_segment[i].length / m_totalLength);
00148         u += m_segment[i].uLength;
00149     }
00150     m_segment[count-1].uStart = 1.0f;
00151 }
00152
00153 //----------------------------------------------------------------------
00154
00155 XMFLOAT3 AnimateLineListPosition::Evaluate(_In_ float t)
00156 {
00157     if (t <= m_startTime)
00158     {
00159         return m_segment[0].position;
00160     }
00161
00162     if ((t >= (m_startTime + m_duration)) && !m_continuous)
00163     {
00164         return m_segment[m_count-1].position;
00165     }
00166
00167     float startTime = m_startTime;
00168     if (m_continuous)
00169     {
00170         // For continuous operation move the start time forward to
00171         // eliminate previous iterations.
00172         startTime += ((int)((t - m_startTime) / m_duration)) * m_duration;
00173     }
00174
00175     float u = (t - startTime) / m_duration;
00176     // Find the right segment.
00177     unsigned int i = 0;
00178     while (u > m_segment[i + 1].uStart)
00179     {
00180         i++;
00181     }
00182
00183     u -= m_segment[i].uStart;
00184     u /= m_segment[i].uLength;
00185
00186     XMFLOAT3 currentPosition;
00187     currentPosition.x = m_segment[i].position.x + (m_segment[i + 1].position.x - m_segment[i].position.x)*u;
00188     currentPosition.y = m_segment[i].position.y + (m_segment[i + 1].position.y - m_segment[i].position.y)*u;
00189     currentPosition.z = m_segment[i].position.z + (m_segment[i + 1].position.z - m_segment[i].position.z)*u;
00190
00191     return currentPosition;
00192 }
00193
00194 //----------------------------------------------------------------------
00195
00196 AnimateCirclePosition:: AnimateCirclePosition(
00197     _In_ XMFLOAT3 center,
00198     _In_ XMFLOAT3 startPosition,
00199     _In_ XMFLOAT3 planeNormal,
00200     _In_ float duration,
00201     _In_ bool continuous,
00202     _In_ bool clockwise)
00203 {
00204     m_center = center;
00205     m_planeNormal = planeNormal;
00206     m_startPosition = startPosition;
00207     m_duration = duration;
00208     m_continuous = continuous;
00209     m_clockwise = clockwise;
00210
00211     XMVECTOR coordX = XMLoadFloat3(&m_startPosition) - XMLoadFloat3(&m_center);
00212     m_radius = XMVectorGetX(XMVector3Length(coordX));
00213
00214     XMVector3Normalize(coordX);
00215
00216     XMVECTOR coordZ = XMLoadFloat3(&m_planeNormal);
00217     XMVector3Normalize(coordZ);
00218
00219     XMVECTOR coordY;
00220     if (m_clockwise)
00221     {
00222         coordY = XMVector3Cross(coordZ, coordX);
00223     }
00224     else
00225     {
00226         coordY = XMVector3Cross(coordX, coordZ);
00227     }
00228
00229     XMVECTOR vectorX = XMVectorSet(1.0f, 0.0f, 0.0f, 1.0f);
00230     XMVECTOR vectorY = XMVectorSet(0.0f, 1.0f, 0.0f, 1.0f);
00231     XMMATRIX mat1 = XMMatrixIdentity();
00232     XMMATRIX mat2 = XMMatrixIdentity();
00233
00234     if (!XMVector3Equal(coordX, vectorX))
00235     {
00236         float angle;
00237         angle = XMVectorGetX(
00238             XMVector3AngleBetweenVectors(vectorX, coordX)
00239             );
00240         if ((angle * angle) > 0.025)
00241         {
00242             XMVECTOR axis1 = XMVector3Cross(vectorX, coordX);
00243
00244             mat1 = XMMatrixRotationAxis(axis1, angle);
00245             vectorY = XMVector3TransformCoord(vectorY, mat1);
00246         }
00247     }
00248     if (!XMVector3Equal(vectorY, coordY))
00249     {
00250         float angle;
00251         angle = XMVectorGetX(
00252             XMVector3AngleBetweenVectors(vectorY, coordY)
00253             );
00254         if ((angle * angle) > 0.025)
00255         {
00256             XMVECTOR axis2 = XMVector3Cross(vectorY, coordY);
00257             mat2 = XMMatrixRotationAxis(axis2, angle);
00258         }
00259     }
00260     XMStoreFloat4x4(
00261         &m_rotationMatrix,
00262         mat1 *
00263         mat2 *
00264         XMMatrixTranslation(m_center.x, m_center.y, m_center.z)
00265         );
00266 }
00267
00268 //----------------------------------------------------------------------
00269
00270 XMFLOAT3 AnimateCirclePosition::Evaluate(_In_ float t)
00271 {
00272     if (t <= m_startTime)
00273     {
00274         return m_startPosition;
00275     }
00276
00277     if ((t >= (m_startTime + m_duration)) && !m_continuous)
00278     {
00279         return m_startPosition;
00280     }
00281
00282     float startTime = m_startTime;
00283     if (m_continuous)
00284     {
00285         // For continuous operation move the start time forward to
00286         // eliminate previous iterations.
00287         startTime += ((int)((t - m_startTime) / m_duration)) * m_duration;
00288     }
00289
00290     float u = (t - startTime) / m_duration * XM_2PI;
00291
00292     XMFLOAT3 currentPosition;
00293     currentPosition.x = m_radius * cos(u);
00294     currentPosition.y = m_radius * sin(u);
00295     currentPosition.z = 0.0f;
00296
00297     XMStoreFloat3(
00298         &currentPosition,
00299         XMVector3TransformCoord(
00300             XMLoadFloat3(&currentPosition),
00301             XMLoadFloat4x4(&m_rotationMatrix)
00302             )
00303         );
00304
00305     return currentPosition;
00306 }
00307
00308 //----------------------------------------------------------------------
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::TileContent::TileWideSmallImageAndText01 Member List

This is the complete list of members for NotificationsExtensions::TileContent::TileWideSmallImageAndText01, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
Branding | NotificationsExtensions::TileContent::TileNotificationBase |
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Image | NotificationsExtensions::TileContent::TileWideSmallImageAndText01 |
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
RequireSquareContent | NotificationsExtensions::TileContent::TileWideBase |
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SquareContent | NotificationsExtensions::TileContent::TileWideBase |
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextFields | NotificationsExtensions::NotificationBase |
TextHeadingWrap | NotificationsExtensions::TileContent::TileWideSmallImageAndText01 |
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWideSmallImageAndText01() | NotificationsExtensions::TileContent::TileWideSmallImageAndText01 | [inline]
TileWideSmallImageAndText01() | NotificationsExtensions::TileContent::TileWideSmallImageAndText01 | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:44 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Network information/C++/App.xaml.h Source File

  • Network information

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Wrapper::sealed Member List

This is the complete list of members for Wrapper::sealed, including all inherited members.
Disable() | Wrapper::sealed |
Enable() | Wrapper::sealed |
GetDspSetting() | Wrapper::sealed |
Initialize(Object^o) | Wrapper::sealed |
m_spImpl | Wrapper::sealed | [private]
UpdateDsp(int percentOfScreen) | Wrapper::sealed |
WinRTComponent() | Wrapper::sealed |
~WinRTComponent() | Wrapper::sealed | [private]
Generated on Sat Nov 23 2024 16:09:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Device enumeration/C++/common/suspensionmanager.cpp Source File

  • Device enumeration
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:36 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite hello world/C++/DWriteHelloWorld.cpp Source File

  • DirectWrite hello world

DWriteHelloWorld.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 "DWriteHelloWorld.h"
00010
00011 using namespace Microsoft::WRL;
00012 using namespace Windows::ApplicationModel;
00013 using namespace Windows::ApplicationModel::Core;
00014 using namespace Windows::ApplicationModel::Activation;
00015 using namespace Windows::UI::Core;
00016 using namespace Windows::System;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Graphics::Display;
00019
00020 DWriteHelloWorld::DWriteHelloWorld()
00021 {
00022 }
00023
00024 void DWriteHelloWorld::CreateDeviceIndependentResources()
00025 {
00026     DirectXBase::CreateDeviceIndependentResources();
00027
00028     // Create a DirectWrite text format object.
00029     DX::ThrowIfFailed(
00030         m_dwriteFactory->CreateTextFormat(
00031             L"Gabriola",
00032             nullptr,
00033             DWRITE_FONT_WEIGHT_REGULAR,
00034             DWRITE_FONT_STYLE_NORMAL,
00035             DWRITE_FONT_STRETCH_NORMAL,
00036             64.0f,
00037             L"en-US", // locale
00038             &m_textFormat
00039             )
00040         );
00041
00042     // Center the text horizontally.
00043     DX::ThrowIfFailed(
00044         m_textFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER)
00045         );
00046
00047     // Center the text vertically.
00048     DX::ThrowIfFailed(
00049         m_textFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER)
00050         );
00051 }
00052
00053 void DWriteHelloWorld::CreateDeviceResources()
00054 {
00055     DirectXBase::CreateDeviceResources();
00056
00057     m_sampleOverlay = ref new SampleOverlay();
00058
00059     m_sampleOverlay->Initialize(
00060         m_d2dDevice.Get(),
00061         m_d2dContext.Get(),
00062         m_wicFactory.Get(),
00063         m_dwriteFactory.Get(),
00064         "DirectWrite Hello World sample"
00065         );
00066
00067     DX::ThrowIfFailed(
00068         m_d2dContext->CreateSolidColorBrush(
00069             D2D1::ColorF(D2D1::ColorF::Black),
00070             &m_blackBrush
00071             )
00072         );
00073 }
00074
00075 void DWriteHelloWorld::CreateWindowSizeDependentResources()
00076 {
00077     DirectXBase::CreateWindowSizeDependentResources();
00078
00079     Platform::String^ text = "Hello World From ... DirectWrite!";
00080
00081     D2D1_SIZE_F size = m_d2dContext->GetSize();
00082
00083     // Create a DirectWrite Text Layout object
00084     DX::ThrowIfFailed(
00085         m_dwriteFactory->CreateTextLayout(
00086             text->Data(),                       // Text to be displayed
00087             text->Length(),                     // Length of the text
00088             m_textFormat.Get(),                 // DirectWrite Text Format object
00089             size.width,                         // Width of the Text Layout
00090             size.height,                        // Height of the Text Layout
00091             &m_textLayout
00092             )
00093         );
00094
00095     // Text range for the "DirectWrite!" at the end of the string
00096     DWRITE_TEXT_RANGE textRange = {21, 12}; // 21 references the "D" in DirectWrite! and 12 is the number of characters in the word
00097
00098     // Set the font size on that text range to 100
00099     DX::ThrowIfFailed(
00100         m_textLayout->SetFontSize(100.0f, textRange)
00101         );
00102
00103     // Create a DirectWrite Typography object
00104     DX::ThrowIfFailed(
00105         m_dwriteFactory->CreateTypography(
00106             &m_textTypography
00107             )
00108         );
00109
00110     // Enumerate a stylistic set 6 font feature for application to our text layout
00111     DWRITE_FONT_FEATURE fontFeature = {DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_6, 1};
00112
00113     // Apply the previously enumerated font feature to our Text Typography object
00114     DX::ThrowIfFailed(
00115         m_textTypography->AddFontFeature(fontFeature)
00116         );
00117
00118     // Move our text range to the entire length of the string
00119     textRange.length = text->Length();
00120     textRange.startPosition = 0;
00121
00122     // Apply our recently defined typography to our entire text range
00123     DX::ThrowIfFailed(
00124         m_textLayout->SetTypography(
00125             m_textTypography.Get(),
00126             textRange
00127             )
00128         );
00129
00130     // Move the text range to the end again
00131     textRange.length = 12;
00132     textRange.startPosition = 21;
00133
00134     // Set the underline on the text range
00135     DX::ThrowIfFailed(
00136         m_textLayout->SetUnderline(TRUE, textRange)
00137         );
00138
00139     // Set the font weight on the text range
00140     DX::ThrowIfFailed(
00141         m_textLayout->SetFontWeight(DWRITE_FONT_WEIGHT_BOLD, textRange)
00142         );
00143 }
00144
00145 void DWriteHelloWorld::Render()
00146 {
00147     m_d2dContext->BeginDraw();
00148
00149     m_d2dContext->Clear(D2D1::ColorF(D2D1::ColorF::CornflowerBlue));
00150     m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00151
00152     m_d2dContext->DrawTextLayout(
00153         D2D1::Point2F(0.0f, 0.0f),
00154         m_textLayout.Get(),
00155         m_blackBrush.Get()
00156         );
00157
00158     // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00159     // is lost. It will be handled during the next call to Present.
00160     HRESULT hr = m_d2dContext->EndDraw();
00161     if (hr != D2DERR_RECREATE_TARGET)
00162     {
00163         DX::ThrowIfFailed(hr);
00164     }
00165
00166     m_sampleOverlay->Render();
00167 }
00168
00169 void DWriteHelloWorld::Initialize(
00170     _In_ CoreApplicationView^ applicationView
00171     )
00172 {
00173     applicationView->Activated +=
00174         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &DWriteHelloWorld::OnActivated);
00175
00176     CoreApplication::Suspending +=
00177         ref new EventHandler<SuspendingEventArgs^>(this, &DWriteHelloWorld::OnSuspending);
00178
00179     CoreApplication::Resuming +=
00180         ref new EventHandler<Platform::Object^>(this, &DWriteHelloWorld::OnResuming);
00181 }
00182
00183 void DWriteHelloWorld::SetWindow(
00184     _In_ CoreWindow^ window
00185     )
00186 {
00187     window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
00188
00189     window->SizeChanged +=
00190         ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &DWriteHelloWorld::OnWindowSizeChanged);
00191
00192     DisplayProperties::LogicalDpiChanged +=
00193         ref new DisplayPropertiesEventHandler(this, &DWriteHelloWorld::OnLogicalDpiChanged);
00194
00195     DisplayProperties::DisplayContentsInvalidated +=
00196         ref new DisplayPropertiesEventHandler(this, &DWriteHelloWorld::OnDisplayContentsInvalidated);
00197
00198     DirectXBase::Initialize(window, DisplayProperties::LogicalDpi);
00199 }
00200
00201 void DWriteHelloWorld::Load(
00202     _In_ Platform::String^ entryPoint
00203     )
00204 {
00205 }
00206
00207 void DWriteHelloWorld::Run()
00208 {
00209     Render();
00210     Present();
00211
00212     m_window->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessUntilQuit);
00213 }
00214
00215 void DWriteHelloWorld::Uninitialize()
00216 {
00217 }
00218
00219 void DWriteHelloWorld::OnWindowSizeChanged(
00220     _In_ CoreWindow^ sender,
00221     _In_ WindowSizeChangedEventArgs^ args
00222     )
00223 {
00224     UpdateForWindowSizeChange();
00225     m_sampleOverlay->UpdateForWindowSizeChange();
00226     Render();
00227     Present();
00228 }
00229
00230 void DWriteHelloWorld::OnLogicalDpiChanged(
00231     _In_ Platform::Object^ sender
00232     )
00233 {
00234     SetDpi(DisplayProperties::LogicalDpi);
00235     Render();
00236     Present();
00237 }
00238
00239 void DWriteHelloWorld::OnDisplayContentsInvalidated(
00240     _In_ Platform::Object^ sender
00241     )
00242 {
00243     // Ensure the D3D Device is available for rendering.
00244     ValidateDevice();
00245
00246     Render();
00247     Present();
00248 }
00249
00250 void DWriteHelloWorld::OnActivated(
00251     _In_ CoreApplicationView^ applicationView,
00252     _In_ IActivatedEventArgs^ args
00253     )
00254 {
00255     m_window->Activate();
00256 }
00257
00258 void DWriteHelloWorld::OnSuspending(
00259     _In_ Platform::Object^ sender,
00260     _In_ SuspendingEventArgs^ args
00261     )
00262 {
00263 }
00264
00265 void DWriteHelloWorld::OnResuming(
00266     _In_ Platform::Object^ sender,
00267     _In_ Platform::Object^ args
00268     )
00269 {
00270 }
00271
00272 IFrameworkView^ DirectXAppSource::CreateView()
00273 {
00274     return ref new DWriteHelloWorld();
00275 }
00276
00277 [Platform::MTAThread]
00278 int main(Platform::Array<Platform::String^>^)
00279 {
00280     auto directXAppSource = ref new DirectXAppSource();
00281     CoreApplication::Run(directXAppSource);
00282     return 0;
00283 }
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML images/C++/MainPage.xaml.h Source File

  • XAML images

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Accelerometer sensor/C++/Scenario3.xaml.cpp Source File

  • Accelerometer sensor

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 SDKSample::AccelerometerCPP;
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::Devices::Sensors;
00025 using namespace Windows::Foundation;
00026 using namespace Windows::UI::Core;
00027 using namespace Platform;
00028
00029 Scenario3::Scenario3() : rootPage(MainPage::Current), desiredReportInterval(0)
00030 {
00031     InitializeComponent();
00032
00033     accelerometer = Accelerometer::GetDefault();
00034     if (accelerometer != nullptr)
00035     {
00036         // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
00037         // This value will be used later to activate the sensor.
00038         uint32 minReportInterval = accelerometer->MinimumReportInterval;
00039         desiredReportInterval = minReportInterval > 16 ? minReportInterval : 16;
00040
00041         // Set up a DispatchTimer
00042         TimeSpan span;
00043         span.Duration = static_cast<int32>(desiredReportInterval) * 10000;   // convert to 100ns ticks
00044         dispatcherTimer = ref new DispatcherTimer();
00045         dispatcherTimer->Interval = span;
00046         dispatcherTimer->Tick += ref new Windows::Foundation::EventHandler<Object^>(this, &Scenario3::DisplayCurrentReading);
00047     }
00048     else
00049     {
00050         rootPage->NotifyUser("No accelerometer found", NotifyType::ErrorMessage);
00051     }
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 void Scenario3::OnNavigatedTo(NavigationEventArgs^ e)
00060 {
00061     ScenarioEnableButton->IsEnabled = true;
00062     ScenarioDisableButton->IsEnabled = false;
00063 }
00064
00065 /// <summary>
00066 /// Invoked when this page is no longer displayed.
00067 /// </summary>
00068 /// <param name="e"></param>
00069 void Scenario3::OnNavigatedFrom(NavigationEventArgs^ e)
00070 {
00071     if (ScenarioDisableButton->IsEnabled)
00072     {
00073         Window::Current->VisibilityChanged::remove(visibilityToken);
00074         dispatcherTimer->Stop();
00075
00076         // Restore the default report interval to release resources while the sensor is not in use
00077         accelerometer->ReportInterval = 0;
00078     }
00079 }
00080
00081 /// <summary>
00082 /// This is the event handler for VisibilityChanged events. You would register for these notifications
00083 /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00084 /// </summary>
00085 /// <param name="sender"></param>
00086 /// <param name="e">
00087 /// Event data that can be examined for the current visibility state.
00088 /// </param>
00089 void Scenario3::VisibilityChanged(Object^ sender, VisibilityChangedEventArgs^ e)
00090 {
00091     // The app should watch for VisibilityChanged events to disable and re-enable sensor input as appropriate
00092     if (ScenarioDisableButton->IsEnabled)
00093     {
00094         if (e->Visible)
00095         {
00096             // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00097             dispatcherTimer->Start();
00098         }
00099         else
00100         {
00101             // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00102             dispatcherTimer->Stop();
00103         }
00104     }
00105 }
00106
00107 void Scenario3::DisplayCurrentReading(Object^ sender, Object^ e)
00108 {
00109     AccelerometerReading^ reading = accelerometer->GetCurrentReading();
00110     if (reading != nullptr)
00111     {
00112         ScenarioOutput_X->Text = reading->AccelerationX.ToString();
00113         ScenarioOutput_Y->Text = reading->AccelerationY.ToString();
00114         ScenarioOutput_Z->Text = reading->AccelerationZ.ToString();
00115     }
00116 }
00117
00118 void Scenario3::ScenarioEnable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00119 {
00120     if (accelerometer != nullptr)
00121     {
00122         visibilityToken = Window::Current->VisibilityChanged::add(ref new WindowVisibilityChangedEventHandler(this, &Scenario3::VisibilityChanged));
00123
00124         // Set the report interval to enable the sensor for polling
00125         accelerometer->ReportInterval = desiredReportInterval;
00126
00127         dispatcherTimer->Start();
00128
00129         ScenarioEnableButton->IsEnabled = false;
00130         ScenarioDisableButton->IsEnabled = true;
00131     }
00132     else
00133     {
00134         rootPage->NotifyUser("No accelerometer found", NotifyType::ErrorMessage);
00135     }
00136 }
00137
00138 void Scenario3::ScenarioDisable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00139 {
00140     Window::Current->VisibilityChanged::remove(visibilityToken);
00141
00142     dispatcherTimer->Stop();
00143
00144     // Restore the default report interval to release resources while the sensor is not in use
00145     accelerometer->ReportInterval = 0;
00146
00147     ScenarioEnableButton->IsEnabled = true;
00148     ScenarioDisableButton->IsEnabled = false;
00149 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Secondary tiles/C#,C++/NotificationsExtensions/BadgeContent.cs Source File

  • Secondary tiles
  • C#,C++
  • NotificationsExtensions

BadgeContent.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 System;
00009 #if !WINRT_NOT_PRESENT
00010 using Windows.Data.Xml.Dom;
00011 using Windows.UI.Notifications;
00012 #endif
00013
00014 namespace NotificationsExtensions.BadgeContent
00015 {
00016     /// <summary>
00017     /// Notification content object to display a glyph on a tile's badge.
00018     /// </summary>
00019     public sealed class BadgeGlyphNotificationContent : IBadgeNotificationContent
00020     {
00021         /// <summary>
00022         /// Default constructor to create a glyph badge content object.
00023         /// </summary>
00024         public BadgeGlyphNotificationContent()
00025         {
00026         }
00027
00028         /// <summary>
00029         /// Constructor to create a glyph badge content object with a glyph.
00030         /// </summary>
00031         /// <param name="glyph">The glyph to be displayed on the badge.</param>
00032         public BadgeGlyphNotificationContent(GlyphValue glyph)
00033         {
00034             m_Glyph = glyph;
00035         }
00036
00037         /// <summary>
00038         /// The glyph to be displayed on the badge.
00039         /// </summary>
00040         public GlyphValue Glyph
00041         {
00042             get { return m_Glyph; }
00043             set
00044             {
00045                 if (!Enum.IsDefined(typeof(GlyphValue), value))
00046                 {
00047                     throw new ArgumentOutOfRangeException("value");
00048                 }
00049                 m_Glyph = value;
00050             }
00051         }
00052
00053         /// <summary>
00054         /// Retrieves the notification Xml content as a string.
00055         /// </summary>
00056         /// <returns>The notification Xml content as a string.</returns>
00057         public string GetContent()
00058         {
00059             if (!Enum.IsDefined(typeof(GlyphValue), m_Glyph))
00060             {
00061                 throw new NotificationContentValidationException("The badge glyph property was left unset.");
00062             }
00063
00064             string glyphString = m_Glyph.ToString();
00065             // lower case the first character of the enum value to match the Xml schema
00066             glyphString = String.Format("{0}{1}", Char.ToLowerInvariant(glyphString[0]), glyphString.Substring(1));
00067             return String.Format("<badge version='{0}' value='{1}'/>", Util.NOTIFICATION_CONTENT_VERSION, glyphString);
00068         }
00069
00070         /// <summary>
00071         /// Retrieves the notification Xml content as a string.
00072         /// </summary>
00073         /// <returns>The notification Xml content as a string.</returns>
00074         public override string ToString()
00075         {
00076             return GetContent();
00077         }
00078
00079 #if !WINRT_NOT_PRESENT
00080         /// <summary>
00081         /// Retrieves the notification Xml content as a WinRT Xml document.
00082         /// </summary>
00083         /// <returns>The notification Xml content as a WinRT Xml document.</returns>
00084         public XmlDocument GetXml()
00085         {
00086             XmlDocument xml = new XmlDocument();
00087             xml.LoadXml(GetContent());
00088             return xml;
00089         }
00090
00091         /// <summary>
00092         /// Creates a WinRT BadgeNotification object based on the content.
00093         /// </summary>
00094         /// <returns>A WinRT BadgeNotification object based on the content.</returns>
00095         public BadgeNotification CreateNotification()
00096         {
00097             XmlDocument xmlDoc = new XmlDocument();
00098             xmlDoc.LoadXml(GetContent());
00099             return new BadgeNotification(xmlDoc);
00100         }
00101 #endif
00102
00103         private GlyphValue m_Glyph = (GlyphValue)(-1);
00104     }
00105
00106     /// <summary>
00107     /// Notification content object to display a number on a tile's badge.
00108     /// </summary>
00109     public sealed class BadgeNumericNotificationContent : IBadgeNotificationContent
00110     {
00111         /// <summary>
00112         /// Default constructor to create a numeric badge content object.
00113         /// </summary>
00114         public BadgeNumericNotificationContent()
00115         {
00116         }
00117
00118         /// <summary>
00119         /// Constructor to create a numeric badge content object with a number.
00120         /// </summary>
00121         /// <param name="number">
00122         /// The number that will appear on the badge.  If the number is 0, the badge
00123         /// will be removed.  The largest value that will appear on the badge is 99.
00124         /// Numbers greater than 99 are allowed, but will be displayed as "99+".
00125         /// </param>
00126         public BadgeNumericNotificationContent(uint number)
00127         {
00128             m_Number = number;
00129         }
00130
00131         /// <summary>
00132         /// The number that will appear on the badge.  If the number is 0, the badge
00133         /// will be removed.  The largest value that will appear on the badge is 99.
00134         /// Numbers greater than 99 are allowed, but will be displayed as "99+".
00135         /// </summary>
00136         public uint Number
00137         {
00138             get { return m_Number; }
00139             set { m_Number = value; }
00140         }
00141
00142         /// <summary>
00143         /// Retrieves the notification Xml content as a string.
00144         /// </summary>
00145         /// <returns>The notification Xml content as a string.</returns>
00146         public string GetContent()
00147         {
00148             return String.Format("<badge version='{0}' value='{1}'/>", Util.NOTIFICATION_CONTENT_VERSION, m_Number);
00149         }
00150
00151         /// <summary>
00152         /// Retrieves the notification Xml content as a string.
00153         /// </summary>
00154         /// <returns>The notification Xml content as a string.</returns>
00155         public override string ToString()
00156         {
00157             return GetContent();
00158         }
00159
00160 #if !WINRT_NOT_PRESENT
00161         /// <summary>
00162         /// Retrieves the notification Xml content as a WinRT Xml document.
00163         /// </summary>
00164         /// <returns>The notification Xml content as a WinRT Xml document.</returns>
00165         public XmlDocument GetXml()
00166         {
00167             XmlDocument xml = new XmlDocument();
00168             xml.LoadXml(GetContent());
00169             return xml;
00170         }
00171
00172         /// <summary>
00173         /// Creates a WinRT BadgeNotification object based on the content.
00174         /// </summary>
00175         /// <returns>A WinRT BadgeNotification object based on the content.</returns>
00176         public BadgeNotification CreateNotification()
00177         {
00178             XmlDocument xmlDoc = new XmlDocument();
00179             xmlDoc.LoadXml(GetContent());
00180             return new BadgeNotification(xmlDoc);
00181         }
00182 #endif
00183
00184         private uint m_Number = 0;
00185     }
00186 }
Generated on Sat Nov 23 2024 16:08:19 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/MediaExtensions/Invert/Invert.cpp Source File

  • Media extensions
  • MediaExtensions
  • Invert

Invert.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 "Invert.h"
00009 #include "VideoBufferLock.h"
00010 #include "TextureLock.h"
00011
00012 #include "InvertModule.h"
00013 #include "CopyModule.h"
00014
00015 using namespace Microsoft::WRL;
00016
00017 HRESULT GetDefaultStride(IMFMediaType *pType, LONG *plStride);
00018 HRESULT BufferToDXType(IMFMediaBuffer *pBuffer, _Out_ UINT *uiViewIndex, _Out_ ID3D11Texture2D **ppTexture);
00019
00020 CInvert::CInvert() :
00021     m_imageWidthInPixels(0),
00022     m_imageHeightInPixels(0),
00023     m_cbImageSize(0),
00024     m_bStreamingInitialized(false)
00025 {
00026     InitializeCriticalSectionEx(&m_critSec, 3000, 0);
00027 }
00028
00029 CInvert::~CInvert()
00030 {
00031     DeleteCriticalSection(&m_critSec);
00032     if( m_pTransform )
00033     {
00034         delete m_pTransform;
00035     }
00036 }
00037
00038 // Initialize the instance.
00039 STDMETHODIMP CInvert::RuntimeClassInitialize()
00040 {
00041     HRESULT hr = S_OK;
00042
00043     // Create the attribute store.
00044     hr = MFCreateAttributes(&m_pAttributes, 3);
00045     if (FAILED(hr))
00046     {
00047         goto done;
00048     }
00049
00050     // MFT supports DX11 acceleration
00051     hr = m_pAttributes->SetUINT32(MF_SA_D3D_AWARE, 1);
00052     if (FAILED(hr))
00053     {
00054         goto done;
00055     }
00056
00057     hr = m_pAttributes->SetUINT32(MF_SA_D3D11_AWARE, 1);
00058     if (FAILED(hr))
00059     {
00060         goto done;
00061     }
00062
00063     // output attributes
00064     hr = MFCreateAttributes( &m_spOutputAttributes, 1 );
00065     if (FAILED(hr))
00066     {
00067         goto done;
00068     }
00069
00070     // Load the transform
00071     m_pTransform = new CInvertModule();
00072     if( m_pTransform == nullptr )
00073     {
00074         hr = E_OUTOFMEMORY;
00075         goto done;
00076     }
00077
00078 done:
00079     return hr;
00080 }
00081
00082 // IMediaExtension methods
00083
00084 //-------------------------------------------------------------------
00085 // SetProperties
00086 // Sets the configuration of the effect
00087 //-------------------------------------------------------------------
00088 HRESULT CInvert::SetProperties(ABI::Windows::Foundation::Collections::IPropertySet *pConfiguration)
00089 {
00090     return S_OK;
00091 }
00092
00093 //-------------------------------------------------------------------
00094 // GetStreamLimits
00095 // Returns the minimum and maximum number of streams.
00096 //-------------------------------------------------------------------
00097
00098 HRESULT CInvert::GetStreamLimits(
00099     DWORD   *pdwInputMinimum,
00100     DWORD   *pdwInputMaximum,
00101     DWORD   *pdwOutputMinimum,
00102     DWORD   *pdwOutputMaximum
00103 )
00104 {
00105     if ((pdwInputMinimum == NULL) ||
00106         (pdwInputMaximum == NULL) ||
00107         (pdwOutputMinimum == NULL) ||
00108         (pdwOutputMaximum == NULL))
00109     {
00110         return E_POINTER;
00111     }
00112
00113     // This MFT has a fixed number of streams.
00114     *pdwInputMinimum = 1;
00115     *pdwInputMaximum = 1;
00116     *pdwOutputMinimum = 1;
00117     *pdwOutputMaximum = 1;
00118     return S_OK;
00119 }
00120
00121
00122 //-------------------------------------------------------------------
00123 // GetStreamCount
00124 // Returns the actual number of streams.
00125 //-------------------------------------------------------------------
00126
00127 HRESULT CInvert::GetStreamCount(
00128     DWORD   *pcInputStreams,
00129     DWORD   *pcOutputStreams
00130 )
00131 {
00132     if ((pcInputStreams == NULL) || (pcOutputStreams == NULL))
00133     {
00134         return E_POINTER;
00135     }
00136
00137     // This MFT has a fixed number of streams.
00138     *pcInputStreams = 1;
00139     *pcOutputStreams = 1;
00140     return S_OK;
00141 }
00142
00143
00144 //-------------------------------------------------------------------
00145 // GetInputStreamInfo
00146 // Returns information about an input stream.
00147 //-------------------------------------------------------------------
00148
00149 HRESULT CInvert::GetInputStreamInfo(
00150     DWORD                     dwInputStreamID,
00151     MFT_INPUT_STREAM_INFO *   pStreamInfo
00152 )
00153 {
00154     if (pStreamInfo == NULL)
00155     {
00156         return E_POINTER;
00157     }
00158
00159     if (dwInputStreamID != 0)
00160     {
00161         return MF_E_INVALIDSTREAMNUMBER;
00162     }
00163
00164     EnterCriticalSection(&m_critSec);
00165
00166     pStreamInfo->hnsMaxLatency = 0;
00167     pStreamInfo->dwFlags = MFT_INPUT_STREAM_WHOLE_SAMPLES | MFT_INPUT_STREAM_SINGLE_SAMPLE_PER_BUFFER;
00168     pStreamInfo->cbSize = m_pInputType == NULL ? 0 : m_cbImageSize;
00169     pStreamInfo->cbMaxLookahead = 0;
00170     pStreamInfo->cbAlignment = 0;
00171
00172     LeaveCriticalSection(&m_critSec);
00173     return S_OK;
00174 }
00175
00176 //-------------------------------------------------------------------
00177 // GetOutputStreamInfo
00178 // Returns information about an output stream.
00179 //-------------------------------------------------------------------
00180
00181 HRESULT CInvert::GetOutputStreamInfo(
00182     DWORD                     dwOutputStreamID,
00183     MFT_OUTPUT_STREAM_INFO *  pStreamInfo
00184 )
00185 {
00186     if (pStreamInfo == NULL)
00187     {
00188         return E_POINTER;
00189     }
00190
00191     if (dwOutputStreamID != 0)
00192     {
00193         return MF_E_INVALIDSTREAMNUMBER;
00194     }
00195
00196     EnterCriticalSection(&m_critSec);
00197
00198     pStreamInfo->dwFlags =
00199         MFT_OUTPUT_STREAM_WHOLE_SAMPLES |
00200         MFT_OUTPUT_STREAM_SINGLE_SAMPLE_PER_BUFFER |
00201         MFT_OUTPUT_STREAM_FIXED_SAMPLE_SIZE ;
00202
00203     if( m_pDX11Manager != nullptr )
00204     {
00205         pStreamInfo->dwFlags |= MFT_OUTPUT_STREAM_PROVIDES_SAMPLES;
00206     }
00207
00208     pStreamInfo->cbSize = m_pInputType == NULL ? 0 : m_cbImageSize;
00209     pStreamInfo->cbAlignment = 0;
00210
00211     LeaveCriticalSection(&m_critSec);
00212     return S_OK;
00213 }
00214
00215 //-------------------------------------------------------------------
00216 // Name: GetOutputStreamAttributes
00217 // Returns stream-level attributes for an output stream.
00218 //-------------------------------------------------------------------
00219
00220 HRESULT CInvert::GetOutputStreamAttributes(
00221     DWORD           dwOutputStreamID,
00222     IMFAttributes   **ppAttributes
00223     )
00224 {
00225     HRESULT hr = S_OK;
00226
00227     if (NULL == ppAttributes)
00228     {
00229         return E_POINTER;
00230     }
00231
00232     if (dwOutputStreamID != 0)
00233     {
00234         return MF_E_INVALIDSTREAMNUMBER;
00235     }
00236
00237     m_spOutputAttributes.CopyTo(ppAttributes);
00238
00239     return( hr );
00240 }
00241
00242 //-------------------------------------------------------------------
00243 // GetAttributes
00244 // Returns the attributes for the MFT.
00245 //-------------------------------------------------------------------
00246
00247 HRESULT CInvert::GetAttributes(IMFAttributes** ppAttributes)
00248 {
00249     if (ppAttributes == NULL)
00250     {
00251         return E_POINTER;
00252     }
00253
00254     EnterCriticalSection(&m_critSec);
00255
00256     m_pAttributes.CopyTo(ppAttributes);
00257
00258     LeaveCriticalSection(&m_critSec);
00259     return S_OK;
00260 }
00261
00262
00263 //-------------------------------------------------------------------
00264 // GetInputAvailableType
00265 // Returns a preferred input type.
00266 //-------------------------------------------------------------------
00267
00268 HRESULT CInvert::GetInputAvailableType(
00269     DWORD           dwInputStreamID,
00270     DWORD           dwTypeIndex, // 0-based
00271     IMFMediaType    **ppType
00272 )
00273 {
00274     if (ppType == NULL)
00275     {
00276         return E_INVALIDARG;
00277     }
00278
00279     if (dwInputStreamID != 0)
00280     {
00281         return MF_E_INVALIDSTREAMNUMBER;
00282     }
00283
00284     EnterCriticalSection(&m_critSec);
00285     HRESULT hr = S_OK;
00286
00287     // If the output type is set, return that type as our preferred input type.
00288     if (m_pOutputType == NULL)
00289     {
00290         // The output type is not set. Create a partial media type.
00291         hr = OnGetPartialType(dwTypeIndex, ppType);
00292     }
00293     else if (dwTypeIndex > 0)
00294     {
00295         hr = MF_E_NO_MORE_TYPES;
00296     }
00297     else
00298     {
00299         *ppType = m_pOutputType.Get();
00300         (*ppType)->AddRef();
00301     }
00302
00303     LeaveCriticalSection(&m_critSec);
00304     return hr;
00305 }
00306
00307
00308
00309 //-------------------------------------------------------------------
00310 // GetOutputAvailableType
00311 // Returns a preferred output type.
00312 //-------------------------------------------------------------------
00313
00314 HRESULT CInvert::GetOutputAvailableType(
00315     DWORD           dwOutputStreamID,
00316     DWORD           dwTypeIndex, // 0-based
00317     IMFMediaType    **ppType
00318 )
00319 {
00320     if (ppType == NULL)
00321     {
00322         return E_INVALIDARG;
00323     }
00324
00325     if (dwOutputStreamID != 0)
00326     {
00327         return MF_E_INVALIDSTREAMNUMBER;
00328     }
00329
00330     EnterCriticalSection(&m_critSec);
00331     HRESULT hr = S_OK;
00332
00333     if (m_pInputType == NULL)
00334     {
00335         // The input type is not set. Create a partial media type.
00336         hr = OnGetPartialType(dwTypeIndex, ppType);
00337     }
00338     else if (dwTypeIndex > 0)
00339     {
00340         hr = MF_E_NO_MORE_TYPES;
00341     }
00342     else
00343     {
00344         *ppType = m_pInputType.Get();
00345         (*ppType)->AddRef();
00346     }
00347
00348     LeaveCriticalSection(&m_critSec);
00349     return hr;
00350 }
00351
00352
00353 //-------------------------------------------------------------------
00354 // SetInputType
00355 //-------------------------------------------------------------------
00356
00357 HRESULT CInvert::SetInputType(
00358     DWORD           dwInputStreamID,
00359     IMFMediaType    *pType, // Can be NULL to clear the input type.
00360     DWORD           dwFlags
00361 )
00362 {
00363     // Validate flags.
00364     if (dwFlags & ~MFT_SET_TYPE_TEST_ONLY)
00365     {
00366         return E_INVALIDARG;
00367     }
00368
00369     if (dwInputStreamID != 0)
00370     {
00371         return MF_E_INVALIDSTREAMNUMBER;
00372     }
00373
00374     EnterCriticalSection(&m_critSec);
00375     HRESULT hr = S_OK;
00376
00377     // If we have an input sample, the client cannot change the type now.
00378     if (m_pSample != NULL)
00379     {
00380         hr = MF_E_TRANSFORM_CANNOT_CHANGE_MEDIATYPE_WHILE_PROCESSING;
00381         goto done;
00382     }
00383
00384     // Validate the type, if non-NULL.
00385     if (pType)
00386     {
00387         hr = OnCheckInputType(pType);
00388         if (FAILED(hr))
00389         {
00390             goto done;
00391         }
00392     }
00393
00394     // The type is OK. Set the type, unless the caller was just testing.
00395     if ( (dwFlags & MFT_SET_TYPE_TEST_ONLY) == 0 )
00396     {
00397         m_pInputType = nullptr;
00398         m_pInputType = pType;
00399
00400         // Update the format information.
00401         UpdateFormatInfo();
00402
00403         // When the type changes, end streaming.
00404         m_bStreamingInitialized = false;
00405     }
00406
00407 done:
00408     LeaveCriticalSection(&m_critSec);
00409     return hr;
00410 }
00411
00412
00413
00414 //-------------------------------------------------------------------
00415 // SetOutputType
00416 //-------------------------------------------------------------------
00417
00418 HRESULT CInvert::SetOutputType(
00419     DWORD           dwOutputStreamID,
00420     IMFMediaType    *pType, // Can be NULL to clear the output type.
00421     DWORD           dwFlags
00422 )
00423 {
00424     // Validate flags.
00425     if (dwFlags & ~MFT_SET_TYPE_TEST_ONLY)
00426     {
00427         return E_INVALIDARG;
00428     }
00429
00430     if (dwOutputStreamID != 0)
00431     {
00432         return MF_E_INVALIDSTREAMNUMBER;
00433     }
00434
00435     EnterCriticalSection(&m_critSec);
00436     HRESULT hr = S_OK;
00437
00438     // If we have an input sample, the client cannot change the type now.
00439     if (m_pSample != NULL)
00440     {
00441         hr = MF_E_TRANSFORM_CANNOT_CHANGE_MEDIATYPE_WHILE_PROCESSING;
00442         goto done;
00443     }
00444
00445     // Validate the type, if non-NULL.
00446     if (pType)
00447     {
00448         hr = OnCheckOutputType(pType);
00449         if (FAILED(hr))
00450         {
00451             goto done;
00452         }
00453     }
00454
00455     // The type is OK. Set the type, unless the caller was just testing.
00456     if ( (dwFlags & MFT_SET_TYPE_TEST_ONLY) == 0 )
00457     {
00458         m_pOutputType = pType;
00459
00460         // When the type changes, end streaming.
00461         m_bStreamingInitialized = false;
00462     }
00463
00464 done:
00465     LeaveCriticalSection(&m_critSec);
00466     return hr;
00467 }
00468
00469
00470 //-------------------------------------------------------------------
00471 // GetInputCurrentType
00472 // Returns the current input type.
00473 //-------------------------------------------------------------------
00474
00475 HRESULT CInvert::GetInputCurrentType(
00476     DWORD           dwInputStreamID,
00477     IMFMediaType    **ppType
00478 )
00479 {
00480     if (ppType == NULL)
00481     {
00482         return E_POINTER;
00483     }
00484
00485     if (dwInputStreamID != 0)
00486     {
00487         return MF_E_INVALIDSTREAMNUMBER;
00488     }
00489
00490     HRESULT hr = S_OK;
00491     EnterCriticalSection(&m_critSec);
00492
00493     if (!m_pInputType)
00494     {
00495         hr = MF_E_TRANSFORM_TYPE_NOT_SET;
00496     }
00497     else
00498     {
00499         *ppType = m_pInputType.Get();
00500         (*ppType)->AddRef();
00501     }
00502
00503     LeaveCriticalSection(&m_critSec);
00504     return hr;
00505 }
00506
00507
00508 //-------------------------------------------------------------------
00509 // GetOutputCurrentType
00510 // Returns the current output type.
00511 //-------------------------------------------------------------------
00512
00513 HRESULT CInvert::GetOutputCurrentType(
00514     DWORD           dwOutputStreamID,
00515     IMFMediaType    **ppType
00516 )
00517 {
00518     if (ppType == NULL)
00519     {
00520         return E_POINTER;
00521     }
00522
00523     if( dwOutputStreamID != 0 )
00524     {
00525         return MF_E_INVALIDSTREAMNUMBER;
00526     }
00527
00528     HRESULT hr = S_OK;
00529     EnterCriticalSection(&m_critSec);
00530
00531     if (!m_pOutputType)
00532     {
00533         hr = MF_E_TRANSFORM_TYPE_NOT_SET;
00534     }
00535     else
00536     {
00537         m_pOutputType.CopyTo(ppType);
00538     }
00539
00540     LeaveCriticalSection(&m_critSec);
00541     return hr;
00542 }
00543
00544
00545 //-------------------------------------------------------------------
00546 // GetInputStatus
00547 // Query if the MFT is accepting more input.
00548 //-------------------------------------------------------------------
00549
00550 HRESULT CInvert::GetInputStatus(
00551     DWORD           dwInputStreamID,
00552     DWORD           *pdwFlags
00553 )
00554 {
00555     if (pdwFlags == NULL)
00556     {
00557         return E_POINTER;
00558     }
00559
00560     if (dwInputStreamID != 0)
00561     {
00562         return MF_E_INVALIDSTREAMNUMBER;
00563     }
00564
00565     EnterCriticalSection(&m_critSec);
00566
00567     if (m_pSample == NULL)
00568     {
00569         *pdwFlags = MFT_INPUT_STATUS_ACCEPT_DATA;
00570     }
00571     else
00572     {
00573         *pdwFlags = 0;
00574     }
00575
00576     LeaveCriticalSection(&m_critSec);
00577     return S_OK;
00578 }
00579
00580
00581 //-------------------------------------------------------------------
00582 // GetOutputStatus
00583 // Query if the MFT can produce output.
00584 //-------------------------------------------------------------------
00585
00586 HRESULT CInvert::GetOutputStatus(DWORD *pdwFlags)
00587 {
00588     if (pdwFlags == NULL)
00589     {
00590         return E_POINTER;
00591     }
00592
00593     EnterCriticalSection(&m_critSec);
00594
00595     // The MFT can produce an output sample if (and only if) there an input sample.
00596     if (m_pSample != NULL)
00597     {
00598         *pdwFlags = MFT_OUTPUT_STATUS_SAMPLE_READY;
00599     }
00600     else
00601     {
00602         *pdwFlags = 0;
00603     }
00604
00605     LeaveCriticalSection(&m_critSec);
00606     return S_OK;
00607 }
00608
00609
00610 //-------------------------------------------------------------------
00611 // ProcessMessage
00612 //-------------------------------------------------------------------
00613
00614 HRESULT CInvert::ProcessMessage(
00615     MFT_MESSAGE_TYPE    eMessage,
00616     ULONG_PTR           ulParam
00617 )
00618 {
00619     EnterCriticalSection(&m_critSec);
00620
00621     HRESULT hr = S_OK;
00622     ComPtr<IUnknown> pUnk;
00623     ComPtr<IMFDXGIDeviceManager> pDXGIDeviceManager;
00624
00625     switch (eMessage)
00626     {
00627     case MFT_MESSAGE_COMMAND_FLUSH:
00628         // Flush the MFT.
00629         m_pSample = nullptr;
00630         break;
00631
00632     case MFT_MESSAGE_SET_D3D_MANAGER:
00633         if (ulParam != NULL)
00634         {
00635             pUnk = (IUnknown*)ulParam;
00636             hr = pUnk.As(&pDXGIDeviceManager);
00637
00638             if( SUCCEEDED( hr ) && (m_pDX11Manager != pDXGIDeviceManager) )
00639             {
00640                 InvalidateDX11Resources();
00641                 m_pDX11Manager = nullptr;
00642                 m_pDX11Manager = pDXGIDeviceManager;
00643
00644                 hr = UpdateDX11Device();
00645                 if (FAILED(hr))
00646                 {
00647                     goto done;
00648                 }
00649
00650                 if( m_spOutputSampleAllocator )
00651                 {
00652                     hr = m_spOutputSampleAllocator->SetDirectXManager(pUnk.Get());
00653                     if (FAILED(hr))
00654                     {
00655                         goto done;
00656                     }
00657                 }
00658             }
00659         }
00660         else
00661         {
00662             InvalidateDX11Resources();
00663             m_pDX11Manager = nullptr;
00664         }
00665         break;
00666
00667     case MFT_MESSAGE_NOTIFY_BEGIN_STREAMING:
00668         hr = BeginStreaming();
00669         break;
00670
00671     case MFT_MESSAGE_NOTIFY_END_STREAMING:
00672         m_bStreamingInitialized = false;
00673         break;
00674
00675     // The remaining messages require no action
00676     case MFT_MESSAGE_NOTIFY_END_OF_STREAM:
00677     case MFT_MESSAGE_NOTIFY_START_OF_STREAM:
00678     case MFT_MESSAGE_COMMAND_DRAIN:
00679         break;
00680     }
00681
00682 done:
00683     LeaveCriticalSection(&m_critSec);
00684     return hr;
00685 }
00686
00687
00688 //-------------------------------------------------------------------
00689 // ProcessInput
00690 // Process an input sample.
00691 //-------------------------------------------------------------------
00692
00693 HRESULT CInvert::ProcessInput(
00694     DWORD               dwInputStreamID,
00695     IMFSample           *pSample,
00696     DWORD               dwFlags
00697 )
00698 {
00699     // Check input parameters.
00700     if (pSample == NULL)
00701     {
00702         return E_POINTER;
00703     }
00704
00705     if (dwFlags != 0)
00706     {
00707         return E_INVALIDARG; // dwFlags is reserved and must be zero.
00708     }
00709
00710     // Validate the input stream number.
00711     if (dwInputStreamID != 0)
00712     {
00713         return MF_E_INVALIDSTREAMNUMBER;
00714     }
00715
00716     HRESULT hr = S_OK;
00717
00718     EnterCriticalSection(&m_critSec);
00719
00720     // Check for valid media types.
00721     // The client must set input and output types before calling ProcessInput.
00722     if (!m_pInputType || !m_pOutputType)
00723     {
00724         hr = MF_E_NOTACCEPTING;
00725         goto done;
00726     }
00727
00728     // Check if an input sample is already queued.
00729     if (m_pSample != NULL)
00730     {
00731         hr = MF_E_NOTACCEPTING;   // We already have an input sample.
00732         goto done;
00733     }
00734
00735     // Initialize streaming.
00736     hr = BeginStreaming();
00737     if (FAILED(hr))
00738     {
00739         goto done;
00740     }
00741
00742     // Cache the sample. We do the actual work in ProcessOutput.
00743     m_pSample = pSample;
00744
00745 done:
00746     LeaveCriticalSection(&m_critSec);
00747     return hr;
00748 }
00749
00750
00751 //-------------------------------------------------------------------
00752 // ProcessOutput
00753 // Process an output sample.
00754 //-------------------------------------------------------------------
00755
00756 HRESULT CInvert::ProcessOutput(
00757     DWORD                   dwFlags,
00758     DWORD                   cOutputBufferCount,
00759     MFT_OUTPUT_DATA_BUFFER  *pOutputSamples, // one per stream
00760     DWORD                   *pdwStatus
00761 )
00762 {
00763     if (dwFlags != 0)
00764     {
00765         return E_INVALIDARG;
00766     }
00767
00768     if (pOutputSamples == NULL || pdwStatus == NULL)
00769     {
00770         return E_POINTER;
00771     }
00772
00773     // There must be exactly one output buffer.
00774     if (cOutputBufferCount != 1)
00775     {
00776         return E_INVALIDARG;
00777     }
00778
00779     // It must contain a sample.
00780     if (pOutputSamples[0].pSample == NULL && m_pDX11Manager == nullptr)
00781     {
00782         return E_INVALIDARG;
00783     }
00784
00785     HRESULT hr = S_OK;
00786     ComPtr<IMFMediaBuffer> pInput;
00787     ComPtr<IMFMediaBuffer> pOutput;
00788     ComPtr<ID3D11Device> spDevice;
00789     ComPtr<IMFMediaBuffer> pMediaBuffer;
00790     bool bDeviceLocked = false;
00791
00792     EnterCriticalSection(&m_critSec);
00793
00794     // There must be an input sample available for processing.
00795     if (m_pSample == nullptr)
00796     {
00797         hr = MF_E_TRANSFORM_NEED_MORE_INPUT;
00798         goto done;
00799     }
00800
00801     // Initialize streaming.
00802     hr = BeginStreaming();
00803     if (FAILED(hr))
00804     {
00805         goto done;
00806     }
00807
00808     // Check that our device is still good
00809     hr = CheckDX11Device();
00810     if (FAILED(hr))
00811     {
00812         goto done;
00813     }
00814
00815     // When using DX we provide the output samples...
00816     if (m_pDX11Manager != nullptr)
00817     {
00818         hr = m_spOutputSampleAllocator->AllocateSample( &(pOutputSamples[0].pSample) );
00819         if (FAILED(hr))
00820         {
00821             goto done;
00822         }
00823     }
00824
00825     if (pOutputSamples[0].pSample == nullptr)
00826     {
00827         hr = E_INVALIDARG;
00828         goto done;
00829     }
00830
00831     // Get the input buffer.
00832     hr = m_pSample->GetBufferByIndex(0, &pInput);
00833     if (FAILED(hr))
00834     {
00835         goto done;
00836     }
00837
00838     // Get the output buffer.
00839     hr = pOutputSamples[0].pSample->GetBufferByIndex(0, &pOutput);
00840     if (FAILED(hr))
00841     {
00842         goto done;
00843     }
00844
00845     // Attempt to lock the device if necessary
00846     if (m_pDX11Manager != nullptr)
00847     {
00848         hr = m_pDX11Manager->LockDevice(m_hDeviceHandle, IID_PPV_ARGS( &spDevice ), TRUE );
00849         if (FAILED(hr))
00850         {
00851             goto done;
00852         }
00853         bDeviceLocked = true;
00854     }
00855
00856     hr = OnProcessOutput(pInput.Get(), pOutput.Get());
00857     if (FAILED(hr))
00858     {
00859         goto done;
00860     }
00861
00862     // Set status flags.
00863     pOutputSamples[0].dwStatus = 0;
00864     *pdwStatus = 0;
00865
00866     // Copy the duration and time stamp from the input sample, if present.
00867     LONGLONG hnsDuration = 0;
00868     LONGLONG hnsTime = 0;
00869
00870     if (SUCCEEDED(m_pSample->GetSampleDuration(&hnsDuration)))
00871     {
00872         hr = pOutputSamples[0].pSample->SetSampleDuration(hnsDuration);
00873         if (FAILED(hr))
00874         {
00875             goto done;
00876         }
00877     }
00878
00879     if (SUCCEEDED(m_pSample->GetSampleTime(&hnsTime)))
00880     {
00881         hr = pOutputSamples[0].pSample->SetSampleTime(hnsTime);
00882     }
00883
00884     // Always set the sample size
00885     hr = pOutputSamples[0].pSample->GetBufferByIndex( 0, &pMediaBuffer );
00886     if (FAILED(hr))
00887     {
00888         goto done;
00889     }
00890
00891     hr = pMediaBuffer->SetCurrentLength(m_cbImageSize);
00892     if (FAILED(hr))
00893     {
00894         goto done;
00895     }
00896
00897 done:
00898     m_pSample = nullptr;
00899
00900     if (bDeviceLocked)
00901     {
00902         hr = m_pDX11Manager->UnlockDevice(m_hDeviceHandle, FALSE);
00903     }
00904
00905     LeaveCriticalSection(&m_critSec);
00906     return hr;
00907 }
00908
00909 // PRIVATE METHODS
00910
00911 HRESULT CInvert::CheckDX11Device()
00912 {
00913     HRESULT hr = S_OK;
00914
00915     if(m_pDX11Manager != nullptr && m_hDeviceHandle )
00916     {
00917         if(m_pDX11Manager->TestDevice(m_hDeviceHandle) != S_OK)
00918         {
00919             InvalidateDX11Resources();
00920
00921             hr = UpdateDX11Device();
00922             if (FAILED(hr))
00923             {
00924                 return hr;
00925             }
00926
00927             return m_pTransform->Initialize(m_pDevice.Get(), m_imageWidthInPixels, m_imageHeightInPixels);
00928         }
00929     }
00930
00931     return S_OK;
00932 }
00933
00934 // Delete any resources dependant on the current device we are using
00935 void CInvert::InvalidateDX11Resources()
00936 {
00937     m_pTransform->Invalidate();
00938     m_pDevice  = nullptr;
00939     m_pContext = nullptr;
00940     m_pInBufferTex = nullptr;
00941     m_pOutBufferTex = nullptr;
00942     m_pOutBufferStage = nullptr;
00943 }
00944
00945 // Update the directx device
00946 HRESULT CInvert::UpdateDX11Device()
00947 {
00948     HRESULT hr = S_OK;
00949
00950     if (m_pDX11Manager != nullptr)
00951     {
00952         hr = m_pDX11Manager->OpenDeviceHandle(&m_hDeviceHandle);
00953         if (FAILED(hr))
00954         {
00955             goto done;
00956         }
00957
00958         hr = m_pDX11Manager->GetVideoService(m_hDeviceHandle, __uuidof(m_pDevice), (void**)&m_pDevice);
00959         if (FAILED(hr))
00960         {
00961             goto done;
00962         }
00963
00964         m_pDevice->GetImmediateContext(&m_pContext);
00965     }
00966     else
00967     {
00968         D3D_FEATURE_LEVEL level;
00969         D3D_FEATURE_LEVEL levelsWanted[] =
00970         {
00971             D3D_FEATURE_LEVEL_11_1,
00972             D3D_FEATURE_LEVEL_11_0,
00973             D3D_FEATURE_LEVEL_10_1,
00974             D3D_FEATURE_LEVEL_10_0,
00975         };
00976         DWORD numLevelsWanted = sizeof( levelsWanted ) / sizeof( levelsWanted[0] );
00977
00978         hr = D3D11CreateDevice( NULL, D3D_DRIVER_TYPE_WARP, NULL, 0 , levelsWanted, numLevelsWanted,
00979                                 D3D11_SDK_VERSION, &m_pDevice, &level, &m_pContext);
00980         if (FAILED(hr))
00981         {
00982             goto done;
00983         }
00984
00985     }
00986
00987
00988     return hr;
00989
00990 done:
00991     InvalidateDX11Resources();
00992     return hr;
00993 }
00994
00995 // Create a partial media type.
00996 HRESULT CInvert::OnGetPartialType(DWORD dwTypeIndex, IMFMediaType **ppmt)
00997 {
00998     if (dwTypeIndex > 0)
00999     {
01000         return MF_E_NO_MORE_TYPES;
01001     }
01002
01003     ComPtr<IMFMediaType> pmt;
01004
01005     HRESULT hr = MFCreateMediaType(&pmt);
01006     if (FAILED(hr))
01007     {
01008         goto done;
01009     }
01010
01011     hr = pmt->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video);
01012     if (FAILED(hr))
01013     {
01014         goto done;
01015     }
01016
01017     hr = pmt->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_ARGB32);
01018     if (FAILED(hr))
01019     {
01020         goto done;
01021     }
01022
01023     pmt.CopyTo(ppmt);
01024
01025 done:
01026     return hr;
01027 }
01028
01029 // Validate an input media type.
01030 HRESULT CInvert::OnCheckInputType(IMFMediaType *pmt)
01031 {
01032     assert(pmt != NULL);
01033
01034     HRESULT hr = S_OK;
01035
01036     // If the output type is set, see if they match.
01037     if (m_pOutputType != NULL)
01038     {
01039         DWORD flags = 0;
01040         hr = pmt->IsEqual(m_pOutputType.Get(), &flags);
01041
01042         // IsEqual can return S_FALSE. Treat this as failure.
01043         if (hr != S_OK)
01044         {
01045             hr = MF_E_INVALIDMEDIATYPE;
01046         }
01047     }
01048     else
01049     {
01050         // Output type is not set. Just check this type.
01051         hr = OnCheckMediaType(pmt);
01052     }
01053     return hr;
01054 }
01055
01056 // Validate an output media type.
01057 HRESULT CInvert::OnCheckOutputType(IMFMediaType *pmt)
01058 {
01059     assert(pmt != NULL);
01060
01061     HRESULT hr = S_OK;
01062
01063     // If the input type is set, see if they match.
01064     if (m_pInputType != NULL)
01065     {
01066         DWORD flags = 0;
01067         hr = pmt->IsEqual(m_pInputType.Get(), &flags);
01068
01069         // IsEqual can return S_FALSE. Treat this as failure.
01070         if (hr != S_OK)
01071         {
01072             hr = MF_E_INVALIDMEDIATYPE;
01073         }
01074     }
01075     else
01076     {
01077         // Input type is not set. Just check this type.
01078         hr = OnCheckMediaType(pmt);
01079     }
01080     return hr;
01081 }
01082
01083 // Validate a media type (input or output)
01084 HRESULT CInvert::OnCheckMediaType(IMFMediaType *pmt)
01085 {
01086     // Major type must be video.
01087     GUID major_type;
01088     HRESULT hr = pmt->GetGUID(MF_MT_MAJOR_TYPE, &major_type);
01089     if (FAILED(hr))
01090     {
01091         goto done;
01092     }
01093
01094     if (major_type != MFMediaType_Video)
01095     {
01096         hr = MF_E_INVALIDMEDIATYPE;
01097         goto done;
01098     }
01099
01100     // Get the subtype GUID.
01101     GUID subtype;
01102     hr = pmt->GetGUID(MF_MT_SUBTYPE, &subtype);
01103     if (FAILED(hr))
01104     {
01105         goto done;
01106     }
01107
01108     if(subtype != MFVideoFormat_ARGB32)
01109     {
01110         hr = MF_E_INVALIDMEDIATYPE;
01111         goto done;
01112     }
01113
01114     // Reject single-field media types.
01115     UINT32 interlace = MFGetAttributeUINT32(pmt, MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive);
01116     if (interlace == MFVideoInterlace_FieldSingleUpper  || interlace == MFVideoInterlace_FieldSingleLower)
01117     {
01118         hr = MF_E_INVALIDMEDIATYPE;
01119         goto done;
01120     }
01121
01122     // Reject media types without a frame size
01123     UINT width, height;
01124     hr = MFGetAttributeSize(pmt, MF_MT_FRAME_SIZE, &width, &height);
01125     if (FAILED(hr))
01126     {
01127         goto done;
01128     }
01129
01130 done:
01131     return hr;
01132 }
01133
01134 // Initialize streaming parameters.
01135 HRESULT CInvert::BeginStreaming()
01136 {
01137     HRESULT hr = S_OK;
01138
01139     if (!m_bStreamingInitialized)
01140     {
01141         if( m_pDevice == nullptr )
01142         {
01143             hr = UpdateDX11Device();
01144             if (FAILED(hr))
01145             {
01146                 goto done;
01147             }
01148         }
01149
01150         hr = m_pTransform->Initialize(m_pDevice.Get(), m_imageWidthInPixels, m_imageHeightInPixels);
01151         if (FAILED(hr))
01152         {
01153             goto done;
01154         }
01155
01156         // if the device is dxman we need to alloc samples...
01157         if( m_pDX11Manager != nullptr )
01158         {
01159             DWORD dwBindFlags = MFGetAttributeUINT32( m_spOutputAttributes.Get(), MF_SA_D3D11_BINDFLAGS, D3D11_BIND_RENDER_TARGET );
01160             dwBindFlags |= D3D11_BIND_RENDER_TARGET;        // render target binding must always be set
01161             hr = m_spOutputAttributes->SetUINT32( MF_SA_D3D11_BINDFLAGS, dwBindFlags );
01162             if (FAILED(hr))
01163             {
01164                 goto done;
01165             }
01166             hr = m_spOutputAttributes->SetUINT32( MF_SA_BUFFERS_PER_SAMPLE, 1 );
01167             if (FAILED(hr))
01168             {
01169                 goto done;
01170             }
01171             hr = m_spOutputAttributes->SetUINT32( MF_SA_D3D11_USAGE, D3D11_USAGE_DEFAULT );
01172             if (FAILED(hr))
01173             {
01174                 goto done;
01175             }
01176
01177             if ( NULL == m_spOutputSampleAllocator )
01178             {
01179                 ComPtr<IMFVideoSampleAllocatorEx> spVideoSampleAllocator;
01180                 ComPtr<IUnknown> spDXGIManagerUnk;
01181
01182                 hr = MFCreateVideoSampleAllocatorEx( IID_PPV_ARGS( &spVideoSampleAllocator ) );
01183                 if (FAILED(hr))
01184                 {
01185                     goto done;
01186                 }
01187
01188                 hr = m_pDX11Manager.As( &spDXGIManagerUnk );
01189                 if (FAILED(hr))
01190                 {
01191                     goto done;
01192                 }
01193
01194                 hr = spVideoSampleAllocator->SetDirectXManager( spDXGIManagerUnk.Get() );
01195                 if (FAILED(hr))
01196                 {
01197                     goto done;
01198                 }
01199
01200                 m_spOutputSampleAllocator.Attach( spVideoSampleAllocator.Detach() );
01201             }
01202
01203             hr = m_spOutputSampleAllocator->InitializeSampleAllocatorEx( 1, 10, m_spOutputAttributes.Get(), m_pOutputType.Get() );
01204
01205             if ( FAILED(hr) && (dwBindFlags != D3D11_BIND_RENDER_TARGET) )
01206             {
01207                 // Try again with only the mandatory "render target" binding
01208                 hr = m_spOutputAttributes->SetUINT32( MF_SA_D3D11_BINDFLAGS, D3D11_BIND_RENDER_TARGET );
01209                 if (FAILED(hr))
01210                 {
01211                     goto done;
01212                 }
01213                 hr = m_spOutputSampleAllocator->InitializeSampleAllocatorEx( 1, 10, m_spOutputAttributes.Get(), m_pOutputType.Get() );
01214                 if (FAILED(hr))
01215                 {
01216                     goto done;
01217                 }
01218             }
01219         }
01220
01221         m_bStreamingInitialized = true;
01222     }
01223
01224 done:
01225     return hr;
01226 }
01227
01228 // Reads DX buffers from IMFMediaBuffer
01229 HRESULT BufferToDXType(IMFMediaBuffer *pBuffer, _Out_ UINT *uiViewIndex, _Out_ ID3D11Texture2D **ppTexture)
01230 {
01231     HRESULT hr = S_OK;
01232     ComPtr<IMFDXGIBuffer> spDXGIBuffer;
01233
01234     hr = pBuffer->QueryInterface(__uuidof(IMFDXGIBuffer), (LPVOID *)(&spDXGIBuffer));
01235     if (FAILED(hr))
01236     {
01237         goto done;
01238     }
01239
01240     hr = spDXGIBuffer->GetResource(__uuidof(ID3D11Texture2D), (LPVOID *)(ppTexture));
01241     if (FAILED(hr))
01242     {
01243         goto done;
01244     }
01245
01246     hr = spDXGIBuffer->GetSubresourceIndex(uiViewIndex);
01247     if (FAILED(hr))
01248     {
01249         goto done;
01250     }
01251
01252 done:
01253     return hr;
01254 }
01255
01256 // Generate output data.
01257 HRESULT CInvert::OnProcessOutput(IMFMediaBuffer *pIn, IMFMediaBuffer *pOut)
01258 {
01259     HRESULT hr = S_OK;
01260     ComPtr<ID3D11Texture2D> pInTex;
01261     ComPtr<ID3D11Texture2D> pOutTex;
01262     BOOL bNativeOut = FALSE, bNativeIn = FALSE;
01263     UINT uiInIndex = 0;
01264     UINT uiOutIndex = 0;
01265
01266     // Attempt to convert directly to DX textures
01267     hr = BufferToDXType(pIn, &uiInIndex, &pInTex);
01268     bNativeIn = SUCCEEDED(hr) && pInTex != nullptr;
01269     hr = BufferToDXType(pOut, &uiOutIndex, &pOutTex);
01270     bNativeOut = SUCCEEDED(hr) && pOutTex != nullptr;
01271
01272     // If the input or output textures' device does not match our device
01273     // we have to move them to our device
01274     if (bNativeIn)
01275     {
01276         ComPtr<ID3D11Device> pDev;
01277         pInTex->GetDevice(&pDev);
01278         if( pDev != m_pDevice )
01279         {
01280             bNativeIn = FALSE;
01281         }
01282     }
01283     if (bNativeOut)
01284     {
01285         ComPtr<ID3D11Device> pDev;
01286         pOutTex->GetDevice(&pDev);
01287         if( pDev != m_pDevice )
01288         {
01289             bNativeOut = FALSE;
01290         }
01291     }
01292
01293
01294     if (!bNativeIn)
01295     {
01296         // Native DX texture in the buffer failed
01297         // create a texture we can use and copy the data in
01298         if (m_pInBufferTex == nullptr)
01299         {
01300             D3D11_TEXTURE2D_DESC desc;
01301             ZeroMemory(&desc,sizeof(desc));
01302             desc.Width = m_imageWidthInPixels;
01303             desc.Height = m_imageHeightInPixels;
01304             desc.ArraySize = 1;
01305             desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
01306             desc.Usage = D3D11_USAGE_DYNAMIC;
01307             desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
01308             desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
01309             desc.MipLevels = 1;
01310             desc.SampleDesc.Count = 1;
01311
01312             hr = m_pDevice->CreateTexture2D(&desc, NULL, &m_pInBufferTex);
01313             if (FAILED(hr))
01314             {
01315                 goto done;
01316             }
01317         }
01318
01319         // scope the texture lock
01320         {
01321             TextureLock tlock(m_pContext.Get(), m_pInBufferTex.Get());
01322             hr = tlock.Map(uiInIndex, D3D11_MAP_WRITE_DISCARD, 0);
01323             if (FAILED(hr))
01324             {
01325                 goto done;
01326             }
01327
01328             // scope the video buffer lock
01329             {
01330                 VideoBufferLock lock;
01331                 LONG lStride;
01332
01333                 hr = GetDefaultStride(m_pInputType.Get(), &lStride);
01334                 if (FAILED(hr))
01335                 {
01336                     goto done;
01337                 }
01338
01339                 hr = lock.Lock(pIn, MF2DBuffer_LockFlags_Read, lStride * m_imageHeightInPixels, lStride);
01340                 if (FAILED(hr))
01341                 {
01342                     goto done;
01343                 }
01344
01345                 hr = MFCopyImage((BYTE*)tlock.map.pData, tlock.map.RowPitch, lock.GetData(), lock.GetStride(), abs(lStride), m_imageHeightInPixels);
01346                 if (FAILED(hr))
01347                 {
01348                     goto done;
01349                 }
01350             }
01351         }
01352         pInTex = m_pInBufferTex;
01353     }
01354
01355     if (!bNativeOut)
01356     {
01357         if (m_pOutBufferTex == nullptr)
01358         {
01359             D3D11_TEXTURE2D_DESC desc;
01360             ZeroMemory(&desc,sizeof(desc));
01361             desc.Width = m_imageWidthInPixels;
01362             desc.Height = m_imageHeightInPixels;
01363             desc.ArraySize = 1;
01364             desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
01365             desc.Usage = D3D11_USAGE_DEFAULT;
01366             desc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
01367             desc.MipLevels = 1;
01368             desc.SampleDesc.Count = 1;
01369             hr = m_pDevice->CreateTexture2D(&desc, NULL, &m_pOutBufferTex);
01370             if (FAILED(hr))
01371             {
01372                 goto done;
01373             }
01374         }
01375         pOutTex = m_pOutBufferTex;
01376     }
01377
01378     // do some processing
01379     m_pTransform->ProcessFrame(m_pDevice.Get(),pInTex.Get(),uiInIndex,pOutTex.Get(),uiOutIndex);
01380
01381     // write back pOut if necessary
01382     if (!bNativeOut)
01383     {
01384         if (m_pOutBufferStage == nullptr)
01385         {
01386             D3D11_TEXTURE2D_DESC desc;
01387             ZeroMemory(&desc,sizeof(desc));
01388             desc.Width = m_imageWidthInPixels;
01389             desc.Height = m_imageHeightInPixels;
01390             desc.ArraySize = 1;
01391             desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
01392             desc.Usage = D3D11_USAGE_STAGING;
01393             desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
01394             desc.MipLevels = 1;
01395             desc.SampleDesc.Count = 1;
01396             hr = m_pDevice->CreateTexture2D(&desc, NULL, &m_pOutBufferStage);
01397             if (FAILED(hr))
01398             {
01399                 goto done;
01400             }
01401         }
01402
01403         m_pContext->CopyResource(m_pOutBufferStage.Get(), m_pOutBufferTex.Get());
01404
01405         {
01406             TextureLock tlock(m_pContext.Get(), m_pOutBufferStage.Get());
01407             hr = tlock.Map(uiOutIndex, D3D11_MAP_READ, 0);
01408             if (FAILED(hr))
01409             {
01410                 goto done;
01411             }
01412
01413             // scope the video buffer lock
01414             {
01415                 VideoBufferLock lock;
01416                 LONG lStride;
01417
01418                 hr = GetDefaultStride(m_pOutputType.Get(), &lStride);
01419                 if (FAILED(hr))
01420                 {
01421                     goto done;
01422                 }
01423
01424                 hr = lock.Lock(pOut, MF2DBuffer_LockFlags_Write, lStride * m_imageHeightInPixels, lStride);
01425                 if (FAILED(hr))
01426                 {
01427                     goto done;
01428                 }
01429
01430                 hr = MFCopyImage(lock.GetData(), lock.GetStride(), (BYTE*)tlock.map.pData, tlock.map.RowPitch, abs(lStride), m_imageHeightInPixels);
01431                 if (FAILED(hr))
01432                 {
01433                     goto done;
01434                 }
01435             }
01436         }
01437     }
01438
01439 done:
01440     return hr;
01441 }
01442
01443 // Update the format information. This method is called whenever the
01444 // input type is set.
01445 HRESULT CInvert::UpdateFormatInfo()
01446 {
01447     HRESULT hr = S_OK;
01448     LONG lStride = 0;
01449
01450     m_imageWidthInPixels = 0;
01451     m_imageHeightInPixels = 0;
01452     m_cbImageSize = 0;
01453
01454     if (m_pInputType != NULL)
01455     {
01456         hr = MFGetAttributeSize(m_pInputType.Get(), MF_MT_FRAME_SIZE, &m_imageWidthInPixels, &m_imageHeightInPixels);
01457         if (FAILED(hr))
01458         {
01459             goto done;
01460         }
01461
01462         hr = GetDefaultStride(m_pInputType.Get(), &lStride);
01463         if (FAILED(hr))
01464         {
01465             goto done;
01466         }
01467
01468         // Calculate the image size
01469         m_cbImageSize = abs(lStride) * 4 * m_imageHeightInPixels;
01470     }
01471
01472 done:
01473     return hr;
01474 }
01475
01476 // Get the default stride for a video format.
01477 HRESULT GetDefaultStride(IMFMediaType *pType, LONG *plStride)
01478 {
01479     LONG lStride = 0;
01480
01481     // Try to get the default stride from the media type.
01482     HRESULT hr = pType->GetUINT32(MF_MT_DEFAULT_STRIDE, (UINT32*)&lStride);
01483     if (FAILED(hr))
01484     {
01485         // Attribute not set. Try to calculate the default stride.
01486         GUID subtype = GUID_NULL;
01487
01488         UINT32 width = 0;
01489         UINT32 height = 0;
01490
01491         // Get the subtype and the image size.
01492         hr = pType->GetGUID(MF_MT_SUBTYPE, &subtype);
01493         if (SUCCEEDED(hr))
01494         {
01495             hr = MFGetAttributeSize(pType, MF_MT_FRAME_SIZE, &width, &height);
01496         }
01497         if (SUCCEEDED(hr))
01498         {
01499             lStride = width * 4;
01500         }
01501
01502         // Set the attribute for later reference.
01503         if (SUCCEEDED(hr))
01504         {
01505             (void)pType->SetUINT32(MF_MT_DEFAULT_STRIDE, UINT32(lStride));
01506         }
01507     }
01508     if (SUCCEEDED(hr))
01509     {
01510         *plStride = lStride;
01511     }
01512     return hr;
01513 }
Generated on Sat Nov 23 2024 16:08:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML user and custom controls/C++/BasicUserControl.xaml.h Source File

  • XAML user and custom controls

BasicUserControl.xaml.h

Go to the documentation of this file.
00001 ﻿//
00002 // BasicUserControl.xaml.h
00003 // Declaration of the BasicUserControl class
00004 //
00005
00006 #pragma once
00007
00008 #include "pch.h"
00009 #include "BasicUserControl.g.h"
00010
00011 namespace SDKSample
00012 {
00013     namespace UserAndCustomControls
00014     {
00015       public ref class BasicUserControl sealed
00016       {
00017       public:
00018         BasicUserControl();
00019       private:
00020         void ClickMeButtonClicked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00021       };
00022     }
00023 }
Generated on Sat Nov 23 2024 16:08:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D bump mapping/C++/DDSTextureLoader.cpp Source File

  • Direct3D bump mapping

DDSTextureLoader.cpp

Go to the documentation of this file.
00001 //--------------------------------------------------------------------------------------
00002 // File: DDSTextureLoader.cpp
00003 //
00004 // Function for loading a DDS texture and creating a Direct3D 11 runtime resource for it
00005 //
00006 // Note this function is 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
00018 #include "pch.h"
00019 #include <dxgiformat.h>
00020 #include <assert.h>
00021 #include <memory>
00022 #include <algorithm>
00023 #include "DDSTextureLoader.h"
00024 #include "DirectXSample.h"
00025
00026 using namespace Microsoft::WRL;
00027
00028 //--------------------------------------------------------------------------------------
00029 // Macros
00030 //--------------------------------------------------------------------------------------
00031 #ifndef MAKEFOURCC
00032     #define MAKEFOURCC(ch0, ch1, ch2, ch3)                              \
00033                 ((uint32)(byte)(ch0) | ((uint32)(byte)(ch1) << 8) |       \
00034                 ((uint32)(byte)(ch2) << 16) | ((uint32)(byte)(ch3) << 24))
00035 #endif /* defined(MAKEFOURCC) */
00036
00037 //--------------------------------------------------------------------------------------
00038 // DDS file structure definitions
00039 //
00040 // See DDS.h in the 'Texconv' sample and the 'DirectXTex' library
00041 //--------------------------------------------------------------------------------------
00042 #pragma pack(push, 1)
00043
00044 #define DDS_MAGIC 0x20534444 // "DDS "
00045
00046 struct DDS_PIXELFORMAT
00047 {
00048     uint32  size;
00049     uint32  flags;
00050     uint32  fourCC;
00051     uint32  RGBBitCount;
00052     uint32  RBitMask;
00053     uint32  GBitMask;
00054     uint32  BBitMask;
00055     uint32  ABitMask;
00056 };
00057
00058 #define DDS_FOURCC      0x00000004  // DDPF_FOURCC
00059 #define DDS_RGB         0x00000040  // DDPF_RGB
00060 #define DDS_RGBA        0x00000041  // DDPF_RGB | DDPF_ALPHAPIXELS
00061 #define DDS_LUMINANCE   0x00020000  // DDPF_LUMINANCE
00062 #define DDS_LUMINANCEA  0x00020001  // DDPF_LUMINANCE | DDPF_ALPHAPIXELS
00063 #define DDS_ALPHA       0x00000002  // DDPF_ALPHA
00064 #define DDS_PAL8        0x00000020  // DDPF_PALETTEINDEXED8
00065
00066 #define DDS_HEADER_FLAGS_TEXTURE        0x00001007  // DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT
00067 #define DDS_HEADER_FLAGS_MIPMAP         0x00020000  // DDSD_MIPMAPCOUNT
00068 #define DDS_HEADER_FLAGS_VOLUME         0x00800000  // DDSD_DEPTH
00069 #define DDS_HEADER_FLAGS_PITCH          0x00000008  // DDSD_PITCH
00070 #define DDS_HEADER_FLAGS_LINEARSIZE     0x00080000  // DDSD_LINEARSIZE
00071
00072 #define DDS_HEIGHT 0x00000002 // DDSD_HEIGHT
00073 #define DDS_WIDTH  0x00000004 // DDSD_WIDTH
00074
00075 #define DDS_SURFACE_FLAGS_TEXTURE 0x00001000 // DDSCAPS_TEXTURE
00076 #define DDS_SURFACE_FLAGS_MIPMAP  0x00400008 // DDSCAPS_COMPLEX | DDSCAPS_MIPMAP
00077 #define DDS_SURFACE_FLAGS_CUBEMAP 0x00000008 // DDSCAPS_COMPLEX
00078
00079 #define DDS_CUBEMAP_POSITIVEX 0x00000600 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEX
00080 #define DDS_CUBEMAP_NEGATIVEX 0x00000a00 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEX
00081 #define DDS_CUBEMAP_POSITIVEY 0x00001200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEY
00082 #define DDS_CUBEMAP_NEGATIVEY 0x00002200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEY
00083 #define DDS_CUBEMAP_POSITIVEZ 0x00004200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEZ
00084 #define DDS_CUBEMAP_NEGATIVEZ 0x00008200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEZ
00085
00086 #define DDS_CUBEMAP_ALLFACES (DDS_CUBEMAP_POSITIVEX | DDS_CUBEMAP_NEGATIVEX |\
00087                               DDS_CUBEMAP_POSITIVEY | DDS_CUBEMAP_NEGATIVEY |\
00088                               DDS_CUBEMAP_POSITIVEZ | DDS_CUBEMAP_NEGATIVEZ)
00089
00090 #define DDS_CUBEMAP 0x00000200 // DDSCAPS2_CUBEMAP
00091
00092 #define DDS_FLAGS_VOLUME 0x00200000 // DDSCAPS2_VOLUME
00093
00094 typedef struct
00095 {
00096     uint32          size;
00097     uint32          flags;
00098     uint32          height;
00099     uint32          width;
00100     uint32          pitchOrLinearSize;
00101     uint32          depth; // only if DDS_HEADER_FLAGS_VOLUME is set in flags
00102     uint32          mipMapCount;
00103     uint32          reserved1[11];
00104     DDS_PIXELFORMAT ddspf;
00105     uint32          caps;
00106     uint32          caps2;
00107     uint32          caps3;
00108     uint32          caps4;
00109     uint32          reserved2;
00110 } DDS_HEADER;
00111
00112 typedef struct
00113 {
00114     DXGI_FORMAT dxgiFormat;
00115     uint32      resourceDimension;
00116     uint32      miscFlag; // see D3D11_RESOURCE_MISC_FLAG
00117     uint32      arraySize;
00118     uint32      reserved;
00119 } DDS_HEADER_DXT10;
00120
00121 #pragma pack(pop)
00122
00123 //--------------------------------------------------------------------------------------
00124 // Return the BPP for a particular format
00125 //--------------------------------------------------------------------------------------
00126 static size_t BitsPerPixel(_In_ DXGI_FORMAT fmt)
00127 {
00128     switch (fmt)
00129     {
00130     case DXGI_FORMAT_R32G32B32A32_TYPELESS:
00131     case DXGI_FORMAT_R32G32B32A32_FLOAT:
00132     case DXGI_FORMAT_R32G32B32A32_UINT:
00133     case DXGI_FORMAT_R32G32B32A32_SINT:
00134         return 128;
00135
00136     case DXGI_FORMAT_R32G32B32_TYPELESS:
00137     case DXGI_FORMAT_R32G32B32_FLOAT:
00138     case DXGI_FORMAT_R32G32B32_UINT:
00139     case DXGI_FORMAT_R32G32B32_SINT:
00140         return 96;
00141
00142     case DXGI_FORMAT_R16G16B16A16_TYPELESS:
00143     case DXGI_FORMAT_R16G16B16A16_FLOAT:
00144     case DXGI_FORMAT_R16G16B16A16_UNORM:
00145     case DXGI_FORMAT_R16G16B16A16_UINT:
00146     case DXGI_FORMAT_R16G16B16A16_SNORM:
00147     case DXGI_FORMAT_R16G16B16A16_SINT:
00148     case DXGI_FORMAT_R32G32_TYPELESS:
00149     case DXGI_FORMAT_R32G32_FLOAT:
00150     case DXGI_FORMAT_R32G32_UINT:
00151     case DXGI_FORMAT_R32G32_SINT:
00152     case DXGI_FORMAT_R32G8X24_TYPELESS:
00153     case DXGI_FORMAT_D32_FLOAT_S8X24_UINT:
00154     case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS:
00155     case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT:
00156         return 64;
00157
00158     case DXGI_FORMAT_R10G10B10A2_TYPELESS:
00159     case DXGI_FORMAT_R10G10B10A2_UNORM:
00160     case DXGI_FORMAT_R10G10B10A2_UINT:
00161     case DXGI_FORMAT_R11G11B10_FLOAT:
00162     case DXGI_FORMAT_R8G8B8A8_TYPELESS:
00163     case DXGI_FORMAT_R8G8B8A8_UNORM:
00164     case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
00165     case DXGI_FORMAT_R8G8B8A8_UINT:
00166     case DXGI_FORMAT_R8G8B8A8_SNORM:
00167     case DXGI_FORMAT_R8G8B8A8_SINT:
00168     case DXGI_FORMAT_R16G16_TYPELESS:
00169     case DXGI_FORMAT_R16G16_FLOAT:
00170     case DXGI_FORMAT_R16G16_UNORM:
00171     case DXGI_FORMAT_R16G16_UINT:
00172     case DXGI_FORMAT_R16G16_SNORM:
00173     case DXGI_FORMAT_R16G16_SINT:
00174     case DXGI_FORMAT_R32_TYPELESS:
00175     case DXGI_FORMAT_D32_FLOAT:
00176     case DXGI_FORMAT_R32_FLOAT:
00177     case DXGI_FORMAT_R32_UINT:
00178     case DXGI_FORMAT_R32_SINT:
00179     case DXGI_FORMAT_R24G8_TYPELESS:
00180     case DXGI_FORMAT_D24_UNORM_S8_UINT:
00181     case DXGI_FORMAT_R24_UNORM_X8_TYPELESS:
00182     case DXGI_FORMAT_X24_TYPELESS_G8_UINT:
00183     case DXGI_FORMAT_R9G9B9E5_SHAREDEXP:
00184     case DXGI_FORMAT_R8G8_B8G8_UNORM:
00185     case DXGI_FORMAT_G8R8_G8B8_UNORM:
00186     case DXGI_FORMAT_B8G8R8A8_UNORM:
00187     case DXGI_FORMAT_B8G8R8X8_UNORM:
00188     case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM:
00189     case DXGI_FORMAT_B8G8R8A8_TYPELESS:
00190     case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
00191     case DXGI_FORMAT_B8G8R8X8_TYPELESS:
00192     case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB:
00193         return 32;
00194
00195     case DXGI_FORMAT_R8G8_TYPELESS:
00196     case DXGI_FORMAT_R8G8_UNORM:
00197     case DXGI_FORMAT_R8G8_UINT:
00198     case DXGI_FORMAT_R8G8_SNORM:
00199     case DXGI_FORMAT_R8G8_SINT:
00200     case DXGI_FORMAT_R16_TYPELESS:
00201     case DXGI_FORMAT_R16_FLOAT:
00202     case DXGI_FORMAT_D16_UNORM:
00203     case DXGI_FORMAT_R16_UNORM:
00204     case DXGI_FORMAT_R16_UINT:
00205     case DXGI_FORMAT_R16_SNORM:
00206     case DXGI_FORMAT_R16_SINT:
00207     case DXGI_FORMAT_B5G6R5_UNORM:
00208     case DXGI_FORMAT_B5G5R5A1_UNORM:
00209     case DXGI_FORMAT_B4G4R4A4_UNORM:
00210         return 16;
00211
00212     case DXGI_FORMAT_R8_TYPELESS:
00213     case DXGI_FORMAT_R8_UNORM:
00214     case DXGI_FORMAT_R8_UINT:
00215     case DXGI_FORMAT_R8_SNORM:
00216     case DXGI_FORMAT_R8_SINT:
00217     case DXGI_FORMAT_A8_UNORM:
00218         return 8;
00219
00220     case DXGI_FORMAT_R1_UNORM:
00221         return 1;
00222
00223     case DXGI_FORMAT_BC1_TYPELESS:
00224     case DXGI_FORMAT_BC1_UNORM:
00225     case DXGI_FORMAT_BC1_UNORM_SRGB:
00226     case DXGI_FORMAT_BC4_TYPELESS:
00227     case DXGI_FORMAT_BC4_UNORM:
00228     case DXGI_FORMAT_BC4_SNORM:
00229         return 4;
00230
00231     case DXGI_FORMAT_BC2_TYPELESS:
00232     case DXGI_FORMAT_BC2_UNORM:
00233     case DXGI_FORMAT_BC2_UNORM_SRGB:
00234     case DXGI_FORMAT_BC3_TYPELESS:
00235     case DXGI_FORMAT_BC3_UNORM:
00236     case DXGI_FORMAT_BC3_UNORM_SRGB:
00237     case DXGI_FORMAT_BC5_TYPELESS:
00238     case DXGI_FORMAT_BC5_UNORM:
00239     case DXGI_FORMAT_BC5_SNORM:
00240     case DXGI_FORMAT_BC6H_TYPELESS:
00241     case DXGI_FORMAT_BC6H_UF16:
00242     case DXGI_FORMAT_BC6H_SF16:
00243     case DXGI_FORMAT_BC7_TYPELESS:
00244     case DXGI_FORMAT_BC7_UNORM:
00245     case DXGI_FORMAT_BC7_UNORM_SRGB:
00246         return 8;
00247
00248     default:
00249         return 0;
00250     }
00251 }
00252
00253
00254 //--------------------------------------------------------------------------------------
00255 // Get surface information for a particular format
00256 //--------------------------------------------------------------------------------------
00257 static void GetSurfaceInfo(
00258     _In_ size_t width,
00259     _In_ size_t height,
00260     _In_ DXGI_FORMAT fmt,
00261     _Out_opt_ size_t* outNumBytes,
00262     _Out_opt_ size_t* outRowBytes,
00263     _Out_opt_ size_t* outNumRows
00264     )
00265 {
00266     size_t numBytes = 0;
00267     size_t rowBytes = 0;
00268     size_t numRows = 0;
00269
00270     bool bc = false;
00271     bool packed  = false;
00272     size_t bcnumBytesPerBlock = 0;
00273     switch (fmt)
00274     {
00275     case DXGI_FORMAT_BC1_TYPELESS:
00276     case DXGI_FORMAT_BC1_UNORM:
00277     case DXGI_FORMAT_BC1_UNORM_SRGB:
00278     case DXGI_FORMAT_BC4_TYPELESS:
00279     case DXGI_FORMAT_BC4_UNORM:
00280     case DXGI_FORMAT_BC4_SNORM:
00281         bc = true;
00282         bcnumBytesPerBlock = 8;
00283         break;
00284
00285     case DXGI_FORMAT_BC2_TYPELESS:
00286     case DXGI_FORMAT_BC2_UNORM:
00287     case DXGI_FORMAT_BC2_UNORM_SRGB:
00288     case DXGI_FORMAT_BC3_TYPELESS:
00289     case DXGI_FORMAT_BC3_UNORM:
00290     case DXGI_FORMAT_BC3_UNORM_SRGB:
00291     case DXGI_FORMAT_BC5_TYPELESS:
00292     case DXGI_FORMAT_BC5_UNORM:
00293     case DXGI_FORMAT_BC5_SNORM:
00294     case DXGI_FORMAT_BC6H_TYPELESS:
00295     case DXGI_FORMAT_BC6H_UF16:
00296     case DXGI_FORMAT_BC6H_SF16:
00297     case DXGI_FORMAT_BC7_TYPELESS:
00298     case DXGI_FORMAT_BC7_UNORM:
00299     case DXGI_FORMAT_BC7_UNORM_SRGB:
00300         bc = true;
00301         bcnumBytesPerBlock = 16;
00302         break;
00303
00304     case DXGI_FORMAT_R8G8_B8G8_UNORM:
00305     case DXGI_FORMAT_G8R8_G8B8_UNORM:
00306         packed = true;
00307         break;
00308     }
00309
00310     if (bc)
00311     {
00312         size_t numBlocksWide = 0;
00313         if (width > 0)
00314         {
00315             numBlocksWide = std::max<size_t>(1, (width + 3) / 4);
00316         }
00317         size_t numBlocksHigh = 0;
00318         if (height > 0)
00319         {
00320             numBlocksHigh = std::max<size_t>(1, (height + 3) / 4);
00321         }
00322         rowBytes = numBlocksWide * bcnumBytesPerBlock;
00323         numRows = numBlocksHigh;
00324     }
00325     else if (packed)
00326     {
00327         rowBytes = ((width + 1) >> 1) * 4;
00328         numRows = height;
00329     }
00330     else
00331     {
00332         size_t bpp = BitsPerPixel(fmt);
00333         rowBytes = (width * bpp + 7) / 8; // round up to nearest byte
00334         numRows = height;
00335     }
00336
00337     numBytes = rowBytes * numRows;
00338     if (outNumBytes)
00339     {
00340         *outNumBytes = numBytes;
00341     }
00342     if (outRowBytes)
00343     {
00344         *outRowBytes = rowBytes;
00345     }
00346     if (outNumRows)
00347     {
00348         *outNumRows = numRows;
00349     }
00350 }
00351
00352
00353 //--------------------------------------------------------------------------------------
00354 #define ISBITMASK(r, g, b, a) (ddpf.RBitMask == r && ddpf.GBitMask == g && ddpf.BBitMask == b && ddpf.ABitMask == a)
00355
00356 static DXGI_FORMAT GetDXGIFormat(const DDS_PIXELFORMAT& ddpf)
00357 {
00358     if (ddpf.flags & DDS_RGB)
00359     {
00360         // Note that sRGB formats are written using the "DX10" extended header
00361
00362         switch (ddpf.RGBBitCount)
00363         {
00364         case 32:
00365             if (ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000))
00366             {
00367                 return DXGI_FORMAT_R8G8B8A8_UNORM;
00368             }
00369
00370             if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000))
00371             {
00372                 return DXGI_FORMAT_B8G8R8A8_UNORM;
00373             }
00374
00375             if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0x00000000))
00376             {
00377                 return DXGI_FORMAT_B8G8R8X8_UNORM;
00378             }
00379
00380             // No DXGI format maps to ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0x00000000) aka D3DFMT_X8B8G8R8
00381
00382             // Note that many common DDS reader/writers (including D3DX) swap the
00383             // the RED/BLUE masks for 10:10:10:2 formats. We assumme
00384             // below that the 'backwards' header mask is being used since it is most
00385             // likely written by D3DX. The more robust solution is to use the 'DX10'
00386             // header extension and specify the DXGI_FORMAT_R10G10B10A2_UNORM format directly
00387
00388             // For 'correct' writers, this should be 0x000003ff, 0x000ffc00, 0x3ff00000 for RGB data
00389             if (ISBITMASK(0x3ff00000, 0x000ffc00, 0x000003ff, 0xc0000000))
00390             {
00391                 return DXGI_FORMAT_R10G10B10A2_UNORM;
00392             }
00393
00394             // No DXGI format maps to ISBITMASK(0x000003ff, 0x000ffc00, 0x3ff00000, 0xc0000000) aka D3DFMT_A2R10G10B10
00395
00396             if (ISBITMASK(0x0000ffff, 0xffff0000, 0x00000000, 0x00000000))
00397             {
00398                 return DXGI_FORMAT_R16G16_UNORM;
00399             }
00400
00401             if (ISBITMASK(0xffffffff, 0x00000000, 0x00000000, 0x00000000))
00402             {
00403                 // Only 32-bit color channel format in D3D9 was R32F
00404                 return DXGI_FORMAT_R32_FLOAT; // D3DX writes this out as a FourCC of 114
00405             }
00406             break;
00407
00408         case 24:
00409             // No 24bpp DXGI formats aka D3DFMT_R8G8B8
00410             break;
00411
00412         case 16:
00413             if (ISBITMASK(0x7c00, 0x03e0, 0x001f, 0x8000))
00414             {
00415                 return DXGI_FORMAT_B5G5R5A1_UNORM;
00416             }
00417             if (ISBITMASK(0xf800, 0x07e0, 0x001f, 0x0000))
00418             {
00419                 return DXGI_FORMAT_B5G6R5_UNORM;
00420             }
00421
00422             // No DXGI format maps to ISBITMASK(0x7c00, 0x03e0, 0x001f, 0x0000) aka D3DFMT_X1R5G5B5
00423             if (ISBITMASK(0x0f00, 0x00f0, 0x000f, 0xf000))
00424             {
00425                 return DXGI_FORMAT_B4G4R4A4_UNORM;
00426             }
00427
00428             // No DXGI format maps to ISBITMASK(0x0f00, 0x00f0, 0x000f, 0x0000) aka D3DFMT_X4R4G4B4
00429
00430             // No 3:3:2, 3:3:2:8, or paletted DXGI formats aka D3DFMT_A8R3G3B2, D3DFMT_R3G3B2, D3DFMT_P8, D3DFMT_A8P8, etc.
00431             break;
00432         }
00433     }
00434     else if (ddpf.flags & DDS_LUMINANCE)
00435     {
00436         if (8 == ddpf.RGBBitCount)
00437         {
00438             if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x00000000))
00439             {
00440                 return DXGI_FORMAT_R8_UNORM; // D3DX10/11 writes this out as DX10 extension
00441             }
00442
00443             // No DXGI format maps to ISBITMASK(0x0f, 0x00, 0x00, 0xf0) aka D3DFMT_A4L4
00444         }
00445
00446         if (16 == ddpf.RGBBitCount)
00447         {
00448             if (ISBITMASK(0x0000ffff, 0x00000000, 0x00000000, 0x00000000))
00449             {
00450                 return DXGI_FORMAT_R16_UNORM; // D3DX10/11 writes this out as DX10 extension
00451             }
00452             if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x0000ff00))
00453             {
00454                 return DXGI_FORMAT_R8G8_UNORM; // D3DX10/11 writes this out as DX10 extension
00455             }
00456         }
00457     }
00458     else if (ddpf.flags & DDS_ALPHA)
00459     {
00460         if (8 == ddpf.RGBBitCount)
00461         {
00462             return DXGI_FORMAT_A8_UNORM;
00463         }
00464     }
00465     else if (ddpf.flags & DDS_FOURCC)
00466     {
00467         if (MAKEFOURCC('D', 'X', 'T', '1') == ddpf.fourCC)
00468         {
00469             return DXGI_FORMAT_BC1_UNORM;
00470         }
00471         if (MAKEFOURCC('D', 'X', 'T', '3') == ddpf.fourCC)
00472         {
00473             return DXGI_FORMAT_BC2_UNORM;
00474         }
00475         if (MAKEFOURCC('D', 'X', 'T', '5') == ddpf.fourCC)
00476         {
00477             return DXGI_FORMAT_BC3_UNORM;
00478         }
00479
00480         // While pre-mulitplied alpha isn't directly supported by the DXGI formats,
00481         // they are basically the same as these BC formats so they can be mapped
00482         if (MAKEFOURCC('D', 'X', 'T', '2') == ddpf.fourCC)
00483         {
00484             return DXGI_FORMAT_BC2_UNORM;
00485         }
00486         if (MAKEFOURCC('D', 'X', 'T', '4') == ddpf.fourCC)
00487         {
00488             return DXGI_FORMAT_BC3_UNORM;
00489         }
00490
00491         if (MAKEFOURCC('A', 'T', 'I', '1') == ddpf.fourCC)
00492         {
00493             return DXGI_FORMAT_BC4_UNORM;
00494         }
00495         if (MAKEFOURCC('B', 'C', '4', 'U') == ddpf.fourCC)
00496         {
00497             return DXGI_FORMAT_BC4_UNORM;
00498         }
00499         if (MAKEFOURCC('B', 'C', '4', 'S') == ddpf.fourCC)
00500         {
00501             return DXGI_FORMAT_BC4_SNORM;
00502         }
00503
00504         if (MAKEFOURCC('A', 'T', 'I', '2') == ddpf.fourCC)
00505         {
00506             return DXGI_FORMAT_BC5_UNORM;
00507         }
00508         if (MAKEFOURCC('B', 'C', '5', 'U') == ddpf.fourCC)
00509         {
00510             return DXGI_FORMAT_BC5_UNORM;
00511         }
00512         if (MAKEFOURCC('B', 'C', '5', 'S') == ddpf.fourCC)
00513         {
00514             return DXGI_FORMAT_BC5_SNORM;
00515         }
00516
00517         // BC6H and BC7 are written using the "DX10" extended header
00518
00519         if (MAKEFOURCC('R', 'G', 'B', 'G') == ddpf.fourCC)
00520         {
00521             return DXGI_FORMAT_R8G8_B8G8_UNORM;
00522         }
00523         if (MAKEFOURCC('G', 'R', 'G', 'B') == ddpf.fourCC)
00524         {
00525             return DXGI_FORMAT_G8R8_G8B8_UNORM;
00526         }
00527
00528         // Check for D3DFORMAT enums being set here
00529         switch (ddpf.fourCC)
00530         {
00531         case 36: // D3DFMT_A16B16G16R16
00532             return DXGI_FORMAT_R16G16B16A16_UNORM;
00533
00534         case 110: // D3DFMT_Q16W16V16U16
00535             return DXGI_FORMAT_R16G16B16A16_SNORM;
00536
00537         case 111: // D3DFMT_R16F
00538             return DXGI_FORMAT_R16_FLOAT;
00539
00540         case 112: // D3DFMT_G16R16F
00541             return DXGI_FORMAT_R16G16_FLOAT;
00542
00543         case 113: // D3DFMT_A16B16G16R16F
00544             return DXGI_FORMAT_R16G16B16A16_FLOAT;
00545
00546         case 114: // D3DFMT_R32F
00547             return DXGI_FORMAT_R32_FLOAT;
00548
00549         case 115: // D3DFMT_G32R32F
00550             return DXGI_FORMAT_R32G32_FLOAT;
00551
00552         case 116: // D3DFMT_A32B32G32R32F
00553             return DXGI_FORMAT_R32G32B32A32_FLOAT;
00554         }
00555     }
00556
00557     return DXGI_FORMAT_UNKNOWN;
00558 }
00559
00560
00561 //--------------------------------------------------------------------------------------
00562 static void FillInitData(
00563     _In_ size_t width,
00564     _In_ size_t height,
00565     _In_ size_t depth,
00566     _In_ size_t mipCount,
00567     _In_ size_t arraySize,
00568     _In_ DXGI_FORMAT format,
00569     _In_ size_t maxsize,
00570     _In_ size_t bitSize,
00571     _In_reads_bytes_(bitSize) const byte* bitData,
00572     _Out_ size_t& twidth,
00573     _Out_ size_t& theight,
00574     _Out_ size_t& tdepth,
00575     _Out_ size_t& skipMip,
00576     _Out_writes_(mipCount*arraySize) D3D11_SUBRESOURCE_DATA* initData
00577     )
00578 {
00579     if (!bitData || !initData)
00580     {
00581         throw ref new Platform::InvalidArgumentException();
00582     }
00583
00584     skipMip = 0;
00585     twidth = 0;
00586     theight = 0;
00587     tdepth = 0;
00588
00589     size_t NumBytes = 0;
00590     size_t RowBytes = 0;
00591     size_t NumRows = 0;
00592     const byte* pSrcBits = bitData;
00593     const byte* pEndBits = bitData + bitSize;
00594
00595     size_t index = 0;
00596     for (size_t j = 0; j < arraySize; j++)
00597     {
00598         size_t w = width;
00599         size_t h = height;
00600         size_t d = depth;
00601         for (size_t i = 0; i < mipCount; i++)
00602         {
00603             GetSurfaceInfo(w, h, format, &NumBytes, &RowBytes, &NumRows);
00604
00605             if ((mipCount <= 1) || !maxsize || (w <= maxsize && h <= maxsize && d <= maxsize))
00606             {
00607                 if (!twidth)
00608                 {
00609                     twidth = w;
00610                     theight = h;
00611                     tdepth = d;
00612                 }
00613
00614                 initData[index].pSysMem = (const void*)pSrcBits;
00615                 initData[index].SysMemPitch = static_cast<UINT>(RowBytes);
00616                 initData[index].SysMemSlicePitch = static_cast<UINT>(NumBytes);
00617                 ++index;
00618             }
00619             else
00620             {
00621                 ++skipMip;
00622             }
00623
00624             if (pSrcBits + (NumBytes*d) > pEndBits)
00625             {
00626                 throw ref new Platform::OutOfBoundsException();
00627             }
00628
00629             pSrcBits += NumBytes * d;
00630
00631             w = w >> 1;
00632             h = h >> 1;
00633             d = d >> 1;
00634             if (w == 0)
00635             {
00636                 w = 1;
00637             }
00638             if (h == 0)
00639             {
00640                 h = 1;
00641             }
00642             if (d == 0)
00643             {
00644                 d = 1;
00645             }
00646         }
00647     }
00648
00649     if (!index)
00650     {
00651         throw ref new Platform::FailureException();
00652     }
00653 }
00654
00655
00656 //--------------------------------------------------------------------------------------
00657 static HRESULT CreateD3DResources(
00658     _In_ ID3D11Device* d3dDevice,
00659     _In_ uint32 resDim,
00660     _In_ size_t width,
00661     _In_ size_t height,
00662     _In_ size_t depth,
00663     _In_ size_t mipCount,
00664     _In_ size_t arraySize,
00665     _In_ DXGI_FORMAT format,
00666     _In_ bool isCubeMap,
00667     _In_reads_(mipCount*arraySize) D3D11_SUBRESOURCE_DATA* initData,
00668     _Out_opt_ ID3D11Resource** texture,
00669     _Out_opt_ ID3D11ShaderResourceView** textureView
00670     )
00671 {
00672     if (!d3dDevice || !initData)
00673     {
00674         return E_INVALIDARG;
00675     }
00676
00677     HRESULT hr = E_FAIL;
00678
00679     switch (resDim)
00680     {
00681         case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
00682             {
00683                 D3D11_TEXTURE1D_DESC desc;
00684                 desc.Width = static_cast<UINT>(width);
00685                 desc.MipLevels = static_cast<UINT>(mipCount);
00686                 desc.ArraySize = static_cast<UINT>(arraySize);
00687                 desc.Format = format;
00688                 desc.Usage = D3D11_USAGE_DEFAULT;
00689                 desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
00690                 desc.CPUAccessFlags = 0;
00691                 desc.MiscFlags = 0;
00692
00693                 ID3D11Texture1D* tex = nullptr;
00694                 hr = d3dDevice->CreateTexture1D(&desc, initData, &tex);
00695
00696                 if (SUCCEEDED(hr) && tex != 0)
00697                 {
00698                     if (textureView != 0)
00699                     {
00700                         D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
00701                         memset(&SRVDesc, 0, sizeof(SRVDesc));
00702                         SRVDesc.Format = format;
00703
00704                         if (arraySize > 1)
00705                         {
00706                             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE1DARRAY;
00707                             SRVDesc.Texture1DArray.MipLevels = desc.MipLevels;
00708                             SRVDesc.Texture1DArray.ArraySize = static_cast<UINT>(arraySize);
00709                         }
00710                         else
00711                         {
00712                             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE1D;
00713                             SRVDesc.Texture1D.MipLevels = desc.MipLevels;
00714                         }
00715
00716                         hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView);
00717
00718                         if (FAILED(hr))
00719                         {
00720                             tex->Release();
00721                             return hr;
00722                         }
00723                     }
00724
00725                     if (texture != 0)
00726                     {
00727                         *texture = tex;
00728                     }
00729                     else
00730                     {
00731                         tex->Release();
00732                     }
00733                 }
00734             }
00735             break;
00736
00737         case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
00738             {
00739                 D3D11_TEXTURE2D_DESC desc;
00740                 desc.Width = static_cast<UINT>(width);
00741                 desc.Height = static_cast<UINT>(height);
00742                 desc.MipLevels = static_cast<UINT>(mipCount);
00743                 desc.ArraySize = static_cast<UINT>(arraySize);
00744                 desc.Format = format;
00745                 desc.SampleDesc.Count = 1;
00746                 desc.SampleDesc.Quality = 0;
00747                 desc.Usage = D3D11_USAGE_DEFAULT;
00748                 desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
00749                 desc.CPUAccessFlags = 0;
00750                 desc.MiscFlags = (isCubeMap) ? D3D11_RESOURCE_MISC_TEXTURECUBE : 0;
00751
00752                 ID3D11Texture2D* tex = nullptr;
00753                 hr = d3dDevice->CreateTexture2D(&desc, initData, &tex);
00754
00755                 if (SUCCEEDED(hr) && tex != 0)
00756                 {
00757                     if (textureView != 0)
00758                     {
00759                         D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
00760                         memset(&SRVDesc, 0, sizeof(SRVDesc));
00761                         SRVDesc.Format = format;
00762
00763                         if (isCubeMap)
00764                         {
00765                             if (arraySize > 6)
00766                             {
00767                                 SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURECUBEARRAY;
00768                                 SRVDesc.TextureCubeArray.MipLevels = desc.MipLevels;
00769
00770                                 // Earlier we set arraySize to (NumCubes * 6)
00771                                 SRVDesc.TextureCubeArray.NumCubes = static_cast<UINT>(arraySize / 6);
00772                             }
00773                             else
00774                             {
00775                                 SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURECUBE;
00776                                 SRVDesc.TextureCube.MipLevels = desc.MipLevels;
00777                             }
00778                         }
00779                         else if (arraySize > 1)
00780                         {
00781                             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE2DARRAY;
00782                             SRVDesc.Texture2DArray.MipLevels = desc.MipLevels;
00783                             SRVDesc.Texture2DArray.ArraySize = static_cast<UINT>(arraySize);
00784                         }
00785                         else
00786                         {
00787                             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE2D;
00788                             SRVDesc.Texture2D.MipLevels = desc.MipLevels;
00789                         }
00790
00791                         hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView);
00792
00793                         if (FAILED(hr))
00794                         {
00795                             tex->Release();
00796                             return hr;
00797                         }
00798                     }
00799
00800                     if (texture != 0)
00801                     {
00802                         *texture = tex;
00803                     }
00804                     else
00805                     {
00806                         tex->Release();
00807                     }
00808                 }
00809             }
00810             break;
00811
00812         case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
00813             {
00814                 D3D11_TEXTURE3D_DESC desc;
00815                 desc.Width = static_cast<UINT>(width);
00816                 desc.Height = static_cast<UINT>(height);
00817                 desc.Depth = static_cast<UINT>(depth);
00818                 desc.MipLevels = static_cast<UINT>(mipCount);
00819                 desc.Format = format;
00820                 desc.Usage = D3D11_USAGE_DEFAULT;
00821                 desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
00822                 desc.CPUAccessFlags = 0;
00823                 desc.MiscFlags = 0;
00824
00825                 ID3D11Texture3D* tex = nullptr;
00826                 hr = d3dDevice->CreateTexture3D(&desc, initData, &tex);
00827
00828                 if (SUCCEEDED(hr) && tex != 0)
00829                 {
00830                     if (textureView != 0)
00831                     {
00832                         D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
00833                         memset(&SRVDesc, 0, sizeof(SRVDesc));
00834                         SRVDesc.Format = format;
00835                         SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE3D;
00836                         SRVDesc.Texture3D.MipLevels = desc.MipLevels;
00837
00838                         hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView);
00839
00840                         if (FAILED(hr))
00841                         {
00842                             tex->Release();
00843                             return hr;
00844                         }
00845                     }
00846
00847                     if (texture != 0)
00848                     {
00849                         *texture = tex;
00850                     }
00851                     else
00852                     {
00853                         tex->Release();
00854                     }
00855                 }
00856             }
00857             break;
00858     }
00859
00860     return hr;
00861 }
00862
00863
00864 //--------------------------------------------------------------------------------------
00865 static void CreateTextureFromDDS(
00866     _In_ ID3D11Device* d3dDevice,
00867     _In_ const DDS_HEADER* header,
00868     _In_reads_bytes_(bitSize) const byte* bitData,
00869     _In_ size_t bitSize,
00870     _Out_opt_ ID3D11Resource** texture,
00871     _Out_opt_ ID3D11ShaderResourceView** textureView,
00872     _In_ size_t maxsize
00873     )
00874 {
00875     HRESULT hr = S_OK;
00876
00877     size_t width = header->width;
00878     size_t height = header->height;
00879     size_t depth = header->depth;
00880
00881     uint32 resDim = D3D11_RESOURCE_DIMENSION_UNKNOWN;
00882     size_t arraySize = 1;
00883     DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;
00884     bool isCubeMap = false;
00885
00886     size_t mipCount = header->mipMapCount;
00887     if (0 == mipCount)
00888     {
00889         mipCount = 1;
00890     }
00891
00892     if ((header->ddspf.flags & DDS_FOURCC) &&
00893         (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC))
00894     {
00895         const DDS_HEADER_DXT10* d3d10ext = reinterpret_cast<const DDS_HEADER_DXT10*>((const char*)header + sizeof(DDS_HEADER));
00896
00897         arraySize = d3d10ext->arraySize;
00898         if (arraySize == 0)
00899         {
00900             throw ref new Platform::FailureException();
00901         }
00902
00903         if (BitsPerPixel(d3d10ext->dxgiFormat) == 0)
00904         {
00905             throw ref new Platform::FailureException();
00906         }
00907
00908         format = d3d10ext->dxgiFormat;
00909
00910         switch (d3d10ext->resourceDimension)
00911         {
00912         case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
00913             // D3DX writes 1D textures with a fixed Height of 1
00914             if ((header->flags & DDS_HEIGHT) && height != 1)
00915             {
00916                 throw ref new Platform::FailureException();
00917             }
00918             height = depth = 1;
00919             break;
00920
00921         case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
00922             if (d3d10ext->miscFlag & D3D11_RESOURCE_MISC_TEXTURECUBE)
00923             {
00924                 arraySize *= 6;
00925                 isCubeMap = true;
00926             }
00927             depth = 1;
00928             break;
00929
00930         case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
00931             if (!(header->flags & DDS_HEADER_FLAGS_VOLUME))
00932             {
00933                 throw ref new Platform::FailureException();
00934             }
00935
00936             if (arraySize > 1)
00937             {
00938                 throw ref new Platform::FailureException();
00939             }
00940             break;
00941
00942         default:
00943             return throw ref new Platform::FailureException();
00944         }
00945
00946         resDim = d3d10ext->resourceDimension;
00947     }
00948     else
00949     {
00950         format = GetDXGIFormat(header->ddspf);
00951
00952         if (format == DXGI_FORMAT_UNKNOWN)
00953         {
00954             return throw ref new Platform::FailureException();
00955         }
00956
00957         if (header->flags & DDS_HEADER_FLAGS_VOLUME)
00958         {
00959             resDim = D3D11_RESOURCE_DIMENSION_TEXTURE3D;
00960         }
00961         else
00962         {
00963             if (header->caps2 & DDS_CUBEMAP)
00964             {
00965                 // We require all six faces to be defined
00966                 if ((header->caps2 & DDS_CUBEMAP_ALLFACES) != DDS_CUBEMAP_ALLFACES)
00967                 {
00968                     return throw ref new Platform::FailureException();
00969                 }
00970
00971                 arraySize = 6;
00972                 isCubeMap = true;
00973             }
00974
00975             depth = 1;
00976             resDim = D3D11_RESOURCE_DIMENSION_TEXTURE2D;
00977
00978             // Note there's no way for a legacy Direct3D 9 DDS to express a '1D' texture
00979         }
00980
00981         assert(BitsPerPixel(format) != 0);
00982     }
00983
00984     // Bound sizes (for security purposes we don't trust DDS file metadata larger than the D3D 11.x hardware requirements)
00985     if (mipCount > D3D11_REQ_MIP_LEVELS)
00986     {
00987         return throw ref new Platform::FailureException();
00988     }
00989
00990     switch (resDim)
00991     {
00992         case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
00993             if ((arraySize > D3D11_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION) ||
00994                 (width > D3D11_REQ_TEXTURE1D_U_DIMENSION))
00995             {
00996                 return throw ref new Platform::FailureException();
00997             }
00998             break;
00999
01000         case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
01001             if (isCubeMap)
01002             {
01003                 // This is the right bound because we set arraySize to (NumCubes*6) above
01004                 if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) ||
01005                     (width > D3D11_REQ_TEXTURECUBE_DIMENSION) ||
01006                     (height > D3D11_REQ_TEXTURECUBE_DIMENSION))
01007                 {
01008                     return throw ref new Platform::FailureException();
01009                 }
01010             }
01011             else if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) ||
01012                     (width > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION) ||
01013                     (height > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION))
01014             {
01015                 return throw ref new Platform::FailureException();
01016             }
01017             break;
01018
01019         case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
01020             if ((arraySize > 1) ||
01021                 (width > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) ||
01022                 (height > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) ||
01023                 (depth > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION))
01024             {
01025                 return throw ref new Platform::FailureException();
01026             }
01027             break;
01028     }
01029
01030     // Create the texture
01031     std::unique_ptr<D3D11_SUBRESOURCE_DATA> initData(new D3D11_SUBRESOURCE_DATA[mipCount * arraySize]);
01032
01033     size_t skipMip = 0;
01034     size_t twidth = 0;
01035     size_t theight = 0;
01036     size_t tdepth = 0;
01037     FillInitData(width, height, depth, mipCount, arraySize, format, maxsize, bitSize, bitData, twidth, theight, tdepth, skipMip, initData.get());
01038
01039     hr = CreateD3DResources(d3dDevice, resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize, format, isCubeMap, initData.get(), texture, textureView);
01040
01041     if (FAILED(hr) && !maxsize && (mipCount > 1))
01042     {
01043         // Retry with a maxsize determined by feature level
01044         switch (d3dDevice->GetFeatureLevel())
01045         {
01046         case D3D_FEATURE_LEVEL_9_1:
01047         case D3D_FEATURE_LEVEL_9_2:
01048             if (isCubeMap)
01049             {
01050                 maxsize = D3D_FL9_1_REQ_TEXTURECUBE_DIMENSION;
01051             }
01052             else
01053             {
01054                 maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D)
01055                     ? D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION
01056                     : D3D_FL9_1_REQ_TEXTURE2D_U_OR_V_DIMENSION;
01057             }
01058             break;
01059
01060         case D3D_FEATURE_LEVEL_9_3:
01061             maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D)
01062                 ? D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION
01063                 : D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION;
01064             break;
01065
01066         default: // D3D_FEATURE_LEVEL_10_0 & D3D_FEATURE_LEVEL_10_1
01067             maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D)
01068                 ? D3D10_REQ_TEXTURE3D_U_V_OR_W_DIMENSION
01069                 : D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION;
01070             break;
01071         }
01072
01073         FillInitData(width, height, depth, mipCount, arraySize, format, maxsize, bitSize, bitData, twidth, theight, tdepth, skipMip, initData.get());
01074
01075         hr = CreateD3DResources(d3dDevice, resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize, format, isCubeMap, initData.get(), texture, textureView);
01076     }
01077
01078     DX::ThrowIfFailed(hr);
01079 }
01080
01081 //--------------------------------------------------------------------------------------
01082 void CreateDDSTextureFromMemory(
01083     _In_ ID3D11Device* d3dDevice,
01084     _In_reads_bytes_(ddsDataSize) const byte* ddsData,
01085     _In_ size_t ddsDataSize,
01086     _Out_opt_ ID3D11Resource** texture,
01087     _Out_opt_ ID3D11ShaderResourceView** textureView,
01088     _In_ size_t maxsize
01089     )
01090 {
01091     if (!d3dDevice || !ddsData || (!texture && !textureView))
01092     {
01093         throw ref new Platform::InvalidArgumentException();
01094     }
01095
01096     // Validate DDS file in memory
01097     if (ddsDataSize < (sizeof(uint32) + sizeof(DDS_HEADER)))
01098     {
01099         throw ref new Platform::FailureException();
01100     }
01101
01102     uint32 dwMagicNumber = *(const uint32*)(ddsData);
01103     if (dwMagicNumber != DDS_MAGIC)
01104     {
01105         throw ref new Platform::FailureException();
01106     }
01107
01108     const DDS_HEADER* header = reinterpret_cast<const DDS_HEADER*>(ddsData + sizeof(uint32));
01109
01110     // Verify header to validate DDS file
01111     if (header->size != sizeof(DDS_HEADER) ||
01112         header->ddspf.size != sizeof(DDS_PIXELFORMAT))
01113     {
01114         throw ref new Platform::FailureException();
01115     }
01116
01117     // Check for DX10 extension
01118     bool bDXT10Header = false;
01119     if ((header->ddspf.flags & DDS_FOURCC) &&
01120         (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC))
01121     {
01122         // Must be long enough for both headers and magic value
01123         if (ddsDataSize < (sizeof(DDS_HEADER) + sizeof(uint32) + sizeof(DDS_HEADER_DXT10)))
01124         {
01125             throw ref new Platform::FailureException();
01126         }
01127
01128         bDXT10Header = true;
01129     }
01130
01131     ptrdiff_t offset = sizeof(uint32) + sizeof(DDS_HEADER) + (bDXT10Header ? sizeof(DDS_HEADER_DXT10) : 0);
01132
01133     CreateTextureFromDDS(d3dDevice, header, ddsData + offset, ddsDataSize - offset, texture, textureView, maxsize);
01134 }
Generated on Sat Nov 23 2024 16:08:10 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Message dialog/C++/CancelCommand.xaml.h Source File

  • Message dialog

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 "pch.h"
00019 #include "CancelCommand.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace MessageDialogSample
00025     {
00026         [Windows::Foundation::Metadata::WebHostHidden]
00027         public ref class CancelCommand sealed
00028         {
00029         public:
00030             CancelCommand();
00031
00032         protected:
00033             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00034         private:
00035             MainPage^ rootPage;
00036             void CancelCommandButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00037             void CommandInvokedHandler(Windows::UI::Popups::IUICommand^ command);
00038         };
00039     }
00040 }
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Snap/C++/common/suspensionmanager.cpp Source File

  • Snap
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:37 for Win8-Examples by doxygen 1.7.1


Win8-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]
operator()(void *p) | MemDelete | [inline]
operator()(void *p) | MemDelete | [inline]
Generated on Sat Nov 23 2024 16:09:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File picker/C++/App.xaml.h Source File

  • File picker

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML data binding/C++/Common/suspensionmanager.cpp Source File

  • XAML data binding
  • Common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File and folder thumbnail/C++/MainPage.xaml.cpp Source File

  • File and folder thumbnail

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:42 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Network status background/C++/NetworkStatusTask/pch.cpp Source File

  • Network status background
  • NetworkStatusTask

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/DirectXApp.h Source File

  • DirectX 3D shooting game

DirectXApp.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 // DirectXApp:
00011 // This class implements IFrameworkView, the main class required for Metro style apps.
00012 // It controls the main event processing loop and maintains the overall state of the game.
00013 // The DirectXApp class drives and maintains a state machine for the game.  It can be in
00014 // one of seven major states defined by the UpdateEngineState enum class.
00015 // These are:
00016 //     WaitingForResources - the game has requested the game object or the renderer object
00017 //         to load resources asynchronously.
00018 //     ResourcesLoaded - the asynchronous loading of resources has been completed.  This
00019 //         is a transient state.
00020 //     WaitingForPress - the game is waiting for the player to indicate they are ready to proceed.
00021 //         There are three possible actions from this state.  This is controlled by m_pressResult.
00022 //         The possible outcomes are:
00023 //             LoadGame - The player is ready to start a new game and has acknowledged the status
00024 //                 information provided about the previous state.
00025 //             PlayLevel - The player is ready to play the next level.  The level has already been
00026 //                 loaded so active game play will start.
00027 //             ContinueLevel - The player is ready to continue playing the current level.  Part of the
00028 //                 current level has already been played.
00029 //     Dynamics - the game is active play mode.
00030 //     Snapped - the game is currently in the snapped position on the screen.  It is not possible to
00031 //         play the game in snapped mode.
00032 //     Suspended - the game was suspended by PLM.
00033 //     Deactivated - the game has lost focus.
00034 //
00035 // DirectXApp creates and maintains references to three major objects used for the game:
00036 //     MoveLookController (m_controller) - this object handles all the game specific user input and
00037 //         aggregates touch, mouse/keyboard and Xbox controller input into a unified input control.
00038 //     Simple3DGame (m_game) - this object handles all the game specific logic and game dynamics.
00039 //     GameRenderer (m_renderer) - This object handles all the graphics rendering for the game.
00040 //
00041 // DirectXApp registers for all the necessary Metro style events to maintain and control all state transitions.
00042
00043 #include "Simple3DGame.h"
00044
00045 enum class UpdateEngineState
00046 {
00047     WaitingForResources,
00048     ResourcesLoaded,
00049     WaitingForPress,
00050     Dynamics,
00051     Snapped,
00052     Suspended,
00053     Deactivated,
00054 };
00055
00056 enum class PressResultState
00057 {
00058     LoadGame,
00059     PlayLevel,
00060     ContinueLevel,
00061 };
00062
00063 enum class GameInfoOverlayState
00064 {
00065     Loading,
00066     GameStats,
00067     GameOverExpired,
00068     GameOverCompleted,
00069     LevelStart,
00070     Pause,
00071 };
00072
00073 ref class DirectXApp : public Windows::ApplicationModel::Core::IFrameworkView
00074 {
00075 internal:
00076     DirectXApp();
00077
00078 public:
00079     // IFrameworkView Methods
00080     virtual void Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00081     virtual void SetWindow(_In_ Windows::UI::Core::CoreWindow^ window);
00082     virtual void Load(_In_ Platform::String^ entryPoint);
00083     virtual void Run();
00084     virtual void Uninitialize();
00085
00086 private:
00087     void InitializeGameState();
00088     void OnDeviceLost();
00089     void OnDeviceReset();
00090
00091     // Event Handlers
00092     void OnSuspending(
00093         _In_ Platform::Object^ sender,
00094         _In_ Windows::ApplicationModel::SuspendingEventArgs^ args
00095         );
00096
00097     void OnResuming(
00098         _In_ Platform::Object^ sender,
00099         _In_ Platform::Object^ args
00100         );
00101
00102     void UpdateViewState();
00103
00104     void OnWindowActivationChanged(
00105         _In_ Windows::UI::Core::CoreWindow^ sender,
00106         _In_ Windows::UI::Core::WindowActivatedEventArgs^ args
00107         );
00108
00109     void OnWindowSizeChanged(
00110         _In_ Windows::UI::Core::CoreWindow^ sender,
00111         _In_ Windows::UI::Core::WindowSizeChangedEventArgs^ args
00112         );
00113
00114     void OnWindowClosed(
00115         _In_ Windows::UI::Core::CoreWindow^ sender,
00116         _In_ Windows::UI::Core::CoreWindowEventArgs^ args
00117         );
00118
00119     void OnLogicalDpiChanged(
00120         _In_ Platform::Object^ sender
00121         );
00122
00123     void OnDisplayContentsInvalidated(
00124         _In_ Platform::Object^ sender
00125         );
00126
00127     void OnActivated(
00128         _In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView,
00129         _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^ args
00130         );
00131
00132     void OnVisibilityChanged(
00133         _In_ Windows::UI::Core::CoreWindow^ sender,
00134         _In_ Windows::UI::Core::VisibilityChangedEventArgs^ args
00135         );
00136
00137     void Update();
00138     void SetGameInfoOverlay(GameInfoOverlayState state);
00139     void SetAction (GameInfoOverlayCommand command);
00140     void ShowGameInfoOverlay();
00141     void HideGameInfoOverlay();
00142     void SetSnapped();
00143     void HideSnapped();
00144
00145     bool                                                m_windowClosed;
00146     bool                                                m_renderNeeded;
00147     bool                                                m_haveFocus;
00148     bool                                                m_visible;
00149
00150     MoveLookController^                                 m_controller;
00151     GameRenderer^                                       m_renderer;
00152     Simple3DGame^                                       m_game;
00153
00154     UpdateEngineState                                   m_updateState;
00155     UpdateEngineState                                   m_updateStateNext;
00156     PressResultState                                    m_pressResult;
00157     GameInfoOverlayState                                m_gameInfoOverlayState;
00158     GameInfoOverlayCommand                              m_gameInfoOverlayCommand;
00159     uint32                                              m_loadingCount;
00160 };
00161
00162 ref class DirectXAppSource : Windows::ApplicationModel::Core::IFrameworkViewSource
00163 {
00164 public:
00165     virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00166 };
00167
Generated on Sat Nov 23 2024 16:08:07 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

WICConvert Member List

This is the complete list of members for WICConvert, including all inherited members.
source | WICConvert
target | WICConvert
Generated on Sat Nov 23 2024 16:09:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML two-dimensional transforms/C++/Constants.h Source File

  • XAML two-dimensional transforms

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"XAML Transforms Sample");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/BasicReaderWriter.h Source File

  • DirectX 3D shooting game

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     Platform::String^ m_locationPath;
00019
00020 internal:
00021     BasicReaderWriter();
00022     BasicReaderWriter(
00023         _In_ Windows::Storage::StorageFolder^ folder
00024         );
00025
00026     Platform::Array<byte>^ ReadData(
00027         _In_ Platform::String^ filename
00028         );
00029
00030     concurrency::task<Platform::Array<byte>^> ReadDataAsync(
00031         _In_ Platform::String^ filename
00032         );
00033
00034     uint32 WriteData(
00035         _In_ Platform::String^ filename,
00036         _In_ const Platform::Array<byte>^ fileData
00037         );
00038
00039     concurrency::task<void> WriteDataAsync(
00040         _In_ Platform::String^ filename,
00041         _In_ const Platform::Array<byte>^ fileData
00042         );
00043 };
Generated on Sat Nov 23 2024 16:08:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Mobile broadband account provisioning/C++/UpdateUsage.xaml.cpp Source File

  • Mobile broadband account provisioning

UpdateUsage.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 // UpdateUsage.xaml.cpp
00013 // Implementation of the UpdateUsage class
00014 //
00015
00016 #include "pch.h"
00017 #include "UpdateUsage.xaml.h"
00018
00019 using namespace SDKSample::ProvisioningAgent;
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::System;
00025 using namespace Windows::Foundation;
00026 using namespace Platform;
00027 using namespace Windows::Networking;
00028 using namespace Windows::Networking::Connectivity;
00029 using namespace Windows::Networking::NetworkOperators;
00030
00031 UpdateUsage::UpdateUsage()
00032 {
00033     InitializeComponent();
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 UpdateUsage::OnNavigatedTo(NavigationEventArgs^ e)
00042 {
00043     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00044     // as NotifyUser()
00045     rootPage = MainPage::Current;
00046     util = ref new Util();
00047
00048     mediaType->SelectionChanged += ref new SelectionChangedEventHandler(this, &UpdateUsage::MediaType_SelectionChanged);
00049     mediaType->SelectedItem = mediaType_Wlan;
00050
00051 }
00052
00053 void UpdateUsage::MediaType_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00054 {
00055     if (mediaType->SelectedIndex == 0)
00056     {
00057         profileMediaType = ProfileMediaType::Wlan;
00058     }
00059     else if (mediaType->SelectedIndex == 1)
00060     {
00061         profileMediaType = ProfileMediaType::Wwan;
00062     }
00063 }
00064
00065 void UpdateUsage::UpdateUsage_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00066 {
00067     if (profileNameText->Text == L"")
00068     {
00069         rootPage->NotifyUser("Profile name cannot be empty", NotifyType::ErrorMessage);
00070         return;
00071     }
00072
00073     int usageInMegabytesValue;
00074     if (1 != swscanf_s( usageInMegabytesText->Text->Data(), L"%I32u", &usageInMegabytesValue))
00075     {
00076         rootPage->NotifyUser("Usage in megabytes should be a valid number", NotifyType::ErrorMessage);
00077         return;
00078     }
00079
00080     auto profileName = profileNameText->Text;
00081
00082     try
00083     {
00084         // Get the network account ID.
00085         auto networkAccIds = MobileBroadbandAccount::AvailableNetworkAccountIds;
00086         if (networkAccIds->Size == 0)
00087         {
00088             rootPage->NotifyUser("No network account ID found", NotifyType::ErrorMessage);
00089             return;
00090         }
00091
00092         UpdateUsageButton->IsEnabled = false;
00093
00094         // For the sake of simplicity, assume we want to use the first account.
00095         // Refer to the MobileBroadbandAccount API's for how to select a specific account ID.
00096         auto networkAccountId = networkAccIds->GetAt(0);
00097
00098         // Create provisioning agent for specified network account ID
00099         auto provisioningAgent = Windows::Networking::NetworkOperators::ProvisioningAgent::CreateFromNetworkAccountId(networkAccountId);
00100
00101         // Retrieve associated provisioned profile
00102         auto provisionedProfile = provisioningAgent->GetProvisionedProfile(profileMediaType, profileName);
00103
00104         ProfileUsage profileUsage;
00105         profileUsage.UsageInMegabytes = usageInMegabytesValue;
00106
00107         //Get Current time as FILETIME
00108         FILETIME fileTime;
00109         GetSystemTimeAsFileTime(&fileTime);
00110
00111         ULARGE_INTEGER uiCurrTime;
00112         uiCurrTime.LowPart = fileTime.dwLowDateTime;
00113         uiCurrTime.HighPart = fileTime.dwHighDateTime;
00114
00115         DateTime dtCurrentTime;
00116         dtCurrentTime.UniversalTime = uiCurrTime.QuadPart;
00117         profileUsage.LastSyncTime = dtCurrentTime;
00118
00119         // Update usage
00120         provisionedProfile->UpdateUsage(profileUsage);
00121
00122         wchar_t buf[5000];
00123         HRESULT hr = StringCchPrintf(buf, ARRAYSIZE(buf), L"Usage of %dMB has been set for the profile %s", usageInMegabytesValue, profileName->Data());
00124         if (FAILED(hr))
00125         {
00126             throw Exception::CreateException(hr);
00127         }
00128         String^ str = ref new String(buf);
00129         rootPage->NotifyUser(str, NotifyType::StatusMessage);
00130     }
00131     catch (Exception^ ex)
00132     {
00133         rootPage->NotifyUser(util->PrintExceptionCode(ex), NotifyType::ErrorMessage);
00134     }
00135
00136     UpdateUsageButton->IsEnabled = true;
00137 }
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SecondaryTiles::Common::LayoutAwarePage Member List

This is the complete list of members for SecondaryTiles::Common::LayoutAwarePage, including all inherited members.
__pad0__ | SecondaryTiles::Common::LayoutAwarePage |
_defaultViewModel | SecondaryTiles::Common::LayoutAwarePage | [private]
_layoutAwareControls | SecondaryTiles::Common::LayoutAwarePage | [private]
_windowSizeEventToken | SecondaryTiles::Common::LayoutAwarePage | [private]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SecondaryTiles::Common::LayoutAwarePage | [virtual]
GoBack(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SecondaryTiles::Common::LayoutAwarePage | [virtual]
InvalidateVisualState() | SecondaryTiles::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SecondaryTiles::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SecondaryTiles::Common::LayoutAwarePage |
WindowSizeChanged(Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SecondaryTiles::Common::LayoutAwarePage | [private]
Generated on Sat Nov 23 2024 16:09:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Store device app for camera/C++/MainPage.xaml.h Source File

  • Windows Store device app for camera

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace DeviceAppForWebcam
00024 {
00025     [Windows::Foundation::Metadata::WebHostHidden]
00026     public ref class MainPage sealed
00027     {
00028     public:
00029         MainPage();
00030
00031         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00032
00033     private:
00034         void SetDeviceAppForWebcam(Platform::String^ strFeature);
00035         void InvalidateSize();
00036         void InvalidateViewState();
00037         ~MainPage();
00038
00039         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00040         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041
00042
00043     protected:
00044         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00045         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00046
00047     internal:
00048         static MainPage^ Current;
00049
00050     };
00051 }
Generated on Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Account picture name/C++/MainPage.xaml.h Source File

  • Account picture name

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace AccountPictureName
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     [Windows::Foundation::Metadata::WebHostHidden]
00052     public ref class MainPage sealed
00053     {
00054     public:
00055         MainPage();
00056
00057         property bool AutoSizeInputSectionWhenSnapped
00058         {
00059             bool get()
00060             {
00061                 return autoSizeInputSectionWhenSnapped;
00062             }
00063
00064             void set(bool value)
00065             {
00066                 autoSizeInputSectionWhenSnapped = value;
00067             }
00068         }
00069
00070         property Windows::ApplicationModel::Activation::ProtocolActivatedEventArgs^ ProtocolEvent
00071         {
00072             Windows::ApplicationModel::Activation::ProtocolActivatedEventArgs^ get() { return _protocolEventArgs; }
00073             void set(Windows::ApplicationModel::Activation::ProtocolActivatedEventArgs^ value) { _protocolEventArgs = value; }
00074         }
00075
00076         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00077
00078         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00079         void LoadScenario(Platform::String^ scenarioName);
00080         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00081         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00082
00083
00084     private:
00085         void SetAccountPictureName(Platform::String^ strFeature);
00086         void PopulateScenarios();
00087         void InvalidateSize();
00088         void InvalidateViewState();
00089         ~MainPage();
00090
00091         Platform::Collections::Vector<Object^>^ ScenarioList;
00092         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00093         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00094         bool autoSizeInputSectionWhenSnapped;
00095
00096         Windows::ApplicationModel::Activation::ProtocolActivatedEventArgs^ _protocolEventArgs;
00097
00098     protected:
00099         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00100         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00101         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00102
00103     internal:
00104         static MainPage^ Current;
00105     };
00106 }
Generated on Sat Nov 23 2024 16:07:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

IRenderer Member List

This is the complete list of members for IRenderer, including all inherited members.
RequestRedraw()=0 | IRenderer | [pure virtual]
ViewSize()=0 | IRenderer | [pure virtual]
Generated on Sat Nov 23 2024 16:09:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/StereoProjection.h Source File

  • XAML DirectX 3D shooting game

StereoProjection.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 typedef struct STEREO_PARAMETERS
00011 {
00012     float viewerDistanceInches;
00013     float displaySizeInches;
00014     float pixelResolutionWidth;
00015     float pixelResolutionHeight;
00016     float stereoSeparationFactor;
00017     float stereoExaggerationFactor;
00018 } STEREO_PARAMETERS;
00019
00020 // Enumeration for stereo channels (left and right).
00021 typedef enum class STEREO_CHANNEL
00022 {
00023     LEFT = 0,
00024     RIGHT
00025 } STEREO_CHANNEL;
00026
00027 // Enumeration for stereo mode (normal or inverted).
00028 typedef enum class STEREO_MODE
00029 {
00030     NORMAL = 0,
00031     INVERTED,
00032 } STEREO_MODE;
00033
00034 void StereoCreateDefaultParameters(_Out_ STEREO_PARAMETERS* pStereoParameters);
00035
00036 DirectX::XMMATRIX MatrixStereoProjectionFovLH(
00037     _In_opt_ const STEREO_PARAMETERS* stereoParameters,
00038     STEREO_CHANNEL channel,
00039     float fovAngleY,
00040     float aspectHByW,
00041     float nearZ,
00042     float farZ,
00043     STEREO_MODE stereoMode
00044     );
00045
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::LightSensorCPP::sealed Member List

This is the complete list of members for SDKSample::LightSensorCPP::sealed, including all inherited members.
desiredReportInterval | SDKSample::LightSensorCPP::sealed | [private]
dispatcher | SDKSample::LightSensorCPP::sealed | [private]
dispatcherTimer | SDKSample::LightSensorCPP::sealed | [private]
DisplayCurrentReading(Platform::Object^sender, Platform::Object^e) | SDKSample::LightSensorCPP::sealed | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::LightSensorCPP::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::LightSensorCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::LightSensorCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::LightSensorCPP::sealed | [protected, virtual]
ReadingChanged(Windows::Devices::Sensors::LightSensor^sender, Windows::Devices::Sensors::LightSensorReadingChangedEventArgs^e) | SDKSample::LightSensorCPP::sealed | [private]
readingToken | SDKSample::LightSensorCPP::sealed | [private]
rootPage | SDKSample::LightSensorCPP::sealed | [private]
Scenario1() | SDKSample::LightSensorCPP::sealed |
Scenario2() | SDKSample::LightSensorCPP::sealed |
ScenarioDisable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::LightSensorCPP::sealed | [private]
ScenarioDisable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::LightSensorCPP::sealed | [private]
ScenarioEnable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::LightSensorCPP::sealed | [private]
ScenarioEnable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::LightSensorCPP::sealed | [private]
sensor | SDKSample::LightSensorCPP::sealed | [private]
VisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | SDKSample::LightSensorCPP::sealed | [private]
VisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | SDKSample::LightSensorCPP::sealed | [private]
visibilityToken | SDKSample::LightSensorCPP::sealed | [private]
Generated on Sat Nov 23 2024 16:09:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Splash screen/C++/Constants.cpp Source File

  • Splash screen

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     { "Registering for dismissal notifications", "SDKSample.SplashScreen.Scenario1" },
00020     { "Extending the splash screen",             "SDKSample.SplashScreen.Scenario2" },
00021 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Transcoding media/C++/Trim.xaml.cpp Source File

  • Transcoding media

Trim.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 // Trim.xaml.cpp
00013 // Implementation of the Trim class
00014 //
00015
00016 #include "pch.h"
00017 #include "Trim.xaml.h"
00018
00019 using namespace SDKSample::Transcode;
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::Storage::Streams;
00025 using namespace Platform;
00026 using namespace Windows::Foundation;
00027 using namespace Windows::Media;
00028 using namespace Windows::Media::MediaProperties;
00029 using namespace Windows::Media::Transcoding;
00030 using namespace Windows::Storage;
00031 using namespace Windows::Storage::Pickers;
00032 using namespace Windows::Storage::Streams;
00033 using namespace concurrency;
00034
00035 static const long c_TickToSec = (1000 * 1000 * 10);
00036
00037 Trim::Trim()
00038 {
00039     InitializeComponent();
00040
00041     // Hook up UI
00042     PickFileButton->Click += ref new RoutedEventHandler(this, &Trim::PickFile);
00043     TargetFormat->SelectionChanged += ref new SelectionChangedEventHandler(this, &Trim::OnTargetFormatChanged);
00044     Transcode->Click += ref new RoutedEventHandler(this, &Trim::TranscodeTrim);
00045     Cancel->Click += ref new RoutedEventHandler(this, &Trim::TranscodeCancel);
00046     MarkInButton->Click += ref new RoutedEventHandler(this, &Trim::MarkIn);
00047     MarkOutButton->Click += ref new RoutedEventHandler(this, &Trim::MarkOut);
00048
00049     // Disable manual manipulation of trim points
00050     StartTimeText->Text = ((float)(_start.Duration) / c_TickToSec).ToString();
00051     EndTimeText->Text = ((float)(_stop.Duration) / c_TickToSec).ToString();
00052     StartTimeText->IsEnabled = false;
00053     EndTimeText->IsEnabled = false;
00054
00055
00056     // Media Controls
00057     InputPlayButton->Click += ref new RoutedEventHandler(this, &Trim::InputPlayButton_Click);
00058     InputPauseButton->Click += ref new RoutedEventHandler(this, &Trim::InputPauseButton_Click);
00059     InputStopButton->Click += ref new RoutedEventHandler(this, &Trim::InputStopButton_Click);
00060     OutputPlayButton->Click += ref new RoutedEventHandler(this, &Trim::OutputPlayButton_Click);
00061     OutputPauseButton->Click += ref new RoutedEventHandler(this, &Trim::OutputPauseButton_Click);
00062     OutputStopButton->Click += ref new RoutedEventHandler(this, &Trim::OutputStopButton_Click);
00063
00064     // File is not selected, disable all buttons but PickFileButton
00065     DisableButtons();
00066     SetPickFileButton(true);
00067     SetCancelButton(false);
00068
00069     // Initialize Objects
00070     _Transcoder = ref new MediaTranscoder();
00071     _Profile = nullptr;
00072     _InputFile = nullptr;
00073     _OutputFile = nullptr;
00074     _OutputFileName = "TranscodeSampleOutput.mp4";
00075
00076     _UseMp4 = true;
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 void Trim::OnNavigatedTo(NavigationEventArgs^ e)
00085 {
00086     // A pointer back to the main page.  This is needed if you want to call methods in Presets such
00087     // as NotifyUser()
00088     rootPage = MainPage::Current;
00089 }
00090
00091 void Trim::GetPresetProfile(ComboBox^ comboBox)
00092 {
00093     _Profile = nullptr;
00094     VideoEncodingQuality videoEncodingProfile = VideoEncodingQuality::Wvga;
00095     switch (comboBox->SelectedIndex)
00096     {
00097     case 0:
00098         videoEncodingProfile = VideoEncodingQuality::HD1080p;
00099         break;
00100     case 1:
00101         videoEncodingProfile = VideoEncodingQuality::HD720p;
00102         break;
00103     case 2:
00104         videoEncodingProfile = VideoEncodingQuality::Wvga;
00105         break;
00106     case 3:
00107         videoEncodingProfile = VideoEncodingQuality::Ntsc;
00108         break;
00109     case 4:
00110         videoEncodingProfile = VideoEncodingQuality::Pal;
00111         break;
00112     case 5:
00113         videoEncodingProfile = VideoEncodingQuality::Vga;
00114         break;
00115     case 6:
00116         videoEncodingProfile = VideoEncodingQuality::Qvga;
00117         break;
00118     }
00119
00120     if(_UseMp4)
00121     {
00122         _Profile = MediaEncodingProfile::CreateMp4(videoEncodingProfile);
00123     }
00124     else
00125     {
00126         _Profile = MediaEncodingProfile::CreateWmv(videoEncodingProfile);
00127     }
00128 }
00129
00130 void Trim::MarkIn(Object^ sender, RoutedEventArgs^ e)
00131 {
00132     _start = InputVideo->Position;
00133     StartTimeText->Text = ((float)(_start.Duration) / c_TickToSec).ToString();
00134     // Make sure end time is after start time.
00135     if (_start.Duration > _stop.Duration || (_start.Duration == _stop.Duration && _start.Duration != 0))
00136     {
00137         _stop.Duration = _start.Duration + c_TickToSec;
00138         EndTimeText->Text = ((float)(_stop.Duration) / c_TickToSec).ToString();
00139     }
00140 }
00141
00142 void Trim::MarkOut(Object^ sender, RoutedEventArgs^ e)
00143 {
00144     _stop = InputVideo->Position;
00145     EndTimeText->Text = ((float)(_stop.Duration) / c_TickToSec).ToString();
00146     // Make sure end time is after start time.
00147     if ( (_start.Duration > _stop.Duration) || (_start.Duration == _stop.Duration && _start.Duration != 0) )
00148     {
00149         if (_stop.Duration > c_TickToSec)
00150         {
00151             _start.Duration = _stop.Duration - c_TickToSec;
00152         }
00153         else
00154         {
00155             _start.Duration = 0;
00156         }
00157         StartTimeText->Text = ((float)(_start.Duration) / c_TickToSec).ToString();
00158     }
00159 }
00160
00161 void Trim::TranscodeTrim(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00162 {
00163     StopPlayers();
00164     DisableButtons();
00165     GetPresetProfile(ProfileSelect);
00166     _Transcoder->TrimStartTime = _start;
00167     _Transcoder->TrimStopTime = _stop;
00168
00169     // Clear messages
00170     StatusMessage->Text = "";
00171
00172     try
00173     {
00174                 if (_InputFile != nullptr)
00175         {
00176             auto videoLibrary = KnownFolders::VideosLibrary;
00177             create_task(videoLibrary->CreateFileAsync(_OutputFileName, CreationCollisionOption::GenerateUniqueName), _CTS.get_token()).then(
00178                 [this](StorageFile^ destinationFile)
00179             {
00180                 try
00181                 {
00182                     _OutputFile = destinationFile;
00183                     return _Transcoder->PrepareFileTranscodeAsync(_InputFile, _OutputFile, _Profile);
00184                 }
00185                 catch (Platform::Exception^ exception)
00186                 {
00187                     TranscodeError(exception->Message);
00188                 }
00189
00190                 cancel_current_task();
00191             }).then(
00192                 [this](PrepareTranscodeResult^ transcode)
00193             {
00194                 try
00195                 {
00196                     if(transcode->CanTranscode)
00197                     {
00198                         OutputMsg->Text = "";
00199                         SetCancelButton(true);
00200                         Windows::Foundation::IAsyncActionWithProgress<double>^ transcodeOp = transcode->TranscodeAsync();
00201
00202                         // Set Progress Callback
00203                         transcodeOp->Progress = ref new AsyncActionProgressHandler<double>(
00204                         [this](IAsyncActionWithProgress<double>^ asyncInfo, double percent){
00205                             TranscodeProgress(asyncInfo, percent);
00206                         }, Platform::CallbackContext::Same);
00207
00208                         return transcodeOp;
00209                     }
00210                     else
00211                     {
00212                         TranscodeFailure(transcode->FailureReason);
00213                     }
00214                 }
00215                 catch (Platform::Exception^ exception)
00216                 {
00217                     TranscodeError(exception->Message);
00218                 }
00219
00220                 cancel_current_task();
00221             }).then(
00222                 [this](task<void> transcodeTask)
00223             {
00224                 try
00225                 {
00226                     transcodeTask.get();
00227                     OutputMsg->Text = "Transcode Completed.";
00228                     OutputPath->Text = "Output (" + _OutputFile->Path + ")";
00229                     PlayFile(_OutputFile);
00230                 }
00231                 catch (task_canceled&)
00232                 {
00233                     OutputMsg->Foreground = ref new Windows::UI::Xaml::Media::SolidColorBrush(Windows::UI::Colors::Red);
00234                     OutputMsg->Text = "Transcode Cancelled.";
00235                 }
00236                 catch(Exception^ exception)
00237                 {
00238                     TranscodeError(exception->Message);
00239                 }
00240
00241                 EnableButtons();
00242                 SetCancelButton(false);
00243             });
00244         }
00245     }
00246     catch (Platform::Exception^ exception)
00247     {
00248         TranscodeError(exception->Message);
00249     }
00250 }
00251
00252 void Trim::TranscodeCancel(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00253 {
00254     try
00255     {
00256         _CTS.cancel();
00257         _CTS = cancellation_token_source();
00258
00259         if(_OutputFile != nullptr)
00260         {
00261             create_task(_OutputFile->DeleteAsync()).then(
00262                 [this](task<void> deleteTask)
00263             {
00264                 try
00265                 {
00266                     deleteTask.get();
00267                 }
00268                 catch (Platform::Exception^ exception)
00269                 {
00270                     TranscodeError(exception->Message);
00271                 }
00272             });
00273         }
00274     }
00275     catch (Platform::Exception^ exception)
00276     {
00277         TranscodeError(exception->Message);
00278     }
00279 }
00280
00281 void Trim::TranscodeProgress(IAsyncActionWithProgress<double>^ asyncInfo, double percent)
00282 {
00283     OutputMsg->Foreground = ref new Windows::UI::Xaml::Media::SolidColorBrush(Windows::UI::Colors::Green);
00284     OutputMsg->Text = "Progress:  " + ((int)percent).ToString() + "%";
00285 }
00286
00287 void Trim::TranscodeError(Platform::String^ error)
00288 {
00289     StatusMessage->Foreground = ref new Windows::UI::Xaml::Media::SolidColorBrush(Windows::UI::Colors::Red);
00290     StatusMessage->Text = error;
00291     EnableButtons();
00292     SetCancelButton(false);
00293 }
00294
00295 void Trim::TranscodeFailure(TranscodeFailureReason reason)
00296 {
00297     try
00298     {
00299         if(_OutputFile != nullptr)
00300         {
00301             create_task(_OutputFile->DeleteAsync()).then(
00302                 [this](task<void> deleteTask)
00303             {
00304                 try
00305                 {
00306                     deleteTask.get();
00307                 }
00308                 catch (Platform::Exception^ exception)
00309                 {
00310                     TranscodeError(exception->Message);
00311                 }
00312             });
00313         }
00314     }
00315     catch(Platform::Exception^ exception)
00316     {
00317         TranscodeError(exception->Message);
00318     }
00319
00320     switch (reason)
00321     {
00322     case TranscodeFailureReason::CodecNotFound:
00323         TranscodeError("Codec not found.");
00324         break;
00325     case TranscodeFailureReason::InvalidProfile:
00326         TranscodeError("Invalid profile.");
00327         break;
00328     default:
00329         TranscodeError("Unknown failure.");
00330     }
00331 }
00332
00333 void Trim::SetCancelButton(bool isEnabled)
00334 {
00335     Cancel->IsEnabled = isEnabled;
00336 }
00337
00338 void Trim::EnableButtons()
00339 {
00340     PickFileButton->IsEnabled = true;
00341     TargetFormat->IsEnabled = true;
00342     ProfileSelect->IsEnabled = true;
00343     Transcode->IsEnabled = true;
00344 }
00345
00346 void Trim::DisableButtons()
00347 {
00348     ProfileSelect->IsEnabled = false;
00349     Transcode->IsEnabled = false;
00350     PickFileButton->IsEnabled = false;
00351     TargetFormat->IsEnabled = false;
00352 }
00353
00354 void Trim::PickFile(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00355 {
00356     try
00357     {
00358     Windows::UI::ViewManagement::ApplicationViewState currentState = Windows::UI::ViewManagement::ApplicationView::Value;
00359     if(currentState == Windows::UI::ViewManagement::ApplicationViewState::Snapped && !Windows::UI::ViewManagement::ApplicationView::TryUnsnap())
00360     {
00361       TranscodeError("Cannot pick files while application is in snapped view");
00362     }
00363     else
00364     {
00365       FileOpenPicker^ picker = ref new FileOpenPicker();
00366       picker->SuggestedStartLocation = PickerLocationId::VideosLibrary;
00367       picker->FileTypeFilter->Append(".wmv");
00368       picker->FileTypeFilter->Append(".mp4");
00369
00370       create_task(picker->PickSingleFileAsync()).then(
00371         [this](StorageFile^ inputFile)
00372       {
00373         try
00374         {
00375           _InputFile = inputFile;
00376
00377           if(_InputFile != nullptr)
00378           {
00379             return inputFile->OpenAsync(FileAccessMode::Read);
00380           }
00381         }
00382         catch (Platform::Exception^ exception)
00383         {
00384           TranscodeError(exception->Message);
00385         }
00386
00387         cancel_current_task();
00388       }).then(
00389         [this](IRandomAccessStream^ inputStream)
00390       {
00391         try
00392         {
00393           InputVideo->SetSource(inputStream, _InputFile->ContentType);;
00394           InputVideo->Play();
00395
00396           //Enable buttons
00397           EnableButtons();
00398         }
00399         catch (Platform::Exception^ exception)
00400         {
00401           TranscodeError(exception->Message);
00402         }
00403       });
00404     }
00405     }
00406     catch(Exception^ exception)
00407     {
00408         TranscodeError(exception->Message);
00409     }
00410 }
00411
00412 void Trim::OnTargetFormatChanged(Object^ sender, SelectionChangedEventArgs^ e)
00413 {
00414     if (TargetFormat->SelectedIndex > 0)
00415     {
00416         _OutputFileName = "TranscodeSampleOutput.wmv";
00417         _UseMp4 = false;
00418     }
00419     else
00420     {
00421         _OutputFileName = "TranscodeSampleOutput.mp4";
00422         _UseMp4 = true;
00423     }
00424 }
00425
00426 void Trim::InputPlayButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00427 {
00428     if (InputVideo->DefaultPlaybackRate == 0)
00429     {
00430         InputVideo->DefaultPlaybackRate = 1.0;
00431         InputVideo->PlaybackRate = 1.0;
00432     }
00433
00434     InputVideo->Play();
00435 }
00436
00437 void Trim::InputStopButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00438 {
00439     InputVideo->Stop();
00440 }
00441
00442 void Trim::InputPauseButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00443 {
00444     InputVideo->Pause();
00445 }
00446
00447 void Trim::OutputPlayButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00448 {
00449     if (OutputVideo->DefaultPlaybackRate == 0)
00450     {
00451         OutputVideo->DefaultPlaybackRate = 1.0;
00452         OutputVideo->PlaybackRate = 1.0;
00453     }
00454
00455     OutputVideo->Play();
00456 }
00457
00458 void Trim::OutputStopButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00459 {
00460     OutputVideo->Stop();
00461 }
00462
00463 void Trim::OutputPauseButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00464 {
00465     OutputVideo->Pause();
00466 }
00467
00468 void Trim::SetPickFileButton(bool isEnabled)
00469 {
00470     PickFileButton->IsEnabled = isEnabled;
00471 }
00472
00473
00474 void Trim::StopPlayers()
00475 {
00476     if(InputVideo->CurrentState != Media::MediaElementState::Paused)
00477     {
00478         InputVideo->Pause();
00479     }
00480     if(OutputVideo->CurrentState != Media::MediaElementState::Paused)
00481     {
00482         OutputVideo->Pause();
00483     }
00484 }
00485
00486 void Trim::PlayFile(Windows::Storage::StorageFile^ MediaFile)
00487 {
00488     try
00489     {
00490         create_task(MediaFile->OpenAsync(FileAccessMode::Read)).then(
00491             [&, this, MediaFile](IRandomAccessStream^ outputStream)
00492         {
00493             try
00494             {
00495                 OutputVideo->SetSource(outputStream, MediaFile->ContentType);
00496                 OutputVideo->Play();
00497             }
00498             catch (Platform::Exception^ exception)
00499             {
00500                 TranscodeError(exception->Message);
00501             }
00502         });
00503     }
00504     catch (Exception^ exception)
00505     {
00506         TranscodeError(exception->Message);
00507     }
00508 }
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Date and time formatting/C++/common/suspensionmanager.cpp Source File

  • Date and time formatting
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:36 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SimpleCommunication::Common::CaptureDevice Member List

This is the complete list of members for SimpleCommunication::Common::CaptureDevice, including all inherited members.
CaptureDevice() | SimpleCommunication::Common::CaptureDevice | [inline]
CaptureFailed | SimpleCommunication::Common::CaptureDevice |
CaptureSource | SimpleCommunication::Common::CaptureDevice |
CheckForRecordingDeviceAsync() | SimpleCommunication::Common::CaptureDevice | [inline, static]
CleanUpAsync() | SimpleCommunication::Common::CaptureDevice | [inline]
CleanupSink() | SimpleCommunication::Common::CaptureDevice | [inline, private]
DoCleanup() | SimpleCommunication::Common::CaptureDevice | [inline, private]
forwardEvents | SimpleCommunication::Common::CaptureDevice | [private]
IncomingConnectionArrived | SimpleCommunication::Common::CaptureDevice |
InitializeAsync() | SimpleCommunication::Common::CaptureDevice | [inline]
mediaCapture | SimpleCommunication::Common::CaptureDevice | [private]
mediaCapture_Failed(MediaCapture sender, MediaCaptureFailedEventArgs errorEventArgs) | SimpleCommunication::Common::CaptureDevice | [inline, private]
mediaSink | SimpleCommunication::Common::CaptureDevice | [private]
mediaSink_IncomingConnectionEvent(StspMediaSink sender, IncomingConnectionEventArgs args) | SimpleCommunication::Common::CaptureDevice | [inline, private]
recordingStarted | SimpleCommunication::Common::CaptureDevice | [private]
SelectPreferredCameraStreamSettingAsync(MediaStreamType mediaStreamType, Func< IMediaEncodingProperties, bool > filterSettings) | SimpleCommunication::Common::CaptureDevice | [inline]
StartRecordingAsync(MediaEncodingProfile encodingProfile) | SimpleCommunication::Common::CaptureDevice | [inline]
StopRecordingAsync() | SimpleCommunication::Common::CaptureDevice | [inline]
Generated on Sat Nov 23 2024 16:09:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XInput game controller/C++/SampleOverlay.h Source File

  • XInput game controller

SampleOverlay.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 "DirectXSample.h"
00011
00012 // This class is responsible for initializing and rendering the title overlay visible
00013 // at the top of the DirectX SDK samples.
00014 ref class SampleOverlay
00015 {
00016 internal:
00017     SampleOverlay();
00018
00019     void Initialize(
00020         _In_ ID2D1Device*         d2dDevice,
00021         _In_ ID2D1DeviceContext*  d2dContext,
00022         _In_ IWICImagingFactory*  wicFactory,
00023         _In_ IDWriteFactory*      dwriteFactory,
00024         _In_ Platform::String^    caption
00025         );
00026
00027     void ResetDirectXResources();
00028
00029     void UpdateForWindowSizeChange();
00030
00031     void Render();
00032
00033     float GetTitleHeightInDips();
00034
00035 private:
00036
00037     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00038     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00039     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00040     Microsoft::WRL::ComPtr<IDWriteFactory>          m_dwriteFactory;
00041     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_whiteBrush;
00042     Microsoft::WRL::ComPtr<ID2D1DrawingStateBlock>  m_stateBlock;
00043
00044     Microsoft::WRL::ComPtr<IWICImagingFactory>      m_wicFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Bitmap>             m_logoBitmap;
00046     Microsoft::WRL::ComPtr<IDWriteTextLayout>       m_textLayout;
00047
00048     UINT                                            m_idIncrement;
00049     bool                                            m_drawOverlay;
00050     Platform::String^                               m_sampleName;
00051     float                                           m_padding;
00052     float                                           m_textVerticalOffset;
00053     D2D1_SIZE_F                                     m_logoSize;
00054     float                                           m_overlayWidth;
00055 };
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Credential locker/C++/Constants.cpp Source File

  • Credential locker

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
00021     { "Single user, single resource", "SDKSample.PasswordVaultCPP.Scenario1" },
00022     { "Multi-user, single resource", "SDKSample.PasswordVaultCPP.Scenario2" },
00023     { "Multi-user, multi-resource", "SDKSample.PasswordVaultCPP.Scenario4" },
00024     { "Delete all credentials", "SDKSample.PasswordVaultCPP.Scenario3" }
00025 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Web authentication broker/C++/Constants.cpp Source File

  • Web authentication broker

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
00021     { "Connect to Facebook Services", "SDKSample.WebAuthentication.Scenario1" },
00022     { "Connect to Google Services", "SDKSample.WebAuthentication.Scenario2" }
00023 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Certificate enrollment/C++/MainPage.xaml.h Source File

  • Certificate enrollment

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/WideFiveImageTile.cpp Source File

  • Hilo C++
  • Hilo

WideFiveImageTile.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 #include "LocalResourceLoader.h"
00009 #include "WideFiveImageTile.h"
00010 #include "LocalResourceLoader.h"
00011
00012 using namespace Hilo;
00013 using namespace std;
00014 using namespace Platform;
00015 using namespace Windows::UI::Notifications;
00016 using namespace Windows::Data::Xml::Dom;
00017
00018 const unsigned int MaxTemplateImages = 5;
00019
00020 WideFiveImageTile::WideFiveImageTile()
00021 {
00022     m_loader = ref new LocalResourceLoader();
00023 }
00024
00025 WideFiveImageTile::WideFiveImageTile(Hilo::IResourceLoader^ loader) : m_loader(loader)
00026 {
00027 }
00028
00029 TileNotification^ WideFiveImageTile::GetTileNotification()
00030 {
00031     auto content = TileUpdateManager::GetTemplateContent(TileTemplateType::TileWideImageCollection);
00032
00033     UpdateContentWithValues(content);
00034
00035     return ref new TileNotification(content);
00036 }
00037
00038 void WideFiveImageTile::SetImageFilePaths(const vector<wstring>& fileNames)
00039 {
00040     if (fileNames.size() > MaxTemplateImages)
00041     {
00042         throw ref new FailureException(m_loader->GetString("ErrorWideTileTooBig"));
00043     }
00044
00045     m_fileNames = fileNames;
00046 }
00047
00048 void WideFiveImageTile::UpdateContentWithValues(XmlDocument^ content)
00049 {
00050     if (m_fileNames.size() == 0) return;
00051
00052     // Update wide tile template with the selected images.
00053     for(unsigned int image = 0; image < m_fileNames.size(); image++)
00054     {
00055         IXmlNode^ tileImage = content->GetElementsByTagName("image")->GetAt(image);
00056         tileImage->Attributes->GetNamedItem("src")->InnerText = ref new String(
00057             m_fileNames[image].c_str());
00058     }
00059
00060     // Update square tile template with the first image.
00061     TileTemplateType squareTileTemplate = TileTemplateType::TileSquareImage;
00062     XmlDocument^ squareTileXml = TileUpdateManager::GetTemplateContent(squareTileTemplate);
00063
00064     IXmlNode^ tileImage = squareTileXml->GetElementsByTagName("image")->First()->Current;
00065     tileImage->Attributes->GetNamedItem("src")->InnerText = ref new String(
00066         m_fileNames[0].c_str());
00067
00068     auto node = content->ImportNode(squareTileXml->GetElementsByTagName("binding")->First()->Current, true);
00069     content->GetElementsByTagName("visual")->First()->Current->AppendChild(node);
00070 }
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

BasicSound Member List

This is the complete list of members for BasicSound, including all inherited members.
__pad0__ | BasicSound |
CreateDeviceIndependentResources() override | BasicSound | [virtual]
CreateDeviceResources() override | BasicSound | [virtual]
CreateWindowSizeDependentResources() override | BasicSound | [virtual]
m_dataTextFormat | BasicSound | [private]
m_greenBrush | BasicSound | [private]
m_rectangleHeight | BasicSound | [private]
m_rectangleWidth | BasicSound | [private]
m_sampleOverlay | BasicSound | [private]
m_soundPlayer | BasicSound | [private]
m_textBrush | BasicSound | [private]
m_whiteBrush | BasicSound | [private]
OnPointerPressed(_In_ Windows::UI::Input::PointerPoint^p) | BasicSound |
OnResuming() | BasicSound |
OnSuspending() | BasicSound |
Render() override | BasicSound | [virtual]
~BasicSound() | BasicSound | [private]
Generated on Sat Nov 23 2024 16:09:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Globalization preferences/C++/MainPage.xaml.h Source File

  • Globalization preferences

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:46 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Language font mapping/C++/ScenarioOutput1.xaml.cpp Source File

  • Language font mapping

ScenarioOutput1.xaml.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 //
00009 // Scenario1Output.xaml.cpp
00010 // Implementation of the Scenario1Output class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioOutput1.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace LanguageFontCPP;
00018
00019 using namespace Platform;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Graphics::Display;
00023 using namespace Windows::UI::ViewManagement;
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 ScenarioOutput1::ScenarioOutput1()
00033 {
00034     InitializeComponent();
00035 }
00036
00037 ScenarioOutput1::~ScenarioOutput1()
00038 {
00039 }
00040
00041 #pragma region Template-Related Code - Do not remove
00042 void ScenarioOutput1::OnNavigatedTo(NavigationEventArgs^ e)
00043 {
00044     // Get a pointer to our main page.
00045     rootPage = dynamic_cast<MainPage^>(e->Parameter);
00046
00047     // We want to be notified with the OutputFrame is loaded so we can get to the content.
00048     _frameLoadedToken = rootPage->InputFrameLoaded += ref new Windows::Foundation::EventHandler<Platform::Object^>(this, &ScenarioOutput1::rootPage_InputFrameLoaded);
00049 }
00050
00051 void ScenarioOutput1::OnNavigatedFrom(NavigationEventArgs^ e)
00052 {
00053     rootPage->InputFrameLoaded -= _frameLoadedToken;
00054 }
00055
00056 #pragma endregion
00057
00058 #pragma region Use this code if you need access to elements in the input frame - otherwise delete
00059 void ScenarioOutput1::rootPage_InputFrameLoaded(Object^ sender, Object^ e)
00060 {
00061     // Get a pointer to the content within the OutputFrame.
00062     Page^ inputFrame = dynamic_cast<Page^>(rootPage->InputFrame->Content);
00063
00064     // Go find the elements that we need for this scenario
00065     // ex: flipView1 = dynamic_cast<FlipView^>(inputFrame->FindName("FlipView1"));
00066 }
00067
00068 #pragma endregion
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Custom driver access/C#,C++/app_cs/Scenario4_DeviceAsync.xaml.cs Source File

  • Custom driver access
  • C#,C++
  • app_cs

Scenario4_DeviceAsync.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 CustomDeviceAccess
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 DeviceAsync : SDKTemplate.Common.LayoutAwarePage
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 DeviceAsync()
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         private void deviceAsyncSet_Click_1(object sender, RoutedEventArgs e)
00043         {
00044             if (DeviceList.Current.Fx2Device == null)
00045             {
00046                 rootPage.NotifyUser("Fx2 device not connected or accessible", NotifyType.ErrorMessage);
00047                 return;
00048             }
00049
00050             // Get the selector element
00051             var val = barGraphInput.SelectedIndex;
00052             bool[] barGraphArray = new bool[8];
00053
00054             for (var i = 0; i < barGraphArray.Length; i += 1)
00055             {
00056                 barGraphArray[i] = i < val;
00057             }
00058
00059             try
00060             {
00061                 DeviceList.Current.Fx2Device.SetBarGraphDisplay(barGraphArray);
00062             }
00063             catch (Exception exception)
00064             {
00065                 rootPage.NotifyUser(exception.ToString(), NotifyType.ErrorMessage);
00066                 return;
00067             }
00068
00069             ClearBarGraphTable();
00070             rootPage.NotifyUser("Bar Graph Set to " + val, NotifyType.StatusMessage);
00071         }
00072
00073
00074         private async void deviceAsyncGet_Click_1(object sender, RoutedEventArgs e)
00075         {
00076             if (DeviceList.Current.Fx2Device == null)
00077             {
00078                 rootPage.NotifyUser("Fx2 device not connected or accessible", NotifyType.ErrorMessage);
00079                 return;
00080             }
00081
00082             try
00083             {
00084                 rootPage.NotifyUser("Getting Fx2 bars", NotifyType.StatusMessage);
00085
00086                 var result = await DeviceList.Current.Fx2Device.GetBarGraphDisplayAsync();
00087                 rootPage.NotifyUser("Got bars value", NotifyType.StatusMessage);
00088                 UpdateBarGraphTable(result.BarGraphDisplay);
00089             }
00090             catch (Exception exception)
00091             {
00092                 rootPage.NotifyUser(exception.Message, NotifyType.ErrorMessage);
00093             }
00094         }
00095
00096         private void ClearBarGraphTable()
00097         {
00098             barGraphOutput.Inlines.Clear();
00099         }
00100
00101         private void UpdateBarGraphTable(bool[] barGraphArray)
00102         {
00103             var output = barGraphOutput;
00104
00105             DeviceList.CreateBooleanTable(
00106                 output.Inlines,
00107                 barGraphArray,
00108                 null,
00109                 "Bar Number",
00110                 "Bar State",
00111                 "Lit",
00112                 "Not Lit"
00113                 );
00114         }
00115
00116
00117     }
00118 }
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/MediaExtensions/Invert/InvertTransform.idl Source File

  • Media extensions
  • MediaExtensions
  • Invert

InvertTransform.idl

Go to the documentation of this file.
00001 import "Windows.Media.idl";
00002
00003 #include <sdkddkver.h>
00004
00005 namespace InvertTransform
00006 {
00007   [version(NTDDI_WIN8)]
00008   runtimeclass InvertEffect
00009     {
00010   }
00011 }
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAudio2 audio file playback/C++/RandomAccessReader.cpp Source File

  • XAudio2 audio file playback

RandomAccessReader.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 "RandomAccessReader.h"
00010
00011 //
00012 // For package
00013 //
00014 using namespace Windows::ApplicationModel;
00015
00016 RandomAccessReader::RandomAccessReader(
00017     _In_ Platform::String^ fileName
00018     )
00019 {
00020     Platform::String^ fullPath = Package::Current->InstalledLocation->Path;
00021     fullPath += "\\";
00022     fullPath += fileName;
00023
00024     HANDLE fileHandle = ::CreateFile2(
00025         fullPath->Data(),
00026         GENERIC_READ,
00027         FILE_SHARE_READ,
00028         OPEN_EXISTING,
00029         nullptr
00030         );
00031
00032     if (fileHandle == INVALID_HANDLE_VALUE)
00033     {
00034         throw ref new Platform::FailureException();
00035     }
00036
00037     m_file.Attach(fileHandle);
00038 }
00039
00040 Platform::Array<byte>^ RandomAccessReader::Read(
00041     _In_ size_t bytesToRead
00042     )
00043 {
00044     Platform::Array<byte>^ fileData = ref new Platform::Array<byte>(static_cast<uint>(bytesToRead));
00045
00046     if (!ReadFile(
00047         m_file.Get(),
00048         fileData->Data,
00049         fileData->Length,
00050         nullptr,
00051         nullptr
00052         ))
00053     {
00054         throw ref new Platform::FailureException();
00055     }
00056
00057     return fileData;
00058 }
00059
00060 uint64 RandomAccessReader::GetFileSize()
00061 {
00062     FILE_STANDARD_INFO fileStandardInfo = { 0 };
00063     BOOL result = ::GetFileInformationByHandleEx(
00064         m_file.Get(),
00065         FileStandardInfo,
00066         &fileStandardInfo,
00067         sizeof(fileStandardInfo)
00068         );
00069
00070     if ((result == 0) || (fileStandardInfo.AllocationSize.QuadPart < 0))
00071     {
00072         throw ref new Platform::FailureException();
00073     }
00074
00075     return fileStandardInfo.AllocationSize.QuadPart;
00076 }
00077
00078 uint64 RandomAccessReader::GetPosition()
00079 {
00080     LARGE_INTEGER position = { 0 };
00081     LARGE_INTEGER zero = { 0 };
00082     BOOL result = ::SetFilePointerEx(m_file.Get(), zero, &position, FILE_CURRENT);
00083     if ((result == 0) || (position.QuadPart < 0))
00084     {
00085         throw ref new Platform::FailureException();
00086     }
00087
00088     return position.QuadPart;
00089 }
00090
00091 void RandomAccessReader::SeekRelative(_In_ int64 offset)
00092 {
00093     LARGE_INTEGER position;
00094     position.QuadPart = offset;
00095     BOOL result = ::SetFilePointerEx(m_file.Get(), position, nullptr, FILE_CURRENT);
00096     if (result == 0)
00097     {
00098         throw ref new Platform::FailureException();
00099     }
00100 }
00101
00102 void RandomAccessReader::SeekAbsolute(_In_ int64 position)
00103 {
00104     if (position < 0)
00105     {
00106         throw ref new Platform::FailureException();
00107     }
00108
00109     LARGE_INTEGER pos;
00110     pos.QuadPart = position;
00111     BOOL result = ::SetFilePointerEx(m_file.Get(), pos, nullptr, FILE_BEGIN);
00112     if (result == 0)
00113     {
00114         throw ref new Platform::FailureException();
00115     }
00116 }
00117
00118
00119 void RandomAccessReader::SeekToStart()
00120 {
00121     LARGE_INTEGER zero = { 0 };
00122     BOOL result = ::SetFilePointerEx(m_file.Get(), zero, nullptr, FILE_BEGIN);
00123     if (result == 0)
00124     {
00125         throw ref new Platform::FailureException();
00126     }
00127 }
00128
00129 void RandomAccessReader::SeekToEnd()
00130 {
00131     LARGE_INTEGER zero = { 0 };
00132     BOOL result = ::SetFilePointerEx(m_file.Get(), zero, nullptr, FILE_END);
00133     if (result == 0)
00134     {
00135         throw ref new Platform::FailureException();
00136     }
00137 }
00138
00139
Generated on Sat Nov 23 2024 16:08:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Accelerometer sensor/C++/pch.h Source File

  • Accelerometer sensor

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: AtomPub/C++/Scenario3.xaml.cpp Source File

  • AtomPub

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 SDKSample::AtomPub;
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::Foundation;
00025 using namespace Concurrency;
00026 using namespace Platform;
00027
00028 Scenario3::Scenario3()
00029 {
00030     InitializeComponent();
00031
00032     // Helps iterating through feeds.
00033     this->feedIterator = ref new SyndicationItemIterator();
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::OnNavigatedTo(NavigationEventArgs^ e)
00042 {
00043     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00044     // as NotifyUser().
00045     this->rootPage = MainPage::Current;
00046
00047     CommonData::Restore(this);
00048 }
00049
00050 void Scenario3::OnNavigatingFrom(NavigatingCancelEventArgs^ e)
00051 {
00052     CommonData::Save(ServiceAddressField->Text, UserNameField->Text, PasswordField->Password);
00053 }
00054
00055 // Download a feed.
00056 void Scenario3::GetFeed_Click(Object^ sender, RoutedEventArgs^ e)
00057 {
00058     OutputField->Text = "";
00059
00060     // If we retrieve the feed via the Edit uri then we will be logged in and will be
00061     // able to modify/delete the resource.
00062
00063     // Since the value of 'ServiceAddressField' was provided by the user it is untrusted input. We'll validate it
00064     // by using TryGetUri().
00065     // Note that this app has both "Internet (Client)" and "Home and Work Networking" capabilities set, since
00066     // the user may provide URIs for servers located on the intErnet or intrAnet. If apps only communicate
00067     // with servers on the intErnet, only the "Internet (Client)" capability should be set. Similarly if an
00068     // app is only intended to communicate on the intrAnet, only the "Home and Work Networking" capability should be set.
00069     Uri^ resourceUri;
00070     if (!rootPage->TryGetUri(StringHelper::Trim(ServiceAddressField->Text) + CommonData::EditUri, &resourceUri))
00071     {
00072         return;
00073     }
00074
00075     rootPage->NotifyUser("Fetching feed...", NotifyType::StatusMessage);
00076     OutputField->Text = "Requested feed: " + resourceUri->DisplayUri + "\r\n";
00077
00078     task<SyndicationFeed^>(CommonData::GetClient()->RetrieveFeedAsync(resourceUri)).then([this] (SyndicationFeed^ feed)
00079     {
00080         this->feedIterator->AttachFeed(feed);
00081
00082         rootPage->NotifyUser("Fetching feed completed.", NotifyType::StatusMessage);
00083
00084         OutputField->Text += "Got feed\r\n";
00085         OutputField->Text += "Title: " + this->feedIterator->GetTitle() + "\r\n";
00086         OutputField->Text += "EditUri: " + this->feedIterator->GetEditUri()->DisplayUri + "\r\n";
00087
00088         TitleField->Text = this->feedIterator->GetTitle();
00089         ContentWebView->NavigateToString(this->feedIterator->GetContent());
00090     }).then([this] (task<void> t)
00091     {
00092         try
00093         {
00094             t.get();
00095         }
00096         catch (Exception^ exception)
00097         {
00098             if (!rootPage->HandleException(exception, OutputField))
00099             {
00100                 throw;
00101             }
00102         }
00103     });
00104 }
00105
00106 // Delete the current item.
00107 void Scenario3::DeleteItem_Click(Object^ sender, RoutedEventArgs^ e)
00108 {
00109     if (!this->feedIterator->HasElements())
00110     {
00111         rootPage->NotifyUser("No item currently displayed, please download a feed first.", NotifyType::ErrorMessage);
00112         return;
00113     }
00114
00115     rootPage->NotifyUser("Deleting item...", NotifyType::StatusMessage);
00116     OutputField->Text += "Item location: " + this->feedIterator->GetEditUri()->DisplayUri + "\r\n";
00117
00118     task<void>(CommonData::GetClient()->DeleteResourceItemAsync(feedIterator->GetSyndicationItem())).then([this] (task<void> t)
00119     {
00120         try
00121         {
00122             t.get();
00123
00124             rootPage->NotifyUser("Deleting item completed.", NotifyType::StatusMessage);
00125
00126             // Our feed is now out of date.  Re-fetch the feed before deleting something else.
00127             IndexField->Text = "0 of 0";
00128             TitleField->Text = "";
00129             ContentWebView->NavigateToString("<HTML></HTML>");
00130         }
00131         catch (Exception^ exception)
00132         {
00133             if (!rootPage->HandleException(exception, OutputField))
00134             {
00135                 throw;
00136             }
00137         }
00138     });
00139 }
00140
00141 void Scenario3::PreviousItem_Click(Object^ sender, RoutedEventArgs^ e)
00142 {
00143     this->feedIterator->MovePrevious();
00144     DisplayItem();
00145 }
00146
00147 void Scenario3::NextItem_Click(Object^ sender, RoutedEventArgs^ e)
00148 {
00149     this->feedIterator->MoveNext();
00150     DisplayItem();
00151 }
00152
00153 void Scenario3::UserNameField_TextChanged(Object^ sender, TextChangedEventArgs^ e)
00154 {
00155     CommonData::Save(ServiceAddressField->Text, UserNameField->Text, PasswordField->Password);
00156 }
00157
00158 void Scenario3::PasswordField_PasswordChanged(Object^ sender, RoutedEventArgs^ e)
00159 {
00160     CommonData::Save(ServiceAddressField->Text, UserNameField->Text, PasswordField->Password);
00161 }
00162
00163 void Scenario3::DisplayItem()
00164 {
00165     IndexField->Text = feedIterator->GetIndexDescription();
00166     TitleField->Text = feedIterator->GetTitle();
00167     ContentWebView->NavigateToString(feedIterator->GetContent());
00168 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D magazine app/C++/Image.h Source File

  • Direct2D magazine app

Image.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 "Resource.h"
00011 #include "ImageFile.h"
00012
00013 ref class Document;
00014 ref class Renderer;
00015
00016 //  <image> represents an image loaded from an image memory stream.
00017 //  Image is a resource and as such it cannot draw. It is also a primitive
00018 //  content and therefore cannot have children.
00019 //
00020 //  Image accepts the following additional markup attributes:
00021 //      file = "<file name>"
00022 //          Relative path file name of the image file to load
00023 //
00024 ref class Image : public Resource
00025 {
00026 internal:
00027     Image();
00028
00029     virtual bool Initialize(
00030         _In_ Document^ document,
00031         _In_ Windows::Data::Xml::Dom::XmlElement^ xmlElement
00032         ) override;
00033
00034     bool DrawBitmap(
00035         _In_ Renderer^ renderer,
00036         D2D1::Matrix3x2F const& transform,
00037         D2D1_RECT_F const& destinationBounds,
00038         D2D1_RECT_F const& bitmapBounds
00039         );
00040
00041 private:
00042     // Decoded image wrapped inside a Direct2D bitmap
00043     Microsoft::WRL::ComPtr<ID2D1Bitmap> m_bitmap;
00044
00045     // Image data file being asynchronously loaded
00046     Microsoft::WRL::ComPtr<ImageFile> m_file;
00047 };
00048
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

PointSnapper Member List

This is the complete list of members for PointSnapper, including all inherited members.
SnapCoordinate(float x) | PointSnapper | [static]
SnapGeometry(ID2D1Geometry *pGeometry, ID2D1Geometry **ppGeometry) | PointSnapper | [static]
SnapPoint(D2D1_POINT_2F pt) | PointSnapper | [static]
SnapPoint(float2 pt) | PointSnapper | [static]
Generated on Sat Nov 23 2024 16:09:19 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/HubGroupType.h Source File

  • Hilo C++
  • Hilo

HubGroupType.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
00009 namespace Hilo
00010 {
00011     public enum class HubGroupType
00012     {
00013         Pictures,
00014         Favorites
00015     };
00016 }
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/Audio.cpp Source File

  • XAML DirectX 3D shooting game

Audio.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 "Audio.h"
00010 #include "DirectXSample.h"
00011
00012 using namespace Microsoft::WRL;
00013 using namespace Windows::Foundation;
00014 using namespace Windows::UI::Core;
00015 using namespace Windows::Graphics::Display;
00016
00017 Audio::Audio():
00018     m_audioAvailable(false)
00019 {
00020 }
00021
00022 void Audio::Initialize()
00023 {
00024 }
00025
00026 void Audio::CreateDeviceIndependentResources()
00027 {
00028     UINT32 flags = 0;
00029
00030     DX::ThrowIfFailed(
00031         XAudio2Create(&m_musicEngine, flags)
00032         );
00033
00034 #if defined(_DEBUG)
00035     XAUDIO2_DEBUG_CONFIGURATION debugConfiguration = {0};
00036     debugConfiguration.BreakMask = XAUDIO2_LOG_ERRORS;
00037     debugConfiguration.TraceMask = XAUDIO2_LOG_ERRORS;
00038     m_musicEngine->SetDebugConfiguration(&debugConfiguration);
00039 #endif
00040
00041
00042     HRESULT hr = m_musicEngine->CreateMasteringVoice(&m_musicMasteringVoice);
00043     if (FAILED(hr))
00044     {
00045         // Unable to create an audio device
00046         m_audioAvailable = false;
00047         return;
00048     }
00049
00050     DX::ThrowIfFailed(
00051         XAudio2Create(&m_soundEffectEngine, flags)
00052         );
00053
00054 #if defined(_DEBUG)
00055     m_soundEffectEngine->SetDebugConfiguration(&debugConfiguration);
00056 #endif
00057
00058     DX::ThrowIfFailed(
00059         m_soundEffectEngine->CreateMasteringVoice(&m_soundEffectMasteringVoice)
00060         );
00061
00062     m_audioAvailable = true;
00063 }
00064
00065 IXAudio2* Audio::MusicEngine()
00066 {
00067     return m_musicEngine.Get();
00068 }
00069
00070 IXAudio2* Audio::SoundEffectEngine()
00071 {
00072     return m_soundEffectEngine.Get();
00073 }
00074
00075 void Audio::SuspendAudio()
00076 {
00077     if (m_audioAvailable)
00078     {
00079         m_musicEngine->StopEngine();
00080         m_soundEffectEngine->StopEngine();
00081     }
00082 }
00083
00084 void Audio::ResumeAudio()
00085 {
00086     if (m_audioAvailable)
00087     {
00088         DX::ThrowIfFailed(m_musicEngine->StartEngine());
00089         DX::ThrowIfFailed(m_soundEffectEngine->StartEngine());
00090     }
00091 }
00092
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::TileContent::TileSquareImage Member List

This is the complete list of members for NotificationsExtensions::TileContent::TileSquareImage, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
Branding | NotificationsExtensions::TileContent::TileNotificationBase |
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
NotificationsExtensions::GetContent() | NotificationsExtensions::TileContent::TileSquareBase | [inline]
NotificationsExtensions::GetContent() | NotificationsExtensions::TileContent::TileSquareBase | [inline]
NotificationsExtensions::TileContent::TileNotificationBase::GetContent() | NotificationsExtensions::NotificationBase | [pure virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Image | NotificationsExtensions::TileContent::TileSquareImage |
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeBinding(string globalLang, string globalBaseUri, TileBranding globalBranding, bool globalAddImageQuery) | NotificationsExtensions::TileContent::TileSquareBase | [inline]
SerializeBinding(string globalLang, string globalBaseUri, TileBranding globalBranding, bool globalAddImageQuery) | NotificationsExtensions::TileContent::TileSquareBase | [inline]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextFields | NotificationsExtensions::NotificationBase |
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileSquareBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileSquareBase | [inline]
TileSquareBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileSquareBase | [inline]
TileSquareImage() | NotificationsExtensions::TileContent::TileSquareImage | [inline]
TileSquareImage() | NotificationsExtensions::TileContent::TileSquareImage | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:43 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::TileContent::TileWidePeekImage03 Member List

This is the complete list of members for NotificationsExtensions::TileContent::TileWidePeekImage03, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
Branding | NotificationsExtensions::TileContent::TileNotificationBase |
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Image | NotificationsExtensions::TileContent::TileWidePeekImage03 |
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
RequireSquareContent | NotificationsExtensions::TileContent::TileWideBase |
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SquareContent | NotificationsExtensions::TileContent::TileWideBase |
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextFields | NotificationsExtensions::NotificationBase |
TextHeadingWrap | NotificationsExtensions::TileContent::TileWidePeekImage03 |
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWidePeekImage03() | NotificationsExtensions::TileContent::TileWidePeekImage03 | [inline]
TileWidePeekImage03() | NotificationsExtensions::TileContent::TileWidePeekImage03 | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:44 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DXGI offer and reclaim resources/C++/DirectXApp.cpp Source File

  • DXGI offer and reclaim resources

DirectXApp.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 "DirectXApp.h"
00010 #include "BasicTimer.h"
00011
00012 using namespace Windows::ApplicationModel;
00013 using namespace Windows::ApplicationModel::Core;
00014 using namespace Windows::ApplicationModel::Activation;
00015 using namespace Windows::UI::Core;
00016 using namespace Windows::System;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Graphics::Display;
00019
00020 DirectXApp::DirectXApp() :
00021     m_windowClosed(false),
00022     m_windowVisible(true)
00023 {
00024 }
00025
00026 void DirectXApp::Initialize(
00027     _In_ CoreApplicationView^ applicationView
00028     )
00029 {
00030     applicationView->Activated +=
00031         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &DirectXApp::OnActivated);
00032
00033     CoreApplication::Suspending +=
00034         ref new EventHandler<SuspendingEventArgs^>(this, &DirectXApp::OnSuspending);
00035
00036     CoreApplication::Resuming +=
00037         ref new EventHandler<Platform::Object^>(this, &DirectXApp::OnResuming);
00038
00039     m_renderer = ref new OfferReclaimAPI();
00040 }
00041
00042 void DirectXApp::SetWindow(
00043     _In_ CoreWindow^ window
00044     )
00045 {
00046     window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
00047
00048     window->SizeChanged +=
00049         ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &DirectXApp::OnWindowSizeChanged);
00050
00051     window->VisibilityChanged +=
00052         ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &DirectXApp::OnVisibilityChanged);
00053
00054     window->Closed +=
00055         ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &DirectXApp::OnWindowClosed);
00056
00057     DisplayProperties::LogicalDpiChanged +=
00058         ref new DisplayPropertiesEventHandler(this, &DirectXApp::OnLogicalDpiChanged);
00059
00060     m_renderer->Initialize(window, DisplayProperties::LogicalDpi);
00061 }
00062
00063 void DirectXApp::Load(
00064     _In_ Platform::String^ entryPoint
00065     )
00066 {
00067 }
00068
00069 void DirectXApp::Run()
00070 {
00071     BasicTimer^ timer = ref new BasicTimer();
00072
00073     while (!m_windowClosed)
00074     {
00075         if (m_windowVisible)
00076         {
00077             timer->Update();
00078             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
00079             m_renderer->Update(timer->Total, timer->Delta);
00080             m_renderer->Render();
00081             m_renderer->Present(); // This call is synchronized to the display frame rate.
00082         }
00083         else
00084         {
00085             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
00086         }
00087     }
00088 }
00089
00090 void DirectXApp::Uninitialize()
00091 {
00092 }
00093
00094 void DirectXApp::OnWindowSizeChanged(
00095     _In_ CoreWindow^ sender,
00096     _In_ WindowSizeChangedEventArgs^ args
00097     )
00098 {
00099     m_renderer->UpdateForWindowSizeChange();
00100 }
00101
00102 void DirectXApp::OnVisibilityChanged(
00103     _In_ CoreWindow^ sender,
00104     _In_ VisibilityChangedEventArgs^ args
00105     )
00106 {
00107     m_windowVisible = args->Visible;
00108 }
00109
00110 void DirectXApp::OnWindowClosed(
00111     _In_ CoreWindow^ sender,
00112     _In_ CoreWindowEventArgs^ args
00113     )
00114 {
00115     m_windowClosed = true;
00116 }
00117
00118 void DirectXApp::OnLogicalDpiChanged(
00119     _In_ Platform::Object^ sender
00120     )
00121 {
00122     m_renderer->SetDpi(DisplayProperties::LogicalDpi);
00123 }
00124
00125 void DirectXApp::OnActivated(
00126     _In_ CoreApplicationView^ applicationView,
00127     _In_ IActivatedEventArgs^ args
00128     )
00129 {
00130     CoreWindow::GetForCurrentThread()->Activate();
00131 }
00132
00133 void DirectXApp::OnSuspending(
00134     _In_ Platform::Object^ sender,
00135     _In_ SuspendingEventArgs^ args
00136     )
00137 {
00138     m_renderer->OnSuspending();
00139 }
00140
00141 void DirectXApp::OnResuming(
00142     _In_ Platform::Object^ sender,
00143     _In_ Platform::Object^ args
00144     )
00145 {
00146     m_renderer->OnResuming();
00147 }
00148
00149 IFrameworkView^ DirectXAppSource::CreateView()
00150 {
00151     return ref new DirectXApp();
00152 }
00153
00154 [Platform::MTAThread]
00155 int main(Platform::Array<Platform::String^>^)
00156 {
00157     auto directXAppSource = ref new DirectXAppSource();
00158     CoreApplication::Run(directXAppSource);
00159     return 0;
00160 }
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML Popup/C++/PopupInputContent.xaml.cpp Source File

  • XAML Popup

PopupInputContent.xaml.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // PopupInputContent.xaml.cpp
00003 // Implementation of the PopupInputContent class
00004 //
00005
00006 #include "pch.h"
00007 #include "PopupInputContent.xaml.h"
00008
00009 using namespace SDKSample::XAMLPopup;
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 PopupInputContent::PopupInputContent()
00023 {
00024   InitializeComponent();
00025 }
00026
00027 // Handles the Click event of the 'Save' button simulating a save and close
00028 void SDKSample::XAMLPopup::PopupInputContent::SimulateSaveClicked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00029 {
00030   // in this example we assume the parent of the UserControl is a Popup
00031   Popup^ p = dynamic_cast<Popup^>(this->Parent);
00032   p->IsOpen = false; // close the Popup
00033 }
Generated on Sat Nov 23 2024 16:08:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DXGI offer and reclaim resources/C++/BasicReaderWriter.cpp Source File

  • DXGI offer and reclaim resources

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     m_locationPath = Platform::String::Concat(m_location->Path, "\\");
00023 }
00024
00025 BasicReaderWriter::BasicReaderWriter(
00026     _In_ Windows::Storage::StorageFolder^ folder
00027     )
00028 {
00029     m_location = folder;
00030     Platform::String^ path = m_location->Path;
00031     if (path->Length() == 0)
00032     {
00033         // Applications are not permitted to access certain
00034         // folders, such as the Documents folder, using this
00035         // code path.  In such cases, the Path property for
00036         // the folder will be an empty string.
00037         throw ref new Platform::FailureException();
00038     }
00039     m_locationPath = Platform::String::Concat(path, "\\");
00040 }
00041
00042 Platform::Array<byte>^ BasicReaderWriter::ReadData(
00043     _In_ Platform::String^ filename
00044     )
00045 {
00046     CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {0};
00047     extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
00048     extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
00049     extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN;
00050     extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
00051     extendedParams.lpSecurityAttributes = nullptr;
00052     extendedParams.hTemplateFile = nullptr;
00053
00054     Wrappers::FileHandle file(
00055         CreateFile2(
00056             Platform::String::Concat(m_locationPath, filename)->Data(),
00057             GENERIC_READ,
00058             FILE_SHARE_READ,
00059             OPEN_EXISTING,
00060             &extendedParams
00061             )
00062         );
00063     if (file.Get() == INVALID_HANDLE_VALUE)
00064     {
00065         throw ref new Platform::FailureException();
00066     }
00067
00068     FILE_STANDARD_INFO fileInfo = {0};
00069     if (!GetFileInformationByHandleEx(
00070         file.Get(),
00071         FileStandardInfo,
00072         &fileInfo,
00073         sizeof(fileInfo)
00074         ))
00075     {
00076         throw ref new Platform::FailureException();
00077     }
00078
00079     if (fileInfo.EndOfFile.HighPart != 0)
00080     {
00081         throw ref new Platform::OutOfMemoryException();
00082     }
00083
00084     Platform::Array<byte>^ fileData = ref new Platform::Array<byte>(fileInfo.EndOfFile.LowPart);
00085
00086     if (!ReadFile(
00087         file.Get(),
00088         fileData->Data,
00089         fileData->Length,
00090         nullptr,
00091         nullptr
00092         ))
00093     {
00094         throw ref new Platform::FailureException();
00095     }
00096
00097     return fileData;
00098 }
00099
00100 task<Platform::Array<byte>^> BasicReaderWriter::ReadDataAsync(
00101     _In_ Platform::String^ filename
00102     )
00103 {
00104     return task<StorageFile^>(m_location->GetFileAsync(filename)).then([=](StorageFile^ file)
00105     {
00106         return FileIO::ReadBufferAsync(file);
00107     }).then([=](IBuffer^ buffer)
00108     {
00109         auto fileData = ref new Platform::Array<byte>(buffer->Length);
00110         DataReader::FromBuffer(buffer)->ReadBytes(fileData);
00111         return fileData;
00112     });
00113 }
00114
00115 uint32 BasicReaderWriter::WriteData(
00116     _In_ Platform::String^ filename,
00117     _In_ const Platform::Array<byte>^ fileData
00118     )
00119 {
00120     CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {0};
00121     extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
00122     extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
00123     extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN;
00124     extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
00125     extendedParams.lpSecurityAttributes = nullptr;
00126     extendedParams.hTemplateFile = nullptr;
00127
00128     Wrappers::FileHandle file(
00129         CreateFile2(
00130             Platform::String::Concat(m_locationPath, filename)->Data(),
00131             GENERIC_WRITE,
00132             0,
00133             CREATE_ALWAYS,
00134             &extendedParams
00135             )
00136         );
00137     if (file.Get() == INVALID_HANDLE_VALUE)
00138     {
00139         throw ref new Platform::FailureException();
00140     }
00141
00142     DWORD numBytesWritten;
00143     if (
00144         !WriteFile(
00145             file.Get(),
00146             fileData->Data,
00147             fileData->Length,
00148             &numBytesWritten,
00149             nullptr
00150             ) ||
00151         numBytesWritten != fileData->Length
00152         )
00153     {
00154         throw ref new Platform::FailureException();
00155     }
00156
00157     return numBytesWritten;
00158 }
00159
00160 task<void> BasicReaderWriter::WriteDataAsync(
00161     _In_ Platform::String^ filename,
00162     _In_ const Platform::Array<byte>^ fileData
00163     )
00164 {
00165     return task<StorageFile^>(m_location->CreateFileAsync(filename, CreationCollisionOption::ReplaceExisting)).then([=](StorageFile^ file)
00166     {
00167         FileIO::WriteBytesAsync(file, fileData);
00168     });
00169 }
Generated on Sat Nov 23 2024 16:08:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D magazine app/C++/List.cpp Source File

  • Direct2D magazine app

List.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
00010 using namespace Windows::Data::Xml::Dom;
00011
00012 List::List() :
00013     Rectangle(),
00014     m_margin(0)
00015 {
00016 }
00017
00018 bool List::Initialize(
00019     _In_ Document^ document,
00020     _In_ XmlElement^ xmlElement
00021     )
00022 {
00023     if (!Rectangle::Initialize(document, xmlElement))
00024     {
00025         return false;
00026     }
00027
00028     Platform::String^ value;
00029
00030     value = xmlElement->GetAttribute("margin");
00031
00032     if (value != nullptr)
00033     {
00034         m_margin = static_cast<float>(_wtof(value->Data()));
00035     }
00036
00037     return true;
00038 }
00039
00040 bool List::AcceptChildNode(
00041     _In_ Document^ document,
00042     _In_ IXmlNode^ childXmlNode
00043     )
00044 {
00045     if (childXmlNode->NodeType == NodeType::ElementNode)
00046     {
00047         XmlElement^ xmlElement = dynamic_cast<XmlElement^>(childXmlNode);
00048
00049         Element^ child = nullptr;
00050         Platform::String^ elementName = xmlElement->TagName;
00051
00052         if (elementName != nullptr)
00053         {
00054             if (elementName == "text-frame")
00055             {
00056                 child = Element::Create<TextFrame>(document, childXmlNode);
00057             }
00058             else if (elementName == "image-frame")
00059             {
00060                 child = Element::Create<ImageFrame>(document, childXmlNode);
00061             }
00062         }
00063
00064         if (child == nullptr)
00065         {
00066             return false;
00067         }
00068
00069         AddChild(child);
00070     }
00071
00072     return true;
00073 }
00074
00075 void List::Measure(
00076     _In_ Document^ document,
00077     D2D1_SIZE_F const& parentSize,
00078     _Out_ D2D1_RECT_F* bounds
00079     )
00080 {
00081     D2D1_SIZE_F size = m_size;
00082
00083     if (size.width <= 0 && size.height <= 0)
00084     {
00085         // When no size is specified, assume its parent size.
00086         size = parentSize;
00087     }
00088
00089     if (m_margin * 2 < size.width && m_margin * 2 < size.height)
00090     {
00091         // Compute the content area for child elements excluding list's designated margins
00092         size = D2D1::SizeF(size.width - 2 * m_margin, size.height - 2 * m_margin);
00093     }
00094     else
00095     {
00096         m_margin = 0;
00097     }
00098
00099     D2D1_RECT_F maxBounds = D2D1::RectF(0, 0, size.width, 0);
00100
00101     Element^ child = GetFirstChild();
00102
00103     while (child)
00104     {
00105         D2D1_RECT_F childBounds = {0};
00106
00107         child->Measure(document, size, &childBounds);
00108
00109         if (maxBounds.bottom - maxBounds.top + childBounds.top < 0)
00110         {
00111             maxBounds.top = childBounds.top + maxBounds.bottom;
00112         }
00113
00114         maxBounds.bottom += childBounds.bottom;
00115
00116         if (childBounds.left < maxBounds.left)
00117         {
00118             maxBounds.left = childBounds.left;
00119         }
00120
00121         if (childBounds.right > maxBounds.right)
00122         {
00123             maxBounds.right = childBounds.right;
00124         }
00125
00126         // Update the list size for the next child
00127         size = D2D1::SizeF(size.width, size.height - childBounds.bottom + childBounds.top);
00128
00129         child = child->GetNextSibling();
00130     }
00131
00132     // List final size needs to accommodate all its children.
00133     m_size = D2D1::SizeF(maxBounds.right - maxBounds.left + 2 * m_margin, maxBounds.bottom - maxBounds.top + 2 * m_margin);
00134
00135     *bounds = D2D1::RectF(
00136         m_offset.x,
00137         m_offset.y,
00138         m_offset.x + m_size.width,
00139         m_offset.y + m_size.height
00140         );
00141 }
00142
00143 bool List::Draw(
00144     _In_ Document^ document,
00145     D2D1::Matrix3x2F const& transform
00146     )
00147 {
00148     Rectangle::Draw(document, transform);
00149
00150     float offsetY = 0;
00151
00152     Element^ child = GetFirstChild();
00153
00154     while (child)
00155     {
00156         if (child->Draw(
00157             document,
00158             D2D1::Matrix3x2F::Translation(m_offset.x + m_margin, m_offset.y + m_margin + offsetY) * transform
00159             ))
00160         {
00161             return true;
00162         }
00163
00164         offsetY += child->GetSize().height;
00165
00166         child = child->GetNextSibling();
00167     }
00168
00169     return false;
00170 }
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML Popup/C++/common/LayoutAwarePage.h Source File

  • XAML Popup
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Bing Maps Trip Optimizer/C++,JavaScript/cpp/AntSystem.h Source File

  • Bing Maps Trip Optimizer
  • C++,JavaScript
  • cpp

AntSystem.h

Go to the documentation of this file.
00001 //-----------------------------------------------------------------------
00002 //
00003 //  Copyright (C) Microsoft Corporation.  All rights reserved.
00004 //
00005 //
00006 // THIS CODE AND INFORMATION ARE PROVIDED AS-IS WITHOUT WARRANTY OF ANY
00007 // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
00008 // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00009 // PARTICULAR PURPOSE.
00010 //-----------------------------------------------------------------------
00011 #pragma once
00012
00013 namespace AntSystem
00014 {
00015     // Represents the latitude and longitude of a single point on a map.
00016     struct LatLong
00017     {
00018         explicit LatLong(double latitude, double longitude)
00019             : Latitude(latitude)
00020             , Longitude(longitude)
00021         {
00022         }
00023
00024         // The coordinates of the location.
00025         double Latitude;
00026         double Longitude;
00027     };
00028
00029     // Represents a node in a graph.
00030     struct Node
00031     {
00032         explicit Node(const std::wstring& inputName)
00033             : InputName(inputName)
00034             , ResolvedLocation(0.0, 0.0)
00035         {
00036         }
00037
00038         // The name of the location as provided by the user.
00039         std::wstring InputName;
00040         // The resolved latitude and longitude of the location as provided by the
00041         // Bing Maps location service.
00042         LatLong ResolvedLocation;
00043         // The resolved name of the location as provided by the
00044         // Bing Maps location service.
00045         std::wstring ResolvedName;
00046
00047         //
00048         // Parallel arrays of string names and latitude, longitude pairs that represent
00049         // all possible resolved locations for the current input name.
00050         // For example, if the input name is "Redmond", the Names array might contain
00051         // "Redmond, WA", "Redmond, OR", "Redmond, UT", and "Redmond, Australia".
00052         // The Locations array would contain the corresponding latitude and longitude
00053         // for each location.
00054         std::vector<std::wstring> Names;
00055         std::vector<LatLong> Locations;
00056     };
00057
00058     // Represents an edge in a graph of Node objects.
00059     // An Edge object connects two nodes and holds the travel distance between
00060     // those nodes. An Edge object also holds the amount of pheromone that
00061     // exists on that edge.
00062     struct Edge
00063     {
00064         explicit Edge(std::shared_ptr<Node> pointA, std::shared_ptr<Node> pointB)
00065             : PointA(pointA)
00066             , PointB(pointB)
00067             , Pheromone(0.0)
00068             , TravelDistance(-1.0)
00069         {
00070         }
00071
00072         // The start node.
00073         std::shared_ptr<Node> PointA;
00074         // The end node.
00075         std::shared_ptr<Node> PointB;
00076         // The amount of pheromone on the edge.
00077         double Pheromone;
00078         // The distance from the start node to the end node.
00079         double TravelDistance;
00080     };
00081
00082     // Optimizes the route among the given nodes for the shortest travel distance.
00083     // This method returns indicies to the provided Node collection.
00084     std::vector<size_t> OptimizeRoute(
00085         std::vector<std::shared_ptr<Node>>& nodes,
00086         std::vector<std::shared_ptr<Edge>>& edges,
00087         double alpha,
00088         double beta,
00089         double rho,
00090         unsigned int iterations,
00091         concurrency::cancellation_token cancellationToken,
00092         std::function<void(unsigned int)>* progressCallback = nullptr,
00093         bool parallel = true);
00094 }
Generated on Sat Nov 23 2024 16:07:58 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CameraCaptureUI/C++/Constants.cpp Source File

  • CameraCaptureUI

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
00021     { "Capture a photo from webcam", "SDKSample.CameraCapture.CapturePhoto" },
00022     { "Capture a video from webcam", "SDKSample.CameraCapture.CaptureVideo" },
00023 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML Popup/C++/Scenario2.xaml.h Source File

  • XAML Popup

Scenario2.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.xaml.h
00013 // Declaration of the Scenario2 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario2.g.h"
00020 #include "MainPage.xaml.h"
00021 #include "PopupInputContent.xaml.h"
00022
00023 namespace SDKSample
00024 {
00025     namespace XAMLPopup
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::UI::Xaml::Controls::Primitives::Popup^ nonParentPopup;
00041             void DoSomething_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00042         void ShowPopupWithParentClicked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00043         void ShowPopupWithoutParentClicked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00044         void OnPopupClosed(Platform::Object^ sender, Platform::Object^ args);
00045       };
00046     }
00047 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XInput game controller/C++/SampleOverlay.cpp Source File

  • XInput game controller

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 Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::UI::ViewManagement;
00015 using namespace Windows::Graphics::Display;
00016 using namespace D2D1;
00017
00018 SampleOverlay::SampleOverlay() :
00019     m_drawOverlay(true)
00020 {
00021 }
00022
00023 void SampleOverlay::Initialize(
00024     _In_ ID2D1Device*         d2dDevice,
00025     _In_ ID2D1DeviceContext*  d2dContext,
00026     _In_ IWICImagingFactory*  wicFactory,
00027     _In_ IDWriteFactory*      dwriteFactory,
00028     _In_ Platform::String^    caption
00029     )
00030 {
00031     m_wicFactory = wicFactory;
00032     m_dwriteFactory = dwriteFactory;
00033     m_sampleName = caption;
00034     m_d2dDevice = d2dDevice;
00035     m_d2dContext = d2dContext;
00036     m_padding = 3.0f;
00037     m_textVerticalOffset = 5.0f;
00038     m_logoSize = D2D1::SizeF(0.0f, 0.0f);
00039     m_overlayWidth = 0.0f;
00040
00041     ComPtr<ID2D1Factory> factory;
00042     d2dDevice->GetFactory(&factory);
00043
00044     DX::ThrowIfFailed(
00045         factory.As(&m_d2dFactory)
00046         );
00047
00048     ResetDirectXResources();
00049 }
00050
00051 void SampleOverlay::ResetDirectXResources()
00052 {
00053     DX::ThrowIfFailed(
00054         m_d2dContext->CreateSolidColorBrush(ColorF(ColorF::White), &m_whiteBrush)
00055         );
00056
00057     ComPtr<IWICBitmapDecoder> wicBitmapDecoder;
00058     DX::ThrowIfFailed(
00059         m_wicFactory->CreateDecoderFromFilename(
00060             L"windowsbig-sdk.png",
00061             nullptr,
00062             GENERIC_READ,
00063             WICDecodeMetadataCacheOnDemand,
00064             &wicBitmapDecoder
00065             )
00066         );
00067
00068     ComPtr<IWICBitmapFrameDecode> wicBitmapFrame;
00069     DX::ThrowIfFailed(
00070         wicBitmapDecoder->GetFrame(0, &wicBitmapFrame)
00071         );
00072
00073     ComPtr<IWICFormatConverter> wicFormatConverter;
00074     DX::ThrowIfFailed(
00075         m_wicFactory->CreateFormatConverter(&wicFormatConverter)
00076         );
00077
00078     DX::ThrowIfFailed(
00079         wicFormatConverter->Initialize(
00080             wicBitmapFrame.Get(),
00081             GUID_WICPixelFormat32bppPBGRA,
00082             WICBitmapDitherTypeNone,
00083             nullptr,
00084             0.0,
00085             WICBitmapPaletteTypeCustom  // the BGRA format has no palette so this value is ignored
00086             )
00087         );
00088
00089     double dpiX = 96.0f;
00090     double dpiY = 96.0f;
00091     DX::ThrowIfFailed(
00092         wicFormatConverter->GetResolution(&dpiX, &dpiY)
00093         );
00094
00095     DX::ThrowIfFailed(
00096         m_d2dContext->CreateBitmapFromWicBitmap(
00097             wicFormatConverter.Get(),
00098             BitmapProperties(
00099                 PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00100                 static_cast<float>(dpiX),
00101                 static_cast<float>(dpiY)
00102                 ),
00103             &m_logoBitmap
00104             )
00105         );
00106
00107     m_logoSize = m_logoBitmap->GetSize();
00108
00109     ComPtr<IDWriteTextFormat> nameTextFormat;
00110     DX::ThrowIfFailed(
00111         m_dwriteFactory->CreateTextFormat(
00112             L"Segoe UI",
00113             nullptr,
00114             DWRITE_FONT_WEIGHT_LIGHT,
00115             DWRITE_FONT_STYLE_NORMAL,
00116             DWRITE_FONT_STRETCH_NORMAL,
00117             36.0f,
00118             L"en-US",
00119             &nameTextFormat
00120             )
00121         );
00122
00123     DX::ThrowIfFailed(
00124         nameTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)
00125         );
00126
00127     DX::ThrowIfFailed(
00128         nameTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)
00129         );
00130
00131     DX::ThrowIfFailed(
00132         m_dwriteFactory->CreateTextLayout(
00133             m_sampleName->Data(),
00134             m_sampleName->Length(),
00135             nameTextFormat.Get(),
00136             4096.0f,
00137             4096.0f,
00138             &m_textLayout
00139             )
00140         );
00141
00142     DWRITE_TEXT_METRICS metrics = {0};
00143     DX::ThrowIfFailed(
00144         m_textLayout->GetMetrics(&metrics)
00145         );
00146
00147     m_overlayWidth = m_padding * 3.0f + m_logoSize.width + metrics.width;
00148
00149     DX::ThrowIfFailed(
00150         m_d2dFactory->CreateDrawingStateBlock(&m_stateBlock)
00151         );
00152
00153     UpdateForWindowSizeChange();
00154 }
00155
00156 void SampleOverlay::UpdateForWindowSizeChange()
00157 {
00158     if (CoreWindow::GetForCurrentThread()->Bounds.Width < m_overlayWidth)
00159     {
00160         m_drawOverlay = false;
00161     }
00162     else
00163     {
00164         m_drawOverlay = true;
00165     }
00166 }
00167
00168 void SampleOverlay::Render()
00169 {
00170     if (m_drawOverlay)
00171     {
00172         m_d2dContext->SaveDrawingState(m_stateBlock.Get());
00173
00174         m_d2dContext->BeginDraw();
00175         m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00176         m_d2dContext->DrawBitmap(
00177             m_logoBitmap.Get(),
00178             D2D1::RectF(m_padding, 0.0f, m_logoSize.width + m_padding, m_logoSize.height)
00179             );
00180
00181         m_d2dContext->DrawTextLayout(
00182             Point2F(m_logoSize.width + 2.0f * m_padding, m_textVerticalOffset),
00183             m_textLayout.Get(),
00184             m_whiteBrush.Get()
00185             );
00186
00187         // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00188         // is lost. It will be handled during the next call to Present.
00189         HRESULT hr = m_d2dContext->EndDraw();
00190         if (hr != D2DERR_RECREATE_TARGET)
00191         {
00192             DX::ThrowIfFailed(hr);
00193         }
00194
00195         m_d2dContext->RestoreDrawingState(m_stateBlock.Get());
00196     }
00197 }
00198
00199 float SampleOverlay::GetTitleHeightInDips()
00200 {
00201     return m_logoSize.height;
00202 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D tutorial/C++/Lesson5.Components/SampleOverlay.h Source File

  • Direct3D tutorial
  • Lesson5.Components

SampleOverlay.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 "DirectXSample.h"
00011
00012 // This class is responsible for initializing and rendering the title overlay visible
00013 // at the top of the DirectX SDK samples.
00014 ref class SampleOverlay
00015 {
00016 internal:
00017     SampleOverlay();
00018
00019     void Initialize(
00020         _In_ ID2D1Device*         d2dDevice,
00021         _In_ ID2D1DeviceContext*  d2dContext,
00022         _In_ IWICImagingFactory*  wicFactory,
00023         _In_ IDWriteFactory*      dwriteFactory,
00024         _In_ Platform::String^    caption
00025         );
00026
00027     void ResetDirectXResources();
00028
00029     void UpdateForWindowSizeChange();
00030
00031     void Render();
00032
00033     float GetTitleHeightInDips();
00034
00035 private:
00036
00037     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00038     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00039     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00040     Microsoft::WRL::ComPtr<IDWriteFactory>          m_dwriteFactory;
00041     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_whiteBrush;
00042     Microsoft::WRL::ComPtr<ID2D1DrawingStateBlock>  m_stateBlock;
00043
00044     Microsoft::WRL::ComPtr<IWICImagingFactory>      m_wicFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Bitmap>             m_logoBitmap;
00046     Microsoft::WRL::ComPtr<IDWriteTextLayout>       m_textLayout;
00047
00048     UINT                                            m_idIncrement;
00049     bool                                            m_drawOverlay;
00050     Platform::String^                               m_sampleName;
00051     float                                           m_padding;
00052     float                                           m_textVerticalOffset;
00053     D2D1_SIZE_F                                     m_logoSize;
00054     float                                           m_overlayWidth;
00055 };
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Clipboard::MainPage Member List

This is the complete list of members for Clipboard::MainPage, including all inherited members.
scenariosInner Clipboard::MainPage [private, static]
Generated on Sat Nov 23 2024 16:09:36 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D magazine app/C++/App.xaml.h Source File

  • Direct2D magazine app

App.xaml.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 "App.g.h"
00011
00012 namespace Magazine
00013 {
00014     ref class App sealed
00015     {
00016     public:
00017         App();
00018         virtual void OnLaunched(
00019             _In_ Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ args
00020             ) override;
00021
00022     private:
00023         ~App();
00024         void OnSuspending(
00025             _In_ Platform::Object^ sender,
00026             _In_ Windows::ApplicationModel::SuspendingEventArgs^ args
00027             );
00028
00029         void OnResuming(
00030             _In_ Platform::Object^ sender,
00031             _In_ Platform::Object^ args
00032             );
00033     };
00034 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML FlipView control/C++/Scenario2.xaml.h Source File

  • XAML FlipView control

Scenario2.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.xaml.h
00013 // Declaration of the Scenario2 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario2.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024   namespace FlipViewCPP
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::WebHostHiddenAttribute]
00030     public ref class Scenario2 sealed
00031     {
00032     public:
00033       Scenario2();
00034
00035     protected:
00036       virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037       void Orientation_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038
00039     private:
00040       MainPage^ rootPage;
00041       bool bHorizontal;
00042
00043     };
00044   }
00045 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Element Member List

This is the complete list of members for Element, including all inherited members.
__pad0__ | Element |
AcceptChildNode(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^childXmlNode) | Element | [virtual]
AddChild(_In_ Element^element) | Element |
AddSibling(_In_ Element^element) | Element |
BindResource(_In_ Element^rootElement) | Element | [virtual]
Create(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^xmlNode) | Element | [static]
Draw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
DrawChildren(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [private]
GetFirstChild() | Element | [inline]
GetName() | Element | [inline]
GetNextSibling() | Element | [inline]
GetOpacity() | Element | [inline, virtual]
GetParent() | Element | [inline]
GetSize() | Element | [inline]
Initialize(_In_ Document^document, _In_ Windows::Data::Xml::Dom::XmlElement^xmlElement) | Element | [virtual]
m_firstChild | Element | [private]
m_name | Element | [private]
m_nextSibling | Element | [private]
m_offset | Element | [private]
m_parent | Element | [private]
m_size | Element | [private]
Measure(_In_ Document^document, D2D1_SIZE_F const &parentSize, _Out_ D2D1_RECT_F *bounds) | Element | [virtual]
ParseColor(_In_ Platform::String^value) | Element | [private]
ParseNameIdentifier(_In_ Platform::String^value) | Element | [private]
PrepareToDraw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
PrepareToDrawChildren(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [private]
ReleaseParent() | Element | [virtual]
Generated on Sat Nov 23 2024 16:09:12 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

MediaExtensionsCS::ScenarioOutput3 Member List

This is the complete list of members for MediaExtensionsCS::ScenarioOutput3, including all inherited members.
__pad0__ | Element |
AcceptChildNode(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^childXmlNode) override | Page | [virtual]
AddChild(_In_ Element^element) | Element |
AddSibling(_In_ Element^element) | Element |
BindResource(_In_ Element^rootElement) | Element | [virtual]
Create(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^xmlNode) | Element | [static]
Draw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
GetFirstChild() | Element | [inline]
GetName() | Element | [inline]
GetNextSibling() | Element | [inline]
GetOpacity() | Element | [inline, virtual]
GetParent() | Element | [inline]
GetSize() | Element | [inline]
Initialize(_In_ Document^document, _In_ Windows::Data::Xml::Dom::XmlElement^xmlElement) | Element | [virtual]
Measure(_In_ Document^document, D2D1_SIZE_F const &parentSize, _Out_ D2D1_RECT_F *bounds) | Element | [virtual]
OnNavigatedFrom(NavigationEventArgs e) | MediaExtensionsCS::ScenarioOutput3 | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | MediaExtensionsCS::ScenarioOutput3 | [inline, protected]
PrepareToDraw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
ReleaseParent() | Element | [virtual]
rootPage | MediaExtensionsCS::ScenarioOutput3 | [private]
ScenarioOutput3() | MediaExtensionsCS::ScenarioOutput3 | [inline]
Generated on Sat Nov 23 2024 16:09:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

HttpRequestStringCallback Member List

This is the complete list of members for HttpRequestStringCallback, including all inherited members.
cancellationToken | HttpRequestStringCallback | [private]
completionEvent | HttpRequestStringCallback | [private]
GetCompletionEvent() const | HttpRequestStringCallback | [inline]
GetCompletionEvent() const | HttpRequestStringCallback | [inline]
GetCompletionEvent() const | HttpRequestStringCallback | [inline]
GetCompletionEvent() const | HttpRequestStringCallback | [inline]
GetCompletionEvent() const | HttpRequestStringCallback | [inline]
GetReasonPhrase() const | HttpRequestStringCallback | [inline]
GetReasonPhrase() const | HttpRequestStringCallback | [inline]
GetReasonPhrase() const | HttpRequestStringCallback | [inline]
GetReasonPhrase() const | HttpRequestStringCallback | [inline]
GetReasonPhrase() const | HttpRequestStringCallback | [inline]
GetStatusCode() const | HttpRequestStringCallback | [inline]
GetStatusCode() const | HttpRequestStringCallback | [inline]
GetStatusCode() const | HttpRequestStringCallback | [inline]
GetStatusCode() const | HttpRequestStringCallback | [inline]
GetStatusCode() const | HttpRequestStringCallback | [inline]
HttpRequestStringCallback(IXMLHTTPRequest2 *httpRequest, cancellation_token ct=concurrency::cancellation_token::none()) | HttpRequestStringCallback | [inline]
HttpRequestStringCallback(IXMLHTTPRequest2 *httpRequest, cancellation_token ct=concurrency::cancellation_token::none()) | HttpRequestStringCallback | [inline]
HttpRequestStringCallback(IXMLHTTPRequest2 *httpRequest, cancellation_token ct=concurrency::cancellation_token::none()) | HttpRequestStringCallback | [inline]
HttpRequestStringCallback(IXMLHTTPRequest2 *httpRequest, cancellation_token ct=concurrency::cancellation_token::none()) | HttpRequestStringCallback | [inline]
HttpRequestStringCallback(IXMLHTTPRequest2 *httpRequest, cancellation_token ct=concurrency::cancellation_token::none()) | HttpRequestStringCallback | [inline]
OnDataAvailable(IXMLHTTPRequest2 *, ISequentialStream *) | HttpRequestStringCallback | [inline]
OnDataAvailable(IXMLHTTPRequest2 *, ISequentialStream *) | HttpRequestStringCallback | [inline]
OnDataAvailable(IXMLHTTPRequest2 *, ISequentialStream *) | HttpRequestStringCallback | [inline]
OnDataAvailable(IXMLHTTPRequest2 *, ISequentialStream *) | HttpRequestStringCallback | [inline]
OnDataAvailable(IXMLHTTPRequest2 *, ISequentialStream *) | HttpRequestStringCallback | [inline]
OnError(IXMLHTTPRequest2 *, HRESULT hrError) | HttpRequestStringCallback | [inline]
OnError(IXMLHTTPRequest2 *, HRESULT hrError) | HttpRequestStringCallback | [inline]
OnError(IXMLHTTPRequest2 *, HRESULT hrError) | HttpRequestStringCallback | [inline]
OnError(IXMLHTTPRequest2 *, HRESULT hrError) | HttpRequestStringCallback | [inline]
OnError(IXMLHTTPRequest2 *, HRESULT hrError) | HttpRequestStringCallback | [inline]
OnHeadersAvailable(IXMLHTTPRequest2 *, DWORD statusCode, PCWSTR reasonPhrase) | HttpRequestStringCallback | [inline]
OnHeadersAvailable(IXMLHTTPRequest2 *, DWORD statusCode, PCWSTR reasonPhrase) | HttpRequestStringCallback | [inline]
OnHeadersAvailable(IXMLHTTPRequest2 *, DWORD statusCode, PCWSTR reasonPhrase) | HttpRequestStringCallback | [inline]
OnHeadersAvailable(IXMLHTTPRequest2 *, DWORD statusCode, PCWSTR reasonPhrase) | HttpRequestStringCallback | [inline]
OnHeadersAvailable(IXMLHTTPRequest2 *, DWORD statusCode, PCWSTR reasonPhrase) | HttpRequestStringCallback | [inline]
OnRedirect(IXMLHTTPRequest2 *, PCWSTR) | HttpRequestStringCallback | [inline]
OnRedirect(IXMLHTTPRequest2 *, PCWSTR) | HttpRequestStringCallback | [inline]
OnRedirect(IXMLHTTPRequest2 *, PCWSTR) | HttpRequestStringCallback | [inline]
OnRedirect(IXMLHTTPRequest2 *, PCWSTR) | HttpRequestStringCallback | [inline]
OnRedirect(IXMLHTTPRequest2 *, PCWSTR) | HttpRequestStringCallback | [inline]
OnResponseReceived(IXMLHTTPRequest2 *, ISequentialStream *responseStream) | HttpRequestStringCallback | [inline]
OnResponseReceived(IXMLHTTPRequest2 *, ISequentialStream *responseStream) | HttpRequestStringCallback | [inline]
OnResponseReceived(IXMLHTTPRequest2 *, ISequentialStream *responseStream) | HttpRequestStringCallback | [inline]
OnResponseReceived(IXMLHTTPRequest2 *, ISequentialStream *responseStream) | HttpRequestStringCallback | [inline]
OnResponseReceived(IXMLHTTPRequest2 *, ISequentialStream *responseStream) | HttpRequestStringCallback | [inline]
ReadUtf8StringFromSequentialStream(ISequentialStream *readStream, wstring &str) | HttpRequestStringCallback | [inline]
ReadUtf8StringFromSequentialStream(ISequentialStream *readStream, wstring &str) | HttpRequestStringCallback | [inline]
ReadUtf8StringFromSequentialStream(ISequentialStream *readStream, wstring &str) | HttpRequestStringCallback | [inline]
ReadUtf8StringFromSequentialStream(ISequentialStream *readStream, wstring &str) | HttpRequestStringCallback | [inline]
ReadUtf8StringFromSequentialStream(ISequentialStream *readStream, wstring &str) | HttpRequestStringCallback | [inline]
reasonPhrase | HttpRequestStringCallback | [private]
registrationToken | HttpRequestStringCallback | [private]
request | HttpRequestStringCallback | [private]
statusCode | HttpRequestStringCallback | [private]
~HttpRequestStringCallback() | HttpRequestStringCallback | [inline, private]
~HttpRequestStringCallback() | HttpRequestStringCallback | [inline, private]
~HttpRequestStringCallback() | HttpRequestStringCallback | [inline, private]
~HttpRequestStringCallback() | HttpRequestStringCallback | [inline, private]
~HttpRequestStringCallback() | HttpRequestStringCallback | [inline, private]
Generated on Sat Nov 23 2024 16:09:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Inclinometer sensor/C++/pch.cpp Source File

  • Inclinometer sensor

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Mobile broadband account provisioning/C++/pch.cpp Source File

  • Mobile broadband account provisioning

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

BasicSprites::SpriteBatch Member List

This is the complete list of members for BasicSprites::SpriteBatch, including all inherited members.
__pad0__ | BasicSprites::SpriteBatch |
AddTexture(_In_ ID3D11Texture2D *texture) | BasicSprites::SpriteBatch |
Begin() | BasicSprites::SpriteBatch |
Draw(_In_ ID3D11Texture2D *texture, _In_ float2 position, _In_ PositionUnits positionUnits) | BasicSprites::SpriteBatch |
Draw(_In_ ID3D11Texture2D *texture, _In_ float2 position, _In_ PositionUnits positionUnits, _In_ float2 size, _In_ SizeUnits sizeUnits) | BasicSprites::SpriteBatch |
Draw(_In_ ID3D11Texture2D *texture, _In_ float2 position, _In_ PositionUnits positionUnits, _In_ float2 size, _In_ SizeUnits sizeUnits, _In_ float4 color) | BasicSprites::SpriteBatch |
Draw(_In_ ID3D11Texture2D *texture, _In_ float2 position, _In_ PositionUnits positionUnits, _In_ float2 size, _In_ SizeUnits sizeUnits, _In_ float4 color, _In_ float rotation) | BasicSprites::SpriteBatch |
Draw(_In_ ID3D11Texture2D *texture, _In_ float2 position, _In_ PositionUnits positionUnits, _In_ float2 size, _In_ SizeUnits sizeUnits, _In_ float4 color, _In_ float rotation, _In_ BlendMode blendMode) | BasicSprites::SpriteBatch |
End() | BasicSprites::SpriteBatch |
Initialize(_In_ ID3D11Device1 *d3dDevice, _In_ int capacity) | BasicSprites::SpriteBatch |
m_blendStateAdditive | BasicSprites::SpriteBatch | [private]
m_blendStateAlpha | BasicSprites::SpriteBatch | [private]
m_capacity | BasicSprites::SpriteBatch | [private]
m_currentBlendState | BasicSprites::SpriteBatch | [private]
m_currentTextureView | BasicSprites::SpriteBatch | [private]
m_d3dContext | BasicSprites::SpriteBatch | [private]
m_d3dDevice | BasicSprites::SpriteBatch | [private]
m_dpi | BasicSprites::SpriteBatch | [private]
m_geometryShader | BasicSprites::SpriteBatch | [private]
m_indexBuffer | BasicSprites::SpriteBatch | [private]
m_inputLayout | BasicSprites::SpriteBatch | [private]
m_instanceData | BasicSprites::SpriteBatch | [private]
m_instanceDataBuffer | BasicSprites::SpriteBatch | [private]
m_linearSampler | BasicSprites::SpriteBatch | [private]
m_numSpritesDrawn | BasicSprites::SpriteBatch | [private]
m_pixelShader | BasicSprites::SpriteBatch | [private]
m_renderTargetInfoCbuffer | BasicSprites::SpriteBatch | [private]
m_renderTargetSize | BasicSprites::SpriteBatch | [private]
m_spriteRuns | BasicSprites::SpriteBatch | [private]
m_spritesInRun | BasicSprites::SpriteBatch | [private]
m_technique | BasicSprites::SpriteBatch | [private]
m_textureMap | BasicSprites::SpriteBatch | [private]
m_vertexBuffer | BasicSprites::SpriteBatch | [private]
m_vertexData | BasicSprites::SpriteBatch | [private]
m_vertexShader | BasicSprites::SpriteBatch | [private]
MakeUnorm(float4 color) | BasicSprites::SpriteBatch | [private]
RemoveTexture(_In_ ID3D11Texture2D *texture) | BasicSprites::SpriteBatch |
StandardOffset(float2 size, SizeUnits sizeUnits, float2 spriteSize, float dpi) | BasicSprites::SpriteBatch | [private]
StandardOrigin(float2 position, PositionUnits positionUnits, float2 renderTargetSize, float dpi) | BasicSprites::SpriteBatch | [private]
Generated on Sat Nov 23 2024 16:09:36 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CameraCaptureUI/C++/common/suspensionmanager.cpp Source File

  • CameraCaptureUI
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: PlayToReceiver/C++/pch.cpp Source File

  • PlayToReceiver

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D 3D transform effect/C++/DirectXSample.h Source File

  • Direct2D 3D transform effect

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
00010 // This header defines helper utilities to make DirectX APIs work with exceptions.
00011 namespace DX
00012 {
00013     inline void ThrowIfFailed(HRESULT hr)
00014     {
00015         if (FAILED(hr))
00016         {
00017             // Set a breakpoint on this line to catch DX API errors.
00018             throw Platform::Exception::CreateException(hr);
00019         }
00020     }
00021 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D magazine app/C++/Page.cpp Source File

  • Direct2D magazine app

Page.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
00010 using namespace Windows::Data::Xml::Dom;
00011
00012 bool ::Page::AcceptChildNode(
00013     _In_ Document^ document,
00014     _In_ IXmlNode^ childXmlNode
00015     )
00016 {
00017     if (childXmlNode->NodeType == NodeType::ElementNode)
00018     {
00019         XmlElement^ xmlElement = dynamic_cast<XmlElement^>(childXmlNode);
00020
00021         Element^ child = nullptr;
00022         Platform::String^ elementName = xmlElement->TagName;
00023
00024         if (elementName != nullptr)
00025         {
00026             if (elementName == "layer")
00027             {
00028                 child = Element::Create<Layer>(document, childXmlNode);
00029             }
00030         }
00031
00032         if (child == nullptr)
00033         {
00034             return false;
00035         }
00036
00037         AddChild(child);
00038     }
00039
00040     return true;
00041 }
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/GameRenderer.cpp Source File

  • XAML DirectX 3D shooting game

GameRenderer.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 "DirectXSample.h"
00010 #include "GameRenderer.h"
00011 #include "ConstantBuffers.h"
00012 #include "TargetTexture.h"
00013 #include "BasicLoader.h"
00014 #include "CylinderMesh.h"
00015 #include "FaceMesh.h"
00016 #include "SphereMesh.h"
00017 #include "WorldMesh.h"
00018 #include "Face.h"
00019 #include "Sphere.h"
00020 #include "Cylinder.h"
00021 #include "windows.ui.xaml.media.dxinterop.h"
00022
00023 using namespace concurrency;
00024 using namespace DirectX;
00025 using namespace Microsoft::WRL;
00026 using namespace Windows::UI::Core;
00027 using namespace Windows::UI::Xaml::Controls;
00028
00029 //----------------------------------------------------------------------
00030
00031 GameRenderer::GameRenderer() :
00032     m_initialized(false),
00033     m_gameResourcesLoaded(false),
00034     m_levelResourcesLoaded(false)
00035 {
00036 }
00037
00038 //----------------------------------------------------------------------
00039
00040 void GameRenderer::Initialize(
00041     _In_ CoreWindow^ window,
00042     _In_ SwapChainBackgroundPanel^ swapChainPanel,
00043     float dpi
00044     )
00045 {
00046     m_gameHud = ref new GameHud(
00047         "Windows 8 Samples",
00048         "DirectX/XAML first-person game sample",
00049         "License state unknown"
00050         );
00051
00052     DirectXBase::Initialize(window, swapChainPanel, dpi);
00053 }
00054
00055 //----------------------------------------------------------------------
00056
00057 void GameRenderer::HandleDeviceLost()
00058 {
00059     // On device lost all the device resources are invalid.
00060     // Set the state of the renderer to not have a pointer to the
00061     // Simple3DGame object.  It will be reset as a part of the
00062     // game devices resources being recreated.
00063     m_game = nullptr;
00064
00065     DirectXBase::HandleDeviceLost();
00066 }
00067
00068 //----------------------------------------------------------------------
00069
00070 void GameRenderer::CreateDeviceIndependentResources()
00071 {
00072     DirectXBase::CreateDeviceIndependentResources();
00073     m_gameHud->CreateDeviceIndependentResources(m_dwriteFactory.Get(), m_wicFactory.Get());
00074 }
00075
00076 //----------------------------------------------------------------------
00077
00078 void GameRenderer::CreateDeviceResources()
00079 {
00080     m_gameResourcesLoaded = false;
00081     m_levelResourcesLoaded = false;
00082
00083     DirectXBase::CreateDeviceResources();
00084
00085     m_gameHud->CreateDeviceResources(m_d2dContext.Get());
00086 }
00087
00088 //----------------------------------------------------------------------
00089
00090 void GameRenderer::UpdateForWindowSizeChange()
00091 {
00092     DirectXBase::UpdateForWindowSizeChange();
00093
00094     m_gameHud->UpdateForWindowSizeChange(m_windowBounds);
00095
00096     if (m_game != nullptr)
00097     {
00098         // Update the Projection Matrix and the associated Constant Buffer.
00099         m_game->GameCamera()->SetProjParams(
00100             XM_PI / 2, m_renderTargetSize.Width / m_renderTargetSize.Height,
00101             0.01f,
00102             100.0f
00103             );
00104         ConstantBufferChangeOnResize changesOnResize;
00105         XMStoreFloat4x4(
00106             &changesOnResize.projection,
00107             XMMatrixMultiply(
00108                 XMMatrixTranspose(m_game->GameCamera()->Projection()),
00109                 XMMatrixTranspose(XMLoadFloat4x4(&m_rotationTransform3D))
00110                 )
00111             );
00112
00113         m_d3dContext->UpdateSubresource(
00114             m_constantBufferChangeOnResize.Get(),
00115             0,
00116             nullptr,
00117             &changesOnResize,
00118             0,
00119             0
00120             );
00121     }
00122 }
00123
00124 //----------------------------------------------------------------------
00125
00126 task<void> GameRenderer::CreateGameDeviceResourcesAsync(_In_ Simple3DGame^ game)
00127 {
00128     // Create the device dependent game resources.
00129     // Only the m_d3dDevice is used in this method.  It is expected
00130     // to not run on the same thread as the GameRenderer was created.
00131     // Create methods on the m_d3dDevice are free-threaded and are safe while any methods
00132     // in the m_d3dContext should only be used on a single thread and handled
00133     // in the FinalizeCreateGameDeviceResources method.
00134     m_game = game;
00135
00136     D3D11_BUFFER_DESC bd;
00137     ZeroMemory(&bd, sizeof(bd));
00138
00139     // Create the constant buffers.
00140     bd.Usage = D3D11_USAGE_DEFAULT;
00141     bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
00142     bd.CPUAccessFlags = 0;
00143     bd.ByteWidth = (sizeof(ConstantBufferNeverChanges) + 15) / 16 * 16;
00144     DX::ThrowIfFailed(
00145         m_d3dDevice->CreateBuffer(&bd, nullptr, &m_constantBufferNeverChanges)
00146         );
00147
00148     bd.ByteWidth = (sizeof(ConstantBufferChangeOnResize) + 15) / 16 * 16;
00149     DX::ThrowIfFailed(
00150         m_d3dDevice->CreateBuffer(&bd, nullptr, &m_constantBufferChangeOnResize)
00151         );
00152
00153     bd.ByteWidth = (sizeof(ConstantBufferChangesEveryFrame) + 15) / 16 * 16;
00154     DX::ThrowIfFailed(
00155         m_d3dDevice->CreateBuffer(&bd, nullptr, &m_constantBufferChangesEveryFrame)
00156         );
00157
00158     bd.ByteWidth = (sizeof(ConstantBufferChangesEveryPrim) + 15) / 16 * 16;
00159     DX::ThrowIfFailed(
00160         m_d3dDevice->CreateBuffer(&bd, nullptr, &m_constantBufferChangesEveryPrim)
00161         );
00162
00163     D3D11_SAMPLER_DESC sampDesc;
00164     ZeroMemory(&sampDesc, sizeof(sampDesc));
00165
00166     sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
00167     sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
00168     sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
00169     sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
00170     sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
00171     sampDesc.MinLOD = 0;
00172     sampDesc.MaxLOD = FLT_MAX;
00173     DX::ThrowIfFailed(
00174         m_d3dDevice->CreateSamplerState(&sampDesc, &m_samplerLinear)
00175         );
00176
00177     // Start the async tasks to load the shaders and textures.
00178     BasicLoader^ loader = ref new BasicLoader(m_d3dDevice.Get());
00179
00180     std::vector<task<void>> tasks;
00181
00182     uint32 numElements = ARRAYSIZE(PNTVertexLayout);
00183     tasks.push_back(loader->LoadShaderAsync("VertexShader.cso", PNTVertexLayout, numElements, &m_vertexShader, &m_vertexLayout));
00184     tasks.push_back(loader->LoadShaderAsync("VertexShaderFlat.cso", nullptr, numElements, &m_vertexShaderFlat, nullptr));
00185     tasks.push_back(loader->LoadShaderAsync("PixelShader.cso", &m_pixelShader));
00186     tasks.push_back(loader->LoadShaderAsync("PixelShaderFlat.cso", &m_pixelShaderFlat));
00187
00188     // Make sure the previous versions if any of the textures are released.
00189     m_sphereTexture = nullptr;
00190     m_cylinderTexture = nullptr;
00191     for (uint32 i = 0; i < GameConstants::MaxBackgroundTextures; i++)
00192     {
00193         m_ceilingTexture[i] = nullptr;
00194         m_floorTexture[i] = nullptr;
00195         m_wallsTexture[i] = nullptr;
00196     }
00197
00198     // Load Game specific textures.
00199     tasks.push_back(loader->LoadTextureAsync("seafloor.dds", nullptr, &m_sphereTexture));
00200     tasks.push_back(loader->LoadTextureAsync("metal_texture.dds", nullptr, &m_cylinderTexture));
00201     tasks.push_back(loader->LoadTextureAsync("cellceiling.dds", nullptr, &m_ceilingTexture[0]));
00202     tasks.push_back(loader->LoadTextureAsync("cellfloor.dds", nullptr, &m_floorTexture[0]));
00203     tasks.push_back(loader->LoadTextureAsync("cellwall.dds", nullptr, &m_wallsTexture[0]));
00204     tasks.push_back(loader->LoadTextureAsync("nightceiling.dds", nullptr, &m_ceilingTexture[1]));
00205     tasks.push_back(loader->LoadTextureAsync("nightfloor.dds", nullptr, &m_floorTexture[1]));
00206     tasks.push_back(loader->LoadTextureAsync("nightwall.dds", nullptr, &m_wallsTexture[1]));
00207     tasks.push_back(loader->LoadTextureAsync("dayceiling.dds", nullptr, &m_ceilingTexture[2]));
00208     tasks.push_back(loader->LoadTextureAsync("dayfloor.dds", nullptr, &m_floorTexture[2]));
00209     tasks.push_back(loader->LoadTextureAsync("daywall.dds", nullptr, &m_wallsTexture[2]));
00210     tasks.push_back(create_task([]()
00211     {
00212         // Simulate loading additional resources by introducing a delay.
00213         wait(GameConstants::InitialLoadingDelay);
00214     }));
00215
00216     // Return the task group of all the async tasks for loading the shader and texture assets.
00217     return when_all(tasks.begin(), tasks.end());
00218 }
00219
00220 //----------------------------------------------------------------------
00221
00222 void GameRenderer::FinalizeCreateGameDeviceResources()
00223 {
00224     // All asynchronously loaded resources have completed loading.
00225     // Now associate all the resources with the appropriate game objects.
00226     // This method is expected to run in the same thread as the GameRenderer
00227     // was created. All work will happen behind the "Loading ..." screen after the
00228     // main loop has been entered.
00229
00230     // Initialize the Constant buffer with the light positions
00231     // These are handled here to ensure that the d3dContext is only
00232     // used in one thread.
00233
00234     ConstantBufferNeverChanges constantBufferNeverChanges;
00235     constantBufferNeverChanges.lightPosition[0] = XMFLOAT4( 3.5f, 2.5f,  5.5f, 1.0f);
00236     constantBufferNeverChanges.lightPosition[1] = XMFLOAT4( 3.5f, 2.5f, -5.5f, 1.0f);
00237     constantBufferNeverChanges.lightPosition[2] = XMFLOAT4(-3.5f, 2.5f, -5.5f, 1.0f);
00238     constantBufferNeverChanges.lightPosition[3] = XMFLOAT4( 3.5f, 2.5f,  5.5f, 1.0f);
00239     constantBufferNeverChanges.lightColor = XMFLOAT4(0.25f, 0.25f, 0.25f, 1.0f);
00240     m_d3dContext->UpdateSubresource(m_constantBufferNeverChanges.Get(), 0, nullptr, &constantBufferNeverChanges, 0, 0);
00241
00242     // For the targets, there are two unique generated textures.
00243     // Each texture image includes the number of the texture.
00244     // Make sure the 2D rendering is occurring on the same thread
00245     // as the main rendering.
00246
00247     TargetTexture^ textureGenerator = ref new TargetTexture(
00248         m_d3dDevice.Get(),
00249         m_d2dFactory.Get(),
00250         m_dwriteFactory.Get(),
00251         m_d2dContext.Get()
00252         );
00253
00254     MeshObject^ cylinderMesh = ref new CylinderMesh(m_d3dDevice.Get(), 26);
00255     MeshObject^ targetMesh = ref new FaceMesh(m_d3dDevice.Get());
00256     MeshObject^ sphereMesh = ref new SphereMesh(m_d3dDevice.Get(), 26);
00257
00258     Material^ cylinderMaterial = ref new Material(
00259         XMFLOAT4(0.8f, 0.8f, 0.8f, .5f),
00260         XMFLOAT4(0.8f, 0.8f, 0.8f, .5f),
00261         XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f),
00262         15.0f,
00263         m_cylinderTexture.Get(),
00264         m_vertexShader.Get(),
00265         m_pixelShader.Get()
00266         );
00267
00268     Material^ sphereMaterial = ref new Material(
00269         XMFLOAT4(0.8f, 0.4f, 0.0f, 1.0f),
00270         XMFLOAT4(0.8f, 0.4f, 0.0f, 1.0f),
00271         XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f),
00272         50.0f,
00273         m_sphereTexture.Get(),
00274         m_vertexShader.Get(),
00275         m_pixelShader.Get()
00276         );
00277
00278     auto objects = m_game->RenderObjects();
00279
00280     // Attach the textures to the appropriate game objects.
00281     for (auto object = objects.begin(); object != objects.end(); object++)
00282     {
00283         if ((*object)->TargetId() == GameConstants::WorldFloorId)
00284         {
00285             (*object)->NormalMaterial(
00286                 ref new Material(
00287                     XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f),
00288                     XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f),
00289                     XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f),
00290                     150.0f,
00291                     m_floorTexture[0].Get(),
00292                     m_vertexShaderFlat.Get(),
00293                     m_pixelShaderFlat.Get()
00294                     )
00295                 );
00296             (*object)->Mesh(ref new WorldFloorMesh(m_d3dDevice.Get()));
00297         }
00298         else if ((*object)->TargetId() == GameConstants::WorldCeilingId)
00299         {
00300             (*object)->NormalMaterial(
00301                 ref new Material(
00302                     XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f),
00303                     XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f),
00304                     XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f),
00305                     150.0f,
00306                     m_ceilingTexture[0].Get(),
00307                     m_vertexShaderFlat.Get(),
00308                     m_pixelShaderFlat.Get()
00309                     )
00310                 );
00311             (*object)->Mesh(ref new WorldCeilingMesh(m_d3dDevice.Get()));
00312         }
00313         else if ((*object)->TargetId() == GameConstants::WorldWallsId)
00314         {
00315             (*object)->NormalMaterial(
00316                 ref new Material(
00317                     XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f),
00318                     XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f),
00319                     XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f),
00320                     150.0f,
00321                     m_wallsTexture[0].Get(),
00322                     m_vertexShaderFlat.Get(),
00323                     m_pixelShaderFlat.Get()
00324                     )
00325                 );
00326             (*object)->Mesh(ref new WorldWallsMesh(m_d3dDevice.Get()));
00327         }
00328         else if (Cylinder^ cylinder = dynamic_cast<Cylinder^>(*object))
00329         {
00330             cylinder->Mesh(cylinderMesh);
00331             cylinder->NormalMaterial(cylinderMaterial);
00332         }
00333         else if (Face^ target = dynamic_cast<Face^>(*object))
00334         {
00335             const int bufferLength = 16;
00336             char16 str[bufferLength];
00337             int len = swprintf_s(str, bufferLength, L"%d", target->TargetId());
00338             Platform::String^ string = ref new Platform::String(str, len);
00339
00340             ComPtr<ID3D11ShaderResourceView> texture;
00341             textureGenerator->CreateTextureResourceView(string, &texture);
00342             target->NormalMaterial(
00343                 ref new Material(
00344                     XMFLOAT4(0.8f, 0.8f, 0.8f, 0.5f),
00345                     XMFLOAT4(0.8f, 0.8f, 0.8f, 0.5f),
00346                     XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f),
00347                     5.0f,
00348                     texture.Get(),
00349                     m_vertexShader.Get(),
00350                     m_pixelShader.Get()
00351                     )
00352                 );
00353
00354             textureGenerator->CreateHitTextureResourceView(string, &texture);
00355             target->HitMaterial(
00356                 ref new Material(
00357                     XMFLOAT4(0.8f, 0.8f, 0.8f, 0.5f),
00358                     XMFLOAT4(0.8f, 0.8f, 0.8f, 0.5f),
00359                     XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f),
00360                     5.0f,
00361                     texture.Get(),
00362                     m_vertexShader.Get(),
00363                     m_pixelShader.Get()
00364                     )
00365                 );
00366
00367             target->Mesh(targetMesh);
00368         }
00369         else if (Sphere^ sphere = dynamic_cast<Sphere^>(*object))
00370         {
00371             sphere->Mesh(sphereMesh);
00372             sphere->NormalMaterial(sphereMaterial);
00373         }
00374     }
00375
00376     // Ensure that the camera has been initialized with the right Projection
00377     // matrix.  The camera is not created at the time the first window resize event
00378     // occurs.
00379     m_game->GameCamera()->SetProjParams(
00380         XM_PI / 2,
00381         m_renderTargetSize.Width / m_renderTargetSize.Height,
00382         0.01f,
00383         100.0f
00384         );
00385
00386     // Make sure that Projection matrix has been set in the constant buffer
00387     // now that all the resources are loaded.
00388     // DirectXBase is handling screen rotations directly to eliminate an unaligned
00389     // fullscreen copy.  As a result, it is necessary to post multiply the rotationTransform3D
00390     // matrix to the camera projection matrix.
00391     // The matrices are transposed due to the shader code expecting the matrices in the opposite
00392     // row/column order from the DirectX math library.
00393     ConstantBufferChangeOnResize changesOnResize;
00394     XMStoreFloat4x4(
00395         &changesOnResize.projection,
00396         XMMatrixMultiply(
00397             XMMatrixTranspose(m_game->GameCamera()->Projection()),
00398             XMMatrixTranspose(XMLoadFloat4x4(&m_rotationTransform3D))
00399             )
00400         );
00401
00402     m_d3dContext->UpdateSubresource(
00403         m_constantBufferChangeOnResize.Get(),
00404         0,
00405         nullptr,
00406         &changesOnResize,
00407         0,
00408         0
00409         );
00410
00411     m_gameResourcesLoaded = true;
00412 }
00413
00414 //----------------------------------------------------------------------
00415
00416 task<void> GameRenderer::LoadLevelResourcesAsync()
00417 {
00418     m_levelResourcesLoaded = false;
00419
00420     return create_task([this]()
00421     {
00422         // This is where additional async loading of level specific resources
00423         // would be done.  Since there aren't any to load, just simulate
00424         // by delaying for some time.
00425         wait(GameConstants::LevelLoadingDelay);
00426     });
00427 }
00428
00429 //----------------------------------------------------------------------
00430
00431 void GameRenderer::FinalizeLoadLevelResources()
00432 {
00433     // Once the level specific resources had been loaded, this method is
00434     // where D3D context specific actions would be handled.  This method
00435     // runs in the same thread context as the GameRenderer was created.
00436
00437     m_levelResourcesLoaded = true;
00438 }
00439
00440 //--------------------------------------------------------------------------------------
00441
00442 void GameRenderer::SetBackground(uint32 background)
00443 {
00444     if (background < GameConstants::MaxBackgroundTextures)
00445     {
00446         if (m_ceilingTexture[background] != nullptr &&
00447             m_floorTexture[background] != nullptr &&
00448             m_wallsTexture[background] != nullptr)
00449         {
00450             auto objects = m_game->RenderObjects();
00451
00452             // Attach the textures to the appropriate game objects.
00453             for (auto object = objects.begin(); object != objects.end(); object++)
00454             {
00455                 if ((*object)->TargetId() == GameConstants::WorldFloorId)
00456                 {
00457                     (*object)->NormalMaterial()->SetTexture(m_floorTexture[background].Get());
00458                 }
00459                 else if ((*object)->TargetId() == GameConstants::WorldCeilingId)
00460                 {
00461                     (*object)->NormalMaterial()->SetTexture(m_ceilingTexture[background].Get());
00462                 }
00463                 else if ((*object)->TargetId() == GameConstants::WorldWallsId)
00464                 {
00465                     (*object)->NormalMaterial()->SetTexture(m_wallsTexture[background].Get());
00466                 }
00467             }
00468         }
00469     }
00470 }
00471
00472 //----------------------------------------------------------------------
00473
00474 void GameRenderer::Render()
00475 {
00476     int renderingPasses = 1;
00477     if (m_stereoEnabled)
00478     {
00479         renderingPasses = 2;
00480     }
00481
00482     for (int i = 0; i < renderingPasses; i++)
00483     {
00484         // Iterate through the number of rendering passes to be completed.
00485         if (m_stereoEnabled && i > 0)
00486         {
00487             // Doing the Right Eye View.
00488             m_d3dContext->OMSetRenderTargets(1, m_d3dRenderTargetViewRight.GetAddressOf(), m_d3dDepthStencilView.Get());
00489             m_d3dContext->ClearDepthStencilView(m_d3dDepthStencilView.Get(), D3D11_CLEAR_DEPTH, 1.0f, 0);
00490             m_d2dContext->SetTarget(m_d2dTargetBitmapRight.Get());
00491         }
00492         else
00493         {
00494             // Doing the Mono or Left Eye View.
00495             m_d3dContext->OMSetRenderTargets(1, m_d3dRenderTargetView.GetAddressOf(), m_d3dDepthStencilView.Get());
00496             m_d3dContext->ClearDepthStencilView(m_d3dDepthStencilView.Get(), D3D11_CLEAR_DEPTH, 1.0f, 0);
00497             m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
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 (m_stereoEnabled)
00505             {
00506                 // When doing stereo, it is necessary to update the projection matrix once per rendering pass.
00507                 ConstantBufferChangeOnResize changesOnResize;
00508                 XMStoreFloat4x4(
00509                     &changesOnResize.projection,
00510                     XMMatrixMultiply(
00511                         XMMatrixTranspose(
00512                             i == 0 ?
00513                             m_game->GameCamera()->LeftEyeProjection() :
00514                             m_game->GameCamera()->RightEyeProjection()
00515                             ),
00516                         XMMatrixTranspose(XMLoadFloat4x4(&m_rotationTransform3D))
00517                         )
00518                     );
00519
00520                 m_d3dContext->UpdateSubresource(
00521                     m_constantBufferChangeOnResize.Get(),
00522                     0,
00523                     nullptr,
00524                     &changesOnResize,
00525                     0,
00526                     0
00527                     );
00528             }
00529             // Update variables that change once per frame.
00530
00531             ConstantBufferChangesEveryFrame constantBufferChangesEveryFrame;
00532             XMStoreFloat4x4(
00533                 &constantBufferChangesEveryFrame.view,
00534                 XMMatrixTranspose(m_game->GameCamera()->View())
00535                 );
00536             m_d3dContext->UpdateSubresource(
00537                 m_constantBufferChangesEveryFrame.Get(),
00538                 0,
00539                 nullptr,
00540                 &constantBufferChangesEveryFrame,
00541                 0,
00542                 0
00543                 );
00544
00545             // Setup the graphics pipeline. This sample uses the same InputLayout and set of
00546             // constant buffers for all shaders, so they only need to be set once per frame.
00547
00548             m_d3dContext->IASetInputLayout(m_vertexLayout.Get());
00549             m_d3dContext->VSSetConstantBuffers(0, 1, m_constantBufferNeverChanges.GetAddressOf());
00550             m_d3dContext->VSSetConstantBuffers(1, 1, m_constantBufferChangeOnResize.GetAddressOf());
00551             m_d3dContext->VSSetConstantBuffers(2, 1, m_constantBufferChangesEveryFrame.GetAddressOf());
00552             m_d3dContext->VSSetConstantBuffers(3, 1, m_constantBufferChangesEveryPrim.GetAddressOf());
00553
00554             m_d3dContext->PSSetConstantBuffers(2, 1, m_constantBufferChangesEveryFrame.GetAddressOf());
00555             m_d3dContext->PSSetConstantBuffers(3, 1, m_constantBufferChangesEveryPrim.GetAddressOf());
00556             m_d3dContext->PSSetSamplers(0, 1, m_samplerLinear.GetAddressOf());
00557
00558             auto objects = m_game->RenderObjects();
00559             for (auto object = objects.begin(); object != objects.end(); object++)
00560             {
00561                 (*object)->Render(m_d3dContext.Get(), m_constantBufferChangesEveryPrim.Get());
00562             }
00563         }
00564         else
00565         {
00566             const float ClearColor[4] = {0.1f, 0.1f, 0.1f, 1.0f};
00567
00568             // Only need to clear the background when not rendering the full 3D scene since
00569             // the 3D world is a fully enclosed box and the dynamics prevents the camera from
00570             // moving outside this space.
00571             if (m_stereoEnabled && i > 0)
00572             {
00573                 // Doing the Right Eye View.
00574                 m_d3dContext->ClearRenderTargetView(m_d3dRenderTargetViewRight.Get(), ClearColor);
00575             }
00576             else
00577             {
00578                 // Doing the Mono or Left Eye View.
00579                 m_d3dContext->ClearRenderTargetView(m_d3dRenderTargetView.Get(), ClearColor);
00580             }
00581         }
00582
00583         m_d2dContext->BeginDraw();
00584
00585         // To handle the swapchain being pre-rotated, set the D2D transformation to include it.
00586         m_d2dContext->SetTransform(m_rotationTransform2D);
00587
00588         if (m_game != nullptr && m_gameResourcesLoaded)
00589         {
00590             // This is only used after the game state has been initialized.
00591             m_gameHud->Render(m_game, m_d2dContext.Get(), m_windowBounds);
00592         }
00593
00594         // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00595         // is lost. It will be handled during the next call to Present.
00596         HRESULT hr = m_d2dContext->EndDraw();
00597         if (hr != D2DERR_RECREATE_TARGET)
00598         {
00599             DX::ThrowIfFailed(hr);
00600         }
00601     }
00602     Present();
00603 }
00604
00605 //----------------------------------------------------------------------
00606
00607 GameHud^ GameRenderer::Hud()
00608 {
00609     return m_gameHud;
00610 }
00611
00612 //----------------------------------------------------------------------
00613
00614 #if defined(_DEBUG)
00615 void GameRenderer::ReportLiveDeviceObjects()
00616 {
00617     // If the debug layer isn't present on the system then this QI will fail.  In that case
00618     // the routine just exits.   This is a debugging aid to see the active D3D objects and
00619     // is not critical to functional operation of the sample.
00620
00621     ComPtr<ID3D11Debug> debugLayer;
00622     HRESULT hr = m_d3dDevice.As(&debugLayer);
00623     if (FAILED(hr))
00624     {
00625         return;
00626     }
00627     DX::ThrowIfFailed(
00628         debugLayer->ReportLiveDeviceObjects(D3D11_RLDO_DETAIL)
00629         );
00630 }
00631
00632 //----------------------------------------------------------------------
00633
00634 #endif
00635
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML data binding/C++/Scenario5.xaml.cpp Source File

  • XAML data binding

Scenario5.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 // Scenario5.xaml.cpp
00013 // Implementation of the Scenario5 class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario5.xaml.h"
00018 #include "Team.h"
00019
00020 using namespace SDKSample::DataBinding;
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Navigation;
00025
00026 Scenario5::Scenario5()
00027 {
00028     InitializeComponent();
00029   Scenario5Reset(nullptr,nullptr);
00030 }
00031
00032 void SDKSample::DataBinding::Scenario5::Scenario5Reset(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00033 {
00034     auto teams = ref new Teams();
00035   lvDataTemplates->ItemsSource = teams->Items;
00036 }
00037
00038
00039
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: LightSensor/C++/common/LayoutAwarePage.h Source File

  • LightSensor
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DirectX::HDREndPntPair Member List

This is the complete list of members for DirectX::HDREndPntPair, including all inherited members.
A | DirectX::HDREndPntPair
B | DirectX::HDREndPntPair
Generated on Sat Nov 23 2024 16:09:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/WorldMesh.h Source File

  • XAML DirectX 3D shooting game

WorldMesh.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 "MeshObject.h"
00011
00012 // WorldCeilingMesh:
00013 // This class derives from MeshObject and creates a ID3D11Buffer of
00014 // vertices and indices to represent the ceiling of the bounding cube
00015 // of the world.
00016 // The vertices are defined by a position, a normal and a single
00017 // 2D texture coordinate.
00018
00019 ref class WorldCeilingMesh: public MeshObject
00020 {
00021 internal:
00022     WorldCeilingMesh(_In_ ID3D11Device *device);
00023 };
00024
00025 // WorldFloorMesh:
00026 // This class derives from MeshObject and creates a ID3D11Buffer of
00027 // vertices and indices to represent the floor of the bounding cube
00028 // of the world.
00029
00030 ref class WorldFloorMesh: public MeshObject
00031 {
00032 internal:
00033     WorldFloorMesh(_In_ ID3D11Device *device);
00034 };
00035
00036 // WorldWallsMesh:
00037 // This class derives from MeshObject and creates a ID3D11Buffer of
00038 // vertices and indices to represent the walls of the bounding cube
00039 // of the world.
00040
00041 ref class WorldWallsMesh: public MeshObject
00042 {
00043 internal:
00044     WorldWallsMesh(_In_ ID3D11Device *device);
00045 };
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Portable device API/C++/S1_DeviceProperties.xaml.cpp Source File

  • Portable device API

S1_DeviceProperties.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 // S1_DeviceProperties.xaml.cpp
00013 // Implementation of the S1_DeviceProperties class
00014 //
00015
00016 #include "pch.h"
00017 #include "Constants.h"
00018 #include "S1_DeviceProperties.xaml.h"
00019
00020 using namespace SDKSample::PortableDeviceCPP;
00021
00022 using namespace concurrency;
00023 using namespace Microsoft::WRL;
00024 using namespace Platform;
00025 using namespace Platform::Collections;
00026 using namespace Windows::Devices::Enumeration;
00027 using namespace Windows::UI::Xaml;
00028 using namespace Windows::UI::Xaml::Controls;
00029 using namespace Windows::UI::Xaml::Navigation;
00030
00031 S1_DeviceProperties::S1_DeviceProperties() : rootPage(MainPage::Current)
00032 {
00033     InitializeComponent();
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 S1_DeviceProperties::OnNavigatedTo(NavigationEventArgs^ e)
00042 {
00043     ScenarioOutput->Text = "";
00044     DeviceSelector->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00045 }
00046
00047 /// <summary>
00048 /// This is the click handler for the 'Run' button.
00049 /// </summary>
00050 /// <param name="sender"></param>
00051 /// <param name="e"></param>
00052 void S1_DeviceProperties::Run_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00053 {
00054     ShowDeviceSelectorAsync();
00055 }
00056
00057 /// <summary>
00058 /// Enumerates all portable devices and populates the device selection list.
00059 /// </summary>
00060 void S1_DeviceProperties::ShowDeviceSelectorAsync()
00061 {
00062     ScenarioOutput->Text = "";
00063     _deviceInfoCollection = nullptr;
00064
00065     // Find all portable devices
00066     String^ aqsFilter = "System.Devices.InterfaceClassGuid:=\"{6AC27878-A6FA-4155-BA85-F98F491D4F33}\" AND System.Devices.InterfaceEnabled:=System.StructuredQueryType.Boolean#True";
00067     create_task(DeviceInformation::FindAllAsync(aqsFilter)).then([this] (DeviceInformationCollection^ deviceInfoCollection)
00068     {
00069         _deviceInfoCollection = deviceInfoCollection;
00070         if (_deviceInfoCollection->Size > 0)
00071         {
00072             auto items = ref new Vector<String^>();
00073             std::for_each(begin(_deviceInfoCollection), end(_deviceInfoCollection), [items](IDeviceInformation^ deviceInfoElement)
00074             {
00075                 items->Append(ref new String(deviceInfoElement->Name->Begin()));
00076             });
00077             cvs->Source = items;
00078             DeviceSelector->Visibility = Windows::UI::Xaml::Visibility::Visible;
00079         }
00080         else
00081         {
00082             rootPage->NotifyUser("No portable devices were found. Please attach a portable device to the system (e.g. a camera, music player, or cellular phone)", NotifyType::ErrorMessage);
00083         }
00084     });
00085 }
00086
00087 /// <summary>
00088 /// This is the tapped handler for the device selection list. It runs the scenario
00089 /// for the selected portable device.
00090 /// </summary>
00091 /// <param name="sender"></param>
00092 /// <param name="e"></param>
00093 void S1_DeviceProperties::DeviceList_Tapped(Platform::Object^ sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^ e)
00094 {
00095     DeviceSelector->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00096     if (_deviceInfoCollection == nullptr)
00097     {
00098         return; // not yet populated
00099     }
00100
00101     auto deviceInfo = _deviceInfoCollection->GetAt(DeviceList->SelectedIndex);
00102     DisplayDeviceProperties(deviceInfo);
00103 }
00104
00105 /// <summary>
00106 /// Retrieves properties using the Portable Device COM APIs for the selected portable device
00107 /// and displays them.
00108 /// </summary>
00109 /// <param name="deviceInfoElement">Contains information about a selected device.</param>
00110 void S1_DeviceProperties::DisplayDeviceProperties(DeviceInformation^ deviceInfoElement)
00111 {
00112     ComPtr<IPortableDevice> device;
00113     ThrowIfFailed(CoCreateInstance(CLSID_PortableDeviceFTM, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&device)));
00114
00115     auto clientInfo = GetClientInfo();
00116     HRESULT hr = device->Open(deviceInfoElement->Id->Begin(), clientInfo.Get());
00117     if (hr == E_ACCESSDENIED)
00118     {
00119         rootPage->NotifyUser("Access to " + deviceInfoElement->Name + " is denied. Only a Privileged Application may access this device.", NotifyType::ErrorMessage);
00120         return;
00121     }
00122     ThrowIfFailed(hr);
00123
00124     rootPage->NotifyUser("Getting device properties for " + deviceInfoElement->Name, NotifyType::StatusMessage);
00125
00126     ComPtr<IPortableDeviceContent> content;
00127     ComPtr<IPortableDeviceProperties> properties;
00128
00129     ThrowIfFailed(device->Content(&content));
00130     ThrowIfFailed(content->Properties(&properties));
00131
00132     ComPtr<IPortableDeviceKeyCollection> propertiesToRead;
00133     ThrowIfFailed(CoCreateInstance(CLSID_PortableDeviceKeyCollection, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&propertiesToRead)));
00134     ThrowIfFailed(propertiesToRead->Add(WPD_DEVICE_MANUFACTURER));
00135     ThrowIfFailed(propertiesToRead->Add(WPD_DEVICE_SERIAL_NUMBER));
00136     ThrowIfFailed(propertiesToRead->Add(WPD_DEVICE_PROTOCOL));
00137
00138     ComPtr<IPortableDeviceValues> deviceProperties;
00139     ThrowIfFailed(properties->GetValues(WPD_DEVICE_OBJECT_ID, propertiesToRead.Get(), &deviceProperties));
00140     ScenarioOutput->Text = "";
00141
00142     PWSTR manufacturer = nullptr;
00143     if (SUCCEEDED(deviceProperties->GetStringValue(WPD_DEVICE_MANUFACTURER, &manufacturer)))
00144     {
00145         CoTaskMemString manufacturerPtr(manufacturer);
00146         ScenarioOutput->Text += "Manufacturer: " + ref new String(manufacturer) + "\n";
00147     }
00148
00149     PWSTR serialNumber = nullptr;
00150     if (SUCCEEDED(deviceProperties->GetStringValue(WPD_DEVICE_SERIAL_NUMBER, &serialNumber)))
00151     {
00152         CoTaskMemString serialNumberPtr(serialNumber);
00153         ScenarioOutput->Text += "Serial Number: " + ref new String(serialNumber) + "\n";
00154     }
00155
00156     PWSTR protocol = nullptr;
00157     if (SUCCEEDED(deviceProperties->GetStringValue(WPD_DEVICE_SERIAL_NUMBER, &protocol)))
00158     {
00159         CoTaskMemString protocolPtr(protocol);
00160         ScenarioOutput->Text += "Protocol: " + ref new String(protocol) + "\n";
00161     }
00162 }
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Syndication/C++/MainPage.xaml.cpp Source File

  • Syndication

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:44 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Compression/C++/CompressionUtils.h Source File

  • Compression

CompressionUtils.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 // Reads Stream into Destination. It's up to caller to ensure that Destination is not destructed until
00004 // ReadStreamTask::GetTask() is completed. If error is encountered during read Destination doesn't
00005 // change and Stream state is undefined.
00006 // NOTE: Generally you don't need to read entire stream into memory - we only use this task in order to
00007 //       interoperate with Compression API style buffer compression/decompression. Recommended way to
00008 //       work with WinRT streams of unknown length (including Comressor/Decompressor) is processing
00009 //       data chunk by chunk as it arrives.
00010 class ReadStreamTask
00011 {
00012 public:
00013     ReadStreamTask(Windows::Storage::Streams::IInputStream^ Stream, std::vector<byte> &Destination);
00014     ReadStreamTask(const ReadStreamTask& Task);
00015     ReadStreamTask &operator=(const ReadStreamTask& Task);
00016
00017     concurrency::task<size_t> GetTask();
00018
00019 private:
00020     static const unsigned int MinReadChunkSize = 0x10000;
00021
00022     struct ReadStreamTaskImpl;
00023     ReadStreamTaskImpl *_Impl;
00024 };
00025
00026 // Common context for all scenarios for simplicity - not all fields are used by every scenario
00027 struct ScenarioContext
00028 {
00029     Windows::Storage::Streams::InMemoryRandomAccessStream^  raStream;
00030     Windows::Storage::Compression::Compressor^              compressor;
00031     Windows::Storage::Streams::DataWriter^                  writer;
00032     std::vector<byte>                                       originalData;
00033     std::vector<byte>                                       compressedData;
00034     std::vector<byte>                                       decompressedData;
00035 };
Generated on Sat Nov 23 2024 16:07:59 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D perspective transform/C++/DirectXBase.cpp Source File

  • Direct2D perspective transform

DirectXBase.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 "DirectXBase.h"
00010
00011 using namespace Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::Graphics::Display;
00015 using namespace D2D1;
00016
00017 // Constructor.
00018 DirectXBase::DirectXBase() :
00019     m_windowSizeChangeInProgress(false),
00020     m_dpi(-1.0f)
00021 {
00022 }
00023
00024 // Initialize the DirectX resources required to run.
00025 void DirectXBase::Initialize(CoreWindow^ window, float dpi)
00026 {
00027     m_window = window;
00028
00029     CreateDeviceIndependentResources();
00030     CreateDeviceResources();
00031     SetDpi(dpi);
00032 }
00033
00034 // Recreate all device resources and set them back to the current state.
00035 void DirectXBase::HandleDeviceLost()
00036 {
00037     // Reset these member variables to ensure that SetDpi recreates all resources.
00038     float dpi = m_dpi;
00039     m_dpi = -1.0f;
00040     m_windowBounds.Width = 0;
00041     m_windowBounds.Height = 0;
00042     m_swapChain = nullptr;
00043
00044     CreateDeviceResources();
00045     SetDpi(dpi);
00046 }
00047
00048 // These are the resources required independent of the device.
00049 void DirectXBase::CreateDeviceIndependentResources()
00050 {
00051     D2D1_FACTORY_OPTIONS options;
00052     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00053
00054 #if defined(_DEBUG)
00055     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00056     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00057 #endif
00058
00059     DX::ThrowIfFailed(
00060         D2D1CreateFactory(
00061             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00062             __uuidof(ID2D1Factory1),
00063             &options,
00064             &m_d2dFactory
00065             )
00066         );
00067
00068     DX::ThrowIfFailed(
00069         DWriteCreateFactory(
00070             DWRITE_FACTORY_TYPE_SHARED,
00071             __uuidof(IDWriteFactory),
00072             &m_dwriteFactory
00073             )
00074         );
00075
00076     DX::ThrowIfFailed(
00077         CoCreateInstance(
00078             CLSID_WICImagingFactory,
00079             nullptr,
00080             CLSCTX_INPROC_SERVER,
00081             IID_PPV_ARGS(&m_wicFactory)
00082             )
00083         );
00084 }
00085
00086 // These are the resources that depend on the device.
00087 void DirectXBase::CreateDeviceResources()
00088 {
00089     // This flag adds support for surfaces with a different color channel ordering
00090     // than the API default. It is required for compatibility with Direct2D.
00091     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00092     ComPtr<IDXGIDevice> dxgiDevice;
00093
00094 #if defined(_DEBUG)
00095     // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00096     creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00097 #endif
00098
00099     // This array defines the set of DirectX hardware feature levels this app will support.
00100     // Note the ordering should be preserved.
00101     // Don't forget to declare your application's minimum required feature level in its
00102     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00103     D3D_FEATURE_LEVEL featureLevels[] =
00104     {
00105         D3D_FEATURE_LEVEL_11_1,
00106         D3D_FEATURE_LEVEL_11_0,
00107         D3D_FEATURE_LEVEL_10_1,
00108         D3D_FEATURE_LEVEL_10_0,
00109         D3D_FEATURE_LEVEL_9_3,
00110         D3D_FEATURE_LEVEL_9_2,
00111         D3D_FEATURE_LEVEL_9_1
00112     };
00113
00114     // Create the Direct3D 11 API device object and a corresponding context.
00115     ComPtr<ID3D11Device> device;
00116     ComPtr<ID3D11DeviceContext> context;
00117     DX::ThrowIfFailed(
00118         D3D11CreateDevice(
00119             nullptr,                    // Specify nullptr to use the default adapter.
00120             D3D_DRIVER_TYPE_HARDWARE,
00121             0,
00122             creationFlags,              // Set debug and Direct2D compatibility flags.
00123             featureLevels,              // List of feature levels this app can support.
00124             ARRAYSIZE(featureLevels),
00125             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Metro style apps.
00126             &device,                    // Returns the Direct3D device created.
00127             &m_featureLevel,            // Returns feature level of device created.
00128             &context                    // Returns the device immediate context.
00129             )
00130         );
00131
00132     // Get the Direct3D 11.1 API device and context interfaces.
00133     DX::ThrowIfFailed(
00134         device.As(&m_d3dDevice)
00135         );
00136
00137     DX::ThrowIfFailed(
00138         context.As(&m_d3dContext)
00139         );
00140
00141     // Get the underlying DXGI device of the Direct3D device.
00142     DX::ThrowIfFailed(
00143         m_d3dDevice.As(&dxgiDevice)
00144         );
00145
00146     // Create the Direct2D device object and a corresponding context.
00147     DX::ThrowIfFailed(
00148         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00149         );
00150
00151     DX::ThrowIfFailed(
00152         m_d2dDevice->CreateDeviceContext(
00153             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00154             &m_d2dContext
00155             )
00156         );
00157 }
00158
00159 // Helps track the DPI in the helper class.
00160 // This is called in the dpiChanged event handler in the view class.
00161 void DirectXBase::SetDpi(float dpi)
00162 {
00163     if (dpi != m_dpi)
00164     {
00165         // Save the DPI of this display in our class.
00166         m_dpi = dpi;
00167
00168         // Update Direct2D's stored DPI.
00169         m_d2dContext->SetDpi(m_dpi, m_dpi);
00170
00171         // Often a DPI change implies a window size change. In some cases Windows will issue
00172         // both a size changed event and a DPI changed event. In this case, the resulting bounds
00173         // will not change, and the window resize code will only be executed once.
00174         UpdateForWindowSizeChange();
00175     }
00176 }
00177
00178 // This routine is called in the event handler for the view SizeChanged event.
00179 void DirectXBase::UpdateForWindowSizeChange()
00180 {
00181     // Only handle window size changed if there is no pending DPI change.
00182     if (m_dpi != DisplayProperties::LogicalDpi)
00183     {
00184         return;
00185     }
00186
00187     if (m_window->Bounds.Width  != m_windowBounds.Width ||
00188         m_window->Bounds.Height != m_windowBounds.Height)
00189     {
00190         m_d2dContext->SetTarget(nullptr);
00191         m_d2dTargetBitmap = nullptr;
00192         m_d3dRenderTargetView = nullptr;
00193         m_d3dDepthStencilView = nullptr;
00194         m_windowSizeChangeInProgress = true;
00195         CreateWindowSizeDependentResources();
00196     }
00197 }
00198
00199 // Allocate all memory resources that change on a window SizeChanged event.
00200 void DirectXBase::CreateWindowSizeDependentResources()
00201 {
00202     // Store the window bounds so the next time we get a SizeChanged event we can
00203     // avoid rebuilding everything if the size is identical.
00204     m_windowBounds = m_window->Bounds;
00205
00206     if (m_swapChain != nullptr)
00207     {
00208         // If the swap chain already exists, resize it.
00209         HRESULT hr = m_swapChain->ResizeBuffers(2, 0, 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0);
00210
00211         if (hr == DXGI_ERROR_DEVICE_REMOVED)
00212         {
00213             // If the device was removed for any reason, a new device and swapchain will need to be created.
00214             HandleDeviceLost();
00215
00216             // Everything is set up now. Do not continue execution of this method.
00217             return;
00218         }
00219         else
00220         {
00221             DX::ThrowIfFailed(hr);
00222         }
00223     }
00224     else
00225     {
00226         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00227         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00228         swapChainDesc.Width = 0;                                     // Use automatic sizing.
00229         swapChainDesc.Height = 0;
00230         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;           // This is the most common swap chain format.
00231         swapChainDesc.Stereo = false;
00232         swapChainDesc.SampleDesc.Count = 1;                          // Don't use multi-sampling.
00233         swapChainDesc.SampleDesc.Quality = 0;
00234         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00235         swapChainDesc.BufferCount = 2;                               // Use double-buffering to minimize latency.
00236         swapChainDesc.Scaling = DXGI_SCALING_NONE;
00237         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Metro style apps must use this SwapEffect.
00238         swapChainDesc.Flags = 0;
00239
00240         ComPtr<IDXGIDevice1> dxgiDevice;
00241         DX::ThrowIfFailed(
00242             m_d3dDevice.As(&dxgiDevice)
00243             );
00244
00245         ComPtr<IDXGIAdapter> dxgiAdapter;
00246         DX::ThrowIfFailed(
00247             dxgiDevice->GetAdapter(&dxgiAdapter)
00248             );
00249
00250         ComPtr<IDXGIFactory2> dxgiFactory;
00251         DX::ThrowIfFailed(
00252             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00253             );
00254
00255         CoreWindow^ window = m_window.Get();
00256         DX::ThrowIfFailed(
00257             dxgiFactory->CreateSwapChainForCoreWindow(
00258                 m_d3dDevice.Get(),
00259                 reinterpret_cast<IUnknown*>(window),
00260                 &swapChainDesc,
00261                 nullptr,
00262                 &m_swapChain
00263                 )
00264             );
00265
00266         // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
00267         // ensures that the application will only render after each VSync, minimizing power consumption.
00268         DX::ThrowIfFailed(
00269             dxgiDevice->SetMaximumFrameLatency(1)
00270             );
00271     }
00272
00273     // Create a Direct3D render target view of the swap chain back buffer.
00274     ComPtr<ID3D11Texture2D> backBuffer;
00275     DX::ThrowIfFailed(
00276         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00277         );
00278
00279     DX::ThrowIfFailed(
00280         m_d3dDevice->CreateRenderTargetView(
00281             backBuffer.Get(),
00282             nullptr,
00283             &m_d3dRenderTargetView
00284             )
00285         );
00286
00287     // Cache the rendertarget dimensions in our helper class for convenient use.
00288     D3D11_TEXTURE2D_DESC backBufferDesc = {0};
00289     backBuffer->GetDesc(&backBufferDesc);
00290     m_renderTargetSize.Width  = static_cast<float>(backBufferDesc.Width);
00291     m_renderTargetSize.Height = static_cast<float>(backBufferDesc.Height);
00292
00293     // Create a depth stencil view for use with 3D rendering if needed.
00294     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00295         DXGI_FORMAT_D24_UNORM_S8_UINT,
00296         backBufferDesc.Width,
00297         backBufferDesc.Height,
00298         1,
00299         1,
00300         D3D11_BIND_DEPTH_STENCIL
00301         );
00302
00303     ComPtr<ID3D11Texture2D> depthStencil;
00304     DX::ThrowIfFailed(
00305         m_d3dDevice->CreateTexture2D(
00306             &depthStencilDesc,
00307             nullptr,
00308             &depthStencil
00309             )
00310         );
00311
00312     auto viewDesc = CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D);
00313     DX::ThrowIfFailed(
00314         m_d3dDevice->CreateDepthStencilView(
00315             depthStencil.Get(),
00316             &viewDesc,
00317             &m_d3dDepthStencilView
00318             )
00319         );
00320
00321     // Set the 3D rendering viewport to target the entire window.
00322     CD3D11_VIEWPORT viewport(
00323         0.0f,
00324         0.0f,
00325         static_cast<float>(backBufferDesc.Width),
00326         static_cast<float>(backBufferDesc.Height)
00327         );
00328
00329     m_d3dContext->RSSetViewports(1, &viewport);
00330
00331     // Create a Direct2D target bitmap associated with the
00332     // swap chain back buffer and set it as the current target.
00333     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00334         BitmapProperties1(
00335             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00336             PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00337             m_dpi,
00338             m_dpi
00339             );
00340
00341     ComPtr<IDXGISurface> dxgiBackBuffer;
00342     DX::ThrowIfFailed(
00343         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00344         );
00345
00346     DX::ThrowIfFailed(
00347         m_d2dContext->CreateBitmapFromDxgiSurface(
00348             dxgiBackBuffer.Get(),
00349             &bitmapProperties,
00350             &m_d2dTargetBitmap
00351             )
00352         );
00353
00354     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00355
00356     // Grayscale text anti-aliasing is recommended for all Metro style apps.
00357     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00358 }
00359
00360 // Method to deliver the final image to the display.
00361 void DirectXBase::Present()
00362 {
00363     // The application may optionally specify "dirty" or "scroll" rects to improve efficiency
00364     // in certain scenarios.  In this sample, however, we do not utilize those features.
00365     DXGI_PRESENT_PARAMETERS parameters = {0};
00366     parameters.DirtyRectsCount = 0;
00367     parameters.pDirtyRects = nullptr;
00368     parameters.pScrollRect = nullptr;
00369     parameters.pScrollOffset = nullptr;
00370
00371     // The first argument instructs DXGI to block until VSync, putting the application
00372     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00373     // frames that will never be displayed to the screen.
00374     HRESULT hr = m_swapChain->Present1(1, 0, &parameters);
00375
00376     // Discard the contents of the render target.
00377     // This is a valid operation only when the existing contents will be entirely
00378     // overwritten. If dirty or scroll rects are used, this call should be removed.
00379     m_d3dContext->DiscardView(m_d3dRenderTargetView.Get());
00380
00381     // Discard the contents of the depth stencil.
00382     m_d3dContext->DiscardView(m_d3dDepthStencilView.Get());
00383
00384     // If the device was removed either by a disconnect or a driver upgrade, we
00385     // must recreate all device resources.
00386     if (hr == DXGI_ERROR_DEVICE_REMOVED)
00387     {
00388         HandleDeviceLost();
00389     }
00390     else
00391     {
00392         DX::ThrowIfFailed(hr);
00393     }
00394
00395     if (m_windowSizeChangeInProgress)
00396     {
00397         // A window size change has been initiated and the app has just completed presenting
00398         // the first frame with the new size. Notify the resize manager so we can short
00399         // circuit any resize animation and prevent unnecessary delays.
00400         CoreWindowResizeManager::GetForCurrentView()->NotifyLayoutCompleted();
00401         m_windowSizeChangeInProgress = false;
00402     }
00403 }
00404
00405 void DirectXBase::ValidateDevice()
00406 {
00407     // The D3D Device is no longer valid if the default adapter changes or if
00408     // the device has been removed.
00409
00410     // First, get the information for the adapter related to the current device.
00411
00412     ComPtr<IDXGIDevice1> dxgiDevice;
00413     ComPtr<IDXGIAdapter> deviceAdapter;
00414     DXGI_ADAPTER_DESC deviceDesc;
00415     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00416     DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter));
00417     DX::ThrowIfFailed(deviceAdapter->GetDesc(&deviceDesc));
00418
00419     // Next, get the information for the default adapter.
00420
00421     ComPtr<IDXGIFactory2> dxgiFactory;
00422     ComPtr<IDXGIAdapter1> currentAdapter;
00423     DXGI_ADAPTER_DESC currentDesc;
00424     DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)));
00425     DX::ThrowIfFailed(dxgiFactory->EnumAdapters1(0, &currentAdapter));
00426     DX::ThrowIfFailed(currentAdapter->GetDesc(&currentDesc));
00427
00428     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00429     // a new D3D device must be created.
00430
00431     if ((deviceDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart) ||
00432         (deviceDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart) ||
00433         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00434     {
00435         // Release references to resources related to the old device.
00436         dxgiDevice = nullptr;
00437         deviceAdapter = nullptr;
00438
00439         // Create a new device and swap chain.
00440         HandleDeviceLost();
00441     }
00442 }
Generated on Sat Nov 23 2024 16:08:02 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML Popup/C++/Constants.cpp Source File

  • XAML Popup

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully qualified name for the class that implements the scenario" }
00021     { "Popup Fundamentals", "SDKSample.XAMLPopup.Scenario1" },
00022     { "Popup and Input Controls", "SDKSample.XAMLPopup.Scenario2" },
00023     { "Popup as 'Flyout'", "SDKSample.XAMLPopup.Scenario3" }
00024 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: PlayToReceiver/C++/pch.h Source File

  • PlayToReceiver

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Date and time formatting/C++/Constants.h Source File

  • Date and time formatting

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"Date and Time Formatting Sample");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044
00045
00046 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

D2DLightingEffectsRenderer Member List

This is the complete list of members for D2DLightingEffectsRenderer, including all inherited members.
__pad0__ | D2DLightingEffectsRenderer |
CreateDeviceIndependentResources() override | D2DLightingEffectsRenderer | [virtual]
CreateDeviceResources() override | D2DLightingEffectsRenderer | [virtual]
CreateWindowSizeDependentResources() override | D2DLightingEffectsRenderer | [virtual]
HandleDeviceLost() override | D2DLightingEffectsRenderer | [virtual]
m_bitmapSourceEffect | D2DLightingEffectsRenderer | [private]
m_currentEffect | D2DLightingEffectsRenderer | [private]
m_distantDiffuseEffect | D2DLightingEffectsRenderer | [private]
m_distantSpecularEffect | D2DLightingEffectsRenderer | [private]
m_imageSize | D2DLightingEffectsRenderer | [private]
m_lightPositionZ | D2DLightingEffectsRenderer | [private]
m_needsResourceUpdate | D2DLightingEffectsRenderer | [private]
m_pointDiffuseEffect | D2DLightingEffectsRenderer | [private]
m_pointSpecularEffect | D2DLightingEffectsRenderer | [private]
m_spotDiffuseEffect | D2DLightingEffectsRenderer | [private]
m_spotSpecularEffect | D2DLightingEffectsRenderer | [private]
m_wicConverter | D2DLightingEffectsRenderer | [private]
m_windowState | D2DLightingEffectsRenderer | [private]
NeedsResourceUpdate() | D2DLightingEffectsRenderer | [inline]
OnPointerMoved(float x, float y) | D2DLightingEffectsRenderer |
Render() override | D2DLightingEffectsRenderer | [virtual]
SetLightingEffect(LightingEffect lightingEffect) | D2DLightingEffectsRenderer |
SetLightingProperty(LightingProperty lightingProperty, float value) | D2DLightingEffectsRenderer |
UpdateForViewStateChanged(Windows::UI::ViewManagement::ApplicationViewState state) | D2DLightingEffectsRenderer |
Generated on Sat Nov 23 2024 16:09:10 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Touch hit testing/C++/SampleOverlay.cpp Source File

  • Input Touch hit testing

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 Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::UI::ViewManagement;
00015 using namespace Windows::Graphics::Display;
00016 using namespace D2D1;
00017
00018 SampleOverlay::SampleOverlay() :
00019     m_drawOverlay(true)
00020 {
00021 }
00022
00023 void SampleOverlay::Initialize(
00024     _In_ ID2D1Device*         d2dDevice,
00025     _In_ ID2D1DeviceContext*  d2dContext,
00026     _In_ IWICImagingFactory*  wicFactory,
00027     _In_ IDWriteFactory*      dwriteFactory,
00028     _In_ Platform::String^    caption
00029     )
00030 {
00031     m_wicFactory = wicFactory;
00032     m_dwriteFactory = dwriteFactory;
00033     m_sampleName = caption;
00034     m_d2dDevice = d2dDevice;
00035     m_d2dContext = d2dContext;
00036     m_padding = 3.0f;
00037     m_textVerticalOffset = 5.0f;
00038     m_logoSize = D2D1::SizeF(0.0f, 0.0f);
00039     m_overlayWidth = 0.0f;
00040
00041     ComPtr<ID2D1Factory> factory;
00042     d2dDevice->GetFactory(&factory);
00043
00044     DX::ThrowIfFailed(
00045         factory.As(&m_d2dFactory)
00046         );
00047
00048     ResetDirectXResources();
00049 }
00050
00051 void SampleOverlay::ResetDirectXResources()
00052 {
00053     DX::ThrowIfFailed(
00054         m_d2dContext->CreateSolidColorBrush(ColorF(ColorF::White), &m_whiteBrush)
00055         );
00056
00057     ComPtr<IWICBitmapDecoder> wicBitmapDecoder;
00058     DX::ThrowIfFailed(
00059         m_wicFactory->CreateDecoderFromFilename(
00060             L"windowsbig-sdk.png",
00061             nullptr,
00062             GENERIC_READ,
00063             WICDecodeMetadataCacheOnDemand,
00064             &wicBitmapDecoder
00065             )
00066         );
00067
00068     ComPtr<IWICBitmapFrameDecode> wicBitmapFrame;
00069     DX::ThrowIfFailed(
00070         wicBitmapDecoder->GetFrame(0, &wicBitmapFrame)
00071         );
00072
00073     ComPtr<IWICFormatConverter> wicFormatConverter;
00074     DX::ThrowIfFailed(
00075         m_wicFactory->CreateFormatConverter(&wicFormatConverter)
00076         );
00077
00078     DX::ThrowIfFailed(
00079         wicFormatConverter->Initialize(
00080             wicBitmapFrame.Get(),
00081             GUID_WICPixelFormat32bppPBGRA,
00082             WICBitmapDitherTypeNone,
00083             nullptr,
00084             0.0,
00085             WICBitmapPaletteTypeCustom  // the BGRA format has no palette so this value is ignored
00086             )
00087         );
00088
00089     double dpiX = 96.0f;
00090     double dpiY = 96.0f;
00091     DX::ThrowIfFailed(
00092         wicFormatConverter->GetResolution(&dpiX, &dpiY)
00093         );
00094
00095     DX::ThrowIfFailed(
00096         m_d2dContext->CreateBitmapFromWicBitmap(
00097             wicFormatConverter.Get(),
00098             BitmapProperties(
00099                 PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00100                 static_cast<float>(dpiX),
00101                 static_cast<float>(dpiY)
00102                 ),
00103             &m_logoBitmap
00104             )
00105         );
00106
00107     m_logoSize = m_logoBitmap->GetSize();
00108
00109     ComPtr<IDWriteTextFormat> nameTextFormat;
00110     DX::ThrowIfFailed(
00111         m_dwriteFactory->CreateTextFormat(
00112             L"Segoe UI",
00113             nullptr,
00114             DWRITE_FONT_WEIGHT_LIGHT,
00115             DWRITE_FONT_STYLE_NORMAL,
00116             DWRITE_FONT_STRETCH_NORMAL,
00117             36.0f,
00118             L"en-US",
00119             &nameTextFormat
00120             )
00121         );
00122
00123     DX::ThrowIfFailed(
00124         nameTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)
00125         );
00126
00127     DX::ThrowIfFailed(
00128         nameTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)
00129         );
00130
00131     DX::ThrowIfFailed(
00132         m_dwriteFactory->CreateTextLayout(
00133             m_sampleName->Data(),
00134             m_sampleName->Length(),
00135             nameTextFormat.Get(),
00136             4096.0f,
00137             4096.0f,
00138             &m_textLayout
00139             )
00140         );
00141
00142     DWRITE_TEXT_METRICS metrics = {0};
00143     DX::ThrowIfFailed(
00144         m_textLayout->GetMetrics(&metrics)
00145         );
00146
00147     m_overlayWidth = m_padding * 3.0f + m_logoSize.width + metrics.width;
00148
00149     DX::ThrowIfFailed(
00150         m_d2dFactory->CreateDrawingStateBlock(&m_stateBlock)
00151         );
00152
00153     UpdateForWindowSizeChange();
00154 }
00155
00156 void SampleOverlay::UpdateForWindowSizeChange()
00157 {
00158     if (CoreWindow::GetForCurrentThread()->Bounds.Width < m_overlayWidth)
00159     {
00160         m_drawOverlay = false;
00161     }
00162     else
00163     {
00164         m_drawOverlay = true;
00165     }
00166 }
00167
00168 void SampleOverlay::Render()
00169 {
00170     if (m_drawOverlay)
00171     {
00172         m_d2dContext->SaveDrawingState(m_stateBlock.Get());
00173
00174         m_d2dContext->BeginDraw();
00175         m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00176         m_d2dContext->DrawBitmap(
00177             m_logoBitmap.Get(),
00178             D2D1::RectF(m_padding, 0.0f, m_logoSize.width + m_padding, m_logoSize.height)
00179             );
00180
00181         m_d2dContext->DrawTextLayout(
00182             Point2F(m_logoSize.width + 2.0f * m_padding, m_textVerticalOffset),
00183             m_textLayout.Get(),
00184             m_whiteBrush.Get()
00185             );
00186
00187         // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00188         // is lost. It will be handled during the next call to Present.
00189         HRESULT hr = m_d2dContext->EndDraw();
00190         if (hr != D2DERR_RECREATE_TARGET)
00191         {
00192             DX::ThrowIfFailed(hr);
00193         }
00194
00195         m_d2dContext->RestoreDrawingState(m_stateBlock.Get());
00196     }
00197 }
00198
00199 float SampleOverlay::GetTitleHeightInDips()
00200 {
00201     return m_logoSize.height;
00202 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/texconv/DirectXTexDDS.cpp Source File

  • Direct3D resource loading
  • texconv

DirectXTexDDS.cpp

Go to the documentation of this file.
00001 //-------------------------------------------------------------------------------------
00002 // DirectXTexDDS.cpp
00003 //
00004 // DirectX Texture Library - Microsoft DirectDraw Surface (DDS) file format reader/writer
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 #include "directxtexp.h"
00015
00016 #include "dds.h"
00017
00018 namespace DirectX
00019 {
00020
00021 //-------------------------------------------------------------------------------------
00022 // Legacy format mapping table (used for DDS files without 'DX10' extended header)
00023 //-------------------------------------------------------------------------------------
00024 enum CONVERSION_FLAGS
00025 {
00026     CONV_FLAGS_NONE     = 0x0,
00027     CONV_FLAGS_EXPAND   = 0x1,      // Conversion requires expanded pixel size
00028     CONV_FLAGS_NOALPHA  = 0x2,      // Conversion requires setting alpha to known value
00029     CONV_FLAGS_SWIZZLE  = 0x4,      // BGR/RGB order swizzling required
00030     CONV_FLAGS_PAL8     = 0x8,      // Has an 8-bit palette
00031     CONV_FLAGS_888      = 0x10,     // Source is an 8:8:8 (24bpp) format
00032     CONV_FLAGS_565      = 0x20,     // Source is a 5:6:5 (16bpp) format
00033     CONV_FLAGS_5551     = 0x40,     // Source is a 5:5:5:1 (16bpp) format
00034     CONV_FLAGS_4444     = 0x80,     // Source is a 4:4:4:4 (16bpp) format
00035     CONV_FLAGS_44       = 0x100,    // Source is a 4:4 (8bpp) format
00036     CONV_FLAGS_332      = 0x200,    // Source is a 3:3:2 (8bpp) format
00037     CONV_FLAGS_8332     = 0x400,    // Source is a 8:3:3:2 (16bpp) format
00038     CONV_FLAGS_A8P8     = 0x800,    // Has an 8-bit palette with an alpha channel
00039     CONV_FLAGS_DX10     = 0x10000,  // Has the 'DX10' extension header
00040 };
00041
00042 struct LegacyDDS
00043 {
00044     DXGI_FORMAT     format;
00045     DWORD           convFlags;
00046     DDS_PIXELFORMAT ddpf;
00047 };
00048
00049 const LegacyDDS g_LegacyDDSMap[] =
00050 {
00051     { DXGI_FORMAT_BC1_UNORM,          CONV_FLAGS_NONE,        DDSPF_DXT1 }, // D3DFMT_DXT1
00052     { DXGI_FORMAT_BC2_UNORM,          CONV_FLAGS_NONE,        DDSPF_DXT3 }, // D3DFMT_DXT3
00053     { DXGI_FORMAT_BC3_UNORM,          CONV_FLAGS_NONE,        DDSPF_DXT5 }, // D3DFMT_DXT5
00054
00055     { DXGI_FORMAT_BC2_UNORM,          CONV_FLAGS_NONE,        DDSPF_DXT2 }, // D3DFMT_DXT2 (ignore premultiply)
00056     { DXGI_FORMAT_BC3_UNORM,          CONV_FLAGS_NONE,        DDSPF_DXT4 }, // D3DFMT_DXT4 (ignore premultiply)
00057
00058     { DXGI_FORMAT_BC4_UNORM,          CONV_FLAGS_NONE,        DDSPF_BC4_UNORM },
00059     { DXGI_FORMAT_BC4_SNORM,          CONV_FLAGS_NONE,        DDSPF_BC4_SNORM },
00060     { DXGI_FORMAT_BC5_UNORM,          CONV_FLAGS_NONE,        DDSPF_BC5_UNORM },
00061     { DXGI_FORMAT_BC5_SNORM,          CONV_FLAGS_NONE,        DDSPF_BC5_SNORM },
00062
00063     { DXGI_FORMAT_BC4_UNORM,          CONV_FLAGS_NONE,        { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC( 'A', 'T', 'I', '1' ), 0, 0, 0, 0, 0 } },
00064     { DXGI_FORMAT_BC5_UNORM,          CONV_FLAGS_NONE,        { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC( 'A', 'T', 'I', '2' ), 0, 0, 0, 0, 0 } },
00065
00066     { DXGI_FORMAT_R8G8_B8G8_UNORM,    CONV_FLAGS_NONE,        DDSPF_R8G8_B8G8 }, // D3DFMT_R8G8_B8G8
00067     { DXGI_FORMAT_G8R8_G8B8_UNORM,    CONV_FLAGS_NONE,        DDSPF_G8R8_G8B8 }, // D3DFMT_G8R8_G8B8
00068
00069     { DXGI_FORMAT_B8G8R8A8_UNORM,     CONV_FLAGS_NONE,        DDSPF_A8R8G8B8 }, // D3DFMT_A8R8G8B8 (uses DXGI 1.1 format)
00070     { DXGI_FORMAT_B8G8R8X8_UNORM,     CONV_FLAGS_NONE,        DDSPF_X8R8G8B8 }, // D3DFMT_X8R8G8B8 (uses DXGI 1.1 format)
00071     { DXGI_FORMAT_R8G8B8A8_UNORM,     CONV_FLAGS_NONE,        DDSPF_A8B8G8R8 }, // D3DFMT_A8B8G8R8
00072     { DXGI_FORMAT_R8G8B8A8_UNORM,     CONV_FLAGS_NOALPHA,     DDSPF_X8B8G8R8 }, // D3DFMT_X8B8G8R8
00073     { DXGI_FORMAT_R16G16_UNORM,       CONV_FLAGS_NONE,        DDSPF_G16R16   }, // D3DFMT_G16R16
00074
00075     { DXGI_FORMAT_R10G10B10A2_UNORM,  CONV_FLAGS_SWIZZLE,     { sizeof(DDS_PIXELFORMAT), DDS_RGB,       0, 32, 0x000003ff, 0x000ffc00, 0x3ff00000, 0xc0000000 } }, // D3DFMT_A2R10G10B10 (D3DX reversal issue workaround)
00076     { DXGI_FORMAT_R10G10B10A2_UNORM,  CONV_FLAGS_NONE,        { sizeof(DDS_PIXELFORMAT), DDS_RGB,       0, 32, 0x3ff00000, 0x000ffc00, 0x000003ff, 0xc0000000 } }, // D3DFMT_A2B10G10R10 (D3DX reversal issue workaround)
00077
00078     { DXGI_FORMAT_R8G8B8A8_UNORM,     CONV_FLAGS_EXPAND
00079                                       | CONV_FLAGS_NOALPHA
00080                                       | CONV_FLAGS_888,       DDSPF_R8G8B8 }, // D3DFMT_R8G8B8
00081
00082     { DXGI_FORMAT_B5G6R5_UNORM,       CONV_FLAGS_565,         DDSPF_R5G6B5 }, // D3DFMT_R5G6B5
00083     { DXGI_FORMAT_B5G5R5A1_UNORM,     CONV_FLAGS_5551,        DDSPF_A1R5G5B5 }, // D3DFMT_A1R5G5B5
00084     { DXGI_FORMAT_B5G5R5A1_UNORM,     CONV_FLAGS_5551
00085                                       | CONV_FLAGS_NOALPHA,   { sizeof(DDS_PIXELFORMAT), DDS_RGB,       0, 16, 0x7c00,     0x03e0,     0x001f,     0x0000     } }, // D3DFMT_X1R5G5B5
00086
00087     { DXGI_FORMAT_R8G8B8A8_UNORM,     CONV_FLAGS_EXPAND
00088                                       | CONV_FLAGS_8332,      { sizeof(DDS_PIXELFORMAT), DDS_RGB,       0, 16, 0x00e0,     0x001c,     0x0003,     0xff00     } }, // D3DFMT_A8R3G3B2
00089     { DXGI_FORMAT_B5G6R5_UNORM,       CONV_FLAGS_EXPAND
00090                                       | CONV_FLAGS_332,       { sizeof(DDS_PIXELFORMAT), DDS_RGB,       0,  8, 0xe0,       0x1c,       0x03,       0x00       } }, // D3DFMT_R3G3B2
00091
00092     { DXGI_FORMAT_R8_UNORM,           CONV_FLAGS_NONE,        DDSPF_L8   }, // D3DFMT_L8
00093     { DXGI_FORMAT_R16_UNORM,          CONV_FLAGS_NONE,        DDSPF_L16  }, // D3DFMT_L16
00094     { DXGI_FORMAT_R8G8_UNORM,         CONV_FLAGS_NONE,        DDSPF_A8L8 }, // D3DFMT_A8L8
00095
00096     { DXGI_FORMAT_A8_UNORM,           CONV_FLAGS_NONE,        DDSPF_A8   }, // D3DFMT_A8
00097
00098     { DXGI_FORMAT_R16G16B16A16_UNORM, CONV_FLAGS_NONE,        { sizeof(DDS_PIXELFORMAT), DDS_FOURCC,   36,  0, 0,          0,          0,          0          } }, // D3DFMT_A16B16G16R16
00099     { DXGI_FORMAT_R16G16B16A16_SNORM, CONV_FLAGS_NONE,        { sizeof(DDS_PIXELFORMAT), DDS_FOURCC,  110,  0, 0,          0,          0,          0          } }, // D3DFMT_Q16W16V16U16
00100     { DXGI_FORMAT_R16_FLOAT,          CONV_FLAGS_NONE,        { sizeof(DDS_PIXELFORMAT), DDS_FOURCC,  111,  0, 0,          0,          0,          0          } }, // D3DFMT_R16F
00101     { DXGI_FORMAT_R16G16_FLOAT,       CONV_FLAGS_NONE,        { sizeof(DDS_PIXELFORMAT), DDS_FOURCC,  112,  0, 0,          0,          0,          0          } }, // D3DFMT_G16R16F
00102     { DXGI_FORMAT_R16G16B16A16_FLOAT, CONV_FLAGS_NONE,        { sizeof(DDS_PIXELFORMAT), DDS_FOURCC,  113,  0, 0,          0,          0,          0          } }, // D3DFMT_A16B16G16R16F
00103     { DXGI_FORMAT_R32_FLOAT,          CONV_FLAGS_NONE,        { sizeof(DDS_PIXELFORMAT), DDS_FOURCC,  114,  0, 0,          0,          0,          0          } }, // D3DFMT_R32F
00104     { DXGI_FORMAT_R32G32_FLOAT,       CONV_FLAGS_NONE,        { sizeof(DDS_PIXELFORMAT), DDS_FOURCC,  115,  0, 0,          0,          0,          0          } }, // D3DFMT_G32R32F
00105     { DXGI_FORMAT_R32G32B32A32_FLOAT, CONV_FLAGS_NONE,        { sizeof(DDS_PIXELFORMAT), DDS_FOURCC,  116,  0, 0,          0,          0,          0          } }, // D3DFMT_A32B32G32R32F
00106
00107     { DXGI_FORMAT_R32_FLOAT,          CONV_FLAGS_NONE,        { sizeof(DDS_PIXELFORMAT), DDS_RGB,       0, 32, 0xffffffff, 0x00000000, 0x00000000, 0x00000000 } }, // D3DFMT_R32F (D3DX uses FourCC 114 instead)
00108
00109     { DXGI_FORMAT_R8G8B8A8_UNORM,     CONV_FLAGS_EXPAND
00110                                       | CONV_FLAGS_PAL8
00111                                       | CONV_FLAGS_A8P8,      { sizeof(DDS_PIXELFORMAT), DDS_PAL8,      0, 16, 0,          0,          0,          0         } }, // D3DFMT_A8P8
00112     { DXGI_FORMAT_R8G8B8A8_UNORM,     CONV_FLAGS_EXPAND
00113                                       | CONV_FLAGS_PAL8,      { sizeof(DDS_PIXELFORMAT), DDS_PAL8,      0,  8, 0,          0,          0,          0         } }, // D3DFMT_P8
00114
00115     { DXGI_FORMAT_B4G4R4A4_UNORM,     CONV_FLAGS_4444,        DDSPF_A4R4G4B4 }, // D3DFMT_A4R4G4B4 (uses DXGI 1.2 format)
00116     { DXGI_FORMAT_B4G4R4A4_UNORM,     CONV_FLAGS_NOALPHA
00117                                       | CONV_FLAGS_4444,      { sizeof(DDS_PIXELFORMAT), DDS_RGB,       0, 16, 0x0f00,     0x00f0,     0x000f,     0x0000     } }, // D3DFMT_X4R4G4B4 (uses DXGI 1.2 format)
00118     { DXGI_FORMAT_B4G4R4A4_UNORM,     CONV_FLAGS_EXPAND
00119                                       | CONV_FLAGS_44,        { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCE, 0,  8, 0x0f,       0x00,       0x00,       0xf0       } }, // D3DFMT_A4L4 (uses DXGI 1.2 format)
00120 };
00121
00122 // Note that many common DDS reader/writers (including D3DX) swap the
00123 // the RED/BLUE masks for 10:10:10:2 formats. We assumme
00124 // below that the 'backwards' header mask is being used since it is most
00125 // likely written by D3DX. The more robust solution is to use the 'DX10'
00126 // header extension and specify the DXGI_FORMAT_R10G10B10A2_UNORM format directly
00127
00128 // We do not support the following legacy Direct3D 9 formats:
00129 //      BumpDuDv D3DFMT_V8U8, D3DFMT_Q8W8V8U8, D3DFMT_V16U16, D3DFMT_A2W10V10U10
00130 //      BumpLuminance D3DFMT_L6V5U5, D3DFMT_X8L8V8U8
00131 //      FourCC "UYVY" D3DFMT_UYVY
00132 //      FourCC "YUY2" D3DFMT_YUY2
00133 //      FourCC 117 D3DFMT_CxV8U8
00134 //      ZBuffer D3DFMT_D16_LOCKABLE
00135 //      FourCC 82 D3DFMT_D32F_LOCKABLE
00136
00137 static DXGI_FORMAT _GetDXGIFormat( const DDS_PIXELFORMAT& ddpf, DWORD flags, _Inout_opt_ DWORD* convFlags )
00138 {
00139     const size_t MAP_SIZE = sizeof(g_LegacyDDSMap) / sizeof(LegacyDDS);
00140     size_t index = 0;
00141     for( index = 0; index < MAP_SIZE; ++index )
00142     {
00143         const LegacyDDS* entry = &g_LegacyDDSMap[index];
00144
00145         if ( ddpf.dwFlags & entry->ddpf.dwFlags )
00146         {
00147             if ( entry->ddpf.dwFlags & DDS_FOURCC )
00148             {
00149                 if ( ddpf.dwFourCC == entry->ddpf.dwFourCC )
00150                     break;
00151             }
00152             else if ( entry->ddpf.dwFlags & DDS_PAL8 )
00153             {
00154                 if (  ddpf.dwRGBBitCount == entry->ddpf.dwRGBBitCount )
00155                     break;
00156             }
00157             else if ( ddpf.dwRGBBitCount == entry->ddpf.dwRGBBitCount )
00158             {
00159                 // RGB, RGBA, ALPHA, LUMINANCE
00160                 if ( ddpf.dwRBitMask == entry->ddpf.dwRBitMask
00161                      && ddpf.dwGBitMask == entry->ddpf.dwGBitMask
00162                      && ddpf.dwBBitMask == entry->ddpf.dwBBitMask
00163                      && ddpf.dwABitMask == entry->ddpf.dwABitMask )
00164                     break;
00165             }
00166         }
00167     }
00168
00169     if ( index >= MAP_SIZE )
00170         return DXGI_FORMAT_UNKNOWN;
00171
00172     DWORD cflags = g_LegacyDDSMap[index].convFlags;
00173     DXGI_FORMAT format = g_LegacyDDSMap[index].format;
00174
00175     if ( (cflags & CONV_FLAGS_EXPAND) && (flags & DDS_FLAGS_NO_LEGACY_EXPANSION) )
00176         return DXGI_FORMAT_UNKNOWN;
00177
00178     if ( (format == DXGI_FORMAT_R10G10B10A2_UNORM) && (flags & DDS_FLAGS_NO_R10B10G10A2_FIXUP) )
00179     {
00180         cflags ^= CONV_FLAGS_SWIZZLE;
00181     }
00182
00183     if ( convFlags )
00184         *convFlags = cflags;
00185
00186     return format;
00187 }
00188
00189
00190 //-------------------------------------------------------------------------------------
00191 // Decodes DDS header including optional DX10 extended header
00192 //-------------------------------------------------------------------------------------
00193 static HRESULT _DecodeDDSHeader( _In_reads_bytes_(size) LPCVOID pSource, size_t size, DWORD flags, _Out_ TexMetadata& metadata,
00194                                  _Inout_opt_ DWORD* convFlags )
00195 {
00196     if ( !pSource )
00197         return E_INVALIDARG;
00198
00199     memset( &metadata, 0, sizeof(TexMetadata) );
00200
00201     if ( size < (sizeof(DDS_HEADER) + sizeof(uint32_t)) )
00202     {
00203         return HRESULT_FROM_WIN32( ERROR_INVALID_DATA );
00204     }
00205
00206     // DDS files always start with the same magic number ("DDS ")
00207     uint32_t dwMagicNumber = *reinterpret_cast<const uint32_t*>(pSource);
00208     if ( dwMagicNumber != DDS_MAGIC )
00209     {
00210         return E_FAIL;
00211     }
00212
00213     const DDS_HEADER* pHeader = reinterpret_cast<const DDS_HEADER*>( (const uint8_t*)pSource + sizeof( uint32_t ) );
00214     assert( pHeader );
00215
00216     // Verify header to validate DDS file
00217     if ( pHeader->dwSize != sizeof(DDS_HEADER)
00218          || pHeader->ddspf.dwSize != sizeof(DDS_PIXELFORMAT) )
00219     {
00220         return E_FAIL;
00221     }
00222
00223     metadata.mipLevels = pHeader->dwMipMapCount;
00224     if ( metadata.mipLevels == 0 )
00225         metadata.mipLevels = 1;
00226
00227     // Check for DX10 extension
00228     if ( (pHeader->ddspf.dwFlags & DDS_FOURCC)
00229          && (MAKEFOURCC( 'D', 'X', '1', '0' ) == pHeader->ddspf.dwFourCC) )
00230     {
00231         // Buffer must be big enough for both headers and magic value
00232         if ( size < (sizeof(DDS_HEADER)+sizeof(uint32_t)+sizeof(DDS_HEADER_DXT10)) )
00233         {
00234             return E_FAIL;
00235         }
00236
00237         const DDS_HEADER_DXT10* d3d10ext = reinterpret_cast<const DDS_HEADER_DXT10*>( (const uint8_t*)pSource + sizeof( uint32_t ) + sizeof(DDS_HEADER) );
00238         if ( convFlags )
00239             *convFlags |= CONV_FLAGS_DX10;
00240
00241         metadata.arraySize = d3d10ext->arraySize;
00242         if ( metadata.arraySize == 0 )
00243         {
00244             return HRESULT_FROM_WIN32( ERROR_INVALID_DATA );
00245         }
00246
00247         metadata.format = d3d10ext->dxgiFormat;
00248         if ( !IsValid( metadata.format ) )
00249         {
00250             HRESULT_FROM_WIN32( ERROR_INVALID_DATA );
00251         }
00252
00253         switch ( d3d10ext->resourceDimension )
00254         {
00255         case DDS_DIMENSION_TEXTURE1D:
00256
00257             // D3DX writes 1D textures with a fixed Height of 1
00258             if ( (pHeader->dwFlags & DDS_HEIGHT) && pHeader->dwHeight != 1 )
00259             {
00260                 return HRESULT_FROM_WIN32( ERROR_INVALID_DATA );
00261             }
00262
00263             metadata.width = pHeader->dwWidth;
00264             metadata.height = 1;
00265             metadata.depth = 1;
00266             metadata.dimension = TEX_DIMENSION_TEXTURE1D;
00267             break;
00268
00269         case DDS_DIMENSION_TEXTURE2D:
00270             if ( d3d10ext->miscFlag & DDS_RESOURCE_MISC_TEXTURECUBE )
00271             {
00272                 metadata.miscFlags |= TEX_MISC_TEXTURECUBE;
00273                 metadata.arraySize *= 6;
00274             }
00275
00276             metadata.width = pHeader->dwWidth;
00277             metadata.height = pHeader->dwHeight;
00278             metadata.depth = 1;
00279             metadata.dimension = TEX_DIMENSION_TEXTURE2D;
00280             break;
00281
00282         case DDS_DIMENSION_TEXTURE3D:
00283             if ( !(pHeader->dwFlags & DDS_HEADER_FLAGS_VOLUME) )
00284             {
00285                 return HRESULT_FROM_WIN32( ERROR_INVALID_DATA );
00286             }
00287
00288             if ( metadata.arraySize > 1 )
00289                 return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
00290
00291             metadata.width = pHeader->dwWidth;
00292             metadata.height = pHeader->dwHeight;
00293             metadata.depth = pHeader->dwDepth;
00294             metadata.dimension = TEX_DIMENSION_TEXTURE3D;
00295             break;
00296
00297         default:
00298             return HRESULT_FROM_WIN32( ERROR_INVALID_DATA );
00299         }
00300     }
00301     else
00302     {
00303         metadata.arraySize = 1;
00304
00305         if ( pHeader->dwFlags & DDS_HEADER_FLAGS_VOLUME )
00306         {
00307             metadata.width = pHeader->dwWidth;
00308             metadata.height = pHeader->dwHeight;
00309             metadata.depth = pHeader->dwDepth;
00310             metadata.dimension = TEX_DIMENSION_TEXTURE3D;
00311         }
00312         else
00313         {
00314             if ( pHeader->dwCaps2 & DDS_CUBEMAP )
00315             {
00316                // We require all six faces to be defined
00317                if ( (pHeader->dwCaps2 & DDS_CUBEMAP_ALLFACES ) != DDS_CUBEMAP_ALLFACES )
00318                    return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
00319
00320                 metadata.arraySize = 6;
00321                 metadata.miscFlags |= TEX_MISC_TEXTURECUBE;
00322             }
00323
00324             metadata.width = pHeader->dwWidth;
00325             metadata.height = pHeader->dwHeight;
00326             metadata.depth = 1;
00327             metadata.dimension = TEX_DIMENSION_TEXTURE2D;
00328
00329             // Note there's no way for a legacy Direct3D 9 DDS to express a '1D' texture
00330         }
00331
00332         metadata.format = _GetDXGIFormat( pHeader->ddspf, flags, convFlags );
00333
00334         if ( metadata.format == DXGI_FORMAT_UNKNOWN )
00335             return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
00336     }
00337
00338     // Special flag for handling BGR DXGI 1.1 formats
00339     if (flags & DDS_FLAGS_FORCE_RGB)
00340     {
00341         switch ( metadata.format )
00342         {
00343         case DXGI_FORMAT_B8G8R8A8_UNORM:
00344             metadata.format = DXGI_FORMAT_R8G8B8A8_UNORM;
00345             if ( convFlags )
00346                 *convFlags |= CONV_FLAGS_SWIZZLE;
00347             break;
00348
00349         case DXGI_FORMAT_B8G8R8X8_UNORM:
00350             metadata.format = DXGI_FORMAT_R8G8B8A8_UNORM;
00351             if ( convFlags )
00352                 *convFlags |= CONV_FLAGS_SWIZZLE | CONV_FLAGS_NOALPHA;
00353             break;
00354
00355         case DXGI_FORMAT_B8G8R8A8_TYPELESS:
00356             metadata.format = DXGI_FORMAT_R8G8B8A8_TYPELESS;
00357             if ( convFlags )
00358                 *convFlags |= CONV_FLAGS_SWIZZLE;
00359             break;
00360
00361         case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
00362             metadata.format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
00363             if ( convFlags )
00364                 *convFlags |= CONV_FLAGS_SWIZZLE;
00365             break;
00366
00367         case DXGI_FORMAT_B8G8R8X8_TYPELESS:
00368             metadata.format = DXGI_FORMAT_R8G8B8A8_TYPELESS;
00369             if ( convFlags )
00370                 *convFlags |= CONV_FLAGS_SWIZZLE | CONV_FLAGS_NOALPHA;
00371             break;
00372
00373         case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB:
00374             metadata.format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
00375             if ( convFlags )
00376                 *convFlags |= CONV_FLAGS_SWIZZLE | CONV_FLAGS_NOALPHA;
00377             break;
00378         }
00379     }
00380
00381     // Special flag for handling 16bpp formats
00382     if (flags & DDS_FLAGS_NO_16BPP)
00383     {
00384         switch ( metadata.format )
00385         {
00386         case DXGI_FORMAT_B5G6R5_UNORM:
00387         case DXGI_FORMAT_B5G5R5A1_UNORM:
00388         case DXGI_FORMAT_B4G4R4A4_UNORM:
00389             metadata.format = DXGI_FORMAT_R8G8B8A8_UNORM;
00390             if ( convFlags )
00391             {
00392                 *convFlags |= CONV_FLAGS_EXPAND;
00393                 if ( metadata.format == DXGI_FORMAT_B5G6R5_UNORM )
00394                     *convFlags |= CONV_FLAGS_NOALPHA;
00395             }
00396         }
00397     }
00398
00399     return S_OK;
00400 }
00401
00402
00403 //-------------------------------------------------------------------------------------
00404 // Encodes DDS file header (magic value, header, optional DX10 extended header)
00405 //-------------------------------------------------------------------------------------
00406 _Use_decl_annotations_
00407 HRESULT _EncodeDDSHeader( const TexMetadata& metadata, DWORD flags,
00408                           LPVOID pDestination, size_t maxsize, size_t& required )
00409 {
00410     assert( IsValid( metadata.format ) && !IsVideo( metadata.format ) );
00411
00412     if ( metadata.arraySize > 1 )
00413     {
00414         if ( (metadata.arraySize != 6) || (metadata.dimension != TEX_DIMENSION_TEXTURE2D) || !(metadata.miscFlags & TEX_MISC_TEXTURECUBE) )
00415         {
00416             flags |= DDS_FLAGS_FORCE_DX10_EXT;
00417         }
00418     }
00419
00420     DDS_PIXELFORMAT ddpf = { 0 };
00421     if ( !(flags & DDS_FLAGS_FORCE_DX10_EXT) )
00422     {
00423         switch( metadata.format )
00424         {
00425         case DXGI_FORMAT_R8G8B8A8_UNORM:        memcpy_s( &ddpf, sizeof(ddpf), &DDSPF_A8B8G8R8, sizeof(DDS_PIXELFORMAT) ); break;
00426         case DXGI_FORMAT_R16G16_UNORM:          memcpy_s( &ddpf, sizeof(ddpf), &DDSPF_G16R16, sizeof(DDS_PIXELFORMAT) ); break;
00427         case DXGI_FORMAT_R8G8_UNORM:            memcpy_s( &ddpf, sizeof(ddpf), &DDSPF_A8L8, sizeof(DDS_PIXELFORMAT) ); break;
00428         case DXGI_FORMAT_R16_UNORM:             memcpy_s( &ddpf, sizeof(ddpf), &DDSPF_L16, sizeof(DDS_PIXELFORMAT) ); break;
00429         case DXGI_FORMAT_R8_UNORM:              memcpy_s( &ddpf, sizeof(ddpf), &DDSPF_L8, sizeof(DDS_PIXELFORMAT) ); break;
00430         case DXGI_FORMAT_A8_UNORM:              memcpy_s( &ddpf, sizeof(ddpf), &DDSPF_A8, sizeof(DDS_PIXELFORMAT) ); break;
00431         case DXGI_FORMAT_R8G8_B8G8_UNORM:       memcpy_s( &ddpf, sizeof(ddpf), &DDSPF_R8G8_B8G8, sizeof(DDS_PIXELFORMAT) ); break;
00432         case DXGI_FORMAT_G8R8_G8B8_UNORM:       memcpy_s( &ddpf, sizeof(ddpf), &DDSPF_G8R8_G8B8, sizeof(DDS_PIXELFORMAT) ); break;
00433         case DXGI_FORMAT_BC1_UNORM:             memcpy_s( &ddpf, sizeof(ddpf), &DDSPF_DXT1, sizeof(DDS_PIXELFORMAT) ); break;
00434         case DXGI_FORMAT_BC2_UNORM:             memcpy_s( &ddpf, sizeof(ddpf), &DDSPF_DXT3, sizeof(DDS_PIXELFORMAT) ); break;
00435         case DXGI_FORMAT_BC3_UNORM:             memcpy_s( &ddpf, sizeof(ddpf), &DDSPF_DXT5, sizeof(DDS_PIXELFORMAT) ); break;
00436         case DXGI_FORMAT_BC4_UNORM:             memcpy_s( &ddpf, sizeof(ddpf), &DDSPF_BC4_UNORM, sizeof(DDS_PIXELFORMAT) ); break;
00437         case DXGI_FORMAT_BC4_SNORM:             memcpy_s( &ddpf, sizeof(ddpf), &DDSPF_BC4_SNORM, sizeof(DDS_PIXELFORMAT) ); break;
00438         case DXGI_FORMAT_BC5_UNORM:             memcpy_s( &ddpf, sizeof(ddpf), &DDSPF_BC5_UNORM, sizeof(DDS_PIXELFORMAT) ); break;
00439         case DXGI_FORMAT_BC5_SNORM:             memcpy_s( &ddpf, sizeof(ddpf), &DDSPF_BC5_SNORM, sizeof(DDS_PIXELFORMAT) ); break;
00440         case DXGI_FORMAT_B5G6R5_UNORM:          memcpy_s( &ddpf, sizeof(ddpf), &DDSPF_R5G6B5, sizeof(DDS_PIXELFORMAT) ); break;
00441         case DXGI_FORMAT_B5G5R5A1_UNORM:        memcpy_s( &ddpf, sizeof(ddpf), &DDSPF_A1R5G5B5, sizeof(DDS_PIXELFORMAT) ); break;
00442         case DXGI_FORMAT_B8G8R8A8_UNORM:        memcpy_s( &ddpf, sizeof(ddpf), &DDSPF_A8R8G8B8, sizeof(DDS_PIXELFORMAT) ); break; // DXGI 1.1
00443         case DXGI_FORMAT_B8G8R8X8_UNORM:        memcpy_s( &ddpf, sizeof(ddpf), &DDSPF_X8R8G8B8, sizeof(DDS_PIXELFORMAT) ); break; // DXGI 1.1
00444         case DXGI_FORMAT_B4G4R4A4_UNORM:        memcpy_s( &ddpf, sizeof(ddpf), &DDSPF_A4R4G4B4, sizeof(DDS_PIXELFORMAT) ); break;
00445
00446         // Legacy D3DX formats using D3DFMT enum value as FourCC
00447         case DXGI_FORMAT_R32G32B32A32_FLOAT:
00448             ddpf.dwSize = sizeof(DDS_PIXELFORMAT); ddpf.dwFlags = DDS_FOURCC; ddpf.dwFourCC = 116;  // D3DFMT_A32B32G32R32F
00449             break;
00450         case DXGI_FORMAT_R16G16B16A16_FLOAT:
00451             ddpf.dwSize = sizeof(DDS_PIXELFORMAT); ddpf.dwFlags = DDS_FOURCC; ddpf.dwFourCC = 113;  // D3DFMT_A16B16G16R16F
00452             break;
00453         case DXGI_FORMAT_R16G16B16A16_UNORM:
00454             ddpf.dwSize = sizeof(DDS_PIXELFORMAT); ddpf.dwFlags = DDS_FOURCC; ddpf.dwFourCC = 36;  // D3DFMT_A16B16G16R16
00455             break;
00456         case DXGI_FORMAT_R16G16B16A16_SNORM:
00457             ddpf.dwSize = sizeof(DDS_PIXELFORMAT); ddpf.dwFlags = DDS_FOURCC; ddpf.dwFourCC = 110;  // D3DFMT_Q16W16V16U16
00458             break;
00459         case DXGI_FORMAT_R32G32_FLOAT:
00460             ddpf.dwSize = sizeof(DDS_PIXELFORMAT); ddpf.dwFlags = DDS_FOURCC; ddpf.dwFourCC = 115;  // D3DFMT_G32R32F
00461             break;
00462        case DXGI_FORMAT_R16G16_FLOAT:
00463             ddpf.dwSize = sizeof(DDS_PIXELFORMAT); ddpf.dwFlags = DDS_FOURCC; ddpf.dwFourCC = 112;  // D3DFMT_G16R16F
00464             break;
00465         case DXGI_FORMAT_R32_FLOAT:
00466             ddpf.dwSize = sizeof(DDS_PIXELFORMAT); ddpf.dwFlags = DDS_FOURCC; ddpf.dwFourCC = 114;  // D3DFMT_R32F
00467             break;
00468         case DXGI_FORMAT_R16_FLOAT:
00469             ddpf.dwSize = sizeof(DDS_PIXELFORMAT); ddpf.dwFlags = DDS_FOURCC; ddpf.dwFourCC = 111;  // D3DFMT_R16F
00470             break;
00471         }
00472     }
00473
00474     required = sizeof(uint32_t) + sizeof(DDS_HEADER);
00475
00476     if ( ddpf.dwSize == 0 )
00477         required += sizeof(DDS_HEADER_DXT10);
00478
00479     if ( !pDestination )
00480         return S_OK;
00481
00482     if ( maxsize < required )
00483         return E_NOT_SUFFICIENT_BUFFER;
00484
00485     *reinterpret_cast<uint32_t*>(pDestination) = DDS_MAGIC;
00486
00487     DDS_HEADER* header = reinterpret_cast<DDS_HEADER*>( reinterpret_cast<uint8_t*>(pDestination) + sizeof(uint32_t) );
00488     assert( header );
00489
00490     memset( header, 0, sizeof(DDS_HEADER ) );
00491     header->dwSize = sizeof( DDS_HEADER );
00492     header->dwFlags = DDS_HEADER_FLAGS_TEXTURE;
00493     header->dwCaps = DDS_SURFACE_FLAGS_TEXTURE;
00494
00495     if (metadata.mipLevels > 0)
00496     {
00497         header->dwFlags |= DDS_HEADER_FLAGS_MIPMAP;
00498
00499 #ifdef _AMD64_
00500         if ( metadata.mipLevels > 0xFFFFFFFF )
00501             return E_INVALIDARG;
00502 #endif
00503
00504         header->dwMipMapCount = static_cast<uint32_t>( metadata.mipLevels );
00505
00506         if ( header->dwMipMapCount > 1 )
00507             header->dwCaps |= DDS_SURFACE_FLAGS_MIPMAP;
00508     }
00509
00510     switch( metadata.dimension )
00511     {
00512     case TEX_DIMENSION_TEXTURE1D:
00513 #ifdef _AMD64_
00514         if ( metadata.height > 0xFFFFFFFF )
00515             return E_INVALIDARG;
00516 #endif
00517
00518         header->dwHeight = static_cast<uint32_t>( metadata.height );
00519         header->dwWidth = header->dwDepth = 1;
00520         break;
00521
00522     case TEX_DIMENSION_TEXTURE2D:
00523 #ifdef _AMD64_
00524         if ( metadata.height > 0xFFFFFFFF
00525              || metadata.width > 0xFFFFFFFF)
00526             return E_INVALIDARG;
00527 #endif
00528
00529         header->dwHeight = static_cast<uint32_t>( metadata.height );
00530         header->dwWidth = static_cast<uint32_t>( metadata.width );
00531         header->dwDepth = 1;
00532
00533         if ( metadata.miscFlags & TEX_MISC_TEXTURECUBE )
00534         {
00535             header->dwCaps |= DDS_SURFACE_FLAGS_CUBEMAP;
00536             header->dwCaps2 |= DDS_CUBEMAP_ALLFACES;
00537         }
00538         break;
00539
00540     case TEX_DIMENSION_TEXTURE3D:
00541 #ifdef _AMD64_
00542         if ( metadata.height > 0xFFFFFFFF
00543              || metadata.width > 0xFFFFFFFF
00544              || metadata.depth > 0xFFFFFFFF )
00545             return E_INVALIDARG;
00546 #endif
00547
00548         header->dwFlags |= DDS_HEADER_FLAGS_VOLUME;
00549         header->dwCaps2 |= DDS_FLAGS_VOLUME;
00550         header->dwHeight = static_cast<uint32_t>( metadata.height );
00551         header->dwWidth = static_cast<uint32_t>( metadata.width );
00552         header->dwDepth = static_cast<uint32_t>( metadata.depth );
00553         break;
00554
00555     default:
00556         return E_FAIL;
00557     }
00558
00559     size_t rowPitch, slicePitch;
00560     ComputePitch( metadata.format, metadata.width, metadata.height, rowPitch, slicePitch, CP_FLAGS_NONE );
00561
00562 #ifdef _AMD64_
00563     if ( slicePitch > 0xFFFFFFFF
00564          || rowPitch > 0xFFFFFFFF )
00565         return E_FAIL;
00566 #endif
00567
00568     if ( IsCompressed( metadata.format ) )
00569     {
00570         header->dwFlags |= DDS_HEADER_FLAGS_LINEARSIZE;
00571         header->dwPitchOrLinearSize = static_cast<uint32_t>( slicePitch );
00572     }
00573     else
00574     {
00575         header->dwFlags |= DDS_HEADER_FLAGS_PITCH;
00576         header->dwPitchOrLinearSize = static_cast<uint32_t>( rowPitch );
00577     }
00578
00579     if ( ddpf.dwSize == 0 )
00580     {
00581         memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_DX10, sizeof(DDS_PIXELFORMAT) );
00582
00583         DDS_HEADER_DXT10* ext = reinterpret_cast<DDS_HEADER_DXT10*>( reinterpret_cast<uint8_t*>(header) + sizeof(DDS_HEADER) );
00584         assert( ext );
00585
00586         memset( ext, 0, sizeof(DDS_HEADER_DXT10) );
00587         ext->dxgiFormat = metadata.format;
00588         ext->resourceDimension = metadata.dimension;
00589
00590 #ifdef _AMD64_
00591         if ( metadata.arraySize > 0xFFFFFFFF )
00592             return E_INVALIDARG;
00593 #endif
00594
00595         if ( metadata.miscFlags & TEX_MISC_TEXTURECUBE )
00596         {
00597             ext->miscFlag |= TEX_MISC_TEXTURECUBE;
00598             assert( (metadata.arraySize % 6) == 0 );
00599             ext->arraySize = static_cast<UINT>( metadata.arraySize / 6 );
00600         }
00601         else
00602         {
00603             ext->arraySize = static_cast<UINT>( metadata.arraySize );
00604         }
00605     }
00606     else
00607     {
00608         memcpy_s( &header->ddspf, sizeof(header->ddspf), &ddpf, sizeof(ddpf) );
00609     }
00610
00611     return S_OK;
00612 }
00613
00614
00615 //-------------------------------------------------------------------------------------
00616 // Converts an image row with optional clearing of alpha value to 1.0
00617 // Returns true if supported, false if expansion case not supported
00618 //-------------------------------------------------------------------------------------
00619 enum TEXP_LEGACY_FORMAT
00620 {
00621     TEXP_LEGACY_UNKNOWN     = 0,
00622     TEXP_LEGACY_R8G8B8,
00623     TEXP_LEGACY_R3G3B2,
00624     TEXP_LEGACY_A8R3G3B2,
00625     TEXP_LEGACY_P8,
00626     TEXP_LEGACY_A8P8,
00627     TEXP_LEGACY_A4L4,
00628     TEXP_LEGACY_B4G4R4A4,
00629 };
00630
00631 inline static TEXP_LEGACY_FORMAT _FindLegacyFormat( DWORD flags )
00632 {
00633     TEXP_LEGACY_FORMAT lformat = TEXP_LEGACY_UNKNOWN;
00634
00635     if ( flags & CONV_FLAGS_PAL8 )
00636     {
00637         lformat = ( flags & CONV_FLAGS_A8P8 ) ? TEXP_LEGACY_A8P8 : TEXP_LEGACY_P8;
00638     }
00639     else if ( flags & CONV_FLAGS_888 )
00640         lformat = TEXP_LEGACY_R8G8B8;
00641     else if ( flags & CONV_FLAGS_332 )
00642         lformat = TEXP_LEGACY_R3G3B2;
00643     else if ( flags & CONV_FLAGS_8332 )
00644         lformat = TEXP_LEGACY_A8R3G3B2;
00645     else if ( flags & CONV_FLAGS_44 )
00646         lformat = TEXP_LEGACY_A4L4;
00647     else if ( flags & CONV_FLAGS_4444 )
00648         lformat = TEXP_LEGACY_B4G4R4A4;
00649
00650     return lformat;
00651 }
00652
00653 _Success_(return != false)
00654 static bool _LegacyExpandScanline( _Out_writes_bytes_(outSize) LPVOID pDestination, size_t outSize, _In_ DXGI_FORMAT outFormat,
00655                                    _In_reads_bytes_(inSize) LPCVOID pSource, size_t inSize, _In_ TEXP_LEGACY_FORMAT inFormat,
00656                                    _In_reads_opt_(256) const uint32_t* pal8, _In_ DWORD flags )
00657 {
00658     assert( pDestination && outSize > 0 );
00659     assert( pSource && inSize > 0 );
00660     assert( IsValid(outFormat) && !IsVideo(outFormat) );
00661
00662     switch( inFormat )
00663     {
00664     case TEXP_LEGACY_R8G8B8:
00665         if ( outFormat != DXGI_FORMAT_R8G8B8A8_UNORM )
00666             return false;
00667
00668         // D3DFMT_R8G8B8 -> DXGI_FORMAT_R8G8B8A8_UNORM
00669         {
00670             const uint8_t * __restrict sPtr = reinterpret_cast<const uint8_t*>(pSource);
00671             uint32_t * __restrict dPtr = reinterpret_cast<uint32_t*>(pDestination);
00672
00673             for( size_t ocount = 0, icount = 0; ((icount < inSize) && (ocount < outSize)); icount += 3, ocount += 4 )
00674             {
00675                 uint32_t t1 = *sPtr;
00676                 uint32_t t2 = ( *(sPtr+1) << 8 );
00677                 uint32_t t3 = ( *(sPtr+2) << 16 );
00678
00679                 *(dPtr++) = t1 | t2 | t3 | 0xff000000;
00680                 sPtr += 3;
00681             }
00682         }
00683         return true;
00684
00685     case TEXP_LEGACY_R3G3B2:
00686         switch( outFormat )
00687         {
00688         case DXGI_FORMAT_R8G8B8A8_UNORM:
00689             // D3DFMT_R3G3B2 -> DXGI_FORMAT_R8G8B8A8_UNORM
00690             {
00691                 const uint8_t* __restrict sPtr = reinterpret_cast<const uint8_t*>(pSource);
00692                 uint32_t * __restrict dPtr = reinterpret_cast<uint32_t*>(pDestination);
00693
00694                 for( size_t ocount = 0, icount = 0; ((icount < inSize) && (ocount < outSize)); ++icount, ocount += 4 )
00695                 {
00696                     uint8_t t = *(sPtr++);
00697
00698                     uint32_t t1 = (t & 0xe0) | ((t & 0xe0) >> 3) | ((t & 0xc0) >> 6);
00699                     uint32_t t2 = ((t & 0x1c) << 11) | ((t & 0x1c) << 8) | ((t & 0x18) << 5);
00700                     uint32_t t3 = ((t & 0x03) << 22) | ((t & 0x03) << 20) | ((t & 0x03) << 18) | ((t & 0x03) << 16);
00701
00702                     *(dPtr++) = t1 | t2 | t3 | 0xff000000;
00703                 }
00704             }
00705             return true;
00706
00707         case DXGI_FORMAT_B5G6R5_UNORM:
00708             // D3DFMT_R3G3B2 -> DXGI_FORMAT_B5G6R5_UNORM
00709             {
00710                 const uint8_t* __restrict sPtr = reinterpret_cast<const uint8_t*>(pSource);
00711                 uint16_t * __restrict dPtr = reinterpret_cast<uint16_t*>(pDestination);
00712
00713                 for( size_t ocount = 0, icount = 0; ((icount < inSize) && (ocount < outSize)); ++icount, ocount += 2 )
00714                 {
00715                     uint8_t t = *(sPtr++);
00716
00717                     uint16_t t1 = ((t & 0xe0) << 8) | ((t & 0xc0) << 5);
00718                     uint16_t t2 = ((t & 0x1c) << 6) | ((t & 0x1c) << 3);
00719                     uint16_t t3 = ((t & 0x03) << 3) | ((t & 0x03) << 1) | ((t & 0x02) >> 1);
00720
00721                     *(dPtr++) = t1 | t2 | t3;
00722                 }
00723             }
00724             return true;
00725         }
00726         break;
00727
00728     case TEXP_LEGACY_A8R3G3B2:
00729         if ( outFormat != DXGI_FORMAT_R8G8B8A8_UNORM )
00730             return false;
00731
00732         // D3DFMT_A8R3G3B2 -> DXGI_FORMAT_R8G8B8A8_UNORM
00733         {
00734             const uint16_t* __restrict sPtr = reinterpret_cast<const uint16_t*>(pSource);
00735             uint32_t * __restrict dPtr = reinterpret_cast<uint32_t*>(pDestination);
00736
00737             for( size_t ocount = 0, icount = 0; ((icount < inSize) && (ocount < outSize)); icount += 2, ocount += 4 )
00738             {
00739                 uint16_t t = *(sPtr++);
00740
00741                 uint32_t t1 = (t & 0x00e0) | ((t & 0x00e0) >> 3) | ((t & 0x00c0) >> 6);
00742                 uint32_t t2 = ((t & 0x001c) << 11) | ((t & 0x001c) << 8) | ((t & 0x0018) << 5);
00743                 uint32_t t3 = ((t & 0x0003) << 22) | ((t & 0x0003) << 20) | ((t & 0x0003) << 18) | ((t & 0x0003) << 16);
00744                 uint32_t ta = ( flags & TEXP_SCANLINE_SETALPHA ) ? 0xff000000 : ((t & 0xff00) << 16);
00745
00746                 *(dPtr++) = t1 | t2 | t3 | ta;
00747             }
00748         }
00749         return true;
00750
00751     case TEXP_LEGACY_P8:
00752         if ( (outFormat != DXGI_FORMAT_R8G8B8A8_UNORM) || !pal8 )
00753             return false;
00754
00755         // D3DFMT_P8 -> DXGI_FORMAT_R8G8B8A8_UNORM
00756         {
00757             const uint8_t* __restrict sPtr = reinterpret_cast<const uint8_t*>(pSource);
00758             uint32_t * __restrict dPtr = reinterpret_cast<uint32_t*>(pDestination);
00759
00760             for( size_t ocount = 0, icount = 0; ((icount < inSize) && (ocount < outSize)); ++icount, ocount += 4 )
00761             {
00762                 uint8_t t = *(sPtr++);
00763
00764                 *(dPtr++) = pal8[ t ];
00765             }
00766         }
00767         return true;
00768
00769     case TEXP_LEGACY_A8P8:
00770         if ( (outFormat != DXGI_FORMAT_R8G8B8A8_UNORM) || !pal8 )
00771             return false;
00772
00773         // D3DFMT_A8P8 -> DXGI_FORMAT_R8G8B8A8_UNORM
00774         {
00775             const uint16_t* __restrict sPtr = reinterpret_cast<const uint16_t*>(pSource);
00776             uint32_t * __restrict dPtr = reinterpret_cast<uint32_t*>(pDestination);
00777
00778             for( size_t ocount = 0, icount = 0; ((icount < inSize) && (ocount < outSize)); icount += 2, ocount += 4 )
00779             {
00780                 uint16_t t = *(sPtr++);
00781
00782                 uint32_t t1 = pal8[ t & 0xff ];
00783                 uint32_t ta = ( flags & TEXP_SCANLINE_SETALPHA ) ? 0xff000000 : ((t & 0xff00) << 16);
00784
00785                 *(dPtr++) = t1 | ta;
00786             }
00787         }
00788         return true;
00789
00790     case TEXP_LEGACY_A4L4:
00791         switch( outFormat )
00792         {
00793         case DXGI_FORMAT_B4G4R4A4_UNORM :
00794             // D3DFMT_A4L4 -> DXGI_FORMAT_B4G4R4A4_UNORM
00795             {
00796                 const uint8_t * __restrict sPtr = reinterpret_cast<const uint8_t*>(pSource);
00797                 uint16_t * __restrict dPtr = reinterpret_cast<uint16_t*>(pDestination);
00798
00799                 for( size_t ocount = 0, icount = 0; ((icount < inSize) && (ocount < outSize)); ++icount, ocount += 2 )
00800                 {
00801                     uint8_t t = *(sPtr++);
00802
00803                     uint16_t t1 = (t & 0x0f);
00804                     uint16_t ta = ( flags & TEXP_SCANLINE_SETALPHA ) ? 0xf000 : ((t & 0xf0) << 8);
00805
00806                     *(dPtr++) = t1 | (t1 << 4) | (t1 << 8) | ta;
00807                 }
00808             }
00809             return true;
00810
00811         case DXGI_FORMAT_R8G8B8A8_UNORM:
00812             // D3DFMT_A4L4 -> DXGI_FORMAT_R8G8B8A8_UNORM
00813             {
00814                 const uint8_t * __restrict sPtr = reinterpret_cast<const uint8_t*>(pSource);
00815                 uint32_t * __restrict dPtr = reinterpret_cast<uint32_t*>(pDestination);
00816
00817                 for( size_t ocount = 0, icount = 0; ((icount < inSize) && (ocount < outSize)); ++icount, ocount += 4 )
00818                 {
00819                     uint8_t t = *(sPtr++);
00820
00821                     uint32_t t1 = ((t & 0x0f) << 4) | (t & 0x0f);
00822                     uint32_t ta = ( flags & TEXP_SCANLINE_SETALPHA ) ? 0xff000000 : (((t & 0xf0) << 24) | ((t & 0xf0) << 20));
00823
00824                     *(dPtr++) = t1 | (t1 << 8) | (t1 << 16) | ta;
00825                 }
00826             }
00827             return true;
00828         }
00829         break;
00830
00831     case TEXP_LEGACY_B4G4R4A4:
00832         if (outFormat != DXGI_FORMAT_R8G8B8A8_UNORM)
00833             return false;
00834
00835         // D3DFMT_A4R4G4B4 -> DXGI_FORMAT_R8G8B8A8_UNORM
00836         {
00837             const uint16_t * __restrict sPtr = reinterpret_cast<const uint16_t*>(pSource);
00838             uint32_t * __restrict dPtr = reinterpret_cast<uint32_t*>(pDestination);
00839
00840             for( size_t ocount = 0, icount = 0; ((icount < inSize) && (ocount < outSize)); icount += 2, ocount += 4 )
00841             {
00842                 uint16_t t = *(sPtr++);
00843
00844                 uint32_t t1 = ((t & 0x0f00) >> 4) | ((t & 0x0f00) >> 8);
00845                 uint32_t t2 = ((t & 0x00f0) << 8) | ((t & 0x00f0) << 4);
00846                 uint32_t t3 = ((t & 0x000f) << 20) | ((t & 0x000f) << 16);
00847                 uint32_t ta = ( flags & TEXP_SCANLINE_SETALPHA ) ? 0xff000000 : (((t & 0xf000) << 16) | ((t & 0xf000) << 12));
00848
00849                 *(dPtr++) = t1 | t2 | t3 | ta;
00850             }
00851         }
00852         return true;
00853     }
00854
00855     return false;
00856 }
00857
00858
00859 //-------------------------------------------------------------------------------------
00860 // Converts or copies image data from pPixels into scratch image data
00861 //-------------------------------------------------------------------------------------
00862 static HRESULT _CopyImage( _In_reads_bytes_(size) const void* pPixels, _In_ size_t size,
00863                            _In_ const TexMetadata& metadata, _In_ DWORD cpFlags, _In_ DWORD convFlags, _In_reads_opt_(256) const uint32_t *pal8, _In_ const ScratchImage& image )
00864 {
00865     assert( pPixels );
00866     assert( image.GetPixels() );
00867
00868     if ( !size )
00869         return E_FAIL;
00870
00871     if ( convFlags & CONV_FLAGS_EXPAND )
00872     {
00873         if ( convFlags & CONV_FLAGS_888 )
00874             cpFlags |= CP_FLAGS_24BPP;
00875         else if ( convFlags & (CONV_FLAGS_565 | CONV_FLAGS_5551 | CONV_FLAGS_4444 | CONV_FLAGS_8332 | CONV_FLAGS_A8P8 ) )
00876             cpFlags |= CP_FLAGS_16BPP;
00877         else if ( convFlags & (CONV_FLAGS_44 | CONV_FLAGS_332 | CONV_FLAGS_PAL8) )
00878             cpFlags |= CP_FLAGS_8BPP;
00879     }
00880
00881     size_t pixelSize, nimages;
00882     _DetermineImageArray( metadata, cpFlags, nimages, pixelSize );
00883     if ( (nimages == 0) || (nimages != image.GetImageCount()) )
00884     {
00885         return E_FAIL;
00886     }
00887
00888     assert( pixelSize <= size );
00889
00890     std::unique_ptr<Image[]> timages( new Image[nimages] );
00891     if ( !_SetupImageArray( (uint8_t*)pPixels, size, metadata, cpFlags, timages.get(), nimages ) )
00892     {
00893         return E_FAIL;
00894     }
00895
00896     if ( nimages != image.GetImageCount() )
00897     {
00898         return E_FAIL;
00899     }
00900
00901     const Image* images = image.GetImages();
00902     if ( !images )
00903     {
00904         return E_FAIL;
00905     }
00906
00907     DWORD tflags = (convFlags & CONV_FLAGS_NOALPHA) ? TEXP_SCANLINE_SETALPHA : 0;
00908     if ( convFlags & CONV_FLAGS_SWIZZLE )
00909         tflags |= TEXP_SCANLINE_LEGACY;
00910
00911     switch (metadata.dimension)
00912     {
00913     case TEX_DIMENSION_TEXTURE1D:
00914     case TEX_DIMENSION_TEXTURE2D:
00915         {
00916             size_t index = 0;
00917             for( size_t item = 0; item < metadata.arraySize; ++item )
00918             {
00919                 for( size_t level = 0; level < metadata.mipLevels; ++level, ++index )
00920                 {
00921                     if ( index >= nimages )
00922                         return E_FAIL;
00923
00924                     if ( images[ index ].height != timages[ index ].height )
00925                         return E_FAIL;
00926
00927                     size_t dpitch = images[ index ].rowPitch;
00928                     size_t spitch = timages[ index ].rowPitch;
00929
00930                     const uint8_t *pSrc = const_cast<const uint8_t*>( timages[ index ].pixels );
00931                     if ( !pSrc )
00932                         return E_POINTER;
00933
00934                     uint8_t *pDest = images[ index ].pixels;
00935                     if ( !pDest )
00936                         return E_POINTER;
00937
00938                     if ( IsCompressed( metadata.format ) )
00939                     {
00940                         size_t csize = std::min<size_t>( images[ index ].slicePitch, timages[ index ].slicePitch );
00941                         memcpy_s( pDest, images[ index ].slicePitch, pSrc, csize );
00942                     }
00943                     else
00944                     {
00945                         for( size_t h = 0; h < images[ index ].height; ++h )
00946                         {
00947                             if ( convFlags & CONV_FLAGS_EXPAND )
00948                             {
00949                                 if ( convFlags & (CONV_FLAGS_565|CONV_FLAGS_5551|CONV_FLAGS_4444) )
00950                                 {
00951                                     if ( !_ExpandScanline( pDest, dpitch, DXGI_FORMAT_R8G8B8A8_UNORM,
00952                                                            pSrc, spitch,
00953                                                            (convFlags & CONV_FLAGS_565) ? DXGI_FORMAT_B5G6R5_UNORM : DXGI_FORMAT_B5G5R5A1_UNORM,
00954                                                            tflags ) )
00955                                         return E_FAIL;
00956                                 }
00957                                 else
00958                                 {
00959                                     TEXP_LEGACY_FORMAT lformat = _FindLegacyFormat( convFlags );
00960                                     if ( !_LegacyExpandScanline( pDest, dpitch, metadata.format,
00961                                                                  pSrc, spitch, lformat, pal8,
00962                                                                  tflags ) )
00963                                         return E_FAIL;
00964                                 }
00965                             }
00966                             else if ( convFlags & CONV_FLAGS_SWIZZLE )
00967                             {
00968                                 _SwizzleScanline( pDest, dpitch, pSrc, spitch,
00969                                                   metadata.format, tflags );
00970                             }
00971                             else
00972                             {
00973                                 _CopyScanline( pDest, dpitch, pSrc, spitch,
00974                                                metadata.format, tflags );
00975                             }
00976
00977                             pSrc += spitch;
00978                             pDest += dpitch;
00979                         }
00980                     }
00981                 }
00982             }
00983         }
00984         break;
00985
00986     case TEX_DIMENSION_TEXTURE3D:
00987         {
00988             size_t index = 0;
00989             size_t d = metadata.depth;
00990
00991             for( size_t level = 0; level < metadata.mipLevels; ++level )
00992             {
00993                 for( size_t slice = 0; slice < d; ++slice, ++index )
00994                 {
00995                     if ( index >= nimages )
00996                         return E_FAIL;
00997
00998                     if ( images[ index ].height != timages[ index ].height )
00999                         return E_FAIL;
01000
01001                     size_t dpitch = images[ index ].rowPitch;
01002                     size_t spitch = timages[ index ].rowPitch;
01003
01004                     const uint8_t *pSrc = const_cast<const uint8_t*>( timages[ index ].pixels );
01005                     if ( !pSrc )
01006                         return E_POINTER;
01007
01008                     uint8_t *pDest = images[ index ].pixels;
01009                     if ( !pDest )
01010                         return E_POINTER;
01011
01012                     if ( IsCompressed( metadata.format ) )
01013                     {
01014                         size_t csize = std::min<size_t>( images[ index ].slicePitch, timages[ index ].slicePitch );
01015                         memcpy_s( pDest, images[ index ].slicePitch, pSrc, csize );
01016                     }
01017                     else
01018                     {
01019                         for( size_t h = 0; h < images[ index ].height; ++h )
01020                         {
01021                             if ( convFlags & CONV_FLAGS_EXPAND )
01022                             {
01023                                 if ( convFlags & (CONV_FLAGS_565|CONV_FLAGS_5551|CONV_FLAGS_4444) )
01024                                 {
01025                                     if ( !_ExpandScanline( pDest, dpitch, DXGI_FORMAT_R8G8B8A8_UNORM,
01026                                                            pSrc, spitch,
01027                                                            (convFlags & CONV_FLAGS_565) ? DXGI_FORMAT_B5G6R5_UNORM : DXGI_FORMAT_B5G5R5A1_UNORM,
01028                                                            tflags ) )
01029                                         return E_FAIL;
01030                                 }
01031                                 else
01032                                 {
01033                                     TEXP_LEGACY_FORMAT lformat = _FindLegacyFormat( convFlags );
01034                                     if ( !_LegacyExpandScanline( pDest, dpitch, metadata.format,
01035                                                                  pSrc, spitch, lformat, pal8,
01036                                                                  tflags ) )
01037                                         return E_FAIL;
01038                                 }
01039                             }
01040                             else if ( convFlags & CONV_FLAGS_SWIZZLE )
01041                             {
01042                                 _SwizzleScanline( pDest, dpitch, pSrc, spitch, metadata.format, tflags );
01043                             }
01044                             else
01045                             {
01046                                 _CopyScanline( pDest, dpitch, pSrc, spitch, metadata.format, tflags );
01047                             }
01048
01049                             pSrc += spitch;
01050                             pDest += dpitch;
01051                         }
01052                     }
01053                 }
01054
01055                 if ( d > 1 )
01056                     d >>= 1;
01057             }
01058         }
01059         break;
01060
01061     default:
01062         return E_FAIL;
01063     }
01064
01065     return S_OK;
01066 }
01067
01068 static HRESULT _CopyImageInPlace( DWORD convFlags, _In_ const ScratchImage& image )
01069 {
01070     if ( !image.GetPixels() )
01071         return E_FAIL;
01072
01073     const Image* images = image.GetImages();
01074     if ( !images )
01075         return E_FAIL;
01076
01077     const TexMetadata& metadata = image.GetMetadata();
01078
01079     DWORD tflags = (convFlags & CONV_FLAGS_NOALPHA) ? TEXP_SCANLINE_SETALPHA : 0;
01080     if ( convFlags & CONV_FLAGS_SWIZZLE )
01081         tflags |= TEXP_SCANLINE_LEGACY;
01082
01083     for( size_t i = 0; i < image.GetImageCount(); ++i )
01084     {
01085         const Image* img = &images[ i ];
01086         uint8_t *pPixels = img->pixels;
01087         if ( !pPixels )
01088             return E_POINTER;
01089
01090         size_t rowPitch = img->rowPitch;
01091
01092         for( size_t h = 0; h < img->height; ++h )
01093         {
01094             if ( convFlags & CONV_FLAGS_SWIZZLE )
01095             {
01096                 _SwizzleScanline( pPixels, rowPitch, pPixels, rowPitch, metadata.format, tflags );
01097             }
01098             else
01099             {
01100                 _CopyScanline( pPixels, rowPitch, pPixels, rowPitch, metadata.format, tflags );
01101             }
01102
01103             pPixels += rowPitch;
01104         }
01105     }
01106
01107     return S_OK;
01108 }
01109
01110
01111 //=====================================================================================
01112 // Entry-points
01113 //=====================================================================================
01114
01115 //-------------------------------------------------------------------------------------
01116 // Obtain metadata from DDS file in memory/on disk
01117 //-------------------------------------------------------------------------------------
01118
01119 _Use_decl_annotations_
01120 HRESULT GetMetadataFromDDSMemory( LPCVOID pSource, size_t size, DWORD flags, TexMetadata& metadata )
01121 {
01122     if ( !pSource || size == 0 )
01123         return E_INVALIDARG;
01124
01125     return _DecodeDDSHeader( pSource, size, flags, metadata, 0 );
01126 }
01127
01128 _Use_decl_annotations_
01129 HRESULT GetMetadataFromDDSFile( LPCWSTR szFile, DWORD flags, TexMetadata& metadata )
01130 {
01131     if ( !szFile )
01132         return E_INVALIDARG;
01133
01134 #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8)
01135     ScopedHandle hFile( safe_handle( CreateFile2( szFile, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, 0 ) ) );
01136 #else
01137     ScopedHandle hFile( safe_handle( CreateFileW( szFile, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING ,
01138                                                   FILE_FLAG_SEQUENTIAL_SCAN, 0 ) ) );
01139 #endif
01140     if ( !hFile )
01141     {
01142         return HRESULT_FROM_WIN32( GetLastError() );
01143     }
01144
01145     // Get the file size
01146     LARGE_INTEGER fileSize = {0};
01147
01148 #if (_WIN32_WINNT >= _WIN32_WINNT_VISTA)
01149     FILE_STANDARD_INFO fileInfo;
01150     if ( !GetFileInformationByHandleEx( hFile.get(), FileStandardInfo, &fileInfo, sizeof(fileInfo) ) )
01151     {
01152         return HRESULT_FROM_WIN32( GetLastError() );
01153     }
01154     fileSize = fileInfo.EndOfFile;
01155 #else
01156     if ( !GetFileSizeEx( hFile.get(), &fileSize ) )
01157     {
01158         return HRESULT_FROM_WIN32( GetLastError() );
01159     }
01160 #endif
01161
01162     // File is too big for 32-bit allocation, so reject read (4 GB should be plenty large enough for a valid DDS file)
01163     if ( fileSize.HighPart > 0 )
01164     {
01165         return HRESULT_FROM_WIN32( ERROR_FILE_TOO_LARGE );
01166     }
01167
01168     // Need at least enough data to fill the standard header and magic number to be a valid DDS
01169     if ( fileSize.LowPart < ( sizeof(DDS_HEADER) + sizeof(uint32_t) ) )
01170     {
01171         return E_FAIL;
01172     }
01173
01174     // Read the header in (including extended header if present)
01175     const size_t MAX_HEADER_SIZE = sizeof(uint32_t) + sizeof(DDS_HEADER) + sizeof(DDS_HEADER_DXT10);
01176     uint8_t header[MAX_HEADER_SIZE];
01177
01178     DWORD bytesRead = 0;
01179     if ( !ReadFile( hFile.get(), header, MAX_HEADER_SIZE, &bytesRead, 0 ) )
01180     {
01181         return HRESULT_FROM_WIN32( GetLastError() );
01182     }
01183
01184     return _DecodeDDSHeader( header, bytesRead, flags, metadata, 0 );
01185 }
01186
01187
01188 //-------------------------------------------------------------------------------------
01189 // Load a DDS file in memory
01190 //-------------------------------------------------------------------------------------
01191 _Use_decl_annotations_
01192 HRESULT LoadFromDDSMemory( LPCVOID pSource, size_t size, DWORD flags, TexMetadata* metadata, ScratchImage& image )
01193 {
01194     if ( !pSource || size == 0 )
01195         return E_INVALIDARG;
01196
01197     image.Release();
01198
01199     DWORD convFlags = 0;
01200     TexMetadata mdata;
01201     HRESULT hr = _DecodeDDSHeader( pSource, size, flags, mdata, &convFlags );
01202     if ( FAILED(hr) )
01203         return hr;
01204
01205     size_t offset = sizeof(uint32_t) + sizeof(DDS_HEADER);
01206     if ( convFlags & CONV_FLAGS_DX10 )
01207         offset += sizeof(DDS_HEADER_DXT10);
01208
01209     assert( offset <= size );
01210
01211     const uint32_t *pal8 = nullptr;
01212     if ( convFlags & CONV_FLAGS_PAL8 )
01213     {
01214         pal8 = reinterpret_cast<const uint32_t*>( reinterpret_cast<const uint8_t*>(pSource) + offset );
01215         assert( pal8 );
01216         offset += ( 256 * sizeof(uint32_t) );
01217         if ( size < offset )
01218             return E_FAIL;
01219     }
01220
01221     hr = image.Initialize( mdata );
01222     if ( FAILED(hr) )
01223         return hr;
01224
01225     LPCVOID pPixels = reinterpret_cast<LPCVOID>( reinterpret_cast<const uint8_t*>(pSource) + offset );
01226     assert( pPixels );
01227     hr = _CopyImage( pPixels, size - offset, mdata,
01228                      (flags & DDS_FLAGS_LEGACY_DWORD) ? CP_FLAGS_LEGACY_DWORD : CP_FLAGS_NONE, convFlags, pal8, image );
01229     if ( FAILED(hr) )
01230     {
01231         image.Release();
01232         return hr;
01233     }
01234     if ( metadata )
01235         memcpy( metadata, &mdata, sizeof(TexMetadata) );
01236
01237     return S_OK;
01238 }
01239
01240
01241 //-------------------------------------------------------------------------------------
01242 // Load a DDS file from disk
01243 //-------------------------------------------------------------------------------------
01244 _Use_decl_annotations_
01245 HRESULT LoadFromDDSFile( LPCWSTR szFile, DWORD flags, TexMetadata* metadata, ScratchImage& image )
01246 {
01247     if ( !szFile )
01248         return E_INVALIDARG;
01249
01250     image.Release();
01251
01252 #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8)
01253     ScopedHandle hFile( safe_handle( CreateFile2( szFile, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, 0 ) ) );
01254 #else
01255     ScopedHandle hFile( safe_handle( CreateFileW( szFile, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING,
01256                                                   FILE_FLAG_SEQUENTIAL_SCAN, 0 ) ) );
01257 #endif
01258
01259     if ( !hFile )
01260     {
01261         return HRESULT_FROM_WIN32( GetLastError() );
01262     }
01263
01264     // Get the file size
01265     LARGE_INTEGER fileSize = {0};
01266
01267 #if (_WIN32_WINNT >= _WIN32_WINNT_VISTA)
01268     FILE_STANDARD_INFO fileInfo;
01269     if ( !GetFileInformationByHandleEx( hFile.get(), FileStandardInfo, &fileInfo, sizeof(fileInfo) ) )
01270     {
01271         return HRESULT_FROM_WIN32( GetLastError() );
01272     }
01273     fileSize = fileInfo.EndOfFile;
01274 #else
01275     if ( !GetFileSizeEx( hFile.get(), &fileSize ) )
01276     {
01277         return HRESULT_FROM_WIN32( GetLastError() );
01278     }
01279 #endif
01280
01281     // File is too big for 32-bit allocation, so reject read (4 GB should be plenty large enough for a valid DDS file)
01282     if ( fileSize.HighPart > 0 )
01283     {
01284         return HRESULT_FROM_WIN32( ERROR_FILE_TOO_LARGE );
01285     }
01286
01287     // Need at least enough data to fill the standard header and magic number to be a valid DDS
01288     if ( fileSize.LowPart < ( sizeof(DDS_HEADER) + sizeof(uint32_t) ) )
01289     {
01290         return E_FAIL;
01291     }
01292
01293     // Read the header in (including extended header if present)
01294     const size_t MAX_HEADER_SIZE = sizeof(uint32_t) + sizeof(DDS_HEADER) + sizeof(DDS_HEADER_DXT10);
01295     uint8_t header[MAX_HEADER_SIZE];
01296
01297     DWORD bytesRead = 0;
01298     if ( !ReadFile( hFile.get(), header, MAX_HEADER_SIZE, &bytesRead, 0 ) )
01299     {
01300         return HRESULT_FROM_WIN32( GetLastError() );
01301     }
01302
01303     DWORD convFlags = 0;
01304     TexMetadata mdata;
01305     HRESULT hr = _DecodeDDSHeader( header, bytesRead, flags, mdata, &convFlags );
01306     if ( FAILED(hr) )
01307         return hr;
01308
01309     DWORD offset = MAX_HEADER_SIZE;
01310
01311     if ( !(convFlags & CONV_FLAGS_DX10) )
01312     {
01313         // Must reset file position since we read more than the standard header above
01314         LARGE_INTEGER filePos = { sizeof(uint32_t) + sizeof(DDS_HEADER), 0};
01315         if ( !SetFilePointerEx( hFile.get(), filePos, 0, FILE_BEGIN ) )
01316         {
01317             return HRESULT_FROM_WIN32( GetLastError() );
01318         }
01319
01320         offset = sizeof(uint32_t) + sizeof(DDS_HEADER);
01321     }
01322
01323     std::unique_ptr<uint32_t[]> pal8;
01324     if ( convFlags & CONV_FLAGS_PAL8 )
01325     {
01326         pal8.reset( new uint32_t[256] );
01327         if ( !pal8 )
01328         {
01329             return E_OUTOFMEMORY;
01330         }
01331
01332         if ( !ReadFile( hFile.get(), pal8.get(), 256 * sizeof(uint32_t), &bytesRead, 0 ) )
01333         {
01334             return HRESULT_FROM_WIN32( GetLastError() );
01335         }
01336
01337         if ( bytesRead != (256 * sizeof(uint32_t)) )
01338         {
01339             return E_FAIL;
01340         }
01341
01342         offset += ( 256 * sizeof(uint32_t) );
01343     }
01344
01345     DWORD remaining = fileSize.LowPart - offset;
01346     if ( remaining == 0 )
01347         return E_FAIL;
01348
01349     hr = image.Initialize( mdata );
01350     if ( FAILED(hr) )
01351         return hr;
01352
01353     if ( (convFlags & CONV_FLAGS_EXPAND) || (flags & DDS_FLAGS_LEGACY_DWORD) )
01354     {
01355         std::unique_ptr<uint8_t[]> temp( new uint8_t[ remaining ] );
01356         if ( !temp )
01357         {
01358             image.Release();
01359             return E_OUTOFMEMORY;
01360         }
01361
01362         if ( !ReadFile( hFile.get(), temp.get(), remaining, &bytesRead, 0 ) )
01363         {
01364             image.Release();
01365             return HRESULT_FROM_WIN32( GetLastError() );
01366         }
01367
01368         if ( bytesRead != remaining )
01369         {
01370             image.Release();
01371             return E_FAIL;
01372         }
01373
01374         hr = _CopyImage( temp.get(), remaining, mdata,
01375                          (flags & DDS_FLAGS_LEGACY_DWORD) ? CP_FLAGS_LEGACY_DWORD : CP_FLAGS_NONE,
01376                          convFlags, pal8.get(), image );
01377         if ( FAILED(hr) )
01378         {
01379             image.Release();
01380             return hr;
01381         }
01382     }
01383     else
01384     {
01385         if ( remaining > image.GetPixelsSize() )
01386         {
01387             image.Release();
01388             return E_FAIL;
01389         }
01390
01391         if ( !ReadFile( hFile.get(), image.GetPixels(), static_cast<DWORD>( image.GetPixelsSize() ), &bytesRead, 0 ) )
01392         {
01393             image.Release();
01394             return HRESULT_FROM_WIN32( GetLastError() );
01395         }
01396
01397         if ( convFlags & (CONV_FLAGS_SWIZZLE|CONV_FLAGS_NOALPHA) )
01398         {
01399             // Swizzle/copy image in place
01400             hr = _CopyImageInPlace( convFlags, image );
01401             if ( FAILED(hr) )
01402             {
01403                 image.Release();
01404                 return hr;
01405             }
01406         }
01407     }
01408
01409     if ( metadata )
01410         memcpy( metadata, &mdata, sizeof(TexMetadata) );
01411
01412     return S_OK;
01413 }
01414
01415
01416 //-------------------------------------------------------------------------------------
01417 // Save a DDS file to memory
01418 //-------------------------------------------------------------------------------------
01419 _Use_decl_annotations_
01420 HRESULT SaveToDDSMemory( const Image* images, size_t nimages, const TexMetadata& metadata, DWORD flags, Blob& blob )
01421 {
01422     if ( !images || (nimages == 0) )
01423         return E_INVALIDARG;
01424
01425     // Determine memory required
01426     size_t required = 0;
01427     HRESULT hr = _EncodeDDSHeader( metadata, flags, 0, 0, required );
01428     if ( FAILED(hr) )
01429         return hr;
01430
01431     for( size_t i = 0; i < nimages; ++i )
01432     {
01433         required += images[ i ].slicePitch;
01434         if ( !images[ i ].pixels )
01435             return E_POINTER;
01436     }
01437
01438     assert( required > 0 );
01439
01440     blob.Release();
01441
01442     hr = blob.Initialize( required );
01443     if ( FAILED(hr) )
01444         return hr;
01445
01446     uint8_t* pDestination = reinterpret_cast<uint8_t*>( blob.GetBufferPointer() );
01447     assert( pDestination );
01448
01449     hr = _EncodeDDSHeader( metadata, flags, pDestination, blob.GetBufferSize(), required );
01450     if ( FAILED(hr) )
01451     {
01452         blob.Release();
01453         return hr;
01454     }
01455
01456     size_t remaining = blob.GetBufferSize() - required;
01457     pDestination += required;
01458
01459     if ( !remaining )
01460     {
01461         blob.Release();
01462         return E_FAIL;
01463     }
01464
01465     switch( metadata.dimension )
01466     {
01467     case DDS_DIMENSION_TEXTURE1D:
01468     case DDS_DIMENSION_TEXTURE2D:
01469         {
01470             size_t index = 0;
01471             for( size_t item = 0; item < metadata.arraySize; ++item )
01472             {
01473                 for( size_t level = 0; level < metadata.mipLevels; ++level )
01474                 {
01475                     if ( index >= nimages )
01476                     {
01477                         blob.Release();
01478                         return E_FAIL;
01479                     }
01480
01481                     size_t pixsize = images[ index ].slicePitch;
01482                     if ( memcpy_s( pDestination, remaining, images[ index ].pixels, pixsize ) )
01483                     {
01484                         blob.Release();
01485                         return E_FAIL;
01486                     }
01487                     pDestination += pixsize;
01488                     remaining -= pixsize;
01489
01490                     ++index;
01491                 }
01492             }
01493         }
01494         break;
01495
01496     case DDS_DIMENSION_TEXTURE3D:
01497         {
01498             if ( metadata.arraySize != 1 )
01499             {
01500                 blob.Release();
01501                 return E_FAIL;
01502             }
01503
01504             size_t d = metadata.depth;
01505
01506             size_t index = 0;
01507             for( size_t level = 0; level < metadata.mipLevels; ++level )
01508             {
01509                 for( size_t slice = 0; slice < d; ++slice )
01510                 {
01511                     if ( index >= nimages )
01512                     {
01513                         blob.Release();
01514                         return E_FAIL;
01515                     }
01516
01517                     size_t pixsize = images[ index ].slicePitch;
01518                     if ( memcpy_s( pDestination, remaining, images[ index ].pixels, pixsize ) )
01519                     {
01520                         blob.Release();
01521                         return E_FAIL;
01522                     }
01523                     pDestination += pixsize;
01524                     remaining -= pixsize;
01525
01526                     ++index;
01527                 }
01528
01529                 if ( d > 1 )
01530                     d >>= 1;
01531             }
01532         }
01533         break;
01534
01535     default:
01536         blob.Release();
01537         return E_FAIL;
01538     }
01539
01540     return S_OK;
01541 }
01542
01543
01544 //-------------------------------------------------------------------------------------
01545 // Save a DDS file to disk
01546 //-------------------------------------------------------------------------------------
01547 _Use_decl_annotations_
01548 HRESULT SaveToDDSFile( const Image* images, size_t nimages, const TexMetadata& metadata, DWORD flags, LPCWSTR szFile )
01549 {
01550     if ( !szFile )
01551         return E_INVALIDARG;
01552
01553     // Create DDS Header
01554     const size_t MAX_HEADER_SIZE = sizeof(uint32_t) + sizeof(DDS_HEADER) + sizeof(DDS_HEADER_DXT10);
01555     uint8_t header[MAX_HEADER_SIZE];
01556     size_t required;
01557     HRESULT hr = _EncodeDDSHeader( metadata, flags, header, MAX_HEADER_SIZE, required );
01558     if ( FAILED(hr) )
01559         return hr;
01560
01561     // Create file and write header
01562 #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8)
01563     ScopedHandle hFile( safe_handle( CreateFile2( szFile, GENERIC_WRITE, 0, CREATE_ALWAYS, 0 ) ) );
01564 #else
01565     ScopedHandle hFile( safe_handle( CreateFileW( szFile, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, 0 ) ) );
01566 #endif
01567     if ( !hFile )
01568     {
01569         return HRESULT_FROM_WIN32( GetLastError() );
01570     }
01571
01572     DWORD bytesWritten;
01573     if ( !WriteFile( hFile.get(), header, static_cast<DWORD>( required ), &bytesWritten, 0 ) )
01574     {
01575         return HRESULT_FROM_WIN32( GetLastError() );
01576     }
01577
01578     if ( bytesWritten != required )
01579     {
01580         return E_FAIL;
01581     }
01582
01583     // Write images
01584     switch( metadata.dimension )
01585     {
01586     case DDS_DIMENSION_TEXTURE1D:
01587     case DDS_DIMENSION_TEXTURE2D:
01588         {
01589             size_t index = 0;
01590             for( size_t item = 0; item < metadata.arraySize; ++item )
01591             {
01592                 for( size_t level = 0; level < metadata.mipLevels; ++level, ++index )
01593                 {
01594                     if ( index >= nimages )
01595                         return E_FAIL;
01596
01597                     if ( !images[ index ].pixels )
01598                         return E_POINTER;
01599
01600                     size_t pixsize = images[ index ].slicePitch;
01601
01602                     if ( !WriteFile( hFile.get(), images[ index ].pixels, static_cast<DWORD>( pixsize ), &bytesWritten, 0 ) )
01603                     {
01604                         return HRESULT_FROM_WIN32( GetLastError() );
01605                     }
01606
01607                     if ( bytesWritten != pixsize )
01608                     {
01609                         return E_FAIL;
01610                     }
01611                 }
01612             }
01613         }
01614         break;
01615
01616     case DDS_DIMENSION_TEXTURE3D:
01617         {
01618             if ( metadata.arraySize != 1 )
01619                 return E_FAIL;
01620
01621             size_t d = metadata.depth;
01622
01623             size_t index = 0;
01624             for( size_t level = 0; level < metadata.mipLevels; ++level )
01625             {
01626                 for( size_t slice = 0; slice < d; ++slice, ++index )
01627                 {
01628                     if ( index >= nimages )
01629                         return E_FAIL;
01630
01631                     if ( !images[ index ].pixels )
01632                         return E_POINTER;
01633
01634                     size_t pixsize = images[ index ].slicePitch;
01635
01636                     if ( !WriteFile( hFile.get(), images[ index ].pixels, static_cast<DWORD>( pixsize ), &bytesWritten, 0 ) )
01637                     {
01638                         return HRESULT_FROM_WIN32( GetLastError() );
01639                     }
01640
01641                     if ( bytesWritten != pixsize )
01642                     {
01643                         return E_FAIL;
01644                     }
01645                 }
01646
01647                 if ( d > 1 )
01648                     d >>= 1;
01649             }
01650         }
01651         break;
01652
01653     default:
01654         return E_FAIL;
01655     }
01656
01657     return S_OK;
01658 }
01659
01660 }; // namespace
Generated on Sat Nov 23 2024 16:08:12 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DirectX::LDRColorA Member List

This is the complete list of members for DirectX::LDRColorA, including all inherited members.
a | DirectX::LDRColorA |
b | DirectX::LDRColorA |
g | DirectX::LDRColorA |
Interpolate(_In_ const LDRColorA &c0, _In_ const LDRColorA &c1, _In_ size_t wc, _In_ size_t wa, _In_ _In_range_(2, 4) size_t wcprec, _In_ _In_range_(2, 4) size_t waprec, _Out_ LDRColorA &out) | DirectX::LDRColorA | [inline, static]
InterpolateA(_In_ const LDRColorA &c0, _In_ const LDRColorA &c1, _In_ size_t wa, _In_range_(2, 4) _In_ size_t waprec, _Out_ LDRColorA &out) | DirectX::LDRColorA | [inline, static]
InterpolateRGB(_In_ const LDRColorA &c0, _In_ const LDRColorA &c1, _In_ size_t wc, _In_ _In_range_(2, 4) size_t wcprec, _Out_ LDRColorA &out) | DirectX::LDRColorA | [inline, static]
LDRColorA() | DirectX::LDRColorA | [inline]
LDRColorA(uint8_t _r, uint8_t _g, uint8_t _b, uint8_t _a) | DirectX::LDRColorA | [inline]
operator=(_In_ const HDRColorA &c) | DirectX::LDRColorA | [inline]
operator[](_In_range_(0, 3) size_t uElement) const | DirectX::LDRColorA | [inline]
operator[](_In_range_(0, 3) size_t uElement) | DirectX::LDRColorA | [inline]
r | DirectX::LDRColorA |
Generated on Sat Nov 23 2024 16:09:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D tutorial/C++/Lesson5.Components/pch.cpp Source File

  • Direct3D tutorial
  • Lesson5.Components

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

ImageFile Member List

This is the complete list of members for ImageFile, including all inherited members.
AddRef() override | ImageFile | [virtual]
Clone(_Outptr_ IStream **cloneStream) override | ImageFile | [virtual]
Commit(DWORD flags) override | ImageFile | [virtual]
CopyTo(_In_ IStream *destinationStream, ULARGE_INTEGER bytesToCopy, _Out_ ULARGE_INTEGER *bytesRead, _Out_ ULARGE_INTEGER *bytesWritten) override | ImageFile | [virtual]
ImageFile() | ImageFile |
LoadAsync(_In_ Windows::Storage::StorageFolder^location, _In_ Platform::String^fileName) | ImageFile |
LockRegion(ULARGE_INTEGER bytesOffset, ULARGE_INTEGER bytesToLock, DWORD lockType) override | ImageFile | [virtual]
m_data | ImageFile | [private]
m_offset | ImageFile | [private]
m_refCount | ImageFile | [private]
QueryInterface(REFIID uuid, _Outptr_ void **object) override | ImageFile | [virtual]
Read(_Out_writes_bytes_(bytesToRead) void *outputBuffer, ULONG bytesToRead, _Out_ ULONG *bytesRead) override | ImageFile | [virtual]
Ready() | ImageFile | [inline]
Release() override | ImageFile | [virtual]
Revert() override | ImageFile | [virtual]
Seek(LARGE_INTEGER distance, DWORD origin, _Out_ ULARGE_INTEGER *newLocation) override | ImageFile | [virtual]
SetSize(ULARGE_INTEGER) override | ImageFile | [virtual]
Stat(_Out_ STATSTG *statistics, DWORD flags) override | ImageFile | [virtual]
UnlockRegion(ULARGE_INTEGER bytesOffset, ULARGE_INTEGER bytesToLock, DWORD lockType) override | ImageFile | [virtual]
Write(_In_reads_bytes_(bytesToWrite) void const *inputBuffer, ULONG bytesToWrite, _Out_ ULONG *bytesWritten) override | ImageFile | [virtual]
Generated on Sat Nov 23 2024 16:09:14 for Win8-Examples by doxygen 1.7.1


Win8-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.
__pad0__ | Rectangle |
AcceptChildNode(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^childXmlNode) | Element | [virtual]
AddChild(_In_ Element^element) | Element |
AddSibling(_In_ Element^element) | Element |
BindResource(_In_ Element^rootElement) | Element | [virtual]
Create(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^xmlNode) | Element | [static]
Draw(_In_ Document^document, D2D1::Matrix3x2F const &transform) override | Rectangle | [virtual]
GetFirstChild() | Element | [inline]
GetName() | Element | [inline]
GetNextSibling() | Element | [inline]
GetOpacity() override | Rectangle | [inline, virtual]
GetParent() | Element | [inline]
GetSize() | Element | [inline]
Initialize(_In_ Document^document, _In_ Windows::Data::Xml::Dom::XmlElement^xmlElement) override | Rectangle | [virtual]
m_brush | Rectangle | [private]
m_color | Rectangle | [private]
m_opacity | Rectangle | [private]
Measure(_In_ Document^document, D2D1_SIZE_F const &parentSize, _Out_ D2D1_RECT_F *bounds) override | Rectangle | [virtual]
PrepareToDraw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
ReleaseParent() | Element | [virtual]
Generated on Sat Nov 23 2024 16:09:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML AppBar control/C++/Scenario4.xaml.cpp Source File

  • XAML AppBar control

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 "Page3.xaml.h"
00018 #include "Scenario4.xaml.h"
00019
00020 using namespace AppBarControl;
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Interop;
00025 using namespace Windows::UI::Xaml::Navigation;
00026
00027 Scenario4::Scenario4()
00028 {
00029     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 void Scenario4::OnNavigatedTo(NavigationEventArgs^ e)
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     rootPage = MainPage::Current;
00042 }
00043
00044 void AppBarControl::Scenario4::ShowMe_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00045 {
00046   TypeName pageType = {Page3::typeid->FullName, TypeKind::Custom};
00047   rootPage->Frame->Navigate(pageType, rootPage);
00048 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

AmpPixel Member List

This is the complete list of members for AmpPixel, including all inherited members.
__pad0__ | AmpPixel |
AmpPixel() restrict(cpu | AmpPixel |
b | AmpPixel |
b(0) | AmpPixel | [inline]
g | AmpPixel |
g(0) | AmpPixel |
r | AmpPixel |
r(0) | AmpPixel |
SetFromRGB(float r, float g, float b) restrict(cpu | AmpPixel | [inline]
u | AmpPixel |
u(0) | AmpPixel |
v | AmpPixel |
v(0) | AmpPixel |
y | AmpPixel |
Generated on Sat Nov 23 2024 16:09:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Push and periodic notifications client-side/C++/App.xaml.cpp Source File

  • Push and periodic notifications client-side

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:28 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media Play To/C++/Constants.cpp Source File

  • Media Play To

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
00021     { "Stream a media file", "SDKSample.PlayTo.Scenario1" },
00022     { "Stream a photo slideshow", "SDKSample.PlayTo.Scenario2" }
00023 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: AtomPub/C++/MainPage.xaml.h Source File

  • AtomPub

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/FaceMesh.h Source File

  • XAML DirectX 3D shooting game

FaceMesh.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 // FaceMesh:
00011 // This class derives from MeshObject and creates a ID3D11Buffer of
00012 // vertices and indices to represent a canonical face defined as a
00013 // rectangle at the origin extending 1 unit in the +X and
00014 // 1 unit in the +Y direction.
00015 // The face is defined to be two sided, so it is visible from either
00016 // side.
00017
00018 #include "MeshObject.h"
00019
00020 ref class FaceMesh: public MeshObject
00021 {
00022 internal:
00023     FaceMesh(_In_ ID3D11Device *device);
00024 };
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/FileSizeConverter.cpp Source File

  • Hilo C++
  • Hilo

FileSizeConverter.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 #include "FileSizeConverter.h"
00009 #include "LocalResourceLoader.h"
00010
00011 using namespace Hilo;
00012 using namespace Platform;
00013 using namespace Windows::UI::Xaml::Interop;
00014 using namespace Windows::ApplicationModel::Resources;
00015
00016 // See http://go.microsoft.com/fwlink/?LinkId=267279 for info about the FileSizeConverter class
00017 // and other data converters.
00018
00019 FileSizeConverter::FileSizeConverter()
00020 {
00021     m_loader = ref new LocalResourceLoader();
00022 }
00023
00024 FileSizeConverter::FileSizeConverter(Hilo::IResourceLoader^ loader) : m_loader(loader)
00025 {
00026 }
00027
00028 Object^ FileSizeConverter::Convert(Object^ value, TypeName targetType, Object^ parameter, String^)
00029 {
00030     float64 size = static_cast<float64>(safe_cast<uint64>(value));
00031     std::array<String^, 3> units =
00032     {
00033         m_loader->GetString("BytesUnit"),
00034         m_loader->GetString("KilobytesUnit"),
00035         m_loader->GetString("MegabytesUnit")
00036     };
00037     unsigned int index = 0;
00038
00039     while (size >= 1024)
00040     {
00041         size /= 1024;
00042         index++;
00043     }
00044
00045     return ToTwoDecimalPlaces(size) + " " + units[index];
00046 }
00047
00048 float64 FileSizeConverter::ToTwoDecimalPlaces(float64 value)
00049 {
00050     float64 f;
00051     float64 intpart;
00052     float64 fractpart;
00053     fractpart = modf(value, &intpart);
00054     f = floor(fractpart * 100 + 0.5) / 100.0;
00055     return intpart + f;
00056 }
00057
00058 Object^ FileSizeConverter::ConvertBack(Object^ value, TypeName targetType, Object^ parameter, String^)
00059 {
00060     throw ref new NotImplementedException();
00061 }
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Manipulations and gestures (C++)/C++/DrawingObject.h Source File

  • Input Manipulations and gestures (C++)
  • C++

DrawingObject.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 "ManipulatableObject.h"
00011
00012 ref class DrawingObject sealed : public ManipulatableObject
00013 {
00014 public:
00015     DrawingObject(_In_opt_ ManipulatableObject^ parent, _In_ IRenderer^ renderer);
00016
00017     // Returns true if point (x,y) belongs to the object. The point should be in parent coordinate system.
00018     bool HitTest(_In_ Windows::Foundation::Point position);
00019
00020     // Attaches/detaches GestureRecognizer to/from the object.
00021     void Attach(_In_ Windows::UI::Input::GestureRecognizer^ gestureRecognizer);
00022     void Detach(_In_ Windows::UI::Input::GestureRecognizer^ gestureRecognizer);
00023
00024     // Serialization/deserialization methods
00025     virtual void Serialize(_In_ Windows::Foundation::Collections::IPropertySet^ properties) override;
00026     virtual void Deserialize(_In_ Windows::Foundation::Collections::IPropertySet^ properties) override;
00027
00028 internal:
00029     enum class Color
00030     {
00031         First = 0,
00032         Green = First,
00033         Blue,
00034         Orange,
00035         Purple,
00036         Yellow,
00037         Red,
00038         MaxCount
00039     };
00040
00041     // Initialize object state: color, initial position and size. Initial position is relative to view centerpoint.
00042     void Initialize(_In_ Color color, _In_ float x, _In_ float y, _In_ float dx, _In_ float dy);
00043
00044     Color GetColor()  { return _color; }
00045
00046     // Draw the object, given D2D objects.
00047     void Draw(
00048         _In_ ID2D1DeviceContext* deviceContext,
00049         _In_ ID2D1SolidColorBrush* brush);
00050
00051     // Draw overlay text, given D2D objects.
00052     void DrawOverlay(
00053         _In_ ID2D1DeviceContext* deviceContext,
00054         _In_ IDWriteTextFormat* textFormat,
00055         _In_ ID2D1SolidColorBrush* brush);
00056
00057 private:
00058     // GestureRecognizer event handlers.
00059     void OnTapped(
00060         _In_ Windows::UI::Input::GestureRecognizer^ sender,
00061         _In_ Windows::UI::Input::TappedEventArgs^ args);
00062     void OnRightTapped(
00063         _In_ Windows::UI::Input::GestureRecognizer^ sender,
00064         _In_ Windows::UI::Input::RightTappedEventArgs^ args);
00065     void OnHolding(
00066         _In_ Windows::UI::Input::GestureRecognizer^ sender,
00067         _In_ Windows::UI::Input::HoldingEventArgs^ args);
00068     void OnManipulationStarted(
00069         _In_ Windows::UI::Input::GestureRecognizer^ sender,
00070         _In_ Windows::UI::Input::ManipulationStartedEventArgs^ args);
00071     void OnManipulationUpdated(
00072         _In_ Windows::UI::Input::GestureRecognizer^ sender,
00073         _In_ Windows::UI::Input::ManipulationUpdatedEventArgs^ args);
00074     void OnManipulationInertiaStarting(
00075         _In_ Windows::UI::Input::GestureRecognizer^ sender,
00076         _In_ Windows::UI::Input::ManipulationInertiaStartingEventArgs^ args);
00077     void OnManipulationCompleted(
00078         _In_ Windows::UI::Input::GestureRecognizer^ sender,
00079         _In_ Windows::UI::Input::ManipulationCompletedEventArgs^ args);
00080   ~DrawingObject();
00081
00082     // Get object's description.
00083     void GetObjectDescription();
00084
00085 private:
00086     IRenderer^ _renderer;
00087
00088     // Data
00089     Color _color;   // object's current color
00090     Color _initColor; // object's initial color
00091     float _initX;   // object's initial position x, relative to view centerpoint
00092     float _initY;   // object's initial position y, relative to view centerpoint
00093     float _initDX;  // object's initial width
00094     float _initDY;  // object's initial height
00095     WCHAR _descText[128];
00096     Windows::Foundation::Point _descPosition; // text position
00097
00098     // Event tokens for GestureRecognizer events
00099     Windows::Foundation::EventRegistrationToken _tokenTapped;
00100     Windows::Foundation::EventRegistrationToken _tokenRightTapped;
00101     Windows::Foundation::EventRegistrationToken _tokenHolding;
00102     Windows::Foundation::EventRegistrationToken _tokenManipulationStarted;
00103     Windows::Foundation::EventRegistrationToken _tokenManipulationUpdated;
00104     Windows::Foundation::EventRegistrationToken _tokenManipulationInertiaStarting;
00105     Windows::Foundation::EventRegistrationToken _tokenManipulationCompleted;
00106 };
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/Common/LayoutAwarePage.h Source File

  • Hilo C++
  • Hilo
  • Common

LayoutAwarePage.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
00009 #include <collection.h>
00010
00011 namespace Hilo
00012 {
00013   namespace Common
00014   {
00015     /// <summary>
00016     /// Typical implementation of Page that provides several important conveniences:
00017     /// <list type="bullet">
00018     /// <item>
00019     /// <description>Application view state to visual state mapping</description>
00020     /// </item>
00021     /// <item>
00022     /// <description>GoBack, GoForward, and GoHome event handlers</description>
00023     /// </item>
00024     /// <item>
00025     /// <description>Mouse and keyboard shortcuts for navigation</description>
00026     /// </item>
00027     /// <item>
00028     /// <description>State management for navigation and process lifetime management</description>
00029     /// </item>
00030     /// <item>
00031     /// <description>A default view model</description>
00032     /// </item>
00033     /// </list>
00034     /// </summary>
00035     [Windows::Foundation::Metadata::WebHostHidden]
00036     public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00037     {
00038     internal:
00039       LayoutAwarePage();
00040
00041     public:
00042       void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00043       void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00044       void InvalidateVisualState();
00045       static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00046       {
00047         Windows::UI::Xaml::DependencyProperty^ get();
00048       };
00049       property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00050       {
00051         Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00052         void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00053       }
00054
00055     protected:
00056       virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00057       virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00058       virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00059       virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00060       virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00061       virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00062       virtual void LoadState(Platform::Object^ navigationParameter,
00063         Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00064       virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00065
00066     private:
00067       Platform::String^ _pageKey;
00068       bool _navigationShortcutsRegistered;
00069       Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00070       Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00071         _acceleratorKeyEventToken, _pointerPressedEventToken;
00072       Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00073       void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00074       void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00075       void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00076       void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00077         Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00078       void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00079         Windows::UI::Core::PointerEventArgs^ args);
00080       LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00081     };
00082   }
00083 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-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.
__pad0__ | Text |
AcceptChildNode(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^childXmlNode) override | Text | [virtual]
AddChild(_In_ Element^element) | Element |
AddSibling(_In_ Element^element) | Element |
BindResource(_In_ Element^rootElement) | Element | [virtual]
Create(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^xmlNode) | Element | [static]
Draw(_In_ Document^document, D2D1::Matrix3x2F const &transform) override | Resource | [virtual]
GetFirstChild() | Element | [inline]
GetLength() | Text | [inline]
GetName() | Element | [inline]
GetNextSibling() | Element | [inline]
GetOpacity() | Element | [inline, virtual]
GetParent() | Element | [inline]
GetSize() | Element | [inline]
GetText(_In_ Windows::Data::Xml::Dom::IXmlNode^xmlNode) | Text | [private]
GetTextLayout(_Outptr_ IDWriteTextLayout **textLayout) | Text |
Initialize(_In_ Document^document, _In_ Windows::Data::Xml::Dom::XmlElement^xmlElement) override | Text | [virtual]
m_textLayout | Text | [private]
m_textLength | Text | [private]
m_textPosition | Text | [private]
Measure(_In_ Document^document, D2D1_SIZE_F const &parentSize, _Out_ D2D1_RECT_F *bounds) override | Resource | [virtual]
override | Resource |
PrepareToDraw(_In_ Document^document, D2D1::Matrix3x2F const &transform) override | Resource | [virtual]
ReleaseParent() | Element | [virtual]
Generated on Sat Nov 23 2024 16:09:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DirectX::BC4_SNORM Member List

This is the complete list of members for DirectX::BC4_SNORM, including all inherited members.
data | DirectX::BC4_SNORM |
DecodeFromIndex(size_t uIndex) const | DirectX::BC4_SNORM | [inline]
GetIndex(size_t uOffset) const | DirectX::BC4_SNORM | [inline]
indices | DirectX::BC4_SNORM |
R(size_t uOffset) const | DirectX::BC4_SNORM | [inline]
red_0 | DirectX::BC4_SNORM |
red_1 | DirectX::BC4_SNORM |
SetIndex(size_t uOffset, size_t uIndex) | DirectX::BC4_SNORM | [inline]
Generated on Sat Nov 23 2024 16:09:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Simplified ink/C++/pch.cpp Source File

  • Input Simplified ink

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D printing images and effects/C++/DocSource.cpp Source File

  • Direct2D printing images and effects

DocSource.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 "docsource.h"
00010
00011 using namespace Microsoft::WRL;
00012 using namespace Windows::Graphics::Printing;
00013
00014 #pragma region IDocumentPageSource Methods
00015
00016 IFACEMETHODIMP
00017 CDocumentSource::GetPreviewPageCollection(
00018     _In_  IPrintDocumentPackageTarget*  docPackageTarget,
00019     _Out_ IPrintPreviewPageCollection** docPageCollection
00020     )
00021 {
00022     HRESULT hr = (docPackageTarget == nullptr) ? E_INVALIDARG : S_OK;
00023
00024     // Get for IPrintPreviewDxgiPackageTarget interface.
00025     if (SUCCEEDED(hr))
00026     {
00027         hr = docPackageTarget->GetPackageTarget(
00028             ID_PREVIEWPACKAGETARGET_DXGI,
00029             IID_PPV_ARGS(&m_dxgiPreviewTarget)
00030             );
00031     }
00032
00033     ComPtr<IPrintPreviewPageCollection> pageCollection;
00034     if (SUCCEEDED(hr))
00035     {
00036         ComPtr<CDocumentSource> docSource(this);
00037         hr = docSource.As<IPrintPreviewPageCollection>(&pageCollection);
00038     }
00039
00040     if (SUCCEEDED(hr))
00041     {
00042         hr = pageCollection.CopyTo(docPageCollection);
00043     }
00044
00045     return hr;
00046 }
00047
00048 IFACEMETHODIMP
00049 CDocumentSource::MakeDocument(
00050     _In_ IInspectable*                docOptions,
00051     _In_ IPrintDocumentPackageTarget* docPackageTarget
00052     )
00053 {
00054     if (docOptions == nullptr || docPackageTarget == nullptr)
00055     {
00056         return E_INVALIDARG;
00057     }
00058
00059     // Get print settings from PrintTaskOptions for printing, such as page description, which contains page size, imageable area, DPI.
00060     // User can obtain other print settings in the same way, such as ColorMode, NumberOfCopies, etc., which are not shown in this sample.
00061     PrintTaskOptions^ option = reinterpret_cast<PrintTaskOptions^>(docOptions);
00062     PrintPageDescription pageDesc = option->GetPageDescription(1); // Get the description of the first page.
00063
00064     // Create a print control properties and set DPI from PrintPageDescription.
00065     D2D1_PRINT_CONTROL_PROPERTIES printControlProperties;
00066
00067     printControlProperties.rasterDPI  = (float)(min(pageDesc.DpiX, pageDesc.DpiY)); // DPI for rasterization of all unsupported D2D commands or options
00068     printControlProperties.colorSpace = D2D1_COLOR_SPACE_SRGB;                  // Color space for vector graphics in D2D print control.
00069     printControlProperties.fontSubset = D2D1_PRINT_FONT_SUBSET_MODE_DEFAULT;    // Subset for used glyphs, send and discard font resource after every five pages
00070
00071     HRESULT hr = S_OK;
00072
00073     try
00074     {
00075         // Create a new print control linked to the package target.
00076         m_renderer->CreatePrintControl(
00077             docPackageTarget,
00078             &printControlProperties
00079             );
00080
00081         // Calculate imageable area and page size from PrintPageDescription.
00082         D2D1_RECT_F imageableRect = D2D1::RectF(
00083             pageDesc.ImageableRect.X,
00084             pageDesc.ImageableRect.Y,
00085             pageDesc.ImageableRect.X + pageDesc.ImageableRect.Width,
00086             pageDesc.ImageableRect.Y + pageDesc.ImageableRect.Height
00087             );
00088
00089         D2D1_SIZE_F pageSize = D2D1::SizeF(pageDesc.PageSize.Width, pageDesc.PageSize.Height);
00090
00091         // Loop to add page command list to d2d print control.
00092         for (uint32 pageNum = 1; pageNum <= m_totalPages; ++pageNum)
00093         {
00094             m_renderer->PrintPage(
00095                 pageNum,
00096                 imageableRect,
00097                 pageSize,
00098                 nullptr // If a page-level print ticket is not specified here, the package print ticket is applied for each page.
00099                 );
00100         }
00101     }
00102     catch (Platform::Exception^ e)
00103     {
00104         hr = e->HResult;
00105
00106         if (hr == D2DERR_RECREATE_TARGET)
00107         {
00108             // In case of device lost, the whole print job will be aborted, and we should recover
00109             // so that the device is ready when used again. At the same time, we should propagate
00110             // this error to the Modern Print Dialog.
00111             m_renderer->HandleDeviceLost();
00112         }
00113     }
00114
00115     // Make sure to close d2d print control even if AddPage fails.
00116     HRESULT hrClose = m_renderer->ClosePrintControl();
00117
00118     if (SUCCEEDED(hr))
00119     {
00120         hr = hrClose;
00121     }
00122
00123     return hr;
00124 }
00125
00126 #pragma endregion IDocumentPageSource Methods
00127
00128 #pragma region IPrintPreviewPageCollection Methods
00129
00130 IFACEMETHODIMP
00131 CDocumentSource::Paginate(
00132     _In_   uint32           currentJobPage,
00133     _In_   IInspectable*    docOptions
00134     )
00135 {
00136     HRESULT hr = (docOptions == nullptr) ? E_INVALIDARG : S_OK;
00137
00138     if (SUCCEEDED(hr))
00139     {
00140         // Get print settings from PrintTaskOptions for printing, such as page description, which contains page size, imageable area, DPI.
00141         // User can obtain other print settings in the same way, such as ColorMode, NumberOfCopies, etc., which are not shown in this sample.
00142         PrintTaskOptions^ option = reinterpret_cast<PrintTaskOptions^>(docOptions);
00143         PrintPageDescription pageDesc = option->GetPageDescription(currentJobPage);
00144
00145         hr = m_dxgiPreviewTarget->InvalidatePreview();
00146
00147         // Set the total page number.
00148         if (SUCCEEDED(hr))
00149         {
00150             hr = m_dxgiPreviewTarget->SetJobPageCount(PageCountType::FinalPageCount, m_totalPages);
00151         }
00152
00153         if (SUCCEEDED(hr))
00154         {
00155             m_width = pageDesc.PageSize.Width;
00156             m_height = pageDesc.PageSize.Height;
00157
00158             m_imageableRect = D2D1::RectF(
00159                 pageDesc.ImageableRect.X,
00160                 pageDesc.ImageableRect.Y,
00161                 pageDesc.ImageableRect.X + pageDesc.ImageableRect.Width,
00162                 pageDesc.ImageableRect.Y + pageDesc.ImageableRect.Height
00163                 );
00164
00165             // Now we are ready to let MakePage to be called.
00166             m_paginateCalled = true;
00167         }
00168     }
00169
00170     return hr;
00171 }
00172
00173 // Here, desiredWidth/desiredHeight is the desired size of preview surface by print mananger in system.
00174 // The final size of the preview surface must have the same proportion as that of the desired width/height.
00175 // In this sample, we just use it as preview size and return the scale variant for surface drawing.
00176 // The size here is in DIPs.
00177 float
00178 CDocumentSource::TransformedPageSize(
00179     _In_  float                         desiredWidth,
00180     _In_  float                         desiredHeight,
00181     _Out_ Windows::Foundation::Size*    previewSize
00182     )
00183 {
00184     float scale = 1.0f;
00185
00186     if (desiredWidth > 0 && desiredHeight > 0)
00187     {
00188         previewSize->Width  = desiredWidth;
00189         previewSize->Height = desiredHeight;
00190
00191         scale = m_width / desiredWidth;
00192     }
00193     else
00194     {
00195         previewSize->Width = 0;
00196         previewSize->Height = 0;
00197     }
00198
00199     return scale;
00200 }
00201
00202 // This sample only acts upon orientation setting for an example. The orientation is read from the user selection
00203 // in the Print Experience and is then used to reflow the content in a different way.
00204 IFACEMETHODIMP
00205 CDocumentSource::MakePage(
00206     _In_ uint32 desiredJobPage,
00207     _In_ float  width,
00208     _In_ float  height
00209     )
00210 {
00211     HRESULT hr = (width > 0 && height > 0) ? S_OK : E_INVALIDARG;
00212
00213     // When desiredJobPage is JOB_PAGE_APPLICATION_DEFINED, it means a new preview begins. If the implementation here is by an async way,
00214     // for example, queue MakePage calls for preview, app needs to clean resources for previous preview before next.
00215     // In this sample, we will reset page number if Paginate() has been called.
00216     if (desiredJobPage == JOB_PAGE_APPLICATION_DEFINED && m_paginateCalled)
00217     {
00218         desiredJobPage = 1;
00219     }
00220
00221     if (SUCCEEDED(hr) && m_paginateCalled)
00222     {
00223         // Calculate the size of preview surface, according to desired width and height.
00224         Windows::Foundation::Size previewSize;
00225         float scale = TransformedPageSize(width, height, &previewSize);
00226
00227         try
00228         {
00229             m_renderer->DrawPreviewSurface(
00230                 previewSize.Width,
00231                 previewSize.Height,
00232                 scale,
00233                 m_imageableRect,
00234                 desiredJobPage,
00235                 m_dxgiPreviewTarget.Get()
00236                 );
00237         }
00238         catch (Platform::Exception^ e)
00239         {
00240             hr = e->HResult;
00241
00242             if (hr == D2DERR_RECREATE_TARGET)
00243             {
00244                 // In case of device lost, we should recover so that the device is ready to render
00245                 // the next preview page when requested. At the same time, we should propagate this
00246                 // error to the Modern Print Dialog.
00247                 m_renderer->HandleDeviceLost();
00248             }
00249         }
00250     }
00251
00252     return hr;
00253 }
00254
00255 #pragma region IPrintPreviewPageCollection Methods
Generated on Sat Nov 23 2024 16:08:07 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Background Transfer/C++/MainPage.xaml.cpp Source File

  • Background Transfer

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Real-time communication/C++/Utils.cpp Source File

  • Real-time communication

Utils.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 "Utils.h"
00013
00014 using namespace SimpleCommunication;
00015 using namespace Windows::Devices::Enumeration;
00016 using namespace Windows::Foundation;
00017 using namespace Windows::Media::Capture;
00018
00019 using namespace Concurrency;
00020
00021 void
00022     SdkSample::Initialize(Windows::UI::Xaml::Controls::TextBlock^ statusMessage, Windows::UI::Core::CoreDispatcher^ dispatcher)
00023 {
00024     _statusMessage = statusMessage;
00025     _dispatcher = dispatcher;
00026 }
00027
00028 void
00029     SdkSample::Deinitialize()
00030 {
00031     _statusMessage = nullptr;
00032     _dispatcher = nullptr;
00033 }
00034
00035 void
00036     SdkSample::DisplayStatus(Platform::String^ msg)
00037 {
00038     Log(msg);
00039 }
00040
00041 void
00042     SdkSample::DisplayError(Platform::String^ msg)
00043 {
00044     Log(msg, nullptr, "error");
00045 }
00046
00047 void
00048     SdkSample::FormatError(HResult err, Platform::String^ msg, Platform::String^ prefix)
00049 {
00050     if (err.Value)
00051     {
00052         WCHAR dst[33];
00053         _ultow_s(err.Value, dst, ARRAYSIZE(dst), 16);
00054         Log(
00055             prefix +
00056             msg +
00057             ", Error code: " +
00058             ref new Platform::String(dst),
00059             nullptr,
00060             "error"
00061             );
00062     }
00063     else
00064     {
00065         Log(
00066             prefix +
00067             msg,
00068             nullptr,
00069             "error"
00070             );
00071     }
00072 }
00073
00074 void
00075     SdkSample::FormatError(CaptureFailedEventArgs^ e, Platform::String^ prefix)
00076 {
00077     HResult hr;
00078     hr.Value = e->Code;
00079     FormatError(hr, e->Message, prefix);
00080 }
00081
00082 void
00083     SdkSample::ClearLastStatus()
00084 {
00085     Log("");
00086 }
00087
00088 void
00089     SdkSample::Log(Platform::String^ message)
00090 {
00091     Log(message, nullptr, "status");
00092 }
00093
00094 void
00095     SdkSample::Log(Platform::String^ message, Platform::String^ tag, Platform::String^ type)
00096 {
00097     auto isError = (type == "error");
00098     auto isStatus = (type == "status");
00099
00100     if (isError || isStatus)
00101     {
00102         if (_statusMessage && _dispatcher)
00103         {
00104             _dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal,
00105                 ref new Windows::UI::Core::DispatchedHandler([this, message, isError]()
00106             {
00107                 _statusMessage->Text = message;
00108                 if (isError)
00109                 {
00110                     _statusMessage->Foreground = ref new Windows::UI::Xaml::Media::SolidColorBrush(Windows::UI::Colors::Blue);
00111                 }
00112                 else
00113                 {
00114                     _statusMessage->Foreground = ref new Windows::UI::Xaml::Media::SolidColorBrush(Windows::UI::Colors::Green);
00115                 }
00116             }));
00117         }
00118     }
00119 }
00120
00121 CaptureDevice::CaptureDevice()
00122     : _mediaCapture(nullptr)
00123 {
00124
00125 }
00126
00127 Platform::Agile<MediaCapture>
00128     CaptureDevice::MediaCapture::get()
00129 {
00130     return _mediaCapture;
00131 }
00132
00133 /// <summary>
00134 /// Initialization of the device.
00135 /// </summary>
00136 task<void>
00137     CaptureDevice::InitializeAsync()
00138 {
00139     try
00140     {
00141         auto mediaCapture = ref new Windows::Media::Capture::MediaCapture();
00142         _mediaCapture = mediaCapture;
00143         _mediaCaptureFailedEventRegistrationToken = mediaCapture->Failed::add(ref new MediaCaptureFailedEventHandler(this, &CaptureDevice::OnCaptureFailed));
00144
00145         return task<void>(mediaCapture->InitializeAsync());
00146     }
00147     catch (Platform::Exception^ e)
00148     {
00149         DoCleanup();
00150         throw e;
00151     }
00152
00153     return create_task([](){});
00154 }
00155
00156 /// <summary>
00157 /// Cleaning up the sink.
00158 /// </summary>
00159 void
00160     CaptureDevice::CleanupSink()
00161 {
00162     if (_mediaSink)
00163     {
00164         _mediaSink->IncomingConnectionEvent::remove(_mediaSinkIncomingConnectionEventRegistrationToken);
00165         _mediaSink->Close();
00166         _mediaSink = nullptr;
00167         _recordingStarted = false;
00168     }
00169 }
00170
00171 /// <summary>
00172 /// Cleans up the resources.
00173 /// </summary>
00174 void
00175     CaptureDevice::DoCleanup()
00176 {
00177     Windows::Media::Capture::MediaCapture ^mediaCapture = _mediaCapture.Get();
00178     if (mediaCapture != nullptr)
00179     {
00180         mediaCapture->Failed::remove(_mediaCaptureFailedEventRegistrationToken);
00181     }
00182
00183     CleanupSink();
00184 }
00185
00186 /// <summary>
00187 /// Asynchronous method cleaning up resources and stopping recording if necessary.
00188 /// </summary>
00189 task<void>
00190     CaptureDevice::CleanupAsync()
00191 {
00192     Windows::Media::Capture::MediaCapture ^mediaCapture = _mediaCapture.Get();
00193     if (mediaCapture == nullptr && !_mediaSink)
00194     {
00195         return create_task([](){});
00196     }
00197
00198     if (mediaCapture != nullptr)
00199     {
00200         mediaCapture->Failed::remove(_mediaCaptureFailedEventRegistrationToken);
00201     }
00202
00203     if (mediaCapture != nullptr && _recordingStarted)
00204     {
00205         return task<void>(mediaCapture->StopRecordAsync()).then([this](task<void>)
00206         {
00207             DoCleanup();
00208         });
00209     }
00210     else
00211     {
00212         DoCleanup();
00213     }
00214     return create_task([](){});
00215 }
00216
00217 /// <summary>
00218 /// Function allows to select camera settings.
00219 /// </summary>
00220 /// <param name="mediaStreamType" type="Windows.Media.Capture.MediaStreamType">
00221 /// Type of a the media stream.
00222 /// </param>
00223 /// <param name="mediaStreamType">
00224 /// Function which will be called to filter the correct settings.
00225 /// </param>
00226 task<void>
00227     CaptureDevice::SelectPreferredCameraStreamSettingAsync(MediaStreamType mediaStreamType, VideoSettingsFilter^ settingsFilterFunc)
00228 {
00229     auto prefferedSettings = _mediaCapture.Get()->VideoDeviceController->GetAvailableMediaStreamProperties(mediaStreamType);
00230
00231     std::vector<Windows::Media::MediaProperties::IVideoEncodingProperties^> vector;
00232     for (unsigned int i = 0; i < prefferedSettings->Size; i ++)
00233     {
00234         auto prop = prefferedSettings->GetAt(i);
00235         if (settingsFilterFunc(prop, i))
00236         {
00237             vector.push_back(static_cast<Windows::Media::MediaProperties::IVideoEncodingProperties^>(prop));
00238         }
00239     }
00240
00241     std::sort(vector.begin(), vector.end(), [](Windows::Media::MediaProperties::IVideoEncodingProperties^ prop1, Windows::Media::MediaProperties::IVideoEncodingProperties^ prop2)
00242     {
00243         return (prop2->Width - prop1->Width);
00244     }
00245     );
00246
00247     if (vector.size() > 0)
00248     {
00249         return task<void>(_mediaCapture.Get()->VideoDeviceController->SetMediaStreamPropertiesAsync(mediaStreamType, vector.front()));
00250     }
00251
00252     return create_task([]()
00253     {
00254         // Nothing to do
00255     });
00256 }
00257
00258 /// <summary>
00259 /// Begins recording
00260 /// </summary>
00261 /// <param name="mediaEncodingProfile">
00262 /// Encoding profile which should be used for the recording session.
00263 /// </param>
00264 task<void>
00265     CaptureDevice::StartRecordingAsync(Windows::Media::MediaProperties::MediaEncodingProfile^ mediaEncodingProfile)
00266 {
00267     // We cannot start recording twice.
00268     if (_mediaSink && _recordingStarted)
00269     {
00270         throw ref new Platform::Exception(__HRESULT_FROM_WIN32(ERROR_INVALID_STATE));
00271     }
00272
00273     // Release sink if there is one already.
00274     CleanupSink();
00275
00276     // Create new sink
00277     _mediaSink = ref new Microsoft::Samples::SimpleCommunication::StspMediaSink();
00278     _mediaSinkIncomingConnectionEventRegistrationToken = _mediaSink->IncomingConnectionEvent::add(ref new Microsoft::Samples::SimpleCommunication::IncomingConnectionHandler(this, &CaptureDevice::OnIncomingConnection));
00279
00280     return task<void>(_mediaSink->InitializeAsync(mediaEncodingProfile->Audio, mediaEncodingProfile->Video)).then([this, mediaEncodingProfile]()
00281     {
00282         return task<void>(_mediaCapture.Get()->StartRecordToCustomSinkAsync(mediaEncodingProfile, _mediaSink)).then([this](task<void> asyncInfo)
00283         {
00284             try
00285             {
00286                 asyncInfo.get();
00287                 _recordingStarted = true;
00288             }
00289             catch (Platform::Exception^ e)
00290             {
00291                 CleanupSink();
00292                 throw e;
00293             }
00294         });
00295     });
00296 }
00297
00298 /// <summary>
00299 /// Stops recording.
00300 /// </summary>
00301 task<void>
00302     CaptureDevice::StopRecordingAsync()
00303 {
00304     if (_recordingStarted)
00305     {
00306         return task<void>(_mediaCapture.Get()->StopRecordAsync()).then([this]()
00307         {
00308             CleanupSink();
00309         });
00310     }
00311     else
00312     {
00313         // If recording not started just do nothing
00314     }
00315     return create_task([](){});
00316 }
Generated on Sat Nov 23 2024 16:08:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/MeshObject.h Source File

  • XAML DirectX 3D shooting game

MeshObject.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 // MeshObject:
00011 // This class is the generic (abstract) representation of D3D11 Indexed triangle
00012 // list.  Each of the derived classes is just the constructor for the specific
00013 // geometry primitive.  This abstract class does not place any requirements on
00014 // the format of the geometry directly.
00015 // The primary method of the MeshObject is Render.  The default implementation
00016 // just sets the IndexBuffer, VertexBuffer and topology to a TriangleList and
00017 // makes a  DrawIndexed call on the context.  It assumes all other state has
00018 // already been set on the context.
00019
00020 ref class MeshObject abstract
00021 {
00022 internal:
00023     MeshObject();
00024
00025     virtual void Render(_In_ ID3D11DeviceContext *context);
00026
00027 protected private:
00028     Microsoft::WRL::ComPtr<ID3D11Buffer>  m_vertexBuffer;
00029     Microsoft::WRL::ComPtr<ID3D11Buffer>  m_indexBuffer;
00030     int                                   m_vertexCount;
00031     int                                   m_indexCount;
00032 };
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-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.
__pad0__ | List< T * > |
AcceptChildNode(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^childXmlNode) override | List< T * > | [virtual]
AddChild(_In_ Element^element) | Element |
AddSibling(_In_ Element^element) | Element |
Back() const | List< T * > | [inline, protected]
Back() const | List< T * > | [inline, protected]
Back() const | List< T * > | [inline, protected]
BindResource(_In_ Element^rootElement) | Element | [virtual]
Clear() | ComPtrList< T, NULLABLE > | [inline, virtual]
Clear() | ComPtrList< T, NULLABLE > | [inline, virtual]
Clear() | ComPtrList< T, NULLABLE > | [inline, virtual]
List< T * >::Clear(FN &clear_fn) | List< T * > | [inline]
Create(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^xmlNode) | Element | [static]
Draw(_In_ Document^document, D2D1::Matrix3x2F const &transform) override | List< T * > | [virtual]
EndPosition() const | List< T * > | [inline]
EndPosition() const | List< T * > | [inline]
EndPosition() const | List< T * > | [inline]
Front() const | List< T * > | [inline, protected]
Front() const | List< T * > | [inline, protected]
Front() const | List< T * > | [inline, protected]
FrontPosition() | List< T * > | [inline]
FrontPosition() | List< T * > | [inline]
FrontPosition() | List< T * > | [inline]
GetBack(T **ppItem) | List< T * > | [inline]
GetBack(T **ppItem) | List< T * > | [inline]
GetBack(T **ppItem) | List< T * > | [inline]
GetCount() const | List< T * > | [inline]
GetCount() const | List< T * > | [inline]
GetCount() const | List< T * > | [inline]
GetFirstChild() | Element | [inline]
GetFront(T **ppItem) | List< T * > | [inline]
GetFront(T **ppItem) | List< T * > | [inline]
GetFront(T **ppItem) | List< T * > | [inline]
GetItem(const Node *pNode, Ptr *ppItem) | ComPtrList< T, NULLABLE > | [inline, protected]
GetItem(const Node *pNode, Ptr *ppItem) | ComPtrList< T, NULLABLE > | [inline, protected]
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]
GetItemPos(POSITION pos, T **ppItem) | List< T * > | [inline]
GetItemPos(POSITION pos, T **ppItem) | List< T * > | [inline]
GetName() | Element | [inline]
GetNextSibling() | Element | [inline]
GetOpacity() override | Rectangle | [inline, virtual]
GetParent() | Element | [inline]
GetSize() | Element | [inline]
Initialize(_In_ Document^document, _In_ Windows::Data::Xml::Dom::XmlElement^xmlElement) override | List< T * > | [virtual]
InsertAfter(Ptr item, Node *pBefore) | ComPtrList< T, NULLABLE > | [inline, protected]
InsertAfter(Ptr item, Node *pBefore) | ComPtrList< T, NULLABLE > | [inline, protected]
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]
InsertBack(T *item) | List< T * > | [inline]
InsertBack(T *item) | List< T * > | [inline]
InsertFront(T *item) | List< T * > | [inline]
InsertFront(T *item) | List< T * > | [inline]
InsertFront(T *item) | List< T * > | [inline]
InsertPos(POSITION pos, T *item) | List< T * > | [inline]
InsertPos(POSITION pos, T *item) | List< T * > | [inline]
InsertPos(POSITION pos, T *item) | List< T * > | [inline]
IsEmpty() const | List< T * > | [inline]
IsEmpty() const | List< T * > | [inline]
IsEmpty() const | List< T * > | [inline]
List() | List< T * > | [inline]
List() | List< T * > | [inline]
List() | List< T * > | [inline]
m_anchor | List< T * > | [protected]
m_count | List< T * > | [protected]
Measure(_In_ Document^document, D2D1_SIZE_F const &parentSize, _Out_ D2D1_RECT_F *bounds) override | List< T * > | [virtual]
Next(const POSITION pos) | List< T * > | [inline]
Next(const POSITION pos) | List< T * > | [inline]
Next(const POSITION pos) | List< T * > | [inline]
PrepareToDraw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
Ptr typedef | ComPtrList< T, NULLABLE > |
Ptr typedef | ComPtrList< T, NULLABLE > |
Ptr typedef | ComPtrList< T, NULLABLE > |
ReleaseParent() | Element | [virtual]
Remove(POSITION &pos, T **ppItem) | List< T * > | [inline]
Remove(POSITION &pos, T **ppItem) | List< T * > | [inline]
Remove(POSITION &pos, T **ppItem) | List< T * > | [inline]
RemoveBack(T **ppItem) | List< T * > | [inline]
RemoveBack(T **ppItem) | List< T * > | [inline]
RemoveBack(T **ppItem) | List< T * > | [inline]
RemoveFront(T **ppItem) | List< T * > | [inline]
RemoveFront(T **ppItem) | List< T * > | [inline]
RemoveFront(T **ppItem) | List< T * > | [inline]
RemoveItem(Node *pNode, Ptr *ppItem) | ComPtrList< T, NULLABLE > | [inline, protected]
RemoveItem(Node *pNode, Ptr *ppItem) | ComPtrList< T, NULLABLE > | [inline, protected]
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]
~ComPtrList() | ComPtrList< T, NULLABLE > | [inline]
~ComPtrList() | ComPtrList< T, NULLABLE > | [inline]
~List() | List< T * > | [inline, virtual]
~List() | List< T * > | [inline, virtual]
~List() | List< T * > | [inline, virtual]
Generated on Sat Nov 23 2024 16:09:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/LocalResourceLoader.cpp Source File

  • Hilo C++
  • Hilo

LocalResourceLoader.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 #include "LocalResourceLoader.h"
00009
00010 using namespace Hilo;
00011 using namespace Platform;
00012 using namespace Windows::ApplicationModel::Resources;
00013
00014 String^ LocalResourceLoader::GetString(String^ value)
00015 {
00016     auto loader = ref new ResourceLoader();
00017     return loader->GetString(value);
00018 }
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/ScenarioOutput4.xaml.h Source File

  • Media extensions

ScenarioOutput4.xaml.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 //
00009 // ScenarioOutput4.xaml.h
00010 // Declaration of the ScenarioOutput4 class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioOutput4.g.h"
00017 #include "MainPage.xaml.h"
00018
00019 namespace MediaExtensionsCPP
00020 {
00021     [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class ScenarioOutput4 sealed
00023     {
00024     public:
00025         ScenarioOutput4();
00026
00027     protected:
00028         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030
00031     private:
00032         ~ScenarioOutput4();
00033         MainPage^ rootPage;
00034         Windows::Foundation::EventRegistrationToken _mediaFailedToken;
00035     };
00036 }
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Context menu/C++/Scenario1.xaml.cpp Source File

  • Context menu

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::ContextMenu;
00020
00021 using namespace concurrency;
00022 using namespace Windows::Foundation;
00023 using namespace Windows::UI::Popups;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Controls;
00026 using namespace Windows::UI::Xaml::Input;
00027 using namespace Windows::UI::Xaml::Media;
00028 using namespace Windows::UI::Xaml::Navigation;
00029
00030 Scenario1::Scenario1()
00031 {
00032     InitializeComponent();
00033     rootPage = MainPage::Current;
00034     AttachmentImage->RightTapped += ref new RightTappedEventHandler(this, &Scenario1::AttachmentImage_RightTapped);
00035 }
00036
00037 Rect Scenario1::GetElementRect(FrameworkElement^ element)
00038 {
00039     GeneralTransform^ buttonTransform = element->TransformToVisual(nullptr);
00040     const Point pointOrig(0, 0);
00041     const Point pointTransformed = buttonTransform->TransformPoint(pointOrig);
00042     const Rect rect(pointTransformed.X, pointTransformed.Y, safe_cast<float>(element->ActualWidth), safe_cast<float>(element->ActualHeight));
00043     return rect;
00044 }
00045
00046 void Scenario1::AttachmentImage_RightTapped(Object^ sender, RightTappedRoutedEventArgs^ e)
00047 {
00048     // Create a menu and add commands specifying a callback delegate for each.
00049     // Since command delegates are unique, no need to specify command Ids.
00050     auto menu = ref new PopupMenu();
00051     menu->Commands->Append(ref new UICommand("Open with", ref new UICommandInvokedHandler([this](IUICommand^ command)
00052     {
00053         OutputTextBlock->Text = "'" + command->Label + "' selected";
00054     })));
00055
00056     menu->Commands->Append(ref new UICommand("Save attachment", ref new UICommandInvokedHandler([this](IUICommand^ command)
00057     {
00058         OutputTextBlock->Text = "'" + command->Label + "' selected";
00059     })));
00060
00061     // We don't want to obscure content, so pass in a rectangle representing the sender of the context menu event.
00062     auto rect = GetElementRect(safe_cast<FrameworkElement^>(sender));
00063     create_task(menu->ShowForSelectionAsync(rect)).then([this](IUICommand^ command)
00064     {
00065         if (command == nullptr)
00066         {
00067             // The command is null if no command was invoked.
00068             OutputTextBlock->Text = L"Context menu dismissed";
00069         }
00070     });
00071     OutputTextBlock->Text = "Context menu shown";
00072 }
Generated on Sat Nov 23 2024 16:07:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File access/C++/App.xaml.h Source File

  • File access

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D custom image effects/C++/PixelShader/pch.cpp Source File

  • Direct2D custom image effects
  • PixelShader

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Secondary tiles/C#,C++/PinFromAppbar.xaml.h Source File

  • Secondary tiles
  • C#,C++

PinFromAppbar.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 // PinFromAppbar.xaml.h
00013 // Declaration of the PinFromAppbar class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "PinFromAppbar.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SecondaryTiles
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 PinFromAppbar sealed
00029     {
00030     public:
00031         PinFromAppbar();
00032
00033     protected:
00034         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00035         virtual void OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^ e) override;
00036
00037     private:
00038         MainPage^ rootPage;
00039         Windows::UI::Xaml::Controls::Button^ pinToAppBar;
00040         Windows::UI::Xaml::Controls::StackPanel^ rightPanel;
00041         void Init();
00042         void ToggleAppBarButton(bool showPinButton);
00043         void BottomAppBar_Opened(Platform::Object^ sender, Platform::Object^ e);
00044         void Button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00045         Windows::Foundation::EventRegistrationToken appBarOpenedToken;
00046         Windows::Foundation::EventRegistrationToken buttonClickToken;
00047     };
00048 }
Generated on Sat Nov 23 2024 16:08:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media capture using capture device/C++/Constants.h Source File

  • Media capture using capture device

Constants.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 namespace SDKSample
00015 {
00016     public value struct Scenario
00017     {
00018         Platform::String^ Title;
00019         Platform::String^ ClassName;
00020     };
00021
00022     partial ref class MainPage
00023     {
00024     public:
00025         static property Platform::String^ FEATURE_NAME
00026         {
00027             Platform::String^ get()
00028             {
00029                 return ref new Platform::String(L"MediaCapture CPP sample");
00030             }
00031         }
00032
00033         static property Platform::Array<Scenario>^ scenarios
00034         {
00035             Platform::Array<Scenario>^ get()
00036             {
00037                 return scenariosInner;
00038             }
00039         }
00040     private:
00041         static Platform::Array<Scenario>^ scenariosInner;
00042     };
00043
00044
00045 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Custom driver access/C++/app_cpp/Scenario3_DeviceEvents.xaml.h Source File

  • Custom driver access
  • app_cpp

Scenario3_DeviceEvents.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 // DeviceEvents.xaml.h
00013 // Declaration of the DeviceEvents class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario3_DeviceEvents.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace CustomDeviceAccess
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 DeviceEvents sealed
00031         {
00032         public:
00033             DeviceEvents();
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         private:
00039             MainPage^ rootPage;
00040             Windows::Foundation::EventRegistrationToken deviceClosingHandler;
00041
00042             bool switchChangedEventsRegistered;
00043             Windows::Foundation::EventRegistrationToken switchChangedEventsHandler;
00044             Platform::Array<bool>^ previousSwitchValues;
00045
00046             void deviceEventsGet_Click_1(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void deviceEventsRegister_Click_1(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048
00049             void RegisterForSwitchStateChangedEvent(bool r);
00050
00051             void UpdateRegisterButton(void);
00052             void OnSwitchStateChangedEvent(Samples::Devices::Fx2::Fx2Device^ sender, Samples::Devices::Fx2::SwitchStateChangedEventArgs^ e);
00053
00054             void ClearSwitchStateTable();
00055             void UpdateSwitchStateTable(Platform::Array<bool>^ SwitchStateArray);
00056
00057             void Current_DeviceClosing(Platform::Object^ sender, Samples::Devices::Fx2::Fx2Device^ device);
00058         };
00059     }
00060 }
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Lock screen apps/C#,C++/NotificationsExtensions/BadgeContent.cs Source File

  • Lock screen apps
  • C#,C++
  • NotificationsExtensions

BadgeContent.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 System;
00009 #if !WINRT_NOT_PRESENT
00010 using Windows.Data.Xml.Dom;
00011 using Windows.UI.Notifications;
00012 #endif
00013
00014 namespace NotificationsExtensions.BadgeContent
00015 {
00016     /// <summary>
00017     /// Notification content object to display a glyph on a tile's badge.
00018     /// </summary>
00019     public sealed class BadgeGlyphNotificationContent : IBadgeNotificationContent
00020     {
00021         /// <summary>
00022         /// Default constructor to create a glyph badge content object.
00023         /// </summary>
00024         public BadgeGlyphNotificationContent()
00025         {
00026         }
00027
00028         /// <summary>
00029         /// Constructor to create a glyph badge content object with a glyph.
00030         /// </summary>
00031         /// <param name="glyph">The glyph to be displayed on the badge.</param>
00032         public BadgeGlyphNotificationContent(GlyphValue glyph)
00033         {
00034             m_Glyph = glyph;
00035         }
00036
00037         /// <summary>
00038         /// The glyph to be displayed on the badge.
00039         /// </summary>
00040         public GlyphValue Glyph
00041         {
00042             get { return m_Glyph; }
00043             set
00044             {
00045                 if (!Enum.IsDefined(typeof(GlyphValue), value))
00046                 {
00047                     throw new ArgumentOutOfRangeException("value");
00048                 }
00049                 m_Glyph = value;
00050             }
00051         }
00052
00053         /// <summary>
00054         /// Retrieves the notification Xml content as a string.
00055         /// </summary>
00056         /// <returns>The notification Xml content as a string.</returns>
00057         public string GetContent()
00058         {
00059             if (!Enum.IsDefined(typeof(GlyphValue), m_Glyph))
00060             {
00061                 throw new NotificationContentValidationException("The badge glyph property was left unset.");
00062             }
00063
00064             string glyphString = m_Glyph.ToString();
00065             // lower case the first character of the enum value to match the Xml schema
00066             glyphString = String.Format("{0}{1}", Char.ToLowerInvariant(glyphString[0]), glyphString.Substring(1));
00067             return String.Format("<badge version='{0}' value='{1}'/>", Util.NOTIFICATION_CONTENT_VERSION, glyphString);
00068         }
00069
00070         /// <summary>
00071         /// Retrieves the notification Xml content as a string.
00072         /// </summary>
00073         /// <returns>The notification Xml content as a string.</returns>
00074         public override string ToString()
00075         {
00076             return GetContent();
00077         }
00078
00079 #if !WINRT_NOT_PRESENT
00080         /// <summary>
00081         /// Retrieves the notification Xml content as a WinRT Xml document.
00082         /// </summary>
00083         /// <returns>The notification Xml content as a WinRT Xml document.</returns>
00084         public XmlDocument GetXml()
00085         {
00086             XmlDocument xml = new XmlDocument();
00087             xml.LoadXml(GetContent());
00088             return xml;
00089         }
00090
00091         /// <summary>
00092         /// Creates a WinRT BadgeNotification object based on the content.
00093         /// </summary>
00094         /// <returns>A WinRT BadgeNotification object based on the content.</returns>
00095         public BadgeNotification CreateNotification()
00096         {
00097             XmlDocument xmlDoc = new XmlDocument();
00098             xmlDoc.LoadXml(GetContent());
00099             return new BadgeNotification(xmlDoc);
00100         }
00101 #endif
00102
00103         private GlyphValue m_Glyph = (GlyphValue)(-1);
00104     }
00105
00106     /// <summary>
00107     /// Notification content object to display a number on a tile's badge.
00108     /// </summary>
00109     public sealed class BadgeNumericNotificationContent : IBadgeNotificationContent
00110     {
00111         /// <summary>
00112         /// Default constructor to create a numeric badge content object.
00113         /// </summary>
00114         public BadgeNumericNotificationContent()
00115         {
00116         }
00117
00118         /// <summary>
00119         /// Constructor to create a numeric badge content object with a number.
00120         /// </summary>
00121         /// <param name="number">
00122         /// The number that will appear on the badge.  If the number is 0, the badge
00123         /// will be removed.  The largest value that will appear on the badge is 99.
00124         /// Numbers greater than 99 are allowed, but will be displayed as "99+".
00125         /// </param>
00126         public BadgeNumericNotificationContent(uint number)
00127         {
00128             m_Number = number;
00129         }
00130
00131         /// <summary>
00132         /// The number that will appear on the badge.  If the number is 0, the badge
00133         /// will be removed.  The largest value that will appear on the badge is 99.
00134         /// Numbers greater than 99 are allowed, but will be displayed as "99+".
00135         /// </summary>
00136         public uint Number
00137         {
00138             get { return m_Number; }
00139             set { m_Number = value; }
00140         }
00141
00142         /// <summary>
00143         /// Retrieves the notification Xml content as a string.
00144         /// </summary>
00145         /// <returns>The notification Xml content as a string.</returns>
00146         public string GetContent()
00147         {
00148             return String.Format("<badge version='{0}' value='{1}'/>", Util.NOTIFICATION_CONTENT_VERSION, m_Number);
00149         }
00150
00151         /// <summary>
00152         /// Retrieves the notification Xml content as a string.
00153         /// </summary>
00154         /// <returns>The notification Xml content as a string.</returns>
00155         public override string ToString()
00156         {
00157             return GetContent();
00158         }
00159
00160 #if !WINRT_NOT_PRESENT
00161         /// <summary>
00162         /// Retrieves the notification Xml content as a WinRT Xml document.
00163         /// </summary>
00164         /// <returns>The notification Xml content as a WinRT Xml document.</returns>
00165         public XmlDocument GetXml()
00166         {
00167             XmlDocument xml = new XmlDocument();
00168             xml.LoadXml(GetContent());
00169             return xml;
00170         }
00171
00172         /// <summary>
00173         /// Creates a WinRT BadgeNotification object based on the content.
00174         /// </summary>
00175         /// <returns>A WinRT BadgeNotification object based on the content.</returns>
00176         public BadgeNotification CreateNotification()
00177         {
00178             XmlDocument xmlDoc = new XmlDocument();
00179             xmlDoc.LoadXml(GetContent());
00180             return new BadgeNotification(xmlDoc);
00181         }
00182 #endif
00183
00184         private uint m_Number = 0;
00185     }
00186 }
Generated on Sat Nov 23 2024 16:08:19 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML high contrast style/C++/Scenario3.xaml.cpp Source File

  • XAML high contrast style

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 SDKSample::HighContrast;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 Scenario3::Scenario3()
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 Scenario3::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
00043 void SDKSample::HighContrast::Scenario3::Go_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00044 {
00045     Button^ b = safe_cast<Button^>(sender);
00046     if (b != nullptr)
00047     {
00048         rootPage->NotifyUser("You clicked the " + b->Name + " button", NotifyType::StatusMessage);
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML user and custom controls/C++/pch.h Source File

  • XAML user and custom controls

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
00023 #include "BasicCustomControl.h"
00024 #include "ImageWithLabelControl.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

StreamSocketSample::Scenario Member List

This is the complete list of members for StreamSocketSample::Scenario, including all inherited members.
ClassName | StreamSocketSample::Scenario
Title | StreamSocketSample::Scenario
Generated on Sat Nov 23 2024 16:09:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Compression/C++/common/LayoutAwarePage.h Source File

  • Compression
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Touch keyboard text input/C++/ScopedViews.xaml.h Source File

  • Input Touch keyboard text input

ScopedViews.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 // ScopedViews.xaml.h
00013 // Declaration of the ScopedViews class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "ScopedViews.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace TouchKeyboardTextInput
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 ScopedViews sealed
00031         {
00032         public:
00033             ScopedViews();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039         };
00040     }
00041 }
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Proximity/C++/pch.cpp Source File

  • Proximity

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::Common::sealed Member List

This is the complete list of members for SDKSample::Common::sealed, including all inherited members.
__pad0__ | SDKSample::Common::sealed |
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreAsync(void) | SDKSample::Common::sealed | [static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveAsync(void) | SDKSample::Common::sealed | [static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [private, static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
SessionStateForFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
sessionStateKey | SDKSample::Common::sealed |
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
UnregisterFrame(Windows::UI::Xaml::Controls::Frame^frame) | SDKSample::Common::sealed | [static]
Generated on Sat Nov 23 2024 16:09:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Language font mapping/C++/ScenarioInput2.xaml.h Source File

  • Language font mapping

ScenarioInput2.xaml.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 //
00009 // Scenario2Input.xaml.h
00010 // Declaration of the Scenario2Input class.
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioInput2.g.h"
00017 #include "MainPage.g.h"
00018
00019 namespace LanguageFontCPP
00020 {
00021     [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class ScenarioInput2 sealed
00023     {
00024     public:
00025         ScenarioInput2();
00026
00027     protected:
00028         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030
00031     private:
00032         ~ScenarioInput2();
00033         MainPage^ rootPage;
00034         void rootPage_OutputFrameLoaded(Object^ sender, Object^ e);
00035         void ApplyFont_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00036         Windows::Foundation::EventRegistrationToken _frameLoadedToken;
00037     FontInfoLocal^ _oriHeadingUI;
00038     FontInfoLocal^ _oriTextUI;
00039     };
00040 }
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text editing/C++/Scenario2.xaml.h Source File

  • XAML text editing

Scenario2.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.xaml.h
00013 // Declaration of the Scenario2 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario2.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace TextEditing
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 sealed
00031         {
00032         public:
00033             Scenario2();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void DoSomething_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX marble maze game/C++/UserInterface.cpp Source File

  • DirectX marble maze game

UserInterface.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 "UserInterface.h"
00010 #include "DirectXSample.h"
00011
00012 using namespace Windows::UI::Core;
00013 using namespace Windows::Foundation;
00014 using namespace Microsoft::WRL;
00015 using namespace Windows::UI::ViewManagement;
00016 using namespace D2D1;
00017
00018 #pragma region TextStyle
00019
00020 TextStyle::TextStyle()
00021 {
00022     m_fontName = L"Segoe UI";
00023     m_fontSize = 24.0f;
00024     m_fontWeight = DWRITE_FONT_WEIGHT_NORMAL;
00025     m_fontStyle = DWRITE_FONT_STYLE_NORMAL;
00026     m_textAlignment = DWRITE_TEXT_ALIGNMENT_LEADING;
00027 }
00028
00029 void TextStyle::SetFontName(Platform::String^ fontName)
00030 {
00031     if (!m_fontName->Equals(fontName))
00032     {
00033         m_fontName = fontName;
00034         m_textFormat = nullptr;
00035     }
00036 }
00037
00038 void TextStyle::SetFontSize(float fontSize)
00039 {
00040     if (m_fontSize != fontSize)
00041     {
00042         m_fontSize = fontSize;
00043         m_textFormat = nullptr;
00044     }
00045 }
00046
00047 void TextStyle::SetFontWeight(DWRITE_FONT_WEIGHT fontWeight)
00048 {
00049     if (m_fontWeight != fontWeight)
00050     {
00051         m_fontWeight = fontWeight;
00052         m_textFormat = nullptr;
00053     }
00054 }
00055
00056 void TextStyle::SetFontStyle(DWRITE_FONT_STYLE fontStyle)
00057 {
00058     if (m_fontStyle != fontStyle)
00059     {
00060         m_fontStyle = fontStyle;
00061         m_textFormat = nullptr;
00062     }
00063 }
00064
00065 void TextStyle::SetTextAlignment(DWRITE_TEXT_ALIGNMENT textAlignment)
00066 {
00067     if (m_textAlignment != textAlignment)
00068     {
00069         m_textAlignment = textAlignment;
00070         m_textFormat = nullptr;
00071     }
00072 }
00073
00074 IDWriteTextFormat* TextStyle::GetTextFormat()
00075 {
00076     if (m_textFormat == nullptr)
00077     {
00078         IDWriteFactory* dwriteFactory = UserInterface::GetDWriteFactory();
00079
00080         DX::ThrowIfFailed(
00081             dwriteFactory->CreateTextFormat(
00082                 m_fontName->Data(),
00083                 nullptr,
00084                 m_fontWeight,
00085                 m_fontStyle,
00086                 DWRITE_FONT_STRETCH_NORMAL,
00087                 m_fontSize,
00088                 L"en-US",
00089                 &m_textFormat
00090                 )
00091             );
00092
00093         DX::ThrowIfFailed(
00094             m_textFormat->SetTextAlignment(m_textAlignment)
00095             );
00096
00097         DX::ThrowIfFailed(
00098             m_textFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)
00099             );
00100     }
00101
00102     return m_textFormat.Get();
00103 }
00104
00105 #pragma endregion
00106
00107 #pragma region ElementBase
00108
00109 ElementBase::ElementBase():
00110     m_visible(false)
00111 {
00112 }
00113
00114 void ElementBase::SetAlignment(AlignType horizontal, AlignType vertical)
00115 {
00116     m_alignment.horizontal = horizontal;
00117     m_alignment.vertical = vertical;
00118 }
00119
00120 void ElementBase::SetContainer(const D2D1_RECT_F& container)
00121 {
00122     m_container = container;
00123 }
00124
00125 void ElementBase::SetVisible(bool visible)
00126 {
00127     m_visible = visible;
00128 }
00129
00130 D2D1_RECT_F ElementBase::GetBounds()
00131 {
00132     CalculateSize();
00133
00134     D2D1_RECT_F bounds = D2D1::RectF();
00135
00136     switch (m_alignment.horizontal)
00137     {
00138     case AlignNear:
00139         bounds.left = m_container.left;
00140         bounds.right = bounds.left + m_size.width;
00141         break;
00142
00143     case AlignCenter:
00144         bounds.left = m_container.left + (m_container.right - m_container.left - m_size.width) / 2.0f;
00145         bounds.right = bounds.left + m_size.width;
00146         break;
00147
00148     case AlignFar:
00149         bounds.right = m_container.right;
00150         bounds.left = bounds.right - m_size.width;
00151         break;
00152     }
00153
00154     switch (m_alignment.vertical)
00155     {
00156     case AlignNear:
00157         bounds.top = m_container.top;
00158         bounds.bottom = bounds.top + m_size.height;
00159         break;
00160
00161     case AlignCenter:
00162         bounds.top = m_container.top + (m_container.bottom - m_container.top - m_size.height) / 2.0f;
00163         bounds.bottom = bounds.top + m_size.height;
00164         break;
00165
00166     case AlignFar:
00167         bounds.bottom = m_container.bottom;
00168         bounds.top = bounds.bottom - m_size.height;
00169         break;
00170     }
00171
00172     return bounds;
00173 }
00174
00175 #pragma endregion
00176
00177 #pragma region TextElement
00178
00179 TextElement::TextElement():
00180     m_isFadingOut(false)
00181 {
00182 }
00183
00184 void TextElement::Initialize()
00185 {
00186     ID2D1DeviceContext* d2dContext = UserInterface::GetD2DContext();
00187
00188     DX::ThrowIfFailed(
00189         d2dContext->CreateSolidColorBrush(
00190             ColorF(ColorF::White),
00191             &m_textColorBrush
00192             )
00193         );
00194
00195     DX::ThrowIfFailed(
00196         d2dContext->CreateSolidColorBrush(
00197             ColorF(ColorF::Black),
00198             &m_shadowColorBrush
00199             )
00200         );
00201 }
00202
00203 void TextElement::Update(float timeTotal, float timeDelta)
00204 {
00205     if (m_isFadingOut)
00206     {
00207         m_fadeOutTimeElapsed += timeDelta;
00208
00209         float delta = min(1.0f, m_fadeOutTimeElapsed / m_fadeOutTime);
00210         SetTextOpacity((1.0f - delta) * m_fadeStartingOpacity);
00211
00212         if (m_fadeOutTimeElapsed >= m_fadeOutTime)
00213         {
00214             m_isFadingOut = false;
00215             SetVisible(false);
00216         }
00217     }
00218 }
00219
00220 void TextElement::Render()
00221 {
00222     ID2D1DeviceContext* d2dContext = UserInterface::GetD2DContext();
00223
00224     D2D1_RECT_F bounds = GetBounds();
00225     D2D1_POINT_2F origin = Point2F(
00226         bounds.left - m_textExtents.left,
00227         bounds.top - m_textExtents.top
00228         );
00229
00230     m_shadowColorBrush->SetOpacity(m_textColorBrush->GetOpacity() * 0.5f);
00231
00232     d2dContext->DrawTextLayout(
00233         Point2F(origin.x + 4.0f, origin.y + 4.0f),
00234         m_textLayout.Get(),
00235         m_shadowColorBrush.Get(),
00236         D2D1_DRAW_TEXT_OPTIONS_NO_SNAP
00237         );
00238
00239     d2dContext->DrawTextLayout(
00240         origin,
00241         m_textLayout.Get(),
00242         m_textColorBrush.Get(),
00243         D2D1_DRAW_TEXT_OPTIONS_NO_SNAP
00244         );
00245 }
00246
00247 void TextElement::SetTextColor(const D2D1_COLOR_F& textColor)
00248 {
00249     m_textColorBrush->SetColor(textColor);
00250 }
00251
00252 void TextElement::SetTextOpacity(float textOpacity)
00253 {
00254     m_textColorBrush->SetOpacity(textOpacity);
00255 }
00256
00257 void TextElement::SetText(__nullterminated WCHAR* text)
00258 {
00259     SetText(ref new Platform::String(text));
00260 }
00261
00262 void TextElement::SetText(Platform::String^ text)
00263 {
00264     if (!m_text->Equals(text))
00265     {
00266         m_text = text;
00267         m_textLayout = nullptr;
00268     }
00269 }
00270
00271 void TextElement::FadeOut(float fadeOutTime)
00272 {
00273     m_fadeStartingOpacity = m_textColorBrush->GetOpacity();
00274     m_fadeOutTime = fadeOutTime;
00275     m_fadeOutTimeElapsed = 0.0f;
00276     m_isFadingOut = true;
00277 }
00278
00279 void TextElement::CalculateSize()
00280 {
00281     CreateTextLayout();
00282
00283     DWRITE_TEXT_METRICS metrics;
00284     DWRITE_OVERHANG_METRICS overhangMetrics;
00285     DX::ThrowIfFailed(
00286         m_textLayout->GetMetrics(&metrics)
00287         );
00288     DX::ThrowIfFailed(
00289         m_textLayout->GetOverhangMetrics(&overhangMetrics)
00290         );
00291
00292     m_textExtents = RectF(
00293         -overhangMetrics.left,
00294         -overhangMetrics.top,
00295         overhangMetrics.right + metrics.layoutWidth,
00296         overhangMetrics.bottom + metrics.layoutHeight
00297         );
00298
00299     m_size = SizeF(
00300         m_textExtents.right - m_textExtents.left,
00301         m_textExtents.bottom - m_textExtents.top
00302         );
00303 }
00304
00305 void TextElement::CreateTextLayout()
00306 {
00307     if ((m_textLayout == nullptr) || m_textStyle.HasTextFormatChanged())
00308     {
00309         m_textLayout = nullptr;
00310
00311         IDWriteFactory* dwriteFactory = UserInterface::GetDWriteFactory();
00312
00313         DX::ThrowIfFailed(
00314             dwriteFactory->CreateTextLayout(
00315                 m_text->Data(),
00316                 m_text->Length(),
00317                 m_textStyle.GetTextFormat(),
00318                 m_container.right - m_container.left,
00319                 m_container.bottom - m_container.top,
00320                 &m_textLayout
00321                 )
00322             );
00323     }
00324 }
00325
00326 #pragma endregion
00327
00328 #pragma region CountdownTimer
00329
00330 CountdownTimer::CountdownTimer():
00331     m_elapsedTime(0.0f),
00332     m_secondsRemaining(0)
00333 {
00334 }
00335
00336 void CountdownTimer::Initialize()
00337 {
00338     TextElement::Initialize();
00339 }
00340
00341 void CountdownTimer::Update(float timeTotal, float timeDelta)
00342 {
00343     if (m_secondsRemaining > 0)
00344     {
00345         m_elapsedTime += timeDelta;
00346         if (m_elapsedTime >= 1.0f)
00347         {
00348             m_elapsedTime -= 1.0f;
00349
00350             if (--m_secondsRemaining > 0)
00351             {
00352                 WCHAR buffer[4];
00353                 swprintf_s(buffer, L"%2d", m_secondsRemaining);
00354                 SetText(buffer);
00355                 SetTextOpacity(1.0f);
00356                 FadeOut(1.0f);
00357             }
00358             else
00359             {
00360                 SetText(L"Go!");
00361                 SetTextOpacity(1.0f);
00362                 FadeOut(1.0f);
00363             }
00364         }
00365     }
00366
00367     TextElement::Update(timeTotal, timeDelta);
00368 }
00369
00370 void CountdownTimer::Render()
00371 {
00372     TextElement::Render();
00373 }
00374
00375 void CountdownTimer::StartCountdown(int seconds)
00376 {
00377     m_secondsRemaining = seconds;
00378     m_elapsedTime = 0.0f;
00379
00380     WCHAR buffer[4];
00381     swprintf_s(buffer, L"%2d", m_secondsRemaining);
00382     SetText(buffer);
00383     SetTextOpacity(1.0f);
00384     FadeOut(1.0f);
00385 }
00386
00387 bool CountdownTimer::IsCountdownComplete() const
00388 {
00389     return (m_secondsRemaining == 0);
00390 }
00391
00392 #pragma endregion
00393
00394 #pragma region StopwatchTimer
00395
00396 StopwatchTimer::StopwatchTimer():
00397     m_active(false),
00398     m_elapsedTime(0.0f)
00399 {
00400 }
00401
00402 void StopwatchTimer::Initialize()
00403 {
00404     TextElement::Initialize();
00405 }
00406
00407 void StopwatchTimer::Update(float timeTotal, float timeDelta)
00408 {
00409     if (m_active)
00410     {
00411         m_elapsedTime += timeDelta;
00412
00413         WCHAR buffer[16];
00414         GetFormattedTime(buffer);
00415         SetText(buffer);
00416     }
00417
00418     TextElement::Update(timeTotal, timeDelta);
00419 }
00420
00421 void StopwatchTimer::Render()
00422 {
00423     TextElement::Render();
00424 }
00425
00426 void StopwatchTimer::Start()
00427 {
00428     m_active = true;
00429 }
00430
00431 void StopwatchTimer::Stop()
00432 {
00433     m_active = false;
00434 }
00435
00436 void StopwatchTimer::Reset()
00437 {
00438     m_elapsedTime = 0.0f;
00439 }
00440
00441 void StopwatchTimer::GetFormattedTime(WCHAR* buffer, int length) const
00442 {
00443     GetFormattedTime(buffer, length, m_elapsedTime);
00444 }
00445
00446 void StopwatchTimer::GetFormattedTime(WCHAR* buffer, int length, float time)
00447 {
00448     int partial = (int)floor(fmodf(time * 10.0f, 10.0f));
00449     int seconds = (int)floor(fmodf(time, 60.0f));
00450     int minutes = (int)floor(time / 60.0f);
00451     swprintf_s(buffer, length, L"%02d:%02d.%01d", minutes, seconds, partial);
00452 }
00453
00454 #pragma endregion
00455
00456 #pragma region TextButton
00457
00458 TextButton::TextButton():
00459     m_selected(false)
00460 {
00461 }
00462
00463 void TextButton::Initialize()
00464 {
00465     TextElement::Initialize();
00466 }
00467
00468 void TextButton::Update(float timeTotal, float timeDelta)
00469 {
00470     TextElement::Update(timeTotal, timeDelta);
00471 }
00472
00473 void TextButton::Render()
00474 {
00475     ID2D1DeviceContext* d2dContext = UserInterface::GetD2DContext();
00476
00477     if (m_selected)
00478     {
00479         D2D1_RECT_F bounds = GetBounds();
00480
00481         d2dContext->DrawRectangle(
00482             bounds,
00483             m_textColorBrush.Get(),
00484             4.0f
00485             );
00486     }
00487
00488     TextElement::Render();
00489 }
00490
00491 void TextButton::SetPadding(D2D1_SIZE_F padding)
00492 {
00493     m_padding = padding;
00494 }
00495
00496 void TextButton::SetSelected(bool selected)
00497 {
00498     m_selected = selected;
00499 }
00500
00501 void TextButton::SetPressed(bool pressed)
00502 {
00503     m_pressed = pressed;
00504 }
00505
00506 void TextButton::CalculateSize()
00507 {
00508     TextElement::CalculateSize();
00509     m_textExtents.left -= m_padding.width;
00510     m_textExtents.top -= m_padding.height;
00511     m_size.width += m_padding.width * 2;
00512     m_size.height += m_padding.height * 2;
00513 }
00514
00515 #pragma endregion
00516
00517 #pragma region HighScoreTable
00518
00519 HighScoreTable::HighScoreTable()
00520 {
00521 }
00522
00523 void HighScoreTable::Initialize()
00524 {
00525     TextElement::Initialize();
00526     UpdateText();
00527 }
00528
00529 void HighScoreTable::Reset()
00530 {
00531     m_entries.clear();
00532     UpdateText();
00533 }
00534
00535 void HighScoreTable::Update(float timeTotal, float timeDelta)
00536 {
00537     TextElement::Update(timeTotal, timeDelta);
00538 }
00539
00540 void HighScoreTable::Render()
00541 {
00542     TextElement::Render();
00543 }
00544
00545 void HighScoreTable::AddScoreToTable(HighScoreEntry& entry)
00546 {
00547     for (auto iter = m_entries.begin(); iter != m_entries.end(); ++iter)
00548     {
00549         iter->wasJustAdded = false;
00550     }
00551
00552     entry.wasJustAdded = false;
00553
00554     for (auto iter = m_entries.begin(); iter != m_entries.end(); ++iter)
00555     {
00556         if (entry.elapsedTime < iter->elapsedTime)
00557         {
00558             m_entries.insert(iter, entry);
00559             while (m_entries.size() > MAX_HIGH_SCORES)
00560                 m_entries.pop_back();
00561
00562             entry.wasJustAdded = true;
00563             UpdateText();
00564             return;
00565         }
00566     }
00567
00568     if (m_entries.size() < MAX_HIGH_SCORES)
00569     {
00570         m_entries.push_back(entry);
00571         UpdateText();
00572         entry.wasJustAdded = true;
00573     }
00574 }
00575
00576 void HighScoreTable::UpdateText()
00577 {
00578     WCHAR formattedTime[32];
00579     WCHAR lines[1024] = { 0, };
00580     WCHAR buffer[128];
00581
00582     swprintf_s(lines, L"High Scores:");
00583     for (unsigned int i = 0; i < MAX_HIGH_SCORES; ++i)
00584     {
00585         if (i < m_entries.size())
00586         {
00587             StopwatchTimer::GetFormattedTime(formattedTime, m_entries[i].elapsedTime);
00588             swprintf_s(
00589                 buffer,
00590                 (m_entries[i].wasJustAdded ? L"\n>> %s\t%s <<" : L"\n%s\t%s"),
00591                 m_entries[i].tag->Data(),
00592                 formattedTime
00593                 );
00594             wcscat_s(lines, buffer);
00595         }
00596         else
00597         {
00598             wcscat_s(lines, L"\n-");
00599         }
00600     }
00601
00602     SetText(lines);
00603 }
00604
00605 #pragma endregion
00606
00607 #pragma region UserInterface
00608
00609 UserInterface UserInterface::m_instance;
00610
00611 void UserInterface::Initialize(
00612     _In_ ID2D1Device*         d2dDevice,
00613     _In_ ID2D1DeviceContext*  d2dContext,
00614     _In_ IWICImagingFactory*  wicFactory,
00615     _In_ IDWriteFactory*      dwriteFactory
00616     )
00617 {
00618     m_wicFactory = wicFactory;
00619     m_dwriteFactory = dwriteFactory;
00620     m_d2dDevice = d2dDevice;
00621     m_d2dContext = d2dContext;
00622
00623     ComPtr<ID2D1Factory> factory;
00624     d2dDevice->GetFactory(&factory);
00625
00626     DX::ThrowIfFailed(
00627         factory.As(&m_d2dFactory)
00628         );
00629
00630     DX::ThrowIfFailed(
00631         m_d2dFactory->CreateDrawingStateBlock(&m_stateBlock)
00632         );
00633 }
00634
00635 void UserInterface::Update(float timeTotal, float timeDelta)
00636 {
00637     for (auto iter = m_elements.begin(); iter != m_elements.end(); ++iter)
00638     {
00639         (*iter)->Update(timeTotal, timeDelta);
00640     }
00641 }
00642
00643 void UserInterface::Render()
00644 {
00645     m_d2dContext->SaveDrawingState(m_stateBlock.Get());
00646     m_d2dContext->BeginDraw();
00647     m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00648     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00649
00650     for (auto iter = m_elements.begin(); iter != m_elements.end(); ++iter)
00651     {
00652         if ((*iter)->IsVisible())
00653             (*iter)->Render();
00654     }
00655
00656     // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00657     // is lost. It will be handled during the next call to Present.
00658     HRESULT hr = m_d2dContext->EndDraw();
00659     if (hr != D2DERR_RECREATE_TARGET)
00660     {
00661         DX::ThrowIfFailed(hr);
00662     }
00663
00664     m_d2dContext->RestoreDrawingState(m_stateBlock.Get());
00665 }
00666
00667 void UserInterface::RegisterElement(ElementBase* element)
00668 {
00669     m_elements.insert(element);
00670 }
00671
00672 void UserInterface::UnregisterElement(ElementBase* element)
00673 {
00674     auto iter = m_elements.find(element);
00675     if (iter != m_elements.end())
00676     {
00677         m_elements.erase(iter);
00678     }
00679 }
00680
00681 inline bool PointInRect(D2D1_POINT_2F point, D2D1_RECT_F rect)
00682 {
00683     if ((point.x < rect.left) ||
00684         (point.x > rect.right) ||
00685         (point.y < rect.top) ||
00686         (point.y > rect.bottom))
00687     {
00688         return false;
00689     }
00690
00691     return true;
00692 }
00693
00694 void UserInterface::HitTest(D2D1_POINT_2F point)
00695 {
00696     for (auto iter = m_elements.begin(); iter != m_elements.end(); ++iter)
00697     {
00698         if (!(*iter)->IsVisible())
00699             continue;
00700
00701         TextButton* textButton = dynamic_cast<TextButton*>(*iter);
00702         if (textButton != nullptr)
00703         {
00704             D2D1_RECT_F bounds = (*iter)->GetBounds();
00705             textButton->SetPressed(PointInRect(point, bounds));
00706         }
00707     }
00708 }
00709
00710 #pragma endregion
Generated on Sat Nov 23 2024 16:08:15 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/IResourceLoader.h Source File

  • Hilo C++
  • Hilo

IResourceLoader.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
00009 namespace Hilo
00010 {
00011     // The IResourceLoader class defines the interface used to access resource strings.
00012     public interface class IResourceLoader
00013     {
00014         Platform::String^ GetString(Platform::String^ value);
00015     };
00016 }
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Touch hit testing/C++/pch.h Source File

  • Input Touch hit testing

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 <d3d11_1.h>
00012 #include <d2d1_1.h>
00013 #include <d2d1effects.h>
00014 #include <dwrite_1.h>
00015 #include <wincodec.h>
00016 #include <agile.h>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Language font mapping/C++/ScenarioOutput1.xaml.h Source File

  • Language font mapping

ScenarioOutput1.xaml.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 //
00009 // Scenario1Output.xaml.h
00010 // Declaration of the Scenario1Output class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioOutput1.g.h"
00017 #include "MainPage.xaml.h"
00018
00019 namespace LanguageFontCPP
00020 {
00021     [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class ScenarioOutput1 sealed
00023     {
00024     public:
00025         ScenarioOutput1();
00026
00027     protected:
00028         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030
00031     private:
00032         ~ScenarioOutput1();
00033         MainPage^ rootPage;
00034         void rootPage_InputFrameLoaded(Object^ sender, Object^ e);
00035         Windows::Foundation::EventRegistrationToken _frameLoadedToken;
00036     };
00037 }
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Network status background/C++/NetworkStatusApp/pch.h Source File

  • Network status background
  • NetworkStatusApp

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

_FILE_PLAYBACK Member List

This is the complete list of members for _FILE_PLAYBACK, including all inherited members.
Delay | _FILE_PLAYBACK
Path | _FILE_PLAYBACK
Generated on Sat Nov 23 2024 16:09:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

D2D3DTransforms::sealed Member List

This is the complete list of members for D2D3DTransforms::sealed, including all inherited members.
App() | D2D3DTransforms::sealed |
InitializeValues() | D2D3DTransforms::sealed |
m_mainPage | D2D3DTransforms::sealed | [private]
m_renderer | D2D3DTransforms::sealed | [private]
MainPage() | D2D3DTransforms::sealed |
OnDisplayContentsInvalidated(Object^sender) | D2D3DTransforms::sealed | [private]
OnEffectSelectorSelectionChanged(Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^args) | D2D3DTransforms::sealed | [private]
OnGlobalOffsetXValueChanged(Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^args) | D2D3DTransforms::sealed | [private]
OnGlobalOffsetYValueChanged(Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^args) | D2D3DTransforms::sealed | [private]
OnGlobalOffsetZValueChanged(Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^args) | D2D3DTransforms::sealed | [private]
OnLaunched(_In_ Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^args) override | D2D3DTransforms::sealed | [virtual]
OnLocalOffsetXValueChanged(Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^args) | D2D3DTransforms::sealed | [private]
OnLocalOffsetYValueChanged(Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^args) | D2D3DTransforms::sealed | [private]
OnLocalOffsetZValueChanged(Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^args) | D2D3DTransforms::sealed | [private]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | D2D3DTransforms::sealed | [private]
OnLogicalDpiChanged(Object^sender) | D2D3DTransforms::sealed | [private]
OnPerspectiveValueChanged(Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^args) | D2D3DTransforms::sealed | [private]
OnRestoreDefaultsClick(Object^sender, Windows::UI::Xaml::RoutedEventArgs^args) | D2D3DTransforms::sealed | [private]
OnRotationXValueChanged(Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^args) | D2D3DTransforms::sealed | [private]
OnRotationYValueChanged(Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^args) | D2D3DTransforms::sealed | [private]
OnRotationZValueChanged(Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^args) | D2D3DTransforms::sealed | [private]
OnScaleXValueChanged(Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^args) | D2D3DTransforms::sealed | [private]
OnScaleYValueChanged(Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^args) | D2D3DTransforms::sealed | [private]
OnSuspending(_In_ Platform::Object^sender, _In_ Windows::ApplicationModel::SuspendingEventArgs^args) | D2D3DTransforms::sealed | [private]
OnSuspending(Object^sender, Windows::ApplicationModel::SuspendingEventArgs^args) | D2D3DTransforms::sealed |
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | D2D3DTransforms::sealed | [private]
OnWindowSizeChanged(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::WindowSizeChangedEventArgs^args) | D2D3DTransforms::sealed | [private]
ResetValues() | D2D3DTransforms::sealed |
SetTransformEffect(TransformEffect transformEffect) | D2D3DTransforms::sealed | [private]
SetTransformProperty(TransformProperty transformProperty, float value) | D2D3DTransforms::sealed | [private]
Generated on Sat Nov 23 2024 16:09:37 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Context menu/C++/common/suspensionmanager.cpp Source File

  • Context menu
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:36 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML images/C++/pch.cpp Source File

  • XAML images

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C#,C++/ScenarioOutput1.xaml.cs Source File

  • Media extensions
  • C#,C++

ScenarioOutput1.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 System;
00009 using System.Linq;
00010 using System.Collections.Generic;
00011 using Windows.Foundation;
00012 using Windows.Foundation.Collections;
00013 using Windows.Graphics.Display;
00014 using Windows.UI.ViewManagement;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Controls.Primitives;
00018 using Windows.UI.Xaml.Data;
00019 using Windows.UI.Xaml.Input;
00020 using Windows.UI.Xaml.Media;
00021 using Windows.UI.Xaml.Navigation;
00022 using SDKTemplateCS;
00023
00024 namespace MediaExtensionsCS
00025 {
00026     public sealed partial class ScenarioOutput1 : Page
00027     {
00028         // A pointer back to the main page which is used to gain access to the input and output frames and their content.
00029         MainPage rootPage = null;
00030
00031         public ScenarioOutput1()
00032         {
00033             InitializeComponent();
00034         }
00035
00036         #region Template-Related Code - Do not remove
00037         protected override void OnNavigatedTo(NavigationEventArgs e)
00038         {
00039             // Get a pointer to our main page.
00040             rootPage = e.Parameter as MainPage;
00041
00042             Video.MediaFailed += new ExceptionRoutedEventHandler(rootPage.VideoOnError);
00043         }
00044
00045         protected override void OnNavigatedFrom(NavigationEventArgs e)
00046         {
00047             Video.MediaFailed -= new ExceptionRoutedEventHandler(rootPage.VideoOnError);
00048             Video.Source = null;
00049         }
00050         #endregion
00051     }
00052 }
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Scaling according to DPI/C++/common/LayoutAwarePage.cpp Source File

  • Scaling according to DPI
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:32 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Device auto rotation preferences/C++/None.xaml.h Source File

  • Device auto rotation preferences

None.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 // None.xaml.h
00013 // Declaration of the None class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "None.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace Rotation
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 None sealed
00031         {
00032         public:
00033             None();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void ClearPreference_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:08:02 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX marble maze game/C++/MediaStreamer.h Source File

  • DirectX marble maze game

MediaStreamer.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 class MediaStreamer
00011 {
00012 private:
00013     WAVEFORMATEX    m_waveFormat;
00014     uint32          m_maxStreamLengthInBytes;
00015
00016 public:
00017     Microsoft::WRL::ComPtr<IMFSourceReader> m_reader;
00018     Microsoft::WRL::ComPtr<IMFMediaType> m_audioType;
00019
00020 public:
00021     MediaStreamer();
00022     ~MediaStreamer();
00023
00024     WAVEFORMATEX& GetOutputWaveFormatEx()
00025     {
00026         return m_waveFormat;
00027     }
00028
00029     UINT32 GetMaxStreamLengthInBytes()
00030     {
00031         return m_maxStreamLengthInBytes;
00032     }
00033
00034     void Initialize(_In_ const WCHAR* url);
00035     bool GetNextBuffer(uint8* buffer, uint32 maxBufferSize, uint32* bufferLength);
00036     void ReadAll(uint8* buffer, uint32 maxBufferSize, uint32* bufferLength);
00037     void Restart();
00038 };
Generated on Sat Nov 23 2024 16:08:15 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media capture using capture device/C++/pch.cpp Source File

  • Media capture using capture device

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML two-dimensional transforms/C++/Scenario2.xaml.cpp Source File

  • XAML two-dimensional transforms

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 SDKSample::Transforms;
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 // Invoked when this page is about to be displayed in a Frame.
00031 void Scenario2::OnNavigatedTo(NavigationEventArgs^ e)
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     rootPage = MainPage::Current;
00036 }
00037
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: StorageDataSource and GetVirtualizedFilesVector/C++/App.xaml.cpp Source File

  • StorageDataSource and GetVirtualizedFilesVector

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:28 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML Popup/C++/Scenario3.xaml.h Source File

  • XAML Popup

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 SDKSample
00023 {
00024     namespace XAMLPopup
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         void ShowPopupLightDismissClicked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         void ShowPopupAnimationClicked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         void ShowPopupSettingsClicked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00042         void ClosePopupClicked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00043         void CloseAnimatedPopupClicked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00044         void CloseSettingsPopupClicked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00045       };
00046     }
00047 }
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DXGI swap chain rotation/C++/BasicShapes.h Source File

  • DXGI swap chain rotation

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 Sat Nov 23 2024 16:08:10 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C#,C++/ScenarioInput3.xaml.cs Source File

  • Media extensions
  • C#,C++

ScenarioInput3.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 System;
00009 using System.Linq;
00010 using System.Collections.Generic;
00011 using Windows.Foundation;
00012 using Windows.Foundation.Collections;
00013 using Windows.Graphics.Display;
00014 using Windows.UI.ViewManagement;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Controls.Primitives;
00018 using Windows.UI.Xaml.Data;
00019 using Windows.UI.Xaml.Input;
00020 using Windows.UI.Xaml.Media;
00021 using Windows.UI.Xaml.Navigation;
00022 using SDKTemplateCS;
00023
00024 namespace MediaExtensionsCS
00025 {
00026     public sealed partial class ScenarioInput3 : Page
00027     {
00028         // A pointer back to the main page which is used to gain access to the input and output frames and their content.
00029         MainPage rootPage = null;
00030         MediaElement outputVideo;
00031         MediaElement outputVideoStabilized;
00032
00033         public ScenarioInput3()
00034         {
00035             InitializeComponent();
00036         }
00037
00038         #region Template-Related Code - Do not remove
00039         protected override void OnNavigatedTo(NavigationEventArgs e)
00040         {
00041             // Get a pointer to our main page
00042             rootPage = e.Parameter as MainPage;
00043
00044             // We want to be notified with the OutputFrame is loaded so we can get to the content.
00045             rootPage.OutputFrameLoaded += new System.EventHandler(rootPage_OutputFrameLoaded);
00046         }
00047
00048         protected override void OnNavigatedFrom(NavigationEventArgs e)
00049         {
00050             rootPage.OutputFrameLoaded -= new System.EventHandler(rootPage_OutputFrameLoaded);
00051         }
00052
00053         #endregion
00054
00055         #region Event handlers
00056         void rootPage_OutputFrameLoaded(object sender, object e)
00057         {
00058             // At this point, we know that the Output Frame has been loaded and we can go ahead
00059             // and reference elements in the page contained in the Output Frame.
00060
00061             // Get a pointer to the content within the OutputFrame.
00062             Page outputFrame = (Page)rootPage.OutputFrame.Content;
00063
00064             // Go find the elements that we need for this scenario.
00065             outputVideo = outputFrame.FindName("Video") as MediaElement;
00066             outputVideoStabilized = outputFrame.FindName("VideoStabilized") as MediaElement;
00067         }
00068
00069         /// <summary>
00070         /// This is the click handler for the 'Open' button.
00071         /// </summary>
00072         /// <param name="sender"></param>
00073         /// <param name="e"></param>
00074         private void Open_Click(object sender, RoutedEventArgs e)
00075         {
00076             outputVideoStabilized.RemoveAllEffects();
00077             outputVideoStabilized.AddVideoEffect(Windows.Media.VideoEffects.VideoStabilization, true, null);
00078             rootPage.PickSingleFileAndSet(new string[] { ".mp4", ".wmv", ".avi" }, outputVideo, outputVideoStabilized);
00079         }
00080
00081
00082         /// <summary>
00083         /// This is the click handler for the 'Stop' button.
00084         /// </summary>
00085         /// <param name="sender"></param>
00086         /// <param name="e"></param>
00087         private void Stop_Click(object sender, RoutedEventArgs e)
00088         {
00089             outputVideo.Source = null;
00090             outputVideoStabilized.Source = null;
00091         }
00092         #endregion
00093     }
00094 }
Generated on Sat Nov 23 2024 16:08:21 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Clipboard app/C++/MainPage.xaml.cpp Source File

  • Clipboard app

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Platform;
00023 using namespace Clipboard;
00024 using namespace CppSamplesUtils;
00025 using namespace Windows::UI;
00026 using namespace Windows::UI::Core;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::UI::Xaml;
00029 using namespace Windows::UI::Xaml::Controls;
00030 using namespace Windows::UI::Xaml::Navigation;
00031 using namespace Windows::UI::Xaml::Interop;
00032 using namespace Windows::Graphics::Display;
00033 using namespace Windows::UI::ViewManagement;
00034
00035 MainPage^ MainPage::Current = nullptr;
00036
00037 MainPage::MainPage()
00038 {
00039     InitializeComponent();
00040
00041     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00042     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00043     LayoutRoot->Children->Append(HiddenFrame);
00044
00045     SetFeatureName(FEATURE_NAME);
00046
00047     SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00048     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00049
00050     MainPage::Current = this;
00051     autoSizeInputSectionWhenSnapped = true;
00052 }
00053
00054 MainPage::~MainPage()
00055 {
00056 }
00057
00058 void MainPage::OnNavigatedTo(NavigationEventArgs^ e)
00059 {
00060     PopulateScenarios();
00061     InvalidateViewState();
00062 }
00063
00064 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00065 {
00066     InvalidateSize();
00067     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00068     args->ViewState = ApplicationView::Value;
00069     MainPageResized(this, args);
00070 }
00071
00072 void MainPage::InvalidateSize()
00073 {
00074     // Get the window width
00075     double windowWidth = ActualWidth;
00076
00077     if (windowWidth != 0.0)
00078     {
00079         // Get the width of the ListBox.
00080         double listBoxWidth = Scenarios->ActualWidth;
00081
00082         // Is the ListBox using any margins that we need to consider?
00083         double listBoxMarginLeft = Scenarios->Margin.Left;
00084         double listBoxMarginRight = Scenarios->Margin.Right;
00085
00086         // Figure out how much room is left after considering the list box width
00087         double availableWidth = windowWidth - listBoxWidth;
00088
00089         // Is the top most child using margins?
00090         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00091         double layoutRootMarginRight = ContentRoot->Margin.Right;
00092
00093         // We have different widths to use depending on the view state
00094         if (ApplicationView::Value != ApplicationViewState::Snapped)
00095         {
00096             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00097             // and the LayoutRoot's margins
00098             InputSection->Width = ((availableWidth) - (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00099         }
00100         else
00101         {
00102             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00103             if (autoSizeInputSectionWhenSnapped)
00104             {
00105                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00106             }
00107         }
00108     }
00109
00110     InvalidateViewState();
00111 }
00112
00113 void MainPage::InvalidateViewState()
00114 {
00115     // Are we going to snapped mode?
00116     if (ApplicationView::Value == ApplicationViewState::Snapped)
00117     {
00118         Grid::SetRow(DescriptionText, 3);
00119         Grid::SetColumn(DescriptionText, 0);
00120
00121         Grid::SetRow(InputSection, 4);
00122         Grid::SetColumn(InputSection, 0);
00123
00124         Grid::SetRow(FooterPanel, 2);
00125         Grid::SetColumn(FooterPanel, 0);
00126     }
00127     else
00128     {
00129         Grid::SetRow(DescriptionText, 1);
00130         Grid::SetColumn(DescriptionText, 1);
00131
00132         Grid::SetRow(InputSection, 2);
00133         Grid::SetColumn(InputSection, 1);
00134
00135         Grid::SetRow(FooterPanel, 1);
00136         Grid::SetColumn(FooterPanel, 1);
00137     }
00138 }
00139
00140 #pragma optimize("", off)
00141 void MainPage::PopulateScenarios()
00142 {
00143     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00144
00145     // Populate the ListBox with the list of scenarios as defined in Constants.cpp
00146     for (unsigned int i = 0; i < scenarios->Length; ++i)
00147     {
00148         Scenario s = scenarios[i];
00149         ListBoxItem^ item = ref new ListBoxItem();
00150         item->Name = s.ClassName;
00151         item->Content = (i + 1).ToString() + ") " + s.Title;
00152         ScenarioList->Append(item);
00153     }
00154
00155     // Bind the ListBox to the scenario list.
00156     Scenarios->ItemsSource = ScenarioList;
00157
00158     // Starting scenario is the first or based upon a previous selection.
00159     ListBoxItem^ startingScenario = nullptr;
00160
00161     // Starting scenario is the first or based upon a previous selection.
00162     int startingScenarioIndex = -1;
00163
00164     auto ps = SuspensionManager::SessionState();
00165     if (ps->HasKey("SelectedScenarioIndex"))
00166     {
00167         int selectedScenarioIndex = safe_cast<int>(ps->Lookup("SelectedScenarioIndex"));
00168         startingScenarioIndex = selectedScenarioIndex;
00169     }
00170
00171     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00172 }
00173
00174 #pragma optimize("", on)
00175
00176 void MainPage::LoadScenario(String^ scenarioName)
00177 {
00178     autoSizeInputSectionWhenSnapped = true;
00179
00180     // Load the ScenarioX.xaml file into the Frame.
00181     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00182     HiddenFrame->Navigate(scenarioType, this);
00183
00184     // Get the top element, the Page, so we can look up the elements
00185     // that represent the input and output sections of the ScenarioX file.
00186     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00187
00188     // Get each element.
00189     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00190     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00191
00192     if (input == nullptr)
00193     {
00194         // Malformed input section.
00195         NotifyUser("Cannot load scenario input section for " + scenarioName +
00196             " Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00197
00198         return;
00199     }
00200
00201     if (output == nullptr)
00202     {
00203         // Malformed output section.
00204         NotifyUser("Cannot load scenario output section for " + scenarioName +
00205             " Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00206
00207         return;
00208     }
00209
00210     // Find the LayoutRoot which parents the input and output sections in the main page.
00211     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00212
00213     if (panel != nullptr)
00214     {
00215         unsigned int index = 0;
00216         UIElementCollection^ collection = panel->Children;
00217
00218         // Get rid of the content that is currently in the input and output sections.
00219         collection->IndexOf(input, &index);
00220         collection->RemoveAt(index);
00221
00222         collection->IndexOf(output, &index);
00223         collection->RemoveAt(index);
00224
00225         // Populate the input and output sections with the newly loaded content.
00226         InputSection->Content = input;
00227         OutputSection->Content = output;
00228
00229         ScenarioLoaded(this, nullptr);
00230     }
00231     else
00232     {
00233         // Malformed Scenario file.
00234         NotifyUser("Cannot load scenario: " + scenarioName + ". Make sure root tag in the '" +
00235             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00236     }
00237 }
00238
00239 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00240 {
00241     if (Scenarios->SelectedItem != nullptr)
00242     {
00243         NotifyUser("", NotifyType::StatusMessage);
00244
00245         int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00246         SuspensionManager::SessionState()->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00247
00248         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00249         InvalidateSize();
00250     }
00251 }
00252
00253 void MainPage::SetFeatureName(String^ strFeature)
00254 {
00255     Clipboard->Text = strFeature;
00256 }
00257
00258 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00259 {
00260     switch (type)
00261     {
00262     case NotifyType::StatusMessage:
00263         {
00264             // Use the status message style.
00265             StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(Resources->Lookup("StatusStyle"));
00266         }
00267         break;
00268
00269     case NotifyType::ErrorMessage:
00270         {
00271             // Use the error message style.
00272             StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(Resources->Lookup("ErrorStyle"));
00273         }
00274         break;
00275
00276     default:
00277         break;
00278     }
00279
00280     StatusBlock->Text = strMessage;
00281
00282     // Collapsed the StatusBlock if it has no text to conserve real estate.
00283     if (StatusBlock->Text != "")
00284     {
00285         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00286     }
00287     else
00288     {
00289         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00290     }
00291 }
00292
00293 void MainPage::NotifyUserBackgroundThread(String^ message, NotifyType type)
00294 {
00295     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler(
00296         [this, message, type]()
00297         {
00298             NotifyUser(message, type);
00299         }));
00300 }
00301
00302 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00303 {
00304     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00305     Windows::System::Launcher::LaunchUriAsync(uri);
00306 }
Generated on Sat Nov 23 2024 16:07:41 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Association launching/C++/pch.h Source File

  • Association launching

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 //
00009 // pch.h
00010 // Header for standard system include files.
00011 //
00012
00013 #pragma once
00014 #include "CppSamplesUtils.h"
00015 #include <ppltasks.h>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX marble maze game/C++/Primitives.h Source File

  • DirectX marble maze game

Primitives.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 class Triangle
00011 {
00012 public:
00013     XMFLOAT3 A;
00014     XMFLOAT3 B;
00015     XMFLOAT3 C;
00016     XMFLOAT4 plane;
00017
00018     Triangle(const Triangle& rhs)
00019     {
00020         A = rhs.A;
00021         B = rhs.B;
00022         C = rhs.C;
00023         plane = rhs.plane;
00024     }
00025
00026     Triangle(const XMFLOAT3& V0, const XMFLOAT3& V1, const XMFLOAT3& V2) :
00027         A(V0),
00028         B(V1),
00029         C(V2)
00030     {
00031         XMStoreFloat4(&plane, XMPlaneFromPoints(XMLoadFloat3(&V0), XMLoadFloat3(&V1), XMLoadFloat3(&V2)));
00032     }
00033
00034     // Returns true if the triangle is degenerate.
00035     FORCEINLINE BOOL IsDegenerate() const
00036     {
00037         XMVECTOR planeNormal = XMLoadFloat3((XMFLOAT3*)&plane);
00038         return XMVector3Equal(planeNormal, XMVectorZero());
00039     }
00040
00041     // Tests this triangle against another one to see if it a) shares any edges, and b) is coplanar
00042     FORCEINLINE void CheckSharesVertsOrCoplanar(
00043         FXMVECTOR V0,
00044         FXMVECTOR V1,
00045         FXMVECTOR V2,
00046         CXMVECTOR planeIn,
00047         BOOL& sharesEdgeOut,
00048         BOOL& coplanar
00049         ) const
00050     {
00051         const XMVECTOR VA = XMLoadFloat3(&A);
00052         XMVECTOR sharesEdge = XMVectorOrInt(
00053             XMVectorOrInt(
00054                 XMVectorEqual(V0, VA),
00055                 XMVectorEqual(V1, VA)
00056                 ),
00057             XMVectorEqual(V2, VA)
00058             );
00059         const XMVECTOR VB = XMLoadFloat3(&B);
00060         sharesEdge = XMVectorOrInt(
00061             sharesEdge,
00062             XMVectorOrInt(
00063                 XMVectorOrInt(
00064                     XMVectorEqual(V0, VB),
00065                     XMVectorEqual(V1, VB)
00066                     ),
00067                 XMVectorEqual(V2, VB)
00068                 )
00069             );
00070         const XMVECTOR VC = XMLoadFloat3(&C);
00071         sharesEdge = XMVectorOrInt(
00072             sharesEdge,
00073             XMVectorOrInt(
00074                 XMVectorOrInt(
00075                     XMVectorEqual(V0, VC),
00076                     XMVectorEqual(V1, VC)
00077                     ),
00078                 XMVectorEqual(V2, VC)
00079                 )
00080             );
00081
00082         sharesEdgeOut = XMVector3EqualInt(sharesEdge, XMVectorTrueInt());
00083
00084         const XMVECTOR VP = XMLoadFloat3((XMFLOAT3*)&plane);
00085         coplanar = XMVector3Equal(VP, planeIn);
00086     }
00087
00088     // Returns the unit normal of the triangle surface..
00089     FORCEINLINE XMVECTOR Normal() const
00090     {
00091         return XMLoadFloat3((XMFLOAT3*)&plane);
00092     }
00093 };
00094
00095 // Simple sphere wrapper. We store the sphere as a 16-byte aligned FLOAT4, so that we can perform
00096 // fast unaligned reads. All of the parameters are packed into a single FLOAT4.
00097 struct Sphere
00098 {
00099     XMFLOAT4 center;
00100
00101     FORCEINLINE float Radius() const
00102     {
00103         return center.w;
00104     }
00105
00106     Sphere()
00107     {
00108     }
00109
00110     explicit Sphere(const XMFLOAT3& centerIn, FLOAT radius)
00111     {
00112         center = XMFLOAT4(centerIn.x, centerIn.y, centerIn.z, radius);
00113     }
00114
00115     explicit Sphere(float x, float y, float z, float radius)
00116     {
00117         center = XMFLOAT4(x, y, z, radius);
00118     }
00119 };
Generated on Sat Nov 23 2024 16:08:15 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/RotateImageViewModel.h Source File

  • Hilo C++
  • Hilo

RotateImageViewModel.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
00009 #include "ImageBase.h"
00010
00011 namespace Hilo
00012 {
00013     interface class IPhoto;
00014     class Repository;
00015     class ExceptionPolicy;
00016
00017     // See http://go.microsoft.com/fwlink/?LinkId=267276 for info on how view model classes interact
00018     // with view classes (pages) and model classes (the state and operations of business objects).
00019
00020     // The RotateImageViewModel class contains the presentation logic for the rotate image page (RoatateImageView.xaml).
00021     [Windows::UI::Xaml::Data::Bindable]
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class RotateImageViewModel sealed : public ImageBase
00024     {
00025     internal:
00026         RotateImageViewModel(std::shared_ptr<Repository> repository, std::shared_ptr<ExceptionPolicy> exceptionPolicy);
00027
00028         virtual void LoadState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ stateMap) override;
00029         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ stateMap) override;
00030         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00031
00032         void Initialize(Platform::String^ photoPath);
00033         void EndRotation();
00034
00035     public:
00036         property IPhoto^ Photo
00037         {
00038             IPhoto^ get();
00039         }
00040
00041         property Windows::UI::Xaml::Input::ICommand^ RotateCommand
00042         {
00043             Windows::UI::Xaml::Input::ICommand^ get();
00044         }
00045
00046         property Windows::UI::Xaml::Input::ICommand^ ResumeRotateCommand
00047         {
00048             Windows::UI::Xaml::Input::ICommand^ get();
00049         }
00050
00051         property Windows::UI::Xaml::Input::ICommand^ SaveCommand
00052         {
00053             Windows::UI::Xaml::Input::ICommand^ get();
00054         }
00055
00056         property Windows::UI::Xaml::Input::ICommand^ CancelCommand
00057         {
00058             Windows::UI::Xaml::Input::ICommand^ get();
00059         }
00060
00061         property Windows::UI::Xaml::Thickness ImageMargin
00062         {
00063             Windows::UI::Xaml::Thickness get();
00064         }
00065
00066         property bool InProgress { bool get(); }
00067
00068         ///<summary>Returns the rotation angle for image display.</summary>
00069         property float64 RotationAngle
00070         {
00071             float64 get();
00072             void set(float64 value);
00073         }
00074
00075     private:
00076
00077         struct ImageEncodingInformation
00078         {
00079             ImageEncodingInformation() : usesExifOrientation(false), exifOrientation(0){}
00080
00081             Windows::Graphics::Imaging::BitmapDecoder^ decoder;
00082             bool usesExifOrientation;
00083             unsigned short exifOrientation;
00084         };
00085
00086         std::shared_ptr<Repository> m_repository;
00087         bool m_getPhotoAsyncIsRunning;
00088
00089         Windows::UI::Xaml::Input::ICommand^ m_rotateCommand;
00090         Windows::UI::Xaml::Input::ICommand^ m_resumeRotateCommand;
00091         Windows::UI::Xaml::Input::ICommand^ m_saveCommand;
00092         Windows::UI::Xaml::Input::ICommand^ m_cancelCommand;
00093         Windows::UI::Xaml::Thickness m_imageMargin;
00094         bool m_inProgress;
00095         bool m_isSaving;
00096         float64 m_rotationAngle;
00097         Platform::String^ m_photoPath;
00098
00099         void ChangeInProgress(bool value);
00100         concurrency::task<IPhoto^> GetImagePhotoAsync();
00101         concurrency::task<Windows::Storage::Streams::IRandomAccessStream^> RotateImageViewModel::RotateImageAsync(Windows::Storage::Streams::IRandomAccessStream^ sourceStream, float64 angle);
00102         unsigned int CheckRotationAngle(unsigned int angle);
00103         void Rotate90(Platform::Object^ parameter);
00104         void Unsnap(Platform::Object^ parameter);
00105         void SaveImage(Platform::Object^ parameter);
00106         void CancelRotate(Platform::Object^ parameter);
00107
00108
00109         concurrency::task<ImageEncodingInformation> GetDecoderInfo(Windows::Storage::Streams::IRandomAccessStream^ source, concurrency::task_continuation_context backgroundContext);
00110         concurrency::task<Windows::Storage::Streams::IRandomAccessStream^> EncodeRotateImageToStream(
00111             ImageEncodingInformation decoderInfo,
00112             float64 rotationAngle,
00113             concurrency::task_continuation_context backgroundContext);
00114         concurrency::task<Windows::Graphics::Imaging::BitmapEncoder^> RotateImageViewModel::SetEncodingRotation(
00115             Windows::Graphics::Imaging::BitmapEncoder^ encoder,
00116             std::shared_ptr<ImageEncodingInformation> decoderInfo,
00117             float64 rotationAngle,
00118             concurrency::task_continuation_context backgroundContext);
00119     };
00120 }
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C#,C++/MediaExtensions/Invert/TextureLock.h Source File

  • Media extensions
  • C#,C++
  • MediaExtensions
  • Invert

TextureLock.h

Go to the documentation of this file.
00001 #pragma once
00002 #include <assert.h>
00003 #include <D3D11.h>
00004 #include <wrl\client.h>
00005
00006 using namespace Microsoft::WRL;
00007
00008 class TextureLock
00009 {
00010 public:
00011   TextureLock( ID3D11DeviceContext *pContext, ID3D11Texture2D *pTex ) : _pTex(pTex), _pContext(pContext), _bLocked(false) {}
00012
00013   ~TextureLock()
00014   {
00015     assert(_pContext);
00016     assert(_pTex);
00017     if (_pTex && _bLocked)
00018     {
00019
00020       _pContext->Unmap(_pTex.Get(), _uiIndex);
00021       _bLocked = false;
00022     }
00023   }
00024
00025   HRESULT Map(UINT uiIndex, D3D11_MAP mapType, UINT mapFlags)
00026   {
00027     HRESULT hr = S_OK;
00028     assert(_pTex);
00029     assert(_pContext);
00030     assert(!_bLocked);
00031
00032     hr = _pContext->Map(_pTex.Get(), uiIndex, mapType, mapFlags, &map);
00033     _bLocked = SUCCEEDED(hr);
00034     _uiIndex = uiIndex;
00035     return hr;
00036   }
00037
00038   D3D11_MAPPED_SUBRESOURCE map;
00039
00040 private:
00041   ComPtr<ID3D11Texture2D> _pTex;
00042   ComPtr<ID3D11DeviceContext> _pContext;
00043   UINT _uiIndex;
00044   bool _bLocked;
00045 };
Generated on Sat Nov 23 2024 16:08:21 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DirectX::LDREndPntPair Member List

This is the complete list of members for DirectX::LDREndPntPair, including all inherited members.
A | DirectX::LDREndPntPair
B | DirectX::LDREndPntPair
Generated on Sat Nov 23 2024 16:09:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Edge gesture invocation/C++/ScenarioOutput2.xaml.h Source File

  • Edge gesture invocation

ScenarioOutput2.xaml.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 //
00009 // ScenarioOutput2.xaml.h
00010 // Declaration of the ScenarioOutput2 class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioOutput2.g.h"
00017 #include "MainPage.xaml.h"
00018
00019 namespace EdgeGestureSample
00020 {
00021   [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class ScenarioOutput2 sealed
00023     {
00024     public:
00025         ScenarioOutput2();
00026
00027     protected:
00028         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030
00031     private:
00032         void rootPage_InputFrameLoaded(Object^ sender, Object^ e);
00033         ~ScenarioOutput2();
00034
00035         MainPage^ rootPage;
00036         Windows::Foundation::EventRegistrationToken _frameLoadedToken;
00037     };
00038 }
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

FrameData Member List

This is the complete list of members for FrameData, including all inherited members.
FrameData() | FrameData | [inline]
m_BBP | FrameData |
m_colorPlanes | FrameData |
m_endHeight | FrameData |
m_endWidth | FrameData |
m_neighbourArea | FrameData |
m_pFrame | FrameData |
m_pFrameProcessor | FrameData |
m_phaseCount | FrameData |
m_pitch | FrameData |
m_size | FrameData |
m_startHeight | FrameData |
m_startWidth | FrameData |
Generated on Sat Nov 23 2024 16:09:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Raw notifications/C++/MainAppSample/ScenarioInput2.xaml.h Source File

  • Raw notifications
  • MainAppSample

ScenarioInput2.xaml.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 // ScenarioInput1.xaml.h
00009 // Declaration of the ScenarioInput1 class.
00010 //
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "ScenarioInput2.g.h"
00016 #include "MainPage.xaml.h"
00017
00018 using namespace Windows::UI::Xaml;
00019
00020 namespace RawNotificationsSampleCPP
00021 {
00022   [Windows::Foundation::Metadata::WebHostHidden]
00023   public ref class ScenarioInput2 sealed
00024   {
00025   public:
00026     ScenarioInput2();
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     ~ScenarioInput2();
00034     MainPage^ rootPage;
00035         Windows::UI::Core::CoreDispatcher^ _dispatcher;
00036     Windows::Foundation::EventRegistrationToken pushToken;
00037
00038     void Scenario2AddListener_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039     void Scenario2RemoveListener_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040
00041     bool UpdateListener(bool add);
00042     void OnPushNotificationReceived(Windows::Networking::PushNotifications::PushNotificationChannel^ sender, Windows::Networking::PushNotifications::PushNotificationReceivedEventArgs^ e);
00043   };
00044 }
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAudio2 audio stream effect/C++/DirectXBase.cpp Source File

  • XAudio2 audio stream effect

DirectXBase.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 "DirectXBase.h"
00010
00011 using namespace Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::Graphics::Display;
00015 using namespace D2D1;
00016
00017 // Constructor.
00018 DirectXBase::DirectXBase() :
00019     m_windowSizeChangeInProgress(false),
00020     m_dpi(-1.0f)
00021 {
00022 }
00023
00024 // Initialize the DirectX resources required to run.
00025 void DirectXBase::Initialize(CoreWindow^ window, float dpi)
00026 {
00027     m_window = window;
00028
00029     CreateDeviceIndependentResources();
00030     CreateDeviceResources();
00031     SetDpi(dpi);
00032 }
00033
00034 // Recreate all device resources and set them back to the current state.
00035 void DirectXBase::HandleDeviceLost()
00036 {
00037     // Reset these member variables to ensure that SetDpi recreates all resources.
00038     float dpi = m_dpi;
00039     m_dpi = -1.0f;
00040     m_windowBounds.Width = 0;
00041     m_windowBounds.Height = 0;
00042     m_swapChain = nullptr;
00043
00044     CreateDeviceResources();
00045     SetDpi(dpi);
00046 }
00047
00048 // These are the resources required independent of the device.
00049 void DirectXBase::CreateDeviceIndependentResources()
00050 {
00051     D2D1_FACTORY_OPTIONS options;
00052     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00053
00054 #if defined(_DEBUG)
00055     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00056     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00057 #endif
00058
00059     DX::ThrowIfFailed(
00060         D2D1CreateFactory(
00061             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00062             __uuidof(ID2D1Factory1),
00063             &options,
00064             &m_d2dFactory
00065             )
00066         );
00067
00068     DX::ThrowIfFailed(
00069         DWriteCreateFactory(
00070             DWRITE_FACTORY_TYPE_SHARED,
00071             __uuidof(IDWriteFactory),
00072             &m_dwriteFactory
00073             )
00074         );
00075
00076     DX::ThrowIfFailed(
00077         CoCreateInstance(
00078             CLSID_WICImagingFactory,
00079             nullptr,
00080             CLSCTX_INPROC_SERVER,
00081             IID_PPV_ARGS(&m_wicFactory)
00082             )
00083         );
00084 }
00085
00086 // These are the resources that depend on the device.
00087 void DirectXBase::CreateDeviceResources()
00088 {
00089     // This flag adds support for surfaces with a different color channel ordering
00090     // than the API default. It is required for compatibility with Direct2D.
00091     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00092     ComPtr<IDXGIDevice> dxgiDevice;
00093
00094 #if defined(_DEBUG)
00095     // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00096     creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00097 #endif
00098
00099     // This array defines the set of DirectX hardware feature levels this app will support.
00100     // Note the ordering should be preserved.
00101     // Don't forget to declare your application's minimum required feature level in its
00102     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00103     D3D_FEATURE_LEVEL featureLevels[] =
00104     {
00105         D3D_FEATURE_LEVEL_11_1,
00106         D3D_FEATURE_LEVEL_11_0,
00107         D3D_FEATURE_LEVEL_10_1,
00108         D3D_FEATURE_LEVEL_10_0,
00109         D3D_FEATURE_LEVEL_9_3,
00110         D3D_FEATURE_LEVEL_9_2,
00111         D3D_FEATURE_LEVEL_9_1
00112     };
00113
00114     // Create the Direct3D 11 API device object and a corresponding context.
00115     ComPtr<ID3D11Device> device;
00116     ComPtr<ID3D11DeviceContext> context;
00117     DX::ThrowIfFailed(
00118         D3D11CreateDevice(
00119             nullptr,                    // Specify nullptr to use the default adapter.
00120             D3D_DRIVER_TYPE_HARDWARE,
00121             0,
00122             creationFlags,              // Set debug and Direct2D compatibility flags.
00123             featureLevels,              // List of feature levels this app can support.
00124             ARRAYSIZE(featureLevels),
00125             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Metro style apps.
00126             &device,                    // Returns the Direct3D device created.
00127             &m_featureLevel,            // Returns feature level of device created.
00128             &context                    // Returns the device immediate context.
00129             )
00130         );
00131
00132     // Get the Direct3D 11.1 API device and context interfaces.
00133     DX::ThrowIfFailed(
00134         device.As(&m_d3dDevice)
00135         );
00136
00137     DX::ThrowIfFailed(
00138         context.As(&m_d3dContext)
00139         );
00140
00141     // Get the underlying DXGI device of the Direct3D device.
00142     DX::ThrowIfFailed(
00143         m_d3dDevice.As(&dxgiDevice)
00144         );
00145
00146     // Create the Direct2D device object and a corresponding context.
00147     DX::ThrowIfFailed(
00148         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00149         );
00150
00151     DX::ThrowIfFailed(
00152         m_d2dDevice->CreateDeviceContext(
00153             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00154             &m_d2dContext
00155             )
00156         );
00157 }
00158
00159 // Helps track the DPI in the helper class.
00160 // This is called in the dpiChanged event handler in the view class.
00161 void DirectXBase::SetDpi(float dpi)
00162 {
00163     if (dpi != m_dpi)
00164     {
00165         // Save the DPI of this display in our class.
00166         m_dpi = dpi;
00167
00168         // Update Direct2D's stored DPI.
00169         m_d2dContext->SetDpi(m_dpi, m_dpi);
00170
00171         // Often a DPI change implies a window size change. In some cases Windows will issue
00172         // both a size changed event and a DPI changed event. In this case, the resulting bounds
00173         // will not change, and the window resize code will only be executed once.
00174         UpdateForWindowSizeChange();
00175     }
00176 }
00177
00178 // This routine is called in the event handler for the view SizeChanged event.
00179 void DirectXBase::UpdateForWindowSizeChange()
00180 {
00181     // Only handle window size changed if there is no pending DPI change.
00182     if (m_dpi != DisplayProperties::LogicalDpi)
00183     {
00184         return;
00185     }
00186
00187     if (m_window->Bounds.Width  != m_windowBounds.Width ||
00188         m_window->Bounds.Height != m_windowBounds.Height)
00189     {
00190         m_d2dContext->SetTarget(nullptr);
00191         m_d2dTargetBitmap = nullptr;
00192         m_d3dRenderTargetView = nullptr;
00193         m_d3dDepthStencilView = nullptr;
00194         m_windowSizeChangeInProgress = true;
00195         CreateWindowSizeDependentResources();
00196     }
00197 }
00198
00199 // Allocate all memory resources that change on a window SizeChanged event.
00200 void DirectXBase::CreateWindowSizeDependentResources()
00201 {
00202     // Store the window bounds so the next time we get a SizeChanged event we can
00203     // avoid rebuilding everything if the size is identical.
00204     m_windowBounds = m_window->Bounds;
00205
00206     if (m_swapChain != nullptr)
00207     {
00208         // If the swap chain already exists, resize it.
00209         HRESULT hr = m_swapChain->ResizeBuffers(2, 0, 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0);
00210
00211         if (hr == DXGI_ERROR_DEVICE_REMOVED)
00212         {
00213             // If the device was removed for any reason, a new device and swapchain will need to be created.
00214             HandleDeviceLost();
00215
00216             // Everything is set up now. Do not continue execution of this method.
00217             return;
00218         }
00219         else
00220         {
00221             DX::ThrowIfFailed(hr);
00222         }
00223     }
00224     else
00225     {
00226         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00227         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00228         swapChainDesc.Width = 0;                                     // Use automatic sizing.
00229         swapChainDesc.Height = 0;
00230         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;           // This is the most common swap chain format.
00231         swapChainDesc.Stereo = false;
00232         swapChainDesc.SampleDesc.Count = 1;                          // Don't use multi-sampling.
00233         swapChainDesc.SampleDesc.Quality = 0;
00234         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00235         swapChainDesc.BufferCount = 2;                               // Use double-buffering to minimize latency.
00236         swapChainDesc.Scaling = DXGI_SCALING_NONE;
00237         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Metro style apps must use this SwapEffect.
00238         swapChainDesc.Flags = 0;
00239
00240         ComPtr<IDXGIDevice1> dxgiDevice;
00241         DX::ThrowIfFailed(
00242             m_d3dDevice.As(&dxgiDevice)
00243             );
00244
00245         ComPtr<IDXGIAdapter> dxgiAdapter;
00246         DX::ThrowIfFailed(
00247             dxgiDevice->GetAdapter(&dxgiAdapter)
00248             );
00249
00250         ComPtr<IDXGIFactory2> dxgiFactory;
00251         DX::ThrowIfFailed(
00252             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00253             );
00254
00255         CoreWindow^ window = m_window.Get();
00256         DX::ThrowIfFailed(
00257             dxgiFactory->CreateSwapChainForCoreWindow(
00258                 m_d3dDevice.Get(),
00259                 reinterpret_cast<IUnknown*>(window),
00260                 &swapChainDesc,
00261                 nullptr,
00262                 &m_swapChain
00263                 )
00264             );
00265
00266         // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
00267         // ensures that the application will only render after each VSync, minimizing power consumption.
00268         DX::ThrowIfFailed(
00269             dxgiDevice->SetMaximumFrameLatency(1)
00270             );
00271     }
00272
00273     // Create a Direct3D render target view of the swap chain back buffer.
00274     ComPtr<ID3D11Texture2D> backBuffer;
00275     DX::ThrowIfFailed(
00276         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00277         );
00278
00279     DX::ThrowIfFailed(
00280         m_d3dDevice->CreateRenderTargetView(
00281             backBuffer.Get(),
00282             nullptr,
00283             &m_d3dRenderTargetView
00284             )
00285         );
00286
00287     // Cache the rendertarget dimensions in our helper class for convenient use.
00288     D3D11_TEXTURE2D_DESC backBufferDesc = {0};
00289     backBuffer->GetDesc(&backBufferDesc);
00290     m_renderTargetSize.Width  = static_cast<float>(backBufferDesc.Width);
00291     m_renderTargetSize.Height = static_cast<float>(backBufferDesc.Height);
00292
00293     // Create a depth stencil view for use with 3D rendering if needed.
00294     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00295         DXGI_FORMAT_D24_UNORM_S8_UINT,
00296         backBufferDesc.Width,
00297         backBufferDesc.Height,
00298         1,
00299         1,
00300         D3D11_BIND_DEPTH_STENCIL
00301         );
00302
00303     ComPtr<ID3D11Texture2D> depthStencil;
00304     DX::ThrowIfFailed(
00305         m_d3dDevice->CreateTexture2D(
00306             &depthStencilDesc,
00307             nullptr,
00308             &depthStencil
00309             )
00310         );
00311
00312     auto viewDesc = CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D);
00313     DX::ThrowIfFailed(
00314         m_d3dDevice->CreateDepthStencilView(
00315             depthStencil.Get(),
00316             &viewDesc,
00317             &m_d3dDepthStencilView
00318             )
00319         );
00320
00321     // Set the 3D rendering viewport to target the entire window.
00322     CD3D11_VIEWPORT viewport(
00323         0.0f,
00324         0.0f,
00325         static_cast<float>(backBufferDesc.Width),
00326         static_cast<float>(backBufferDesc.Height)
00327         );
00328
00329     m_d3dContext->RSSetViewports(1, &viewport);
00330
00331     // Create a Direct2D target bitmap associated with the
00332     // swap chain back buffer and set it as the current target.
00333     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00334         BitmapProperties1(
00335             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00336             PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00337             m_dpi,
00338             m_dpi
00339             );
00340
00341     ComPtr<IDXGISurface> dxgiBackBuffer;
00342     DX::ThrowIfFailed(
00343         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00344         );
00345
00346     DX::ThrowIfFailed(
00347         m_d2dContext->CreateBitmapFromDxgiSurface(
00348             dxgiBackBuffer.Get(),
00349             &bitmapProperties,
00350             &m_d2dTargetBitmap
00351             )
00352         );
00353
00354     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00355
00356     // Grayscale text anti-aliasing is recommended for all Metro style apps.
00357     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00358 }
00359
00360 // Method to deliver the final image to the display.
00361 void DirectXBase::Present()
00362 {
00363     // The application may optionally specify "dirty" or "scroll" rects to improve efficiency
00364     // in certain scenarios.  In this sample, however, we do not utilize those features.
00365     DXGI_PRESENT_PARAMETERS parameters = {0};
00366     parameters.DirtyRectsCount = 0;
00367     parameters.pDirtyRects = nullptr;
00368     parameters.pScrollRect = nullptr;
00369     parameters.pScrollOffset = nullptr;
00370
00371     // The first argument instructs DXGI to block until VSync, putting the application
00372     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00373     // frames that will never be displayed to the screen.
00374     HRESULT hr = m_swapChain->Present1(1, 0, &parameters);
00375
00376     // Discard the contents of the render target.
00377     // This is a valid operation only when the existing contents will be entirely
00378     // overwritten. If dirty or scroll rects are used, this call should be removed.
00379     m_d3dContext->DiscardView(m_d3dRenderTargetView.Get());
00380
00381     // Discard the contents of the depth stencil.
00382     m_d3dContext->DiscardView(m_d3dDepthStencilView.Get());
00383
00384     // If the device was removed either by a disconnect or a driver upgrade, we
00385     // must recreate all device resources.
00386     if (hr == DXGI_ERROR_DEVICE_REMOVED)
00387     {
00388         HandleDeviceLost();
00389     }
00390     else
00391     {
00392         DX::ThrowIfFailed(hr);
00393     }
00394
00395     if (m_windowSizeChangeInProgress)
00396     {
00397         // A window size change has been initiated and the app has just completed presenting
00398         // the first frame with the new size. Notify the resize manager so we can short
00399         // circuit any resize animation and prevent unnecessary delays.
00400         CoreWindowResizeManager::GetForCurrentView()->NotifyLayoutCompleted();
00401         m_windowSizeChangeInProgress = false;
00402     }
00403 }
00404
00405 void DirectXBase::ValidateDevice()
00406 {
00407     // The D3D Device is no longer valid if the default adapter changes or if
00408     // the device has been removed.
00409
00410     // First, get the information for the adapter related to the current device.
00411
00412     ComPtr<IDXGIDevice1> dxgiDevice;
00413     ComPtr<IDXGIAdapter> deviceAdapter;
00414     DXGI_ADAPTER_DESC deviceDesc;
00415     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00416     DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter));
00417     DX::ThrowIfFailed(deviceAdapter->GetDesc(&deviceDesc));
00418
00419     // Next, get the information for the default adapter.
00420
00421     ComPtr<IDXGIFactory2> dxgiFactory;
00422     ComPtr<IDXGIAdapter1> currentAdapter;
00423     DXGI_ADAPTER_DESC currentDesc;
00424     DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)));
00425     DX::ThrowIfFailed(dxgiFactory->EnumAdapters1(0, &currentAdapter));
00426     DX::ThrowIfFailed(currentAdapter->GetDesc(&currentDesc));
00427
00428     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00429     // a new D3D device must be created.
00430
00431     if ((deviceDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart) ||
00432         (deviceDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart) ||
00433         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00434     {
00435         // Release references to resources related to the old device.
00436         dxgiDevice = nullptr;
00437         deviceAdapter = nullptr;
00438
00439         // Create a new device and swap chain.
00440         HandleDeviceLost();
00441     }
00442 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::TileContent::TileWidePeekImage01 Member List

This is the complete list of members for NotificationsExtensions::TileContent::TileWidePeekImage01, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
Branding | NotificationsExtensions::TileContent::TileNotificationBase |
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Image | NotificationsExtensions::TileContent::TileWidePeekImage01 |
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
RequireSquareContent | NotificationsExtensions::TileContent::TileWideBase |
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SquareContent | NotificationsExtensions::TileContent::TileWideBase |
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextBodyWrap | NotificationsExtensions::TileContent::TileWidePeekImage01 |
TextFields | NotificationsExtensions::NotificationBase |
TextHeading | NotificationsExtensions::TileContent::TileWidePeekImage01 |
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWidePeekImage01() | NotificationsExtensions::TileContent::TileWidePeekImage01 | [inline]
TileWidePeekImage01() | NotificationsExtensions::TileContent::TileWidePeekImage01 | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:44 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Background task/C++/BackgroundTask/common/suspensionmanager.h Source File

  • Background task
  • BackgroundTask
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DatagramSocket/C++/MainPage.xaml.cpp Source File

  • DatagramSocket

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Platform;
00026 using namespace DatagramSocketSample;
00027 using namespace CppSamplesUtils;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     LayoutRoot->Children->Append(HiddenFrame);
00045
00046     // Populate the sample title from the constant in the GlobalVariables.cs file.
00047     SetFeatureName(FEATURE_NAME);
00048
00049     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00050     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00051
00052     MainPage::Current = this;
00053     autoSizeInputSectionWhenSnapped = true;
00054 }
00055
00056 MainPage::~MainPage()
00057 {
00058 }
00059
00060 /// <summary>
00061 /// Invoked when this page is about to be displayed in a Frame.
00062 /// </summary>
00063 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00064 /// property is typically used to configure the page.</param>
00065 void MainPage::OnNavigatedTo(NavigationEventArgs^ e)
00066 {
00067     PopulateScenarios();
00068     InvalidateViewState();
00069 }
00070
00071 /// <summary>
00072 /// We need to handle SizeChanged so that we can make the sample layout property
00073 /// in the various layouts.
00074 /// </summary>
00075 /// <param name="sender"></param>
00076 /// <param name="e"></param>
00077 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00078 {
00079     InvalidateSize();
00080     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00081     args->ViewState = ApplicationView::Value;
00082     MainPageResized(this, args);
00083
00084 }
00085
00086 void MainPage::InvalidateSize()
00087 {
00088     // Get the window width
00089     double windowWidth = this->ActualWidth;
00090
00091     if (windowWidth != 0.0)
00092     {
00093         // Get the width of the ListBox.
00094         double listBoxWidth = Scenarios->ActualWidth;
00095
00096         // Is the ListBox using any margins that we need to consider?
00097         double listBoxMarginLeft = Scenarios->Margin.Left;
00098         double listBoxMarginRight = Scenarios->Margin.Right;
00099
00100         // Figure out how much room is left after considering the list box width
00101         double availableWidth = windowWidth - listBoxWidth;
00102
00103         // Is the top most child using margins?
00104         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00105         double layoutRootMarginRight = ContentRoot->Margin.Right;
00106
00107         // We have different widths to use depending on the view state
00108         if (ApplicationView::Value != ApplicationViewState::Snapped)
00109         {
00110             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00111             // and the LayoutRoot's margins
00112             InputSection->Width = availableWidth -
00113                (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight);
00114         }
00115         else
00116         {
00117             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00118             if (autoSizeInputSectionWhenSnapped)
00119             {
00120                 InputSection->Width = windowWidth - (layoutRootMarginLeft + layoutRootMarginRight);
00121             }
00122         }
00123     }
00124     InvalidateViewState();
00125 }
00126
00127 void MainPage::InvalidateViewState()
00128 {
00129     // Are we going to snapped mode?
00130     if (ApplicationView::Value == ApplicationViewState::Snapped)
00131     {
00132         Grid::SetRow(DescriptionText, 3);
00133         Grid::SetColumn(DescriptionText, 0);
00134
00135         Grid::SetRow(InputSection, 4);
00136         Grid::SetColumn(InputSection, 0);
00137
00138         Grid::SetRow(FooterPanel, 2);
00139         Grid::SetColumn(FooterPanel, 0);
00140     }
00141     else
00142     {
00143         Grid::SetRow(DescriptionText, 1);
00144         Grid::SetColumn(DescriptionText, 1);
00145
00146         Grid::SetRow(InputSection, 2);
00147         Grid::SetColumn(InputSection, 1);
00148
00149         Grid::SetRow(FooterPanel, 1);
00150         Grid::SetColumn(FooterPanel, 1);
00151     }
00152
00153 }
00154
00155 void MainPage::PopulateScenarios()
00156 {
00157     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00158
00159     // Populate the ListBox with the list of scenarios as defined in Constants.cs.
00160     for (unsigned int i = 0; i < scenarios->Length; ++i)
00161     {
00162         Scenario s = scenarios[i];
00163         ListBoxItem^ item = ref new ListBoxItem();
00164         item->Name = s.ClassName;
00165         item->Content = (i + 1).ToString() + ") " + s.Title;
00166         ScenarioList->Append(item);
00167     }
00168
00169     // Bind the ListBox to the scenario list.
00170     Scenarios->ItemsSource = ScenarioList;
00171
00172     // Starting scenario is the first or based upon a previous selection.
00173     ListBoxItem^ startingScenario = nullptr;
00174
00175     // Starting scenario is the first or based upon a previous selection.
00176     int startingScenarioIndex = -1;
00177
00178     auto ps = SuspensionManager::SessionState();
00179     if (ps->HasKey("SelectedScenarioIndex"))
00180     {
00181         int selectedScenarioIndex = safe_cast<int>(ps->Lookup("SelectedScenarioIndex"));
00182         startingScenarioIndex = selectedScenarioIndex;
00183     }
00184
00185     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00186 }
00187
00188 /// <summary>
00189 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00190 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00191 /// and output sections into the respective UserControl on the main page.
00192 /// </summary>
00193 /// <param name="scenarioName"></param>
00194 void MainPage::LoadScenario(String^ scenarioName)
00195 {
00196     autoSizeInputSectionWhenSnapped = true;
00197
00198     // Load the ScenarioX.xaml file into the Frame.
00199     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00200     HiddenFrame->Navigate(scenarioType, this);
00201
00202     // Get the top element, the Page, so we can look up the elements
00203     // that represent the input and output sections of the ScenarioX file.
00204     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00205
00206     // Get each element.
00207     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00208     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00209
00210     if (input == nullptr)
00211     {
00212         // Malformed input section.
00213         NotifyUser("Cannot load scenario input section for " + scenarioName +
00214             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00215         return;
00216     }
00217
00218     if (output == nullptr)
00219     {
00220         // Malformed output section.
00221         NotifyUser("Cannot load scenario output section for " + scenarioName +
00222             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00223         return;
00224     }
00225     // Find the LayoutRoot which parents the input and output sections in the main page.
00226     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00227
00228     if (panel != nullptr)
00229     {
00230         unsigned int index = 0;
00231         UIElementCollection^ collection = panel->Children;
00232
00233         // Get rid of the content that is currently in the intput and output sections.
00234         collection->IndexOf(input, &index);
00235         collection->RemoveAt(index);
00236
00237         collection->IndexOf(output, &index);
00238         collection->RemoveAt(index);
00239
00240         // Populate the input and output sections with the newly loaded content.
00241         InputSection->Content = input;
00242         OutputSection->Content = output;
00243
00244         ScenarioLoaded(this, nullptr);
00245     }
00246     else
00247     {
00248         // Malformed Scenario file.
00249         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00250             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00251     }
00252 }
00253
00254 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00255 {
00256     if (Scenarios->SelectedItem != nullptr)
00257     {
00258         NotifyUser("", NotifyType::StatusMessage);
00259
00260         int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00261         SuspensionManager::SessionState()->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00262
00263         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00264         InvalidateSize();
00265     }
00266 }
00267
00268 void MainPage::SetFeatureName(String^ strFeature)
00269 {
00270     FeatureName->Text = strFeature;
00271 }
00272
00273 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00274 {
00275     switch (type)
00276     {
00277     case NotifyType::StatusMessage:
00278         // Use the status message style.
00279         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00280         break;
00281     case NotifyType::ErrorMessage:
00282         // Use the error message style.
00283         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00284         break;
00285     default:
00286         break;
00287     }
00288     StatusBlock->Text = strMessage;
00289
00290     // Collapsed the StatusBlock if it has no text to conserve real estate.
00291     if (StatusBlock->Text != "")
00292     {
00293         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00294     }
00295     else
00296     {
00297         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00298     }
00299 }
00300
00301 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00302 {
00303     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00304     Windows::System::Launcher::LaunchUriAsync(uri);
00305 }
Generated on Sat Nov 23 2024 16:07:41 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAudio2 audio stream effect/C++/StreamEffect.h Source File

  • XAudio2 audio stream effect

StreamEffect.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
00011 #include "SampleOverlay.h"
00012 #include "DirectXSample.h"
00013 #include "DirectXBase.h"
00014 #include "MediaStreamer.h"
00015
00016 ref class StreamEffect : public DirectXBase
00017 {
00018 public:
00019 //    static const size_t BUFFER_COUNT = 3;
00020 internal:
00021     StreamEffect();
00022
00023     // Overrides from DirectXBase
00024     virtual void CreateDeviceIndependentResources() override;
00025     virtual void CreateDeviceResources() override;
00026     virtual void CreateWindowSizeDependentResources() override;
00027     virtual void Render() override;
00028
00029     void OnSuspending();
00030     void OnResuming();
00031
00032     void Update(float TimeTotal, float TimeDelta);
00033
00034     // Audio Functionality
00035     void CreateAudioResources();
00036     void ReleaseAudioResources();
00037     void RenderAudio();
00038     bool IsAudioSetup();
00039
00040 private:
00041     // Overlay for Graphics
00042     ~StreamEffect();
00043     SampleOverlay^                  m_sampleOverlay;
00044
00045     // Audio Related Members
00046     bool                            m_isAudioStarted;
00047     IXAudio2*                       m_musicEngine;
00048     IXAudio2MasteringVoice*         m_musicMasteringVoice;
00049     IXAudio2SourceVoice*            m_musicSourceVoice;
00050     std::vector<byte>               m_audioBuffers[3];
00051     std::unique_ptr<MediaStreamer>  m_musicStreamer;
00052     size_t                          m_currentBuffer;
00053
00054     // Members for drawing text messages
00055     Microsoft::WRL::ComPtr<IDWriteTextFormat>       m_dataTextFormat;
00056     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_textBrush;
00057 };
Generated on Sat Nov 23 2024 16:08:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File and folder thumbnail/C++/Constants.h Source File

  • File and folder thumbnail

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     class Errors
00024     {
00025     public:
00026         static Platform::String^ NoExifThumbnail;
00027         static Platform::String^ NoThumbnail;
00028         static Platform::String^ NoAlbumArt;
00029         static Platform::String^ NoIcon;
00030         static Platform::String^ NoImages;
00031         static Platform::String^ FileGroupEmpty;
00032         static Platform::String^ FileGroupLocation;
00033         static Platform::String^ Cancel;
00034     };
00035
00036     class FileExtensions
00037     {
00038     public:
00039         static Platform::Array<Platform::String^>^ Document;
00040         static Platform::Array<Platform::String^>^ Image;
00041         static Platform::Array<Platform::String^>^ Music;
00042     };
00043
00044     partial ref class MainPage
00045     {
00046     public:
00047         static property Platform::String^ FEATURE_NAME
00048         {
00049             Platform::String^ get()
00050             {
00051                 return ref new Platform::String(L"File thumbnails C++ sample");
00052             }
00053         }
00054
00055         static property Platform::Array<Scenario>^ scenarios
00056         {
00057             Platform::Array<Scenario>^ get()
00058             {
00059                 return scenariosInner;
00060             }
00061         }
00062
00063     internal:
00064         bool EnsureUnsnapped();
00065         void ResetOutput(Windows::UI::Xaml::Controls::Image^ image, Windows::UI::Xaml::Controls::TextBlock^ output, Windows::UI::Xaml::Controls::TextBlock^ outputDetails);
00066         static void DisplayResult(Windows::UI::Xaml::Controls::Image^ image, Windows::UI::Xaml::Controls::TextBlock^ textBlock,
00067                                   Platform::String^ thumbnailModeName, size_t size,
00068                                   Windows::Storage::IStorageItem^ item, Windows::Storage::FileProperties::StorageItemThumbnail^ thumbnail,
00069                                   bool isGroup);
00070
00071     private:
00072         static Platform::Array<Scenario>^ scenariosInner;
00073
00074         Windows::UI::Xaml::Media::Imaging::BitmapImage^ _placeholder;
00075         Windows::UI::Xaml::Media::Imaging::BitmapImage^ GetPlaceHolderImage();
00076     };
00077 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Getting started with C++ simple blog reader/C++/FeedData.h Source File

  • Getting started with C++ simple blog reader

FeedData.h

Go to the documentation of this file.
00001
00002 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00003 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00004 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00005 // PARTICULAR PURPOSE.
00006 //
00007 // Copyright (c) Microsoft Corporation. All rights reserved
00008
00009 //feeddata.h
00010
00011 #pragma once
00012 #include "pch.h"
00013 #include <collection.h>
00014
00015
00016 namespace SimpleBlogReader
00017 {
00018     // To be bindable, a class must be defined within a namespace
00019     // and a bindable attribute needs to be applied.
00020     // A FeedItem represents a single blog post.
00021     [Windows::UI::Xaml::Data::Bindable]
00022     public ref class FeedItem sealed
00023     {
00024     public:
00025         FeedItem(void){}
00026
00027         property Platform::String^ Title;
00028         property Platform::String^ Author;
00029         property Platform::String^ Content;
00030         property Windows::Foundation::DateTime PubDate;
00031         property Windows::Foundation::Uri^ Link;
00032
00033     private:
00034         ~FeedItem(void){}
00035     };
00036
00037     // A FeedData object represents a feed that contains
00038     // one or more FeedItems.
00039     [Windows::UI::Xaml::Data::Bindable]
00040     public ref class FeedData sealed
00041     {
00042     public:
00043         FeedData(void)
00044         {
00045             m_items = ref new Platform::Collections::Vector<FeedItem^>();
00046         }
00047
00048         // The public members must be Windows Runtime types so that
00049         // the XAML controls can bind to them from a separate .winmd.
00050         property Platform::String^ Title;
00051         property Windows::Foundation::Collections::IVector<FeedItem^>^ Items
00052         {
00053             Windows::Foundation::Collections::IVector<FeedItem^>^ get() {return m_items; }
00054         }
00055
00056         property Platform::String^ Description;
00057         property Windows::Foundation::DateTime PubDate;
00058         property Platform::String^ Uri;
00059
00060     private:
00061         ~FeedData(void){}
00062
00063         Platform::Collections::Vector<FeedItem^>^ m_items;
00064     };
00065
00066     // A FeedDataSource represents a collection of FeedData objects
00067     // and provides the methods to download the source data from which
00068     // FeedData and FeedItem objects are constructed. This class is
00069     // instantiated at startup by this declaration in the
00070     // ResourceDictionary in app.xaml: <local:FeedDataSource x:Key="feedDataSource" />
00071     [Windows::UI::Xaml::Data::Bindable]
00072     public ref class FeedDataSource sealed
00073     {
00074     private:
00075         Platform::Collections::Vector<FeedData^>^ m_feeds;
00076         std::map<Platform::String^, concurrency::task_completion_event<FeedData^>> m_feedCompletionEvents;
00077         FeedData^ GetFeedData(Platform::String^ feedUri, Windows::Web::Syndication::SyndicationFeed^ feed);
00078
00079     public:
00080         FeedDataSource();
00081         property Windows::Foundation::Collections::IObservableVector<FeedData^>^ Feeds
00082         {
00083             Windows::Foundation::Collections::IObservableVector<FeedData^>^ get()
00084             {
00085                 return this->m_feeds;
00086             }
00087         }
00088         void InitDataSource();
00089         static Windows::Foundation::IAsyncOperation<FeedData^>^ GetFeedAsync(Platform::String^ title);
00090         static FeedItem^ GetFeedItem(FeedData^ fd, Platform::String^ uniqueiD);
00091     };
00092 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

PrintSample::BasePrintPage Member List

This is the complete list of members for PrintSample::BasePrintPage, including all inherited members.
__pad0__ | Element |
AcceptChildNode(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^childXmlNode) override | Page | [virtual]
AddChild(_In_ Element^element) | Element |
AddOnePrintPreviewPage(RichTextBlockOverflow^lastRTBOAdded, Windows::Graphics::Printing::PrintPageDescription printPageDescription) | PrintSample::BasePrintPage | [protected, virtual]
AddPrintPages(Object^sender, AddPagesEventArgs^e) | PrintSample::BasePrintPage | [protected, virtual]
AddSibling(_In_ Element^element) | Element |
BindResource(_In_ Element^rootElement) | Element | [virtual]
Create(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^xmlNode) | Element | [static]
CreatePrintPreviewPages(Object^sender, PaginateEventArgs^e) | PrintSample::BasePrintPage | [protected, virtual]
Draw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
GetFirstChild() | Element | [inline]
GetName() | Element | [inline]
GetNextSibling() | Element | [inline]
GetOpacity() | Element | [inline, virtual]
GetParent() | Element | [inline]
GetPrintPreviewPage(Object^sender, GetPreviewPageEventArgs^e) | PrintSample::BasePrintPage | [protected, virtual]
GetSize() | Element | [inline]
Initialize(_In_ Document^document, _In_ Windows::Data::Xml::Dom::XmlElement^xmlElement) | Element | [virtual]
m_currentPage | PrintSample::BasePrintPage | [private]
m_firstPage | PrintSample::BasePrintPage | [private]
m_isRegisteredForPrinting | PrintSample::BasePrintPage | [private]
m_printDocument | PrintSample::BasePrintPage | [private]
m_printDocumentSource | PrintSample::BasePrintPage | [private]
m_printPreviewPages | PrintSample::BasePrintPage | [private]
m_printTaskRequestedEventToken | PrintSample::BasePrintPage | [private]
m_rootPage | PrintSample::BasePrintPage | [private]
Measure(_In_ Document^document, D2D1_SIZE_F const &parentSize, _Out_ D2D1_RECT_F *bounds) | Element | [virtual]
OnContentCreated() | PrintSample::BasePrintPage | [inline, protected, virtual]
OnNavigatedFrom(NavigationEventArgs^e) override | PrintSample::BasePrintPage | [virtual]
OnNavigatedTo(NavigationEventArgs^e) override | PrintSample::BasePrintPage | [virtual]
PrepareToDraw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
PrintTaskRequested(Windows::Graphics::Printing::PrintManager^sender, Windows::Graphics::Printing::PrintTaskRequestedEventArgs^e) | PrintSample::BasePrintPage | [protected, virtual]
RegisterForPrinting() | PrintSample::BasePrintPage | [protected]
RegisterForPrintingButtonClick(Object^sender, RoutedEventArgs^e) | PrintSample::BasePrintPage | [protected]
ReleaseParent() | Element | [virtual]
RemovePageFromPrintPreviewCollection(int pageNumber) | PrintSample::BasePrintPage | [protected]
UnregisterForPrinting() | PrintSample::BasePrintPage | [protected]
Generated on Sat Nov 23 2024 16:09:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Credential locker/C++/App.xaml.h Source File

  • Credential locker

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Lock screen apps/C#,C++/ScenarioOutput3.xaml.cpp Source File

  • Lock screen apps
  • C#,C++

ScenarioOutput3.xaml.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 //
00009 // Scenario2Output.xaml.cpp
00010 // Implementation of the Scenario2Output class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioOutput3.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace LockScreenAppsCPP;
00018
00019 using namespace Platform;
00020
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Foundation::Collections;
00023 using namespace Windows::Graphics::Display;
00024 using namespace Windows::UI::ViewManagement;
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 ScenarioOutput3::ScenarioOutput3()
00034 {
00035     InitializeComponent();
00036 }
00037
00038 ScenarioOutput3::~ScenarioOutput3()
00039 {
00040 }
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playlist/C++/App.xaml.cpp Source File

  • Playlist

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Splash screen/C++/App.xaml.h Source File

  • Splash screen

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Configure keys for media/C++/Constants.h Source File

  • Configure keys for media

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"Media Buttons");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Credential picker/C++/ScenarioInput2.xaml.cpp Source File

  • Credential picker

ScenarioInput2.xaml.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 //
00009 // Scenario2Input.xaml.cpp
00010 // Implementation of the Scenario2Input class.
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioInput2.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace CredentialPickerCPP;
00018
00019 using namespace Platform;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Graphics::Display;
00023 using namespace Windows::UI::ViewManagement;
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 using namespace Windows::Security::Credentials::UI;
00032 using namespace concurrency;
00033
00034 ScenarioInput2::ScenarioInput2()
00035 {
00036     InitializeComponent();
00037 }
00038
00039 ScenarioInput2::~ScenarioInput2()
00040 {
00041 }
00042
00043 void ScenarioInput2::SetError(Platform::String^ errorText)
00044 {
00045     this->rootPage->NotifyUser(errorText,NotifyType::ErrorMessage);
00046 }
00047
00048 void ScenarioInput2::SetResult(CredentialPickerResults^ result)
00049 {
00050     auto domainName = result->CredentialDomainName;
00051     auto userName = result->CredentialUserName;
00052     auto password = result->CredentialPassword;
00053     auto savedByApi = result->CredentialSaved;
00054     auto saveOption = result->CredentialSaveOption;
00055     Page^ outputFrame = (Page^)this->rootPage->OutputFrame->Content;
00056     TextBox^ status = (TextBox^)outputFrame->FindName("Status");
00057     status->Text = "OK";
00058     TextBox^ domain = (TextBox^)outputFrame->FindName("Domain");
00059     domain->Text = domainName;
00060     TextBox^ username = (TextBox^)outputFrame->FindName("Username");
00061     username->Text = userName;
00062     TextBox^ passwordBox = (TextBox^)outputFrame->FindName("Password");
00063     passwordBox->Text = password;
00064     TextBox^ credsaved = (TextBox^)outputFrame->FindName("CredentialSaved");
00065     credsaved->Text = (savedByApi ? "true" : "false");
00066     TextBox^ checkboxState = (TextBox^)outputFrame->FindName("CheckboxState");
00067     switch (result->CredentialSaveOption)
00068     {
00069         case Windows::Security::Credentials::UI::CredentialSaveOption::Hidden:
00070             checkboxState->Text = "Hidden";
00071             break;
00072         case Windows::Security::Credentials::UI::CredentialSaveOption::Selected:
00073             checkboxState->Text = "Selected";
00074             break;
00075         case Windows::Security::Credentials::UI::CredentialSaveOption::Unselected:
00076             checkboxState->Text = "Unselected";
00077             break;
00078     }
00079 }
00080
00081
00082 #pragma region Template-Related Code - Do not remove
00083 void ScenarioInput2::OnNavigatedTo(NavigationEventArgs^ e)
00084 {
00085     // Get a pointer to our main page.
00086     rootPage = dynamic_cast<MainPage^>(e->Parameter);
00087
00088     // We want to be notified with the OutputFrame is loaded so we can get to the content.
00089     _frameLoadedToken = rootPage->OutputFrameLoaded += ref new Windows::Foundation::EventHandler<Platform::Object^>(this, &ScenarioInput2::rootPage_OutputFrameLoaded);
00090 }
00091
00092 void ScenarioInput2::OnNavigatedFrom(NavigationEventArgs^ e)
00093 {
00094     rootPage->OutputFrameLoaded -= _frameLoadedToken;
00095 }
00096
00097 #pragma endregion
00098
00099 #pragma region Use this code if you need access to elements in the output frame - otherwise delete
00100 void ScenarioInput2::rootPage_OutputFrameLoaded(Object^ sender, Object^ e)
00101 {
00102     // Get a pointer to the content within the OutputFrame.
00103     Page^ outputFrame = dynamic_cast<Page^>(rootPage->OutputFrame->Content);
00104
00105     // Go find the elements that we need for this scenario
00106     // ex: flipView1 = dynamic_cast<FlipView^>(outputFrame->FindName("FlipView1"));
00107 }
00108
00109 #pragma endregion
00110
00111 #pragma region Sample click handlers - modify if you need them, otherwise delete
00112 void ScenarioInput2::Launch_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00113 {
00114   if ((Message->Text != nullptr) && (Caption->Text != nullptr) && (Target->Text != nullptr))
00115   {
00116     create_task(CredentialPicker::PickAsync(Message->Text, Caption->Text, Target->Text))
00117       .then([this](CredentialPickerResults^ credPickerResult)
00118     {
00119       SetResult(credPickerResult);
00120     });
00121   }
00122
00123 }
00124
00125 #pragma endregion
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Contact Picker app/C++/ScenarioMultiple.xaml.h Source File

  • Contact Picker app

ScenarioMultiple.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 // ScenarioMultiple.xaml.h
00013 // Declaration of the ScenarioMultiple class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "ScenarioMultiple.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace ContactPicker
00023 {
00024     /// <summary>
00025     /// An empty page that can be used on its own or navigated to within a Frame.
00026     /// </summary>
00027     public ref class ScenarioMultiple sealed
00028     {
00029     public:
00030         ScenarioMultiple();
00031
00032     private:
00033         void PickContactsButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:59 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D HLSL fractal generator/C++/BasicMath.h Source File

  • Direct3D HLSL fractal generator

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 Sat Nov 23 2024 16:08:08 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Extended Linguistic Services (ELS)/C++/common/LayoutAwarePage.h Source File

  • Extended Linguistic Services (ELS)
  • C++
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Extended Linguistic Services (ELS)/C++/pch.h Source File

  • Extended Linguistic Services (ELS)
  • C++

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

AsyncCallback< T > Member List

This is the complete list of members for AsyncCallback< T >, including all inherited members.
AsyncCallback(T *pParent, InvokeFn fn) | AsyncCallback< T > | [inline]
AsyncCallback(T *pParent, InvokeFn fn) | AsyncCallback< T > | [inline]
AsyncCallback(T *pParent, InvokeFn fn) | AsyncCallback< T > | [inline]
GetParameters(DWORD *, DWORD *) | AsyncCallback< T > | [inline]
GetParameters(DWORD *, DWORD *) | AsyncCallback< T > | [inline]
GetParameters(DWORD *, DWORD *) | AsyncCallback< T > | [inline]
Invoke(IMFAsyncResult *pAsyncResult) | AsyncCallback< T > | [inline]
Invoke(IMFAsyncResult *pAsyncResult) | AsyncCallback< T > | [inline]
Invoke(IMFAsyncResult *pAsyncResult) | AsyncCallback< T > | [inline]
InvokeFn typedef | AsyncCallback< T > |
InvokeFn typedef | AsyncCallback< T > |
InvokeFn typedef | AsyncCallback< T > |
m_pInvokeFn | AsyncCallback< T > |
m_pParent | AsyncCallback< T > |
QueryInterface(REFIID iid, void **ppv) | AsyncCallback< T > | [inline]
QueryInterface(REFIID iid, void **ppv) | AsyncCallback< T > | [inline]
QueryInterface(REFIID iid, void **ppv) | AsyncCallback< T > | [inline]
STDMETHODIMP_(ULONG) AddRef() | AsyncCallback< T > | [inline]
STDMETHODIMP_(ULONG) Release() | AsyncCallback< T > | [inline]
STDMETHODIMP_(ULONG) AddRef() | AsyncCallback< T > | [inline]
STDMETHODIMP_(ULONG) Release() | AsyncCallback< T > | [inline]
STDMETHODIMP_(ULONG) AddRef() | AsyncCallback< T > | [inline]
STDMETHODIMP_(ULONG) Release() | AsyncCallback< T > | [inline]
Generated on Sat Nov 23 2024 16:09:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Print/C++/DisplayContent.h Source File

  • Print

DisplayContent.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 PrintSample
00011 {
00012
00013     enum DisplayContent
00014     {
00015         /// <summary>
00016         /// Show only text
00017         /// </summary>
00018         Text = 1,
00019
00020         /// <summary>
00021         /// Show only images
00022         /// </summary>
00023         Images = 2,
00024
00025         /// <summary>
00026         /// Show a combination of images and text
00027         /// </summary>
00028         TextAndImages = 3
00029     };
00030
00031 };
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Display orientation/C++/Scenario2.xaml.cpp Source File

  • Display orientation

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 SDKSample::DisplayOrientation;
00020
00021 using namespace Platform;
00022 using namespace Windows::Devices::Sensors;
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::Media;
00028 using namespace Windows::UI::Xaml::Controls;
00029 using namespace Windows::UI::Xaml::Navigation;
00030
00031 const double toDegrees = 180.0 / M_PI;
00032
00033 Scenario2::Scenario2()
00034 {
00035     InitializeComponent();
00036
00037     rotationAngle = 0;
00038     accelerometer = Accelerometer::GetDefault();
00039 }
00040
00041 void Scenario2::OnNavigatedTo(NavigationEventArgs^ e)
00042 {
00043     deviceRotation->Text = rotationAngle.ToString();
00044
00045     if (accelerometer != nullptr)
00046     {
00047         readingChangedEventToken = accelerometer->ReadingChanged::add(
00048             ref new TypedEventHandler<Accelerometer^, AccelerometerReadingChangedEventArgs^>(this, &Scenario2::CalculateDeviceRotation)
00049             );
00050     }
00051
00052     if (DisplayProperties::AutoRotationPreferences == DisplayOrientations::None)
00053     {
00054         LockButton->Content = "Lock";
00055     }
00056     else
00057     {
00058         LockButton->Content = "Unlock";
00059     }
00060 }
00061
00062 void Scenario2::OnNavigatedFrom(NavigationEventArgs^ e)
00063 {
00064     if (accelerometer != nullptr)
00065     {
00066         accelerometer->ReadingChanged::remove(readingChangedEventToken);
00067     }
00068 }
00069
00070 void Scenario2::Scenario2Button_Click(Object^ sender, RoutedEventArgs^ e)
00071 {
00072     if (DisplayProperties::AutoRotationPreferences == DisplayOrientations::None)
00073     {
00074         // since there is no preference currently set, get the current screen orientation and set it as the preference
00075         DisplayProperties::AutoRotationPreferences = DisplayProperties::CurrentOrientation;
00076         LockButton->Content = "Unlock";
00077     }
00078     else
00079     {
00080         // something is already set, so reset to no preference
00081         DisplayProperties::AutoRotationPreferences = DisplayOrientations::None;
00082         LockButton->Content = "Lock";
00083     }
00084 }
00085
00086 void Scenario2::CalculateDeviceRotation(Accelerometer^ sender, AccelerometerReadingChangedEventArgs^ args)
00087 {
00088     // Compute the rotation angle based on the accelerometer's position
00089     auto angle = atan2(args->Reading->AccelerationY, args->Reading->AccelerationX) * toDegrees;
00090
00091     // Since our arrow points upwards insted of the right, we rotate the coordinate system by 90 degrees
00092     angle += 90;
00093
00094     // Ensure that the range of the value is between [0, 360)
00095     if (angle < 0)
00096     {
00097         angle += 360;
00098     }
00099
00100     rotationAngle = angle;
00101
00102     // Update the UI with the new value
00103     Dispatcher->RunAsync(
00104         CoreDispatcherPriority::Normal,
00105         ref new DispatchedHandler(
00106             [this]()
00107             {
00108                 deviceRotation->Text = rotationAngle.ToString();
00109             })
00110         );
00111
00112     UpdateArrowForRotation();
00113 }
00114
00115 void Scenario2::UpdateArrowForRotation()
00116 {
00117     // Obtain current rotation taking into account a Landscape first or a Portrait first device
00118     auto screenRotation = 0;
00119
00120     // Native orientation can only be Landscape or Portrait
00121     if (DisplayProperties::NativeOrientation == DisplayOrientations::Landscape)
00122     {
00123         switch (DisplayProperties::CurrentOrientation)
00124         {
00125             case DisplayOrientations::Landscape:
00126                 screenRotation = 0;
00127                 break;
00128
00129             case DisplayOrientations::Portrait:
00130                 screenRotation = 90;
00131                 break;
00132
00133             case DisplayOrientations::LandscapeFlipped:
00134                 screenRotation = 180;
00135                 break;
00136
00137             case DisplayOrientations::PortraitFlipped:
00138                 screenRotation = 270;
00139                 break;
00140
00141             default:
00142                 screenRotation = 0;
00143                 break;
00144         }
00145     }
00146     else
00147     {
00148         switch (DisplayProperties::CurrentOrientation)
00149         {
00150             case DisplayOrientations::Landscape:
00151                 screenRotation = 270;
00152                 break;
00153
00154             case DisplayOrientations::Portrait:
00155                 screenRotation = 0;
00156                 break;
00157
00158             case DisplayOrientations::LandscapeFlipped:
00159                 screenRotation = 90;
00160                 break;
00161
00162             case DisplayOrientations::PortraitFlipped:
00163                 screenRotation = 180;
00164                 break;
00165
00166             default:
00167                 screenRotation = 270;
00168                 break;
00169         }
00170     }
00171
00172     double steeringAngle = rotationAngle - screenRotation;
00173
00174     // Keep the steering angle positive
00175     if (steeringAngle < 0)
00176     {
00177         steeringAngle += 360;
00178     }
00179
00180     // Update the UI based on steering action
00181     Dispatcher->RunAsync(
00182         CoreDispatcherPriority::Normal,
00183         ref new DispatchedHandler(
00184             [this, steeringAngle]()
00185             {
00186                 RotateTransform^ transform = ref new RotateTransform();
00187                 transform->Angle = -steeringAngle;
00188                 transform->CenterX = scenario2Image->ActualWidth / 2;
00189                 transform->CenterY = scenario2Image->ActualHeight / 2;
00190
00191                 scenario2Image->RenderTransform = transform;
00192             })
00193         );
00194 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

AppBarControl::Scenario Member List

This is the complete list of members for AppBarControl::Scenario, including all inherited members.
ClassName | AppBarControl::Scenario
Title | AppBarControl::Scenario
Generated on Sat Nov 23 2024 16:09:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Getting started with C++ simple blog reader/C++/App.xaml.h Source File

  • Getting started with C++ simple blog reader

App.xaml.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 // App.xaml.h
00009 // Declaration of the App class.
00010 //
00011
00012 #pragma once
00013
00014 #include "App.g.h"
00015 #include "FeedData.h"
00016
00017 namespace SimpleBlogReader
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^ pArgs) override;
00027         property Platform::String^ CurrentFeedUri;
00028
00029     private:
00030         void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ e);
00031
00032     };
00033
00034
00035
00036 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Portable device API/C++/common/SuspensionManager.cpp Source File

  • Portable device API
  • common

SuspensionManager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:37 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Calendar details and math/C++/MainPage.xaml.h Source File

  • Calendar details and math

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/Level4.h Source File

  • XAML DirectX 3D shooting game

Level4.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 // Level4:
00011 // This class defines the fourth level of the game.  It derives from the
00012 // third level.  The targets must be hit in numeric order.
00013
00014 #include "Level3.h"
00015
00016 ref class Level4: public Level3
00017 {
00018 internal:
00019     Level4();
00020     virtual void Initialize(std::vector<GameObject^> objects) override;
00021
00022     virtual bool Update(
00023         float time,
00024         float elapsedTime,
00025         float timeRemaining,
00026         std::vector<GameObject^> objects
00027         ) override;
00028
00029     virtual void SaveState(PersistentState^ state) override;
00030     virtual void LoadState(PersistentState^ state) override;
00031
00032 private:
00033     int m_nextId;
00034 };
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D 3D transform effect/C++/PersistentState.h Source File

  • Direct2D 3D transform effect

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 Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::UssdApi::sealed Member List

This is the complete list of members for SDKSample::UssdApi::sealed, including all inherited members.
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::UssdApi::sealed | [protected, virtual]
RequestResponse() | SDKSample::UssdApi::sealed |
rootPage | SDKSample::UssdApi::sealed | [private]
SendButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::UssdApi::sealed | [private]
Generated on Sat Nov 23 2024 16:09:53 for Win8-Examples by doxygen 1.7.1


Win8-Examples: App tiles and badges/C#,C++/Globalization.xaml.h Source File

  • App tiles and badges
  • C#,C++

Globalization.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 // Globalization.xaml.h
00013 // Declaration of the Globalization class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Globalization.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace Tiles
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 Globalization sealed
00031       {
00032       public:
00033         Globalization();
00034
00035       protected:
00036         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037       private:
00038         MainPage^ rootPage;
00039         void ViewCurrentResources_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         void SendTileNotificationWithQueryStrings_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         void SendTileNotificationImage_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00042         void SendTileNotificationText_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00043       };
00044     }
00045 }
Generated on Sat Nov 23 2024 16:07:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D magazine app/C++/ContentImageSource.h Source File

  • Direct2D magazine app

ContentImageSource.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 ref class Renderer;
00011 ref class Element;
00012
00013 //  Native host of VirtualSurfaceImageSource, which implements update callback.
00014 //  The callback is called whenever the application needs to populate new content to
00015 //  the image source which occurs when the image source hosting UI element repaints.
00016 //
00017 class ContentImageSource : public IVirtualSurfaceUpdatesCallbackNative
00018 {
00019 public:
00020     ContentImageSource(
00021         _In_ Element^ content,
00022         _In_ Document^ document,
00023         bool isOpaque
00024         );
00025
00026     virtual HRESULT STDMETHODCALLTYPE UpdatesNeeded() override;
00027
00028     virtual HRESULT STDMETHODCALLTYPE QueryInterface(
00029         REFIID uuid,
00030         _Outptr_ void** object
00031         ) override;
00032
00033     virtual ULONG STDMETHODCALLTYPE AddRef() override;
00034
00035     virtual ULONG STDMETHODCALLTYPE Release() override;
00036
00037     Windows::UI::Xaml::Media::ImageSource^ GetImageSource();
00038
00039     SIZE GetImageSize();
00040
00041     void UpdateContent(_In_ Element^ content);
00042
00043 private:
00044
00045     // This class is used to ensure proper pairing of IVirtualSurfaceImageSourceNative::BeginDraw
00046     // and EndDraw within an error condition. The XAML framework expects EndDraw to be called whenever
00047     // BeginDraw is called - even in failure cases
00048     class ImageSourceDrawHelper
00049     {
00050     public:
00051         ImageSourceDrawHelper(
00052             IVirtualSurfaceImageSourceNative *imageSourceNative,
00053             _In_ RECT updateRect,
00054             _Out_ IDXGISurface **pSurface,
00055             _Out_ POINT *offset,
00056             HRESULT *hr
00057             );
00058         ~ImageSourceDrawHelper();
00059
00060     private:
00061         Microsoft::WRL::ComPtr<IVirtualSurfaceImageSourceNative> m_imageSourceNative;
00062         HRESULT *m_hr;
00063     };
00064
00065     void Initialize();
00066
00067     void Measure(_Out_ SIZE* contentSize);
00068
00069     bool Draw(RECT const& drawingBounds);
00070
00071     // Reference counter
00072     ULONG m_refCount;
00073
00074     // The current document being rendered
00075     Document^ m_document;
00076
00077     // Content to render
00078     Element^ m_content;
00079
00080     // Size of the content in pixels
00081     SIZE m_contentSize;
00082
00083     // Virtual surface image source
00084     Windows::UI::Xaml::Media::Imaging::VirtualSurfaceImageSource^ m_imageSource;
00085
00086     // Native interface of the virtual surface image source
00087     Microsoft::WRL::ComPtr<IVirtualSurfaceImageSourceNative> m_imageSourceNative;
00088
00089     // Flag indicating whether the image surface is opaque
00090     bool m_isOpaque;
00091 };
Generated on Sat Nov 23 2024 16:08:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DXGI swap chain rotation/C++/BasicReaderWriter.h Source File

  • DXGI swap chain rotation

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     Platform::String^ m_locationPath;
00019
00020 internal:
00021     BasicReaderWriter();
00022     BasicReaderWriter(
00023         _In_ Windows::Storage::StorageFolder^ folder
00024         );
00025
00026     Platform::Array<byte>^ ReadData(
00027         _In_ Platform::String^ filename
00028         );
00029
00030     concurrency::task<Platform::Array<byte>^> ReadDataAsync(
00031         _In_ Platform::String^ filename
00032         );
00033
00034     uint32 WriteData(
00035         _In_ Platform::String^ filename,
00036         _In_ const Platform::Array<byte>^ fileData
00037         );
00038
00039     concurrency::task<void> WriteDataAsync(
00040         _In_ Platform::String^ filename,
00041         _In_ const Platform::Array<byte>^ fileData
00042         );
00043 };
Generated on Sat Nov 23 2024 16:08:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/SampleOverlay.h Source File

  • Direct3D resource loading

SampleOverlay.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 "DirectXSample.h"
00011
00012 // This class is responsible for initializing and rendering the title overlay visible
00013 // at the top of the DirectX SDK samples.
00014 ref class SampleOverlay
00015 {
00016 internal:
00017     SampleOverlay();
00018
00019     void Initialize(
00020         _In_ ID2D1Device*         d2dDevice,
00021         _In_ ID2D1DeviceContext*  d2dContext,
00022         _In_ IWICImagingFactory*  wicFactory,
00023         _In_ IDWriteFactory*      dwriteFactory,
00024         _In_ Platform::String^    caption
00025         );
00026
00027     void ResetDirectXResources();
00028
00029     void UpdateForWindowSizeChange();
00030
00031     void Render();
00032
00033     float GetTitleHeightInDips();
00034
00035 private:
00036
00037     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00038     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00039     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00040     Microsoft::WRL::ComPtr<IDWriteFactory>          m_dwriteFactory;
00041     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_whiteBrush;
00042     Microsoft::WRL::ComPtr<ID2D1DrawingStateBlock>  m_stateBlock;
00043
00044     Microsoft::WRL::ComPtr<IWICImagingFactory>      m_wicFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Bitmap>             m_logoBitmap;
00046     Microsoft::WRL::ComPtr<IDWriteTextLayout>       m_textLayout;
00047
00048     UINT                                            m_idIncrement;
00049     bool                                            m_drawOverlay;
00050     Platform::String^                               m_sampleName;
00051     float                                           m_padding;
00052     float                                           m_textVerticalOffset;
00053     D2D1_SIZE_F                                     m_logoSize;
00054     float                                           m_overlayWidth;
00055 };
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Language font mapping/C++/MainPage.xaml.h Source File

  • Language font mapping

MainPage.xaml.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 //
00009 // MainPage.xaml.h
00010 // Declaration of the MainPage.xaml class.
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "MainPage.g.h"
00017
00018 namespace LanguageFontCPP
00019 {
00020     public enum class NotifyType
00021     {
00022         StatusMessage,
00023         ErrorMessage
00024     };
00025
00026     [Windows::Foundation::Metadata::WebHostHidden]
00027     public ref class MainPage sealed
00028     {
00029     public:
00030         MainPage();
00031
00032         property Windows::UI::Xaml::Controls::Frame^ ScenariosFrame
00033         {
00034             Windows::UI::Xaml::Controls::Frame^ get() { return _scenariosFrame; }
00035         }
00036         property Windows::UI::Xaml::Controls::Frame^ InputFrame
00037         {
00038             Windows::UI::Xaml::Controls::Frame^ get() { return _inputFrame; }
00039         }
00040         property Windows::UI::Xaml::Controls::Frame^ OutputFrame
00041         {
00042             Windows::UI::Xaml::Controls::Frame^ get() { return _outputFrame; }
00043         }
00044
00045         event Windows::Foundation::EventHandler<Platform::Object^>^ InputFrameLoaded;
00046         event Windows::Foundation::EventHandler<Platform::Object^>^ OutputFrameLoaded;
00047
00048         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00049         void DoNavigation(Windows::UI::Xaml::Interop::TypeName inPageType, Windows::UI::Xaml::Controls::Frame^ inFrame, Windows::UI::Xaml::Interop::TypeName outPageType, Windows::UI::Xaml::Controls::Frame^ outFrame);
00050         Platform::String^ ConvertViewState(Windows::UI::ViewManagement::ApplicationViewState state);
00051         Platform::String^ ConvertResolution(Windows::Graphics::Display::ResolutionScale scale);
00052
00053     private:
00054         ~MainPage();
00055         Windows::UI::Xaml::Controls::Frame^ _scenariosFrame;
00056         Windows::UI::Xaml::Controls::Frame^ _inputFrame;
00057         Windows::UI::Xaml::Controls::Frame^ _outputFrame;
00058         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00059         Windows::Foundation::EventRegistrationToken _displayHandlerToken;
00060         Windows::Foundation::EventRegistrationToken _layoutHandlerToken;
00061         Windows::Foundation::EventRegistrationToken _pageLoadedHandlerToken;
00062         Windows::Foundation::EventRegistrationToken _logicalDpiChangedToken;
00063         Windows::Foundation::EventRegistrationToken _inputFrameLoadedToken;
00064         Windows::Foundation::EventRegistrationToken _outputFrameLoadedToken;
00065         void Page_SizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00066         void DisplayProperties_LogicalDpiChanged(Object^ sender);
00067         void Page_Loaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00068         void CheckResolutionAndViewState();
00069         void SetFeatureName(Platform::String^ strFeature);
00070         void inputFrameNavigated(Object^ sender, Windows::UI::Xaml::Navigation::NavigationEventArgs^ e);
00071         void outputFrameNavigated(Object^ sender,  Windows::UI::Xaml::Navigation::NavigationEventArgs^ e);
00072     };
00073 }
Generated on Sat Nov 23 2024 16:07:46 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX swap chain implementation/C++/DirectXBase.cpp Source File

  • DirectX swap chain implementation

DirectXBase.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 "DirectXBase.h"
00010
00011 using namespace Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::Graphics::Display;
00015 using namespace D2D1;
00016
00017 // Constructor.
00018 DirectXBase::DirectXBase() :
00019     m_windowSizeChangeInProgress(false),
00020     m_dpi(-1.0f)
00021 {
00022 }
00023
00024 // Initialize the DirectX resources required to run.
00025 void DirectXBase::Initialize(CoreWindow^ window, float dpi)
00026 {
00027     m_window = window;
00028
00029     CreateDeviceIndependentResources();
00030     CreateDeviceResources();
00031     SetDpi(dpi);
00032 }
00033
00034 // Recreate all device resources and set them back to the current state.
00035 void DirectXBase::HandleDeviceLost()
00036 {
00037     // Reset these member variables to ensure that SetDpi recreates all resources.
00038     float dpi = m_dpi;
00039     m_dpi = -1.0f;
00040     m_windowBounds.Width = 0;
00041     m_windowBounds.Height = 0;
00042     m_swapChain = nullptr;
00043
00044     CreateDeviceResources();
00045     SetDpi(dpi);
00046 }
00047
00048 // These are the resources required independent of the device.
00049 void DirectXBase::CreateDeviceIndependentResources()
00050 {
00051     D2D1_FACTORY_OPTIONS options;
00052     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00053
00054 #if defined(_DEBUG)
00055     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00056     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00057 #endif
00058
00059     DX::ThrowIfFailed(
00060         D2D1CreateFactory(
00061             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00062             __uuidof(ID2D1Factory1),
00063             &options,
00064             &m_d2dFactory
00065             )
00066         );
00067
00068     DX::ThrowIfFailed(
00069         DWriteCreateFactory(
00070             DWRITE_FACTORY_TYPE_SHARED,
00071             __uuidof(IDWriteFactory),
00072             &m_dwriteFactory
00073             )
00074         );
00075
00076     DX::ThrowIfFailed(
00077         CoCreateInstance(
00078             CLSID_WICImagingFactory,
00079             nullptr,
00080             CLSCTX_INPROC_SERVER,
00081             IID_PPV_ARGS(&m_wicFactory)
00082             )
00083         );
00084 }
00085
00086 // These are the resources that depend on the device.
00087 void DirectXBase::CreateDeviceResources()
00088 {
00089     // This flag adds support for surfaces with a different color channel ordering
00090     // than the API default. It is required for compatibility with Direct2D.
00091     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00092     ComPtr<IDXGIDevice> dxgiDevice;
00093
00094 #if defined(_DEBUG)
00095     // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00096     creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00097 #endif
00098
00099     // This array defines the set of DirectX hardware feature levels this app will support.
00100     // Note the ordering should be preserved.
00101     // Don't forget to declare your application's minimum required feature level in its
00102     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00103     D3D_FEATURE_LEVEL featureLevels[] =
00104     {
00105         D3D_FEATURE_LEVEL_11_1,
00106         D3D_FEATURE_LEVEL_11_0,
00107         D3D_FEATURE_LEVEL_10_1,
00108         D3D_FEATURE_LEVEL_10_0,
00109         D3D_FEATURE_LEVEL_9_3,
00110         D3D_FEATURE_LEVEL_9_2,
00111         D3D_FEATURE_LEVEL_9_1
00112     };
00113
00114     // Create the Direct3D 11 API device object and a corresponding context.
00115     ComPtr<ID3D11Device> device;
00116     ComPtr<ID3D11DeviceContext> context;
00117     DX::ThrowIfFailed(
00118         D3D11CreateDevice(
00119             nullptr,                    // Specify nullptr to use the default adapter.
00120             D3D_DRIVER_TYPE_HARDWARE,
00121             0,
00122             creationFlags,              // Set debug and Direct2D compatibility flags.
00123             featureLevels,              // List of feature levels this app can support.
00124             ARRAYSIZE(featureLevels),
00125             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Metro style apps.
00126             &device,                    // Returns the Direct3D device created.
00127             &m_featureLevel,            // Returns feature level of device created.
00128             &context                    // Returns the device immediate context.
00129             )
00130         );
00131
00132     // Get the Direct3D 11.1 API device and context interfaces.
00133     DX::ThrowIfFailed(
00134         device.As(&m_d3dDevice)
00135         );
00136
00137     DX::ThrowIfFailed(
00138         context.As(&m_d3dContext)
00139         );
00140
00141     // Get the underlying DXGI device of the Direct3D device.
00142     DX::ThrowIfFailed(
00143         m_d3dDevice.As(&dxgiDevice)
00144         );
00145
00146     // Create the Direct2D device object and a corresponding context.
00147     DX::ThrowIfFailed(
00148         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00149         );
00150
00151     DX::ThrowIfFailed(
00152         m_d2dDevice->CreateDeviceContext(
00153             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00154             &m_d2dContext
00155             )
00156         );
00157 }
00158
00159 // Helps track the DPI in the helper class.
00160 // This is called in the dpiChanged event handler in the view class.
00161 void DirectXBase::SetDpi(float dpi)
00162 {
00163     if (dpi != m_dpi)
00164     {
00165         // Save the DPI of this display in our class.
00166         m_dpi = dpi;
00167
00168         // Update Direct2D's stored DPI.
00169         m_d2dContext->SetDpi(m_dpi, m_dpi);
00170
00171         // Often a DPI change implies a window size change. In some cases Windows will issue
00172         // both a size changed event and a DPI changed event. In this case, the resulting bounds
00173         // will not change, and the window resize code will only be executed once.
00174         UpdateForWindowSizeChange();
00175     }
00176 }
00177
00178 // This routine is called in the event handler for the view SizeChanged event.
00179 void DirectXBase::UpdateForWindowSizeChange()
00180 {
00181     // Only handle window size changed if there is no pending DPI change.
00182     if (m_dpi != DisplayProperties::LogicalDpi)
00183     {
00184         return;
00185     }
00186
00187     if (m_window->Bounds.Width  != m_windowBounds.Width ||
00188         m_window->Bounds.Height != m_windowBounds.Height)
00189     {
00190         m_d2dContext->SetTarget(nullptr);
00191         m_d2dTargetBitmap = nullptr;
00192         m_d3dRenderTargetView = nullptr;
00193         m_d3dDepthStencilView = nullptr;
00194         m_windowSizeChangeInProgress = true;
00195         CreateWindowSizeDependentResources();
00196     }
00197 }
00198
00199 // Allocate all memory resources that change on a window SizeChanged event.
00200 void DirectXBase::CreateWindowSizeDependentResources()
00201 {
00202     // Store the window bounds so the next time we get a SizeChanged event we can
00203     // avoid rebuilding everything if the size is identical.
00204     m_windowBounds = m_window->Bounds;
00205
00206     if (m_swapChain != nullptr)
00207     {
00208         // If the swap chain already exists, resize it.
00209         HRESULT hr = m_swapChain->ResizeBuffers(2, 0, 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0);
00210
00211         if (hr == DXGI_ERROR_DEVICE_REMOVED)
00212         {
00213             // If the device was removed for any reason, a new device and swapchain will need to be created.
00214             HandleDeviceLost();
00215
00216             // Everything is set up now. Do not continue execution of this method.
00217             return;
00218         }
00219         else
00220         {
00221             DX::ThrowIfFailed(hr);
00222         }
00223     }
00224     else
00225     {
00226         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00227         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00228         swapChainDesc.Width = 0;                                     // Use automatic sizing.
00229         swapChainDesc.Height = 0;
00230         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;           // This is the most common swap chain format.
00231         swapChainDesc.Stereo = false;
00232         swapChainDesc.SampleDesc.Count = 1;                          // Don't use multi-sampling.
00233         swapChainDesc.SampleDesc.Quality = 0;
00234         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00235         swapChainDesc.BufferCount = 2;                               // Use double-buffering to minimize latency.
00236         swapChainDesc.Scaling = DXGI_SCALING_NONE;
00237         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Metro style apps must use this SwapEffect.
00238         swapChainDesc.Flags = 0;
00239
00240         ComPtr<IDXGIDevice1> dxgiDevice;
00241         DX::ThrowIfFailed(
00242             m_d3dDevice.As(&dxgiDevice)
00243             );
00244
00245         ComPtr<IDXGIAdapter> dxgiAdapter;
00246         DX::ThrowIfFailed(
00247             dxgiDevice->GetAdapter(&dxgiAdapter)
00248             );
00249
00250         ComPtr<IDXGIFactory2> dxgiFactory;
00251         DX::ThrowIfFailed(
00252             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00253             );
00254
00255         CoreWindow^ window = m_window.Get();
00256         DX::ThrowIfFailed(
00257             dxgiFactory->CreateSwapChainForCoreWindow(
00258                 m_d3dDevice.Get(),
00259                 reinterpret_cast<IUnknown*>(window),
00260                 &swapChainDesc,
00261                 nullptr,
00262                 &m_swapChain
00263                 )
00264             );
00265
00266         // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
00267         // ensures that the application will only render after each VSync, minimizing power consumption.
00268         DX::ThrowIfFailed(
00269             dxgiDevice->SetMaximumFrameLatency(1)
00270             );
00271     }
00272
00273     // Create a Direct3D render target view of the swap chain back buffer.
00274     ComPtr<ID3D11Texture2D> backBuffer;
00275     DX::ThrowIfFailed(
00276         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00277         );
00278
00279     DX::ThrowIfFailed(
00280         m_d3dDevice->CreateRenderTargetView(
00281             backBuffer.Get(),
00282             nullptr,
00283             &m_d3dRenderTargetView
00284             )
00285         );
00286
00287     // Cache the rendertarget dimensions in our helper class for convenient use.
00288     D3D11_TEXTURE2D_DESC backBufferDesc = {0};
00289     backBuffer->GetDesc(&backBufferDesc);
00290     m_renderTargetSize.Width  = static_cast<float>(backBufferDesc.Width);
00291     m_renderTargetSize.Height = static_cast<float>(backBufferDesc.Height);
00292
00293     // Create a depth stencil view for use with 3D rendering if needed.
00294     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00295         DXGI_FORMAT_D24_UNORM_S8_UINT,
00296         backBufferDesc.Width,
00297         backBufferDesc.Height,
00298         1,
00299         1,
00300         D3D11_BIND_DEPTH_STENCIL
00301         );
00302
00303     ComPtr<ID3D11Texture2D> depthStencil;
00304     DX::ThrowIfFailed(
00305         m_d3dDevice->CreateTexture2D(
00306             &depthStencilDesc,
00307             nullptr,
00308             &depthStencil
00309             )
00310         );
00311
00312     auto viewDesc = CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D);
00313     DX::ThrowIfFailed(
00314         m_d3dDevice->CreateDepthStencilView(
00315             depthStencil.Get(),
00316             &viewDesc,
00317             &m_d3dDepthStencilView
00318             )
00319         );
00320
00321     // Set the 3D rendering viewport to target the entire window.
00322     CD3D11_VIEWPORT viewport(
00323         0.0f,
00324         0.0f,
00325         static_cast<float>(backBufferDesc.Width),
00326         static_cast<float>(backBufferDesc.Height)
00327         );
00328
00329     m_d3dContext->RSSetViewports(1, &viewport);
00330
00331     // Create a Direct2D target bitmap associated with the
00332     // swap chain back buffer and set it as the current target.
00333     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00334         BitmapProperties1(
00335             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00336             PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00337             m_dpi,
00338             m_dpi
00339             );
00340
00341     ComPtr<IDXGISurface> dxgiBackBuffer;
00342     DX::ThrowIfFailed(
00343         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00344         );
00345
00346     DX::ThrowIfFailed(
00347         m_d2dContext->CreateBitmapFromDxgiSurface(
00348             dxgiBackBuffer.Get(),
00349             &bitmapProperties,
00350             &m_d2dTargetBitmap
00351             )
00352         );
00353
00354     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00355
00356     // Grayscale text anti-aliasing is recommended for all Metro style apps.
00357     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00358 }
00359
00360 // Method to deliver the final image to the display.
00361 void DirectXBase::Present()
00362 {
00363     // The application may optionally specify "dirty" or "scroll" rects to improve efficiency
00364     // in certain scenarios.  In this sample, however, we do not utilize those features.
00365     DXGI_PRESENT_PARAMETERS parameters = {0};
00366     parameters.DirtyRectsCount = 0;
00367     parameters.pDirtyRects = nullptr;
00368     parameters.pScrollRect = nullptr;
00369     parameters.pScrollOffset = nullptr;
00370
00371     // The first argument instructs DXGI to block until VSync, putting the application
00372     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00373     // frames that will never be displayed to the screen.
00374     HRESULT hr = m_swapChain->Present1(1, 0, &parameters);
00375
00376     // Discard the contents of the render target.
00377     // This is a valid operation only when the existing contents will be entirely
00378     // overwritten. If dirty or scroll rects are used, this call should be removed.
00379     m_d3dContext->DiscardView(m_d3dRenderTargetView.Get());
00380
00381     // Discard the contents of the depth stencil.
00382     m_d3dContext->DiscardView(m_d3dDepthStencilView.Get());
00383
00384     // If the device was removed either by a disconnect or a driver upgrade, we
00385     // must recreate all device resources.
00386     if (hr == DXGI_ERROR_DEVICE_REMOVED)
00387     {
00388         HandleDeviceLost();
00389     }
00390     else
00391     {
00392         DX::ThrowIfFailed(hr);
00393     }
00394
00395     if (m_windowSizeChangeInProgress)
00396     {
00397         // A window size change has been initiated and the app has just completed presenting
00398         // the first frame with the new size. Notify the resize manager so we can short
00399         // circuit any resize animation and prevent unnecessary delays.
00400         CoreWindowResizeManager::GetForCurrentView()->NotifyLayoutCompleted();
00401         m_windowSizeChangeInProgress = false;
00402     }
00403 }
00404
00405 void DirectXBase::ValidateDevice()
00406 {
00407     // The D3D Device is no longer valid if the default adapter changes or if
00408     // the device has been removed.
00409
00410     // First, get the information for the adapter related to the current device.
00411
00412     ComPtr<IDXGIDevice1> dxgiDevice;
00413     ComPtr<IDXGIAdapter> deviceAdapter;
00414     DXGI_ADAPTER_DESC deviceDesc;
00415     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00416     DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter));
00417     DX::ThrowIfFailed(deviceAdapter->GetDesc(&deviceDesc));
00418
00419     // Next, get the information for the default adapter.
00420
00421     ComPtr<IDXGIFactory2> dxgiFactory;
00422     ComPtr<IDXGIAdapter1> currentAdapter;
00423     DXGI_ADAPTER_DESC currentDesc;
00424     DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)));
00425     DX::ThrowIfFailed(dxgiFactory->EnumAdapters1(0, &currentAdapter));
00426     DX::ThrowIfFailed(currentAdapter->GetDesc(&currentDesc));
00427
00428     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00429     // a new D3D device must be created.
00430
00431     if ((deviceDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart) ||
00432         (deviceDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart) ||
00433         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00434     {
00435         // Release references to resources related to the old device.
00436         dxgiDevice = nullptr;
00437         deviceAdapter = nullptr;
00438
00439         // Create a new device and swap chain.
00440         HandleDeviceLost();
00441     }
00442 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Removable storage/C++/S1_ListStorages.xaml.h Source File

  • Removable storage

S1_ListStorages.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 // S1_ListStorages.xaml.h
00013 // Declaration of the S1_ListStorages class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "S1_ListStorages.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace RemovableStorageCPP
00025     {
00026         /// <summary>
00027         /// An empty page that can be used on its own or navigated to within a Frame.
00028         /// </summary>
00029         public ref class S1_ListStorages sealed
00030         {
00031         public:
00032             S1_ListStorages();
00033
00034         private:
00035             void ListStorages_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00036             MainPage^ rootPage;
00037         };
00038     }
00039 }
Generated on Sat Nov 23 2024 16:08:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Network status background/C++/NetworkStatusApp/MainPage.xaml.cpp Source File

  • Network status background
  • NetworkStatusApp

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:43 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML user and custom controls/C++/Scenario4.xaml.cpp Source File

  • XAML user and custom controls

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::UserAndCustomControls;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 Scenario4::Scenario4()
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 Scenario4::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 SDKSample::UserAndCustomControls::Scenario4::Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00043 {
00044     Button^ b = safe_cast<Button^>(sender);
00045     if (b != nullptr)
00046     {
00047         rootPage->NotifyUser("You clicked the " + b->Name + " button", NotifyType::StatusMessage);
00048     }
00049 }
00050
00051 void SDKSample::UserAndCustomControls::Scenario4::Other_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00052 {
00053     Button^ b = safe_cast<Button^>(sender);
00054     if (b != nullptr)
00055     {
00056         rootPage->NotifyUser("You clicked the " + b->Name + " button", NotifyType::StatusMessage);
00057     }
00058 }
00059
00060 void SDKSample::UserAndCustomControls::Scenario4::NavigateToLink(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00061 {
00062   auto uri = ref new Windows::Foundation::Uri("http://go.microsoft.com/fwlink/?LinkID=235409");
00063
00064   Windows::System::Launcher::LaunchUriAsync(uri);
00065 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX marble maze game/C++/BasicMath.h Source File

  • DirectX marble maze game

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 Sat Nov 23 2024 16:08:08 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/ImageBrowserViewModel.cpp Source File

  • Hilo C++
  • Hilo

ImageBrowserViewModel.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 #include "ImageBrowserViewModel.h"
00009 #include "IPhoto.h"
00010 #include "IMonthBlock.h"
00011 #include "IYearGroup.h"
00012 #include "IPhotoGroup.h"
00013 #include "PhotoCache.h"
00014 #include "DelegateCommand.h"
00015 #include "ImageNavigationData.h"
00016 #include "TaskExceptionsExtensions.h"
00017 #include "Repository.h"
00018
00019 using namespace concurrency;
00020 using namespace Hilo;
00021 using namespace Platform;
00022 using namespace Platform::Collections;
00023 using namespace std;
00024 using namespace Windows::Foundation::Collections;
00025 using namespace Windows::UI::Xaml::Input;
00026 using namespace Windows::UI::Xaml::Navigation;
00027
00028 ImageBrowserViewModel::ImageBrowserViewModel(shared_ptr<Repository> repository, shared_ptr<ExceptionPolicy> exceptionPolicy) :
00029     m_repository(repository),
00030     ViewModelBase(exceptionPolicy),
00031     m_photoCache(std::make_shared<PhotoCache>()),
00032     m_monthGroups(ref new Vector<IPhotoGroup^>()),
00033     m_yearGroups(ref new Vector<IYearGroup^>()),
00034     m_cancellationTokenSource(cancellation_token_source()),
00035     m_currentQueryId(1),
00036     m_currentMode(Mode::Pending),
00037     m_lastFileChangeTime(0ull),
00038     m_hasFileUpdateTask(false),
00039     m_runningMonthQuery(false), m_runningYearQuery(false)
00040 {
00041     m_groupCommand = ref new DelegateCommand(ref new ExecuteDelegate(this, &ImageBrowserViewModel::NavigateToGroup), nullptr);
00042     m_cropImageCommand = ref new DelegateCommand(
00043         ref new ExecuteDelegate(this, &ImageBrowserViewModel::CropImage),
00044         ref new CanExecuteDelegate(this, &ImageBrowserViewModel::CanProcessImage));
00045     m_rotateImageCommand = ref new DelegateCommand(
00046         ref new ExecuteDelegate(this, &ImageBrowserViewModel::RotateImage),
00047         ref new CanExecuteDelegate(this, &ImageBrowserViewModel::CanProcessImage));
00048     m_cartoonizeImageCommand = ref new DelegateCommand(
00049         ref new ExecuteDelegate(this, &ImageBrowserViewModel::CartoonizeImage),
00050         ref new CanExecuteDelegate(this, &ImageBrowserViewModel::CanProcessImage));
00051
00052     // Register with the repository to receive notifications of file system changes.
00053     auto wr = Platform::WeakReference(this);
00054     function<void()> callback = [wr] {
00055         auto vm = wr.Resolve<ImageBrowserViewModel>();
00056         if (nullptr != vm)
00057         {
00058             vm->OnDataChanged();
00059         }
00060     };
00061     m_repository->AddObserver(callback, PageType::Browse);
00062 }
00063
00064 ImageBrowserViewModel::~ImageBrowserViewModel()
00065 {
00066     if (nullptr != m_repository)
00067     {
00068         m_repository->RemoveObserver(PageType::Browse);
00069     }
00070 }
00071
00072 #pragma region XAML Properties
00073 ICommand^ ImageBrowserViewModel::GroupCommand::get()
00074 {
00075     return m_groupCommand;
00076 }
00077
00078 ICommand^ ImageBrowserViewModel::CropImageCommand::get()
00079 {
00080     return m_cropImageCommand;
00081 }
00082
00083 ICommand^ ImageBrowserViewModel::RotateImageCommand::get()
00084 {
00085     return m_rotateImageCommand;
00086 }
00087
00088 ICommand^ ImageBrowserViewModel::CartoonizeImageCommand::get()
00089 {
00090     return m_cartoonizeImageCommand;
00091 }
00092
00093 bool ImageBrowserViewModel::InProgress::get()
00094 {
00095     return m_runningMonthQuery;
00096 }
00097
00098 Object^ ImageBrowserViewModel::SelectedItem::get()
00099 {
00100     return m_photo;
00101 }
00102
00103 void ImageBrowserViewModel::SelectedItem::set(Object^ value)
00104 {
00105     if (m_photo != value)
00106     {
00107         ViewModelBase::m_isAppBarOpen = false;
00108         m_photo = dynamic_cast<IPhoto^>(value);
00109         bool result = CanProcessImage(nullptr);
00110         m_rotateImageCommand->CanExecute(result);
00111         m_cropImageCommand->CanExecute(result);
00112         m_cartoonizeImageCommand->CanExecute(result);
00113         IsAppBarEnabled = value != nullptr;
00114         IsAppBarOpen = value != nullptr;
00115         IsAppBarSticky = value != nullptr;
00116         OnPropertyChanged("SelectedItem");
00117     }
00118 }
00119
00120 IObservableVector<IPhotoGroup^>^ ImageBrowserViewModel::MonthGroups::get()
00121 {
00122     assert(nullptr != m_monthGroups);
00123     return m_monthGroups;
00124 }
00125
00126 IObservableVector<IYearGroup^>^ ImageBrowserViewModel::YearGroups::get()
00127 {
00128     assert(nullptr != m_yearGroups);
00129     return m_yearGroups;
00130 }
00131
00132 IPhoto^ ImageBrowserViewModel::GetPhotoForYearAndMonth(unsigned int year, unsigned int month)
00133 {
00134     return m_photoCache->GetForYearAndMonth(year, month);
00135 }
00136 #pragma endregion
00137
00138
00139 #pragma region Regulate File Update Events
00140 // To prevent UI flicker, the ImageBrowserViewMode limits the frequency of update events
00141 // that occur when file system changes require the image brower to update the displayed items.
00142
00143 // This is minimum allowed time in milliseconds between successive file system change notifications.
00144 const ULONGLONG EVENTSPACING = 30000ul;
00145
00146 // This is the handler that is invoked whenever the file system notifies the image browser view model of a change in the
00147 // previously submitted month query. The handler propagates updates at a maximum rate of one for each EVENTSPACING/1000 seconds.
00148 void ImageBrowserViewModel::OnDataChanged()
00149 {
00150     assert(IsMainThread());
00151
00152     auto currentTime = GetTickCount64();
00153
00154     if (m_hasFileUpdateTask || m_currentMode == Mode::Pending)
00155     {
00156         // An update is already scheduled to occur. Ignore the current change notification.
00157     }
00158     else if (m_lastFileChangeTime == 0l || currentTime > (m_lastFileChangeTime + EVENTSPACING))
00159     {
00160         // If it's the first change, or more than EVENTSPACING/1000 seconds have elapsed since the last update, observe the change immediately.
00161         m_lastFileChangeTime = currentTime;
00162         ObserveFileChange();
00163     }
00164     else
00165     {
00166         // Otherwise, schedule the update to occur EVENTSPACING/1000 seconds from the previous update.
00167         auto timeSinceUpdate = (currentTime > m_lastFileChangeTime ? currentTime - m_lastFileChangeTime : 0ul);
00168         unsigned int timeToWait = (timeSinceUpdate < EVENTSPACING ? EVENTSPACING - (unsigned int)timeSinceUpdate : EVENTSPACING);
00169         m_lastFileChangeTime = currentTime + timeToWait;
00170         m_hasFileUpdateTask = true;
00171
00172         // Use weak reference to avoid inadvertently extending object lifetime.
00173         auto weakThis = Platform::WeakReference(this);
00174
00175         // Observe the update after waiting the specified amount of time.
00176         create_task([timeToWait]() {
00177             assert(IsBackgroundThread());
00178             ::wait(timeToWait);
00179         }).then([weakThis]() {
00180             assert(IsMainThread());
00181             auto vm = weakThis.Resolve<ImageBrowserViewModel>();
00182             if (nullptr != vm)
00183             {
00184                 vm->ObserveFileChange();
00185                 vm->m_hasFileUpdateTask = false;
00186             }
00187         }, task_continuation_context::use_current()).then(ObserveException<void>(m_exceptionPolicy));
00188     }
00189 }
00190 #pragma endregion
00191
00192 void ImageBrowserViewModel::NavigateToGroup(Object^ parameter)
00193 {
00194     auto group = dynamic_cast<IPhotoGroup^>(parameter);
00195     assert(group != nullptr);
00196     if (group->Items->Size > 0)
00197     {
00198         auto photo = dynamic_cast<IPhoto^>(group->Items->GetAt(0));
00199         assert(photo != nullptr);
00200         ImageNavigationData imageData(photo);
00201         ViewModelBase::GoToPage(PageType::Image, imageData.SerializeToString());
00202     }
00203 }
00204
00205 void ImageBrowserViewModel::CropImage(Object^ parameter)
00206 {
00207     ImageNavigationData data(m_photo);
00208     ViewModelBase::GoToPage(PageType::Crop, data.SerializeToString());
00209 }
00210
00211 void ImageBrowserViewModel::RotateImage(Object^ parameter)
00212 {
00213     ImageNavigationData data(m_photo);
00214     ViewModelBase::GoToPage(PageType::Rotate, data.SerializeToString());
00215 }
00216
00217 void ImageBrowserViewModel::CartoonizeImage(Object^ parameter)
00218 {
00219     ImageNavigationData data(m_photo);
00220     ViewModelBase::GoToPage(PageType::Cartoonize, data.SerializeToString());
00221 }
00222
00223 bool ImageBrowserViewModel::CanProcessImage(Object^ parameter)
00224 {
00225     return (m_photo != nullptr && !m_photo->IsInvalidThumbnail);
00226 }
00227
00228 #pragma region ImageViewModelStateMachine
00229
00230 // The functions in this region implement a finite state machine that handles
00231 // all possible interleavings of ImageBrowserViewModel actions. These include
00232 // user requests, file system update notifications and completions of in-flight
00233 // async operations.
00234
00235 // Possible modes or states:
00236 //    Default (0, 0, 0): no pending data changes, not running query, view inactive
00237 //    Pending (1, 0, 0): pending data changes, not running query, view inactive
00238 //    Active  (0, 0, 1): no pending data changes, not running query, view active
00239 //    Running (0, 1, 1): no pending data changes, running query, view active
00240
00241 // Transitions between modes:
00242 //    OnNavigatedFrom - occurs when view becomes inactive
00243 //    OnNavigatedTo - occurs when becomes active
00244 //    ObserveFileChange - occurs when file system changes invalidate the result of the current query
00245 //    FinishMonthAndYearQueries - occurs when current month and year queries are both complete
00246
00247 // State transition occurs when view model becomes inactive (no longer visible).
00248 void ImageBrowserViewModel::OnNavigatedFrom(NavigationEventArgs^ e)
00249 {
00250     assert(IsMainThread());
00251     switch (m_currentMode)
00252     {
00253     case Mode::Default:
00254         assert(false);       // Can't navigate from an inactive view model
00255         break;
00256
00257     case Mode::Pending:
00258         assert(false);       // Can't navigate from an inactive view model
00259         break;
00260
00261     case Mode::Active:
00262         m_currentMode = Mode::Default;
00263         break;
00264
00265     case Mode::Running:
00266         CancelMonthAndYearQueries();
00267         m_currentMode = Mode::Pending;
00268         break;
00269     }
00270 }
00271
00272 // State transition occurs when view model becomes active (visible).
00273 void ImageBrowserViewModel::OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
00274 {
00275     assert(IsMainThread());
00276     switch (m_currentMode)
00277     {
00278     case Mode::Default:
00279         m_currentMode = Mode::Active;
00280         break;
00281
00282     case Mode::Pending:
00283         StartMonthAndYearQueries();
00284         m_currentMode = Mode::Running;
00285         break;
00286
00287     case Mode::Active:
00288         assert(false);   // Can't navigate to already active view model
00289         break;
00290
00291     case Mode::Running:
00292         assert(false);   // Can't navigate to already active view model
00293         break;
00294     }
00295 }
00296
00297 // State transition occurs when file system changes invalidate the result of the current query.
00298 void ImageBrowserViewModel::ObserveFileChange()
00299 {
00300     assert(IsMainThread());
00301
00302     switch (m_currentMode)
00303     {
00304     case Mode::Default:
00305         m_currentMode = Mode::Pending;
00306         break;
00307
00308     case Mode::Pending:
00309         m_currentMode = Mode::Pending;
00310         break;
00311
00312     case Mode::Active:
00313         StartMonthAndYearQueries();
00314         m_currentMode = Mode::Running;
00315         break;
00316
00317     case Mode::Running:
00318         CancelMonthAndYearQueries();
00319         StartMonthAndYearQueries();
00320         m_currentMode = Mode::Running;
00321         break;
00322     }
00323 }
00324
00325 // State transition occurs when both month and year queries have finished running.
00326 void ImageBrowserViewModel::FinishMonthAndYearQueries()
00327 {
00328     assert(m_runningMonthQuery == false);
00329     assert(m_runningYearQuery == false);
00330     assert(m_currentMode == Mode::Running);
00331
00332     switch (m_currentMode)
00333     {
00334     case Mode::Default:
00335         assert(false);  // There is no query in flight in the Default mode.
00336         break;
00337
00338     case Mode::Pending:
00339         assert(false);  // There is no query in flight in the Pending mode.
00340         break;
00341
00342     case Mode::Active:
00343         assert(false);  // There is no query in flight in the Active mode.
00344         break;
00345
00346     case Mode::Running:
00347         m_currentMode = Mode::Active;
00348         m_currentQueryId++;
00349         break;
00350     }
00351 }
00352 #pragma endregion
00353
00354 #pragma region YearAndMonthQueries
00355 void ImageBrowserViewModel::CancelMonthAndYearQueries()
00356 {
00357     assert(m_currentMode == Mode::Running);
00358
00359     if (m_runningMonthQuery)
00360     {
00361         m_runningMonthQuery = false;
00362         OnPropertyChanged("InProgress");
00363     }
00364     m_runningYearQuery = false;
00365     m_currentQueryId++;
00366     m_cancellationTokenSource.cancel();
00367 }
00368
00369 void ImageBrowserViewModel::StartMonthAndYearQueries()
00370 {
00371     assert(IsMainThread());
00372     assert(!m_runningMonthQuery);
00373     assert(!m_runningYearQuery);
00374     assert(m_currentMode == Mode::Active || m_currentMode == Mode::Running || m_currentMode == Mode::Pending);
00375
00376     m_cancellationTokenSource = cancellation_token_source();
00377     auto token = m_cancellationTokenSource.get_token();
00378     StartMonthQuery(m_currentQueryId, token);
00379     StartYearQuery(m_currentQueryId, token);
00380 }
00381
00382 void ImageBrowserViewModel::StartMonthQuery(int queryId, cancellation_token token)
00383 {
00384     m_runningMonthQuery = true;
00385     OnPropertyChanged("InProgress");
00386     m_photoCache->Clear();
00387     run_async_non_interactive([this, queryId, token]()
00388     {
00389         // if query is obsolete, don't run it.
00390         if (queryId != m_currentQueryId) return;
00391
00392         m_repository->GetMonthGroupedPhotosWithCacheAsync(m_photoCache, token).then([this, queryId](task<IVectorView<IPhotoGroup^>^> priorTask)
00393         {
00394             assert(IsMainThread());
00395             if (queryId != m_currentQueryId)
00396             {
00397                 // Query is obsolete. Propagate exception and quit.
00398                 priorTask.get();
00399                 return;
00400             }
00401
00402             m_runningMonthQuery = false;
00403             OnPropertyChanged("InProgress");
00404             if (!m_runningYearQuery)
00405             {
00406                 FinishMonthAndYearQueries();
00407             }
00408             try
00409             {
00410                 // Update display with results.
00411                 m_monthGroups->Clear();
00412                 for (auto group : priorTask.get())
00413                 {
00414                     m_monthGroups->Append(group);
00415                 }
00416                 OnPropertyChanged("MonthGroups");
00417             }
00418             // On exception (including cancellation), remove any partially computed results and rethrow.
00419             catch (...)
00420             {
00421                 m_monthGroups = ref new Vector<IPhotoGroup^>();
00422                 throw;
00423             }
00424         }, task_continuation_context::use_current()).then(ObserveException<void>(m_exceptionPolicy));
00425     });
00426 }
00427
00428 void ImageBrowserViewModel::StartYearQuery(int queryId, cancellation_token token)
00429 {
00430     assert(!m_runningYearQuery);
00431     assert(m_currentMode == Mode::Active || m_currentMode == Mode::Running || m_currentMode == Mode::Pending);
00432
00433     m_runningYearQuery = true;
00434     run_async_non_interactive([this, queryId, token]()
00435     {
00436         assert(IsMainThread());
00437
00438         // If query is obsolete, don't run it.
00439         if (queryId != m_currentQueryId) return;
00440
00441         m_repository->GetYearGroupedMonthsAsync(token).then([this, queryId](task<IVectorView<IYearGroup^>^> priorTask)
00442         {
00443             assert(IsMainThread());
00444             if (queryId != m_currentQueryId)
00445             {
00446                 // Query is obsolete. Rethrow any exception and exit.
00447                 priorTask.get();
00448                 return;
00449             }
00450
00451             m_runningYearQuery = false;
00452             if (!m_runningMonthQuery)
00453             {
00454                 FinishMonthAndYearQueries();
00455             }
00456
00457             try
00458             {
00459                 // Update display with results.
00460                 m_yearGroups->Clear();
00461                 for (auto group : priorTask.get())
00462                 {
00463                     m_yearGroups->Append(group);
00464                 }
00465                 OnPropertyChanged("YearGroups");
00466             }
00467             // On exception (including cancellation), remove any partially computed results and rethrow.
00468             catch (...)
00469             {
00470                 m_yearGroups = ref new Vector<IYearGroup^>();
00471                 throw;
00472             }
00473         }, task_continuation_context::use_current()).then(ObserveException<void>(m_exceptionPolicy));
00474     });
00475 }
00476 #pragma endregion
00477
00478
00479
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Manipulations and gestures (C++)/C++/pch.cpp Source File

  • Input Manipulations and gestures (C++)
  • C++

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Date and time formatting/C++/StringTemplate.xaml.cpp Source File

  • Date and time formatting

StringTemplate.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 // StringTemplate.xaml.cpp
00013 // Implementation of the StringTemplate class
00014 //
00015
00016 #include "pch.h"
00017 #include "StringTemplate.xaml.h"
00018
00019 using namespace SDKSample::DateTimeFormatting;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024 using namespace Platform;
00025 using namespace Windows::Foundation;
00026 using namespace Windows::Foundation::Collections;
00027 using namespace Windows::Globalization;
00028 using namespace Windows::Globalization::DateTimeFormatting;
00029
00030 StringTemplate::StringTemplate()
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 void StringTemplate::OnNavigatedTo(NavigationEventArgs^ e)
00041 {
00042     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00043     // as NotifyUser()
00044     rootPage = MainPage::Current;
00045 }
00046
00047 void SDKSample::DateTimeFormatting::StringTemplate::Display_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00048 {
00049   // This scenario uses the Windows.Globalization.DateTimeFormatting.DateTimeFormatter class
00050   // to format a date/time via a string template.  Note that the order specifed in the string pattern does
00051   // not determine the order of the parts of the formatted string.  The current application language and region value will
00052   // determine the pattern of the date returned based on the specified parts.
00053
00054   //Get the current application context language
00055   String^ currentLanguage = ApplicationLanguages::Languages->GetAt(0);
00056
00057     // Formatters for dates and times
00058     Array<DateTimeFormatter^> ^dateFormatters = {
00059     ref new DateTimeFormatter("month day"),
00060     ref new DateTimeFormatter("month year"),
00061     ref new DateTimeFormatter("month day year"),
00062     ref new DateTimeFormatter("month day dayofweek year"),
00063     ref new DateTimeFormatter("dayofweek.abbreviated"),
00064     ref new DateTimeFormatter("month.abbreviated"),
00065     ref new DateTimeFormatter("year.abbreviated"),
00066     ref new DateTimeFormatter("hour minute"),
00067     ref new DateTimeFormatter("hour minute second"),
00068     ref new DateTimeFormatter("hour")
00069     };
00070
00071   // Obtain the date that will be formatted.
00072   Windows::Globalization::Calendar^ cal = ref new Windows::Globalization::Calendar();
00073     Windows::Foundation::DateTime dateToFormat = cal->GetDateTime();
00074
00075     // Keep the results here
00076     String^ results = "";
00077   results = results + "Current application context language: " + currentLanguage + "\n\n";
00078
00079   // Generate the results.
00080     for (unsigned int i = 0; i < dateFormatters->Length; i++)
00081     {
00082         // Perform the actual formatting.
00083         try
00084         {
00085             results = results + dateFormatters[i]->Template + ": " + dateFormatters[i]->Format(dateToFormat) + "\n";
00086         }
00087         catch(Platform::Exception^)
00088         {
00089             // Retrieve and display formatter properties.
00090             results = results + "Unable to format using formatter with template: " +
00091                 dateFormatters[i]->Template + ", language: " +
00092                 dateFormatters[i]->Languages->GetAt(0) + ", region: " +
00093                 dateFormatters[i]->GeographicRegion + ", calendar: " +
00094                 dateFormatters[i]->Calendar + ", clock:" +
00095                 dateFormatters[i]->Clock + "\n";
00096         }
00097     }
00098
00099   // Display the results.
00100     rootPage->NotifyUser(results, NotifyType::StatusMessage);
00101 }
Generated on Sat Nov 23 2024 16:08:02 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::TouchKeyboard::sealed Member List

This is the complete list of members for SDKSample::TouchKeyboard::sealed, including all inherited members.
__pad0__ | SDKSample::TouchKeyboard::sealed |
_peer | SDKSample::TouchKeyboard::sealed | [private]
_text | SDKSample::TouchKeyboard::sealed | [private]
accClass | SDKSample::TouchKeyboard::sealed | [private]
AddToSelection() | SDKSample::TouchKeyboard::sealed | [virtual]
Clone() | SDKSample::TouchKeyboard::sealed | [virtual]
Compare(Windows::UI::Xaml::Automation::Provider::ITextRangeProvider^textRangeProvider) | SDKSample::TouchKeyboard::sealed | [virtual]
CompareEndpoints(Windows::UI::Xaml::Automation::Text::TextPatternRangeEndpoint endpoint, Windows::UI::Xaml::Automation::Provider::ITextRangeProvider^textRangeProvider, Windows::UI::Xaml::Automation::Text::TextPatternRangeEndpoint targetEndpoint) | SDKSample::TouchKeyboard::sealed | [virtual]
contentText | SDKSample::TouchKeyboard::sealed | [private]
CustomTextBox() | SDKSample::TouchKeyboard::sealed | [inline]
ExpandToEnclosingUnit(Windows::UI::Xaml::Automation::Text::TextUnit unit) | SDKSample::TouchKeyboard::sealed | [virtual]
FindAttribute(int attributeId, Platform::Object^value, bool backward) | SDKSample::TouchKeyboard::sealed | [virtual]
FindText(Platform::String^text, bool backward, bool ignoreCase) | SDKSample::TouchKeyboard::sealed | [virtual]
GetAttributeValue(int attributeId) | SDKSample::TouchKeyboard::sealed | [virtual]
GetBoundingRectangles(Platform::Array< double >^*returnValue) | SDKSample::TouchKeyboard::sealed | [virtual]
GetChildren() | SDKSample::TouchKeyboard::sealed | [virtual]
GetClassNameCore() override | SDKSample::TouchKeyboard::sealed | [inline, protected, virtual]
GetClassNameCore() override | SDKSample::TouchKeyboard::sealed | [inline, protected, virtual]
GetEnclosingElement() | SDKSample::TouchKeyboard::sealed | [virtual]
GetPatternCore(PatternInterface patternInterface) override | SDKSample::TouchKeyboard::sealed | [inline, protected, virtual]
GetText(int maxLength) | SDKSample::TouchKeyboard::sealed | [virtual]
Launch() | SDKSample::TouchKeyboard::sealed |
Move(Windows::UI::Xaml::Automation::Text::TextUnit unit, int count) | SDKSample::TouchKeyboard::sealed | [virtual]
MoveEndpointByRange(Windows::UI::Xaml::Automation::Text::TextPatternRangeEndpoint endpoint, Windows::UI::Xaml::Automation::Provider::ITextRangeProvider^textRangeProvider, Windows::UI::Xaml::Automation::Text::TextPatternRangeEndpoint targetEndpoint) | SDKSample::TouchKeyboard::sealed | [virtual]
MoveEndpointByUnit(Windows::UI::Xaml::Automation::Text::TextPatternRangeEndpoint endpoint, Windows::UI::Xaml::Automation::Text::TextUnit unit, int count) | SDKSample::TouchKeyboard::sealed | [virtual]
NonTouchableTextBlock() | SDKSample::TouchKeyboard::sealed |
NonTouchableTextBlockAutomationPeer(NonTouchableTextBlock^owner) | SDKSample::TouchKeyboard::sealed | [inline]
OnCreateAutomationPeer() override | SDKSample::TouchKeyboard::sealed | [protected, virtual]
OnCreateAutomationPeer() override | SDKSample::TouchKeyboard::sealed | [protected, virtual]
OnGotFocus(Windows::UI::Xaml::RoutedEventArgs^e) override | SDKSample::TouchKeyboard::sealed | [protected, virtual]
OnGotFocus(Windows::UI::Xaml::RoutedEventArgs^e) override | SDKSample::TouchKeyboard::sealed | [protected, virtual]
OnKeyDown(Windows::UI::Xaml::Input::KeyRoutedEventArgs^e) override | SDKSample::TouchKeyboard::sealed | [protected, virtual]
OnKeyDown(Windows::UI::Xaml::Input::KeyRoutedEventArgs^e) override | SDKSample::TouchKeyboard::sealed | [protected, virtual]
OnLostFocus(Windows::UI::Xaml::RoutedEventArgs^e) override | SDKSample::TouchKeyboard::sealed | [protected, virtual]
OnLostFocus(Windows::UI::Xaml::RoutedEventArgs^e) override | SDKSample::TouchKeyboard::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::TouchKeyboard::sealed | [protected, virtual]
OnTapped(Windows::UI::Xaml::Input::TappedRoutedEventArgs^e) override | SDKSample::TouchKeyboard::sealed | [protected, virtual]
OnTapped(Windows::UI::Xaml::Input::TappedRoutedEventArgs^e) override | SDKSample::TouchKeyboard::sealed | [protected, virtual]
RemoveFromSelection() | SDKSample::TouchKeyboard::sealed | [virtual]
rootPage | SDKSample::TouchKeyboard::sealed | [private]
ScrollIntoView(bool alignToTop) | SDKSample::TouchKeyboard::sealed | [virtual]
Select() | SDKSample::TouchKeyboard::sealed | [virtual]
set(Platform::String^text) | SDKSample::TouchKeyboard::sealed | [inline]
textBlock | SDKSample::TouchKeyboard::sealed | [private]
TouchableTextBlock() | SDKSample::TouchKeyboard::sealed |
TouchableTextBlockAutomationPeer(TouchableTextBlock^owner) | SDKSample::TouchKeyboard::sealed | [inline]
TouchableTextBlockRangeProvider(Platform::String^text, TouchableTextBlockAutomationPeer^peer) | SDKSample::TouchKeyboard::sealed |
Generated on Sat Nov 23 2024 16:09:53 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Bluetooth call control/C++/common/LayoutAwarePage.cpp Source File

  • Bluetooth call control
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:30 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Connecting with WebSockets/C++/common/LayoutAwarePage.h Source File

  • Connecting with WebSockets
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File access/C++/Scenario4.xaml.cpp Source File

  • File access

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::FileAccess;
00020
00021 using namespace concurrency;
00022 using namespace Platform;
00023 using namespace Windows::Storage;
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 Scenario4::Scenario4()
00030 {
00031     InitializeComponent();
00032     rootPage = MainPage::Current;
00033     WriteToStreamButton->Click  += ref new RoutedEventHandler(this, &Scenario4::WriteToStreamButton_Click);
00034     ReadFromStreamButton->Click += ref new RoutedEventHandler(this, &Scenario4::ReadFromStreamButton_Click);
00035 }
00036
00037 void Scenario4::WriteToStreamButton_Click(Object^ sender, RoutedEventArgs^ e)
00038 {
00039     rootPage->ResetScenarioOutput(OutputTextBlock);
00040     StorageFile^ file = rootPage->SampleFile;
00041     if (file != nullptr)
00042     {
00043         String^ userContent = InputTextBox->Text;
00044         if (userContent != nullptr && !userContent->IsEmpty())
00045         {
00046             create_task(file->OpenTransactedWriteAsync()).then([this, file, userContent](task<StorageStreamTransaction^> task)
00047             {
00048                 try
00049                 {
00050                     StorageStreamTransaction^ transaction = task.get();
00051                     DataWriter^ dataWriter = ref new DataWriter(transaction->Stream);
00052                     dataWriter->WriteString(userContent);
00053                     create_task(dataWriter->StoreAsync()).then([this, file, dataWriter, transaction, userContent](unsigned int bytesWritten)
00054                     {
00055                         transaction->Stream->Size = bytesWritten; // reset stream size to override the file
00056                         create_task(transaction->CommitAsync()).then([this, file, userContent]()
00057                         {
00058                             OutputTextBlock->Text = "The following text was written to '" + file->Name + "' using a stream:\n\n" + userContent;
00059                         });
00060                     });
00061                 }
00062                 catch(COMException^ ex)
00063                 {
00064                     rootPage->HandleFileNotFoundException(ex);
00065                 }
00066             });
00067         }
00068         else
00069         {
00070             OutputTextBlock->Text = "The text box is empty, please write something and then click 'Write' again.";
00071         }
00072     }
00073 }
00074
00075 void Scenario4::ReadFromStreamButton_Click(Object^ sender, RoutedEventArgs^ e)
00076 {
00077     rootPage->ResetScenarioOutput(OutputTextBlock);
00078     StorageFile^ file = rootPage->SampleFile;
00079     if (file != nullptr)
00080     {
00081         create_task(file->OpenAsync(FileAccessMode::Read)).then([this, file](task<IRandomAccessStream^> task)
00082         {
00083             try
00084             {
00085                 IRandomAccessStream^ readStream = task.get();
00086                 UINT64 const size = readStream->Size;
00087                 if (size <= MAXUINT32)
00088                 {
00089                     DataReader^ dataReader = ref new DataReader(readStream);
00090                     create_task(dataReader->LoadAsync(static_cast<UINT32>(size))).then([this, file, dataReader](unsigned int numBytesLoaded)
00091                     {
00092                         String^ fileContent = dataReader->ReadString(numBytesLoaded);
00093                         delete dataReader; // As a best practice, explicitly close the dataReader resource as soon as it is no longer needed.
00094                         OutputTextBlock->Text = "The following text was read from '" + file->Name + "' using a stream:\n\n" + fileContent;
00095                     });
00096                 }
00097                 else
00098                 {
00099                     delete readStream; // As a best practice, explicitly close the readStream resource as soon as it is no longer needed.
00100                     OutputTextBlock->Text = "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.";
00101                 }
00102             }
00103             catch(COMException^ ex)
00104             {
00105                 rootPage->HandleFileNotFoundException(ex);
00106             }
00107         });
00108     }
00109 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX marble maze game/C++/LoadScreen.cpp Source File

  • DirectX marble maze game

LoadScreen.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 "LoadScreen.h"
00010
00011 using namespace Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::UI::ViewManagement;
00015 using namespace Windows::Graphics::Display;
00016 using namespace D2D1;
00017
00018 void LoadScreen::Initialize(
00019     _In_ ID2D1Device*         d2dDevice,
00020     _In_ ID2D1DeviceContext*  d2dContext,
00021     _In_ IWICImagingFactory*  wicFactory
00022     )
00023 {
00024     m_wicFactory = wicFactory;
00025     m_d2dDevice = d2dDevice;
00026     m_d2dContext = d2dContext;
00027     m_imageSize = D2D1::SizeF(0.0f, 0.0f);
00028     m_offset = D2D1::SizeF(0.0f, 0.0f);
00029     m_totalSize = D2D1::SizeF(0.0f, 0.0f);
00030
00031     ComPtr<ID2D1Factory> factory;
00032     d2dDevice->GetFactory(&factory);
00033
00034     DX::ThrowIfFailed(
00035         factory.As(&m_d2dFactory)
00036         );
00037
00038     ResetDirectXResources();
00039 }
00040
00041 void LoadScreen::ResetDirectXResources()
00042 {
00043     ComPtr<IWICBitmapDecoder> wicBitmapDecoder;
00044     DX::ThrowIfFailed(
00045         m_wicFactory->CreateDecoderFromFilename(
00046             L"Media\\Textures\\loadscreen.png",
00047             nullptr,
00048             GENERIC_READ,
00049             WICDecodeMetadataCacheOnDemand,
00050             &wicBitmapDecoder
00051             )
00052         );
00053
00054     ComPtr<IWICBitmapFrameDecode> wicBitmapFrame;
00055     DX::ThrowIfFailed(
00056         wicBitmapDecoder->GetFrame(0, &wicBitmapFrame)
00057         );
00058
00059     ComPtr<IWICFormatConverter> wicFormatConverter;
00060     DX::ThrowIfFailed(
00061         m_wicFactory->CreateFormatConverter(&wicFormatConverter)
00062         );
00063
00064     DX::ThrowIfFailed(
00065         wicFormatConverter->Initialize(
00066             wicBitmapFrame.Get(),
00067             GUID_WICPixelFormat32bppPBGRA,
00068             WICBitmapDitherTypeNone,
00069             nullptr,
00070             0.0,
00071             WICBitmapPaletteTypeCustom  // the BGRA format has no palette so this value is ignored
00072             )
00073         );
00074
00075     DX::ThrowIfFailed(
00076         m_d2dContext->CreateBitmapFromWicBitmap(
00077             wicFormatConverter.Get(),
00078             BitmapProperties(PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED)),
00079             &m_bitmap
00080             )
00081         );
00082
00083     m_imageSize = m_bitmap->GetSize();
00084
00085     DX::ThrowIfFailed(
00086         m_d2dFactory->CreateDrawingStateBlock(&m_stateBlock)
00087         );
00088
00089     UpdateForWindowSizeChange();
00090 }
00091
00092 void LoadScreen::UpdateForWindowSizeChange()
00093 {
00094     Windows::Foundation::Rect windowBounds = CoreWindow::GetForCurrentThread()->Bounds;
00095
00096     m_offset.width = (windowBounds.Width - m_imageSize.width) / 2.0f;
00097     m_offset.height = (windowBounds.Height - m_imageSize.height) / 2.0f;
00098
00099     m_totalSize.width = m_offset.width + m_imageSize.width;
00100     m_totalSize.height = m_offset.height + m_imageSize.height;
00101 }
00102
00103 void LoadScreen::Render()
00104 {
00105     m_d2dContext->SaveDrawingState(m_stateBlock.Get());
00106
00107     m_d2dContext->BeginDraw();
00108     m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00109     m_d2dContext->DrawBitmap(
00110         m_bitmap.Get(),
00111         D2D1::RectF(
00112             m_offset.width,
00113             m_offset.height,
00114             m_imageSize.width + m_offset.width,
00115             m_imageSize.height + m_offset.height)
00116         );
00117
00118     // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00119     // is lost. It will be handled during the next call to Present.
00120     HRESULT hr = m_d2dContext->EndDraw();
00121     if (hr != D2DERR_RECREATE_TARGET)
00122     {
00123         DX::ThrowIfFailed(hr);
00124     }
00125
00126     m_d2dContext->RestoreDrawingState(m_stateBlock.Get());
00127 }
Generated on Sat Nov 23 2024 16:08:15 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

BasicShapes Member List

This is the complete list of members for BasicShapes, including all inherited members.
__pad0__ | BasicShapes |
CreateBox(float3 radii, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateBox(float3 radii, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateBox(float3 radii, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateBox(float3 radii, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateBox(float3 radii, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateBox(float3 radii, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateBox(float3 radii, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateBox(float3 radii, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateBox(float3 radii, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateBox(float3 radii, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateBox(float3 radii, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateBox(float3 radii, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateBox(float3 radii, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateBox(float3 radii, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateBox(float3 radii, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateCube(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateCube(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateCube(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateCube(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateCube(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateCube(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateCube(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateCube(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateCube(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateCube(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateCube(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateCube(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateCube(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateCube(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateCube(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateIndexBuffer(_In_ unsigned int numIndices, _In_ unsigned short *indexData, _Out_ ID3D11Buffer **indexBuffer) | BasicShapes | [private]
CreateIndexBuffer(_In_ unsigned int numIndices, _In_ unsigned short *indexData, _Out_ ID3D11Buffer **indexBuffer) | BasicShapes | [private]
CreateIndexBuffer(_In_ unsigned int numIndices, _In_ unsigned short *indexData, _Out_ ID3D11Buffer **indexBuffer) | BasicShapes | [private]
CreateIndexBuffer(_In_ unsigned int numIndices, _In_ unsigned short *indexData, _Out_ ID3D11Buffer **indexBuffer) | BasicShapes | [private]
CreateIndexBuffer(_In_ unsigned int numIndices, _In_ unsigned short *indexData, _Out_ ID3D11Buffer **indexBuffer) | BasicShapes | [private]
CreateIndexBuffer(_In_ unsigned int numIndices, _In_ unsigned short *indexData, _Out_ ID3D11Buffer **indexBuffer) | BasicShapes | [private]
CreateIndexBuffer(_In_ unsigned int numIndices, _In_ unsigned short *indexData, _Out_ ID3D11Buffer **indexBuffer) | BasicShapes | [private]
CreateIndexBuffer(_In_ unsigned int numIndices, _In_ unsigned short *indexData, _Out_ ID3D11Buffer **indexBuffer) | BasicShapes | [private]
CreateIndexBuffer(_In_ unsigned int numIndices, _In_ unsigned short *indexData, _Out_ ID3D11Buffer **indexBuffer) | BasicShapes | [private]
CreateIndexBuffer(_In_ unsigned int numIndices, _In_ unsigned short *indexData, _Out_ ID3D11Buffer **indexBuffer) | BasicShapes | [private]
CreateIndexBuffer(_In_ unsigned int numIndices, _In_ unsigned short *indexData, _Out_ ID3D11Buffer **indexBuffer) | BasicShapes | [private]
CreateIndexBuffer(_In_ unsigned int numIndices, _In_ unsigned short *indexData, _Out_ ID3D11Buffer **indexBuffer) | BasicShapes | [private]
CreateIndexBuffer(_In_ unsigned int numIndices, _In_ unsigned short *indexData, _Out_ ID3D11Buffer **indexBuffer) | BasicShapes | [private]
CreateIndexBuffer(_In_ unsigned int numIndices, _In_ unsigned short *indexData, _Out_ ID3D11Buffer **indexBuffer) | BasicShapes | [private]
CreateIndexBuffer(_In_ unsigned int numIndices, _In_ unsigned short *indexData, _Out_ ID3D11Buffer **indexBuffer) | BasicShapes | [private]
CreateReferenceAxis(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateReferenceAxis(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateReferenceAxis(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateReferenceAxis(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateReferenceAxis(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateReferenceAxis(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateReferenceAxis(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateReferenceAxis(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateReferenceAxis(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateReferenceAxis(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateReferenceAxis(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateReferenceAxis(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateReferenceAxis(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateReferenceAxis(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateReferenceAxis(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateSphere(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateSphere(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateSphere(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateSphere(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateSphere(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateSphere(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateSphere(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateSphere(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateSphere(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateSphere(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateSphere(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateSphere(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateSphere(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateSphere(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateSphere(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateTangentSphere(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateTangentSphere(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateTangentSphere(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateTangentSphere(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateTangentSphere(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateTangentSphere(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateTangentSphere(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateTangentSphere(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateTangentSphere(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateTangentSphere(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateTangentSphere(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateTangentSphere(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateTangentSphere(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateTangentSphere(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateTangentSphere(_Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ unsigned int *vertexCount, _Out_opt_ unsigned int *indexCount) | BasicShapes |
CreateTangentVertexBuffer(_In_ unsigned int numVertices, _In_ TangentVertex *vertexData, _Out_ ID3D11Buffer **vertexBuffer) | BasicShapes | [private]
CreateTangentVertexBuffer(_In_ unsigned int numVertices, _In_ TangentVertex *vertexData, _Out_ ID3D11Buffer **vertexBuffer) | BasicShapes | [private]
CreateTangentVertexBuffer(_In_ unsigned int numVertices, _In_ TangentVertex *vertexData, _Out_ ID3D11Buffer **vertexBuffer) | BasicShapes | [private]
CreateTangentVertexBuffer(_In_ unsigned int numVertices, _In_ TangentVertex *vertexData, _Out_ ID3D11Buffer **vertexBuffer) | BasicShapes | [private]
CreateTangentVertexBuffer(_In_ unsigned int numVertices, _In_ TangentVertex *vertexData, _Out_ ID3D11Buffer **vertexBuffer) | BasicShapes | [private]
CreateTangentVertexBuffer(_In_ unsigned int numVertices, _In_ TangentVertex *vertexData, _Out_ ID3D11Buffer **vertexBuffer) | BasicShapes | [private]
CreateTangentVertexBuffer(_In_ unsigned int numVertices, _In_ TangentVertex *vertexData, _Out_ ID3D11Buffer **vertexBuffer) | BasicShapes | [private]
CreateTangentVertexBuffer(_In_ unsigned int numVertices, _In_ TangentVertex *vertexData, _Out_ ID3D11Buffer **vertexBuffer) | BasicShapes | [private]
CreateTangentVertexBuffer(_In_ unsigned int numVertices, _In_ TangentVertex *vertexData, _Out_ ID3D11Buffer **vertexBuffer) | BasicShapes | [private]
CreateTangentVertexBuffer(_In_ unsigned int numVertices, _In_ TangentVertex *vertexData, _Out_ ID3D11Buffer **vertexBuffer) | BasicShapes | [private]
CreateTangentVertexBuffer(_In_ unsigned int numVertices, _In_ TangentVertex *vertexData, _Out_ ID3D11Buffer **vertexBuffer) | BasicShapes | [private]
CreateTangentVertexBuffer(_In_ unsigned int numVertices, _In_ TangentVertex *vertexData, _Out_ ID3D11Buffer **vertexBuffer) | BasicShapes | [private]
CreateTangentVertexBuffer(_In_ unsigned int numVertices, _In_ TangentVertex *vertexData, _Out_ ID3D11Buffer **vertexBuffer) | BasicShapes | [private]
CreateTangentVertexBuffer(_In_ unsigned int numVertices, _In_ TangentVertex *vertexData, _Out_ ID3D11Buffer **vertexBuffer) | BasicShapes | [private]
CreateTangentVertexBuffer(_In_ unsigned int numVertices, _In_ TangentVertex *vertexData, _Out_ ID3D11Buffer **vertexBuffer) | BasicShapes | [private]
CreateVertexBuffer(_In_ unsigned int numVertices, _In_ BasicVertex *vertexData, _Out_ ID3D11Buffer **vertexBuffer) | BasicShapes | [private]
CreateVertexBuffer(_In_ unsigned int numVertices, _In_ BasicVertex *vertexData, _Out_ ID3D11Buffer **vertexBuffer) | BasicShapes | [private]
CreateVertexBuffer(_In_ unsigned int numVertices, _In_ BasicVertex *vertexData, _Out_ ID3D11Buffer **vertexBuffer) | BasicShapes | [private]
CreateVertexBuffer(_In_ unsigned int numVertices, _In_ BasicVertex *vertexData, _Out_ ID3D11Buffer **vertexBuffer) | BasicShapes | [private]
CreateVertexBuffer(_In_ unsigned int numVertices, _In_ BasicVertex *vertexData, _Out_ ID3D11Buffer **vertexBuffer) | BasicShapes | [private]
CreateVertexBuffer(_In_ unsigned int numVertices, _In_ BasicVertex *vertexData, _Out_ ID3D11Buffer **vertexBuffer) | BasicShapes | [private]
CreateVertexBuffer(_In_ unsigned int numVertices, _In_ BasicVertex *vertexData, _Out_ ID3D11Buffer **vertexBuffer) | BasicShapes | [private]
CreateVertexBuffer(_In_ unsigned int numVertices, _In_ BasicVertex *vertexData, _Out_ ID3D11Buffer **vertexBuffer) | BasicShapes | [private]
CreateVertexBuffer(_In_ unsigned int numVertices, _In_ BasicVertex *vertexData, _Out_ ID3D11Buffer **vertexBuffer) | BasicShapes | [private]
CreateVertexBuffer(_In_ unsigned int numVertices, _In_ BasicVertex *vertexData, _Out_ ID3D11Buffer **vertexBuffer) | BasicShapes | [private]
CreateVertexBuffer(_In_ unsigned int numVertices, _In_ BasicVertex *vertexData, _Out_ ID3D11Buffer **vertexBuffer) | BasicShapes | [private]
CreateVertexBuffer(_In_ unsigned int numVertices, _In_ BasicVertex *vertexData, _Out_ ID3D11Buffer **vertexBuffer) | BasicShapes | [private]
CreateVertexBuffer(_In_ unsigned int numVertices, _In_ BasicVertex *vertexData, _Out_ ID3D11Buffer **vertexBuffer) | BasicShapes | [private]
CreateVertexBuffer(_In_ unsigned int numVertices, _In_ BasicVertex *vertexData, _Out_ ID3D11Buffer **vertexBuffer) | BasicShapes | [private]
CreateVertexBuffer(_In_ unsigned int numVertices, _In_ BasicVertex *vertexData, _Out_ ID3D11Buffer **vertexBuffer) | BasicShapes | [private]
m_d3dDevice | BasicShapes | [private]
Generated on Sat Nov 23 2024 16:09:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Lock screen apps/C#,C++/ScenarioOutput2.xaml.h Source File

  • Lock screen apps
  • C#,C++

ScenarioOutput2.xaml.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 //
00009 // Scenario2Output.xaml.h
00010 // Declaration of the Scenario2Output class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioOutput2.g.h"
00017 #include "MainPage.g.h"
00018
00019 namespace LockScreenAppsCPP
00020 {
00021     public ref class ScenarioOutput2 sealed
00022     {
00023     public:
00024         ScenarioOutput2();
00025
00026   private:
00027         ~ScenarioOutput2();
00028     };
00029 }
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Toast notifications/C#,C++/App.xaml.cpp Source File

  • Toast notifications
  • C#,C++

App.xaml.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 //
00009 // App.xaml.cpp
00010 // Implementation of the App.xaml class.
00011 //
00012
00013 #include "pch.h"
00014 #include "App.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace Windows::UI::Xaml;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::ApplicationModel;
00020 using namespace Windows::ApplicationModel::Activation;
00021 using namespace CppSamplesUtils;
00022 using namespace ToastsSampleCPP;
00023 using namespace Windows::UI::Xaml::Interop;
00024
00025 App::App()
00026 {
00027   InitializeComponent();
00028   this->Suspending += ref new SuspendingEventHandler(this, &ToastsSampleCPP::App::OnSuspending);
00029 }
00030
00031 void App::OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs)
00032 {
00033     auto deferral = pArgs->SuspendingOperation->GetDeferral();
00034     SuspensionManager::StartSaveTask().then([deferral] () {
00035         deferral->Complete();
00036     });
00037 }
00038
00039 void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs)
00040 {
00041     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Terminated)
00042     {
00043         SuspensionManager::StartRestoreTask().then([this, pArgs] () {
00044             auto rootFrame = ref new Frame();
00045             TypeName pageType = { "ToastsSampleCPP.MainPage", TypeKind::Custom };
00046
00047             // The arguments contain the context passed to the toast
00048             rootFrame->Navigate(pageType, pArgs->Arguments);
00049             Window::Current->Content = rootFrame;
00050             Window::Current->Activate();
00051         });
00052     }
00053     else
00054     {
00055         auto rootFrame = ref new Frame();
00056         TypeName pageType = { "ToastsSampleCPP.MainPage", TypeKind::Custom };
00057
00058         // The arguments contain the context passed to the toast
00059         rootFrame->Navigate(pageType, pArgs->Arguments);
00060         Window::Current->Content = rootFrame;
00061         Window::Current->Activate();
00062     }
00063 }
Generated on Sat Nov 23 2024 16:07:28 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML data binding/C++/IncrementalLoadingBase.h Source File

  • XAML data binding

IncrementalLoadingBase.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 //
00009 // IncrementalLoadingBase.h
00010 // Declaration of the IncrementalLoadingBase class
00011 //
00012
00013 #pragma once
00014
00015 #include <ppltasks.h>
00016 #include <collection.h>
00017
00018 namespace SDKSample
00019 {
00020     namespace DataBinding
00021     {
00022     // This class can used as a jumpstart for implementing ISupportIncrementalLoading.
00023       // Implementing the ISupportIncrementalLoading interfaces allows you to create a list that loads
00024       //  more data automatically when the user scrolls to the end of of a GridView or ListView.
00025     ref class IncrementalLoadingBase
00026         : Windows::UI::Xaml::Interop::IBindableObservableVector,
00027         Windows::UI::Xaml::Data::ISupportIncrementalLoading
00028       {
00029     #pragma region Windows::UI::Xaml::Data::ISupportIncrementalLoading
00030
00031       internal:
00032         Concurrency::task<Windows::UI::Xaml::Data::LoadMoreItemsResult> LoadMoreItemsAsync(Concurrency::cancellation_token c, unsigned int count)
00033         {
00034           try
00035           {
00036             return Concurrency::task<void>([=]() {})
00037               .then([=]() {
00038                 return LoadMoreItemsOverride(c, count);
00039             })
00040               .then([=](Windows::Foundation::Collections::IVector<Platform::Object^>^ items) -> Windows::UI::Xaml::Data::LoadMoreItemsResult {
00041                 auto baseIndex = _storage->Size;
00042
00043                 for(unsigned int i=0; i<items->Size; i++)
00044                 {
00045                   _storage->Append(items->GetAt(i));
00046                 }
00047
00048                 Windows::UI::Xaml::Data::LoadMoreItemsResult result;
00049                 result.Count = items->Size;
00050                 return result;
00051             }, Concurrency::task_continuation_context::use_current());
00052           }
00053           catch(Platform::Exception^ e)
00054           {
00055             throw e;
00056           }
00057         }
00058         property Platform::Object^ default[int]
00059         {
00060           Platform::Object^ get(int index)
00061           {
00062             return _storage->GetAt(index);
00063           }
00064           void set(int index, Platform::Object^ value)
00065           {
00066             _storage->SetAt(index, value);
00067           }
00068         }
00069
00070     #pragma region Overridable methods
00071
00072         virtual Concurrency::task<Windows::Foundation::Collections::IVector<Platform::Object^>^> LoadMoreItemsOverride(Concurrency::cancellation_token c, unsigned int count)
00073         {
00074           return Concurrency::task<Windows::Foundation::Collections::IVector<Platform::Object^>^>(
00075           [=]() -> Windows::Foundation::Collections::IVector<Platform::Object^>^ {
00076               auto items = ref new Platform::Collections::Vector<Platform::Object^>();
00077               return items;
00078           });
00079         }
00080         virtual bool HasMoreItemsOverride()
00081         {
00082           return false;
00083         }
00084
00085     #pragma endregion
00086
00087         IncrementalLoadingBase()
00088         {
00089           _storage = ref new Platform::Collections::Vector<Platform::Object^>();
00090           _storage->VectorChanged += ref new Windows::Foundation::Collections::VectorChangedEventHandler<Platform::Object^>(this, &IncrementalLoadingBase::_storageVectorChanged);
00091           _busy = false;
00092           _isVectorChangedObserved = false;
00093         }
00094
00095       public:
00096
00097         virtual Windows::Foundation::IAsyncOperation<Windows::UI::Xaml::Data::LoadMoreItemsResult>^ LoadMoreItemsAsync(unsigned int count)
00098         {
00099           if (_busy)
00100           {
00101             throw ref new Platform::FailureException("Only one operation in flight at a time");
00102           }
00103
00104           _busy = true;
00105
00106           return Concurrency::create_async([=](Concurrency::cancellation_token c) {
00107             return LoadMoreItemsAsync(c, count)
00108               .then([=](Windows::UI::Xaml::Data::LoadMoreItemsResult result) -> Windows::UI::Xaml::Data::LoadMoreItemsResult {
00109                 _busy = false;
00110                 return result;
00111             });
00112           });
00113         }
00114
00115         property bool HasMoreItems
00116         {
00117           virtual bool get() { return HasMoreItemsOverride(); }
00118         }
00119
00120     #pragma endregion
00121
00122     #pragma region IBindableObservableVector
00123
00124         virtual event Windows::UI::Xaml::Interop::BindableVectorChangedEventHandler^ VectorChanged
00125         {
00126           virtual Windows::Foundation::EventRegistrationToken add(Windows::UI::Xaml::Interop::BindableVectorChangedEventHandler^ e)
00127           {
00128             _isVectorChangedObserved = true;
00129             return _privateVectorChanged += e;
00130           }
00131
00132           virtual void remove(Windows::Foundation::EventRegistrationToken t)
00133           {
00134             _privateVectorChanged -= t;
00135           }
00136           virtual void raise(Windows::UI::Xaml::Interop::IBindableObservableVector^ vector, Platform::Object^ e)
00137           {
00138             if(_isVectorChangedObserved)
00139             {
00140               _privateVectorChanged(vector, e);
00141             }
00142           }
00143         }
00144
00145     #pragma endregion
00146
00147     #pragma region Windows::UI::Xaml::Interop::IBindableIterator
00148
00149         virtual Windows::UI::Xaml::Interop::IBindableIterator^ First()
00150         {
00151           return dynamic_cast<Windows::UI::Xaml::Interop::IBindableIterator^>(_storage->First());
00152         }
00153
00154     #pragma endregion
00155
00156     #pragma region Windows::UI::Xaml::Interop::IBindableVector
00157
00158         virtual void Append(Platform::Object^ value)
00159         {
00160           _storage->Append(value);
00161         }
00162
00163         virtual void Clear()
00164         {
00165           _storage->Clear();
00166         }
00167
00168         virtual Platform::Object^ GetAt(unsigned int index)
00169         {
00170           return _storage->GetAt(index);
00171         }
00172
00173         virtual Windows::UI::Xaml::Interop::IBindableVectorView^ GetView()
00174         {
00175           return safe_cast<Windows::UI::Xaml::Interop::IBindableVectorView^>(_storage->GetView());
00176         }
00177
00178         virtual bool IndexOf(Platform::Object^ value, unsigned int* index)
00179         {
00180           return _storage->IndexOf(value, index);
00181         }
00182
00183         virtual void InsertAt(unsigned int index, Platform::Object^ value)
00184         {
00185           _storage->InsertAt(index, value);
00186         }
00187
00188         virtual void RemoveAt(unsigned int index)
00189         {
00190           _storage->RemoveAt(index);
00191         }
00192
00193         virtual void RemoveAtEnd()
00194         {
00195           _storage->RemoveAtEnd();
00196         }
00197
00198         virtual void SetAt(unsigned int index, Platform::Object^ value)
00199         {
00200           _storage->SetAt(index, value);
00201         }
00202
00203         virtual property unsigned int Size
00204         {
00205           unsigned int get() { return _storage->Size; }
00206         }
00207
00208
00209     #pragma endregion
00210
00211     #pragma region State
00212
00213       private:
00214         Platform::Collections::Vector<Platform::Object^>^ _storage;
00215         bool _busy;
00216         bool _isVectorChangedObserved;
00217         event Windows::UI::Xaml::Interop::BindableVectorChangedEventHandler^ _privateVectorChanged;
00218
00219         /// <summary>
00220         ///
00221         /// </summary>
00222         /// <param name="e">IVectorChangedEventArgs</param>
00223         void _storageVectorChanged(Windows::Foundation::Collections::IObservableVector<Platform::Object^>^ sender, Windows::Foundation::Collections::IVectorChangedEventArgs^ e)
00224         {
00225           if (_isVectorChangedObserved)
00226           {
00227             VectorChanged(this, e);
00228           }
00229         }
00230
00231     #pragma endregion
00232       };
00233
00234     }
00235 }
Generated on Sat Nov 23 2024 16:08:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: LightSensor/C++/pch.cpp Source File

  • LightSensor

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2Dapp printing/C++/pch.h Source File

  • Direct2Dapp printing

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 <d3d11_1.h>
00012 #include <d2d1_1.h>
00013 #include <d2d1effects.h>
00014 #include <dwrite_1.h>
00015 #include <wincodec.h>
00016 #include <agile.h>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Clipboard app/C++/CppSamplesUtils.h Source File

  • Clipboard app

CppSamplesUtils.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 <string>
00014 #include <sstream>
00015 #include <algorithm>
00016 #include <collection.h>
00017 #include <ppltasks.h>
00018
00019 namespace CppSamplesUtils
00020 {
00021     namespace Details
00022     {
00023         static Windows::Foundation::Collections::PropertySet^ sessionState = nullptr;
00024         static Platform::String^ sessionStateFileName = ref new Platform::String(L"_cppSessionState.xml");
00025
00026         concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file);
00027         concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file);
00028     }
00029
00030     class SuspensionManager
00031     {
00032     public:
00033         static Windows::Foundation::Collections::PropertySet^ SessionState()
00034         {
00035             using namespace Windows::Foundation::Collections;
00036             using namespace Details;
00037
00038             if (sessionState == nullptr)
00039             {
00040                 sessionState = ref new PropertySet();
00041             }
00042             return sessionState;
00043         }
00044
00045         static concurrency::task<void> StartRestoreTask()
00046         {
00047             using namespace Windows::Foundation;
00048             using namespace Windows::Storage;
00049             using namespace Windows::Storage::Streams;
00050             using namespace Details;
00051
00052             auto state = SessionState();
00053             state->Clear();
00054
00055             concurrency::task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFileName));
00056             return getFileTask.then([=](StorageFile^ file)
00057             {
00058                 return DeserializeSessionState(file);
00059             });
00060         }
00061
00062         static concurrency::task<void> StartSaveTask()
00063         {
00064             using namespace Windows::Foundation;
00065             using namespace Windows::Storage;
00066             using namespace Windows::Storage::Streams;
00067             using namespace Details;
00068
00069             concurrency::task<StorageFile^> createFileTask(ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFileName, CreationCollisionOption::ReplaceExisting));
00070             return createFileTask.then([=](StorageFile^ file)
00071             {
00072                 return SerializeSessionState(file);
00073             });
00074         }
00075     };
00076
00077     namespace Details
00078     {
00079         template <class T>
00080         inline Platform::String^ ToString(T value)
00081         {
00082             std::wstringstream wss;
00083             wss << value;
00084             return ref new Platform::String(wss.str().c_str());
00085         }
00086
00087         template <class T>
00088         inline T FromStringTo(Platform::String^ str)
00089         {
00090             std::wistringstream wiss(str->Data());
00091             T value = 0;
00092             wiss >> value;
00093             return value;
00094         }
00095
00096         template <class T>
00097         inline T FromHexStringTo(Platform::String^ str)
00098         {
00099             std::wistringstream wiss(str->Data());
00100             T value = 0;
00101             wiss >> std::hex >> value;
00102             return value;
00103         }
00104
00105         template <>
00106         inline Platform::Guid FromStringTo<Platform::Guid>(Platform::String^ str)
00107         {
00108             using namespace Platform;
00109
00110             if (str->Length() != 38)
00111             {
00112                 throw ref new InvalidArgumentException;
00113             }
00114             std::wstring ws(str->Data());
00115             if (ws[0] != L'{' || ws[37] != L'}' || ws[9] != L'-' || ws[14] != L'-' || ws[19] != L'-' || ws[24] != L'-')
00116             {
00117                 throw ref new InvalidArgumentException;
00118             }
00119             ws[0] = ws[37] = ws[9] = ws[14] = ws[19] =ws[24] = L' ';
00120             std::wistringstream wiss(ws);
00121             unsigned int a = 0;
00122             unsigned short b = 0;
00123             unsigned short c = 0;
00124             unsigned short d = 0;
00125             unsigned long long e = 0;
00126             static_assert(sizeof(d) == sizeof(char) * 2, "sizeof(d) == sizeof(char) * 2");
00127             static_assert(sizeof(e) == sizeof(char) * 8, "sizeof(e) == sizeof(char) * 8");
00128             wiss >> std::hex >> a >> b >> c >> d >> e;
00129             unsigned char *ad = (unsigned char*)(&d);
00130             unsigned char *ae = (unsigned char*)(&e);
00131             return Platform::Guid(a, b, c, ad[1], ad[0], ae[5], ae[4], ae[3], ae[2], ae[1], ae[0]);
00132         }
00133
00134         inline Platform::Object^ ConvertStringToObject(Windows::Foundation::PropertyType type, Platform::String^ str)
00135         {
00136             using namespace Platform;
00137             using namespace Windows::Foundation;
00138
00139             if (type == PropertyType::String)
00140             {
00141                 return PropertyValue::CreateString(str);
00142             }
00143
00144             switch (type)
00145             {
00146             case PropertyType::UInt8:
00147                 return PropertyValue::CreateUInt8((unsigned char)FromStringTo<unsigned short>(str));
00148             case PropertyType::UInt16:
00149                 return PropertyValue::CreateUInt16(FromStringTo<unsigned short>(str));
00150             case PropertyType::UInt32:
00151                 return PropertyValue::CreateUInt32(FromStringTo<unsigned int>(str));
00152             case PropertyType::UInt64:
00153                 return PropertyValue::CreateUInt64(FromStringTo<unsigned long long>(str));
00154             case PropertyType::Int16:
00155                 return PropertyValue::CreateInt16(FromStringTo<short>(str));
00156             case PropertyType::Int32:
00157                 return PropertyValue::CreateInt32(FromStringTo<int>(str));
00158             case PropertyType::Int64:
00159                 return PropertyValue::CreateInt64(FromStringTo<long long>(str));
00160             case PropertyType::Single:
00161                 return PropertyValue::CreateSingle(FromStringTo<float>(str));
00162             case PropertyType::Double:
00163                 return PropertyValue::CreateDouble(FromStringTo<double>(str));
00164             case PropertyType::Boolean:
00165                 return PropertyValue::CreateBoolean(FromStringTo<bool>(str));
00166             case PropertyType::Char16:
00167                 return PropertyValue::CreateChar16(str->Data()[0]);
00168             case PropertyType::Guid:
00169                 return PropertyValue::CreateGuid(FromStringTo<Guid>(str));
00170             default:
00171                 throw ref new Platform::InvalidCastException;
00172             }
00173         }
00174
00175         inline Platform::String^ ConvertPropertyValueToString(Windows::Foundation::IPropertyValue^ pv)
00176         {
00177             using namespace Platform;
00178             using namespace Windows::Foundation;
00179
00180             String^ valueString;
00181
00182             switch (pv->Type)
00183             {
00184             case PropertyType::String:
00185                 valueString = pv->GetString();
00186                 break;
00187
00188             case PropertyType::UInt8:
00189             case PropertyType::UInt16:
00190             case PropertyType::UInt32:
00191             case PropertyType::UInt64:
00192                 valueString = ToString(pv->GetUInt64());
00193                 break;
00194
00195             case PropertyType::Int16:
00196             case PropertyType::Int32:
00197             case PropertyType::Int64:
00198                 valueString = ToString(pv->GetInt64());
00199                 break;
00200
00201             case PropertyType::Single:
00202                 valueString = ToString(pv->GetSingle());
00203                 break;
00204
00205             case PropertyType::Double:
00206                 valueString = ToString(pv->GetDouble());
00207                 break;
00208
00209             case PropertyType::Boolean:
00210                 valueString = ToString(pv->GetBoolean());
00211                 break;
00212
00213             case PropertyType::Char16:
00214                 wchar_t buffer[2];
00215                 buffer[0] = pv->GetChar16();
00216                 buffer[1] = 0;
00217                 valueString = ref new String(buffer);
00218                 break;
00219
00220             case PropertyType::Guid:
00221                 valueString = pv->GetGuid().ToString();
00222                 break;
00223
00224             default:
00225                 throw ref new InvalidCastException;
00226             }
00227
00228             return valueString;
00229         }
00230
00231         inline Windows::Data::Xml::Dom::XmlElement^ CreateXmlElementFromObject(Windows::Data::Xml::Dom::XmlDocument^ doc, Platform::String^ name, Platform::Object^ value)
00232         {
00233             using namespace Platform;
00234             using namespace Windows::Foundation;
00235             using namespace Windows::Data::Xml::Dom;
00236
00237             XmlElement^ element = doc->CreateElement("item");
00238             element->SetAttribute("name", name);
00239
00240             IPropertyValue^ pv = (IPropertyValue^)value;
00241             element->SetAttribute("type", ToString((int)pv->Type));
00242             element->SetAttribute("value", ConvertPropertyValueToString(pv));
00243
00244             return element;
00245         }
00246
00247         inline concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file)
00248         {
00249             using namespace Windows::Data::Xml::Dom;
00250             using namespace Windows::Foundation;
00251             namespace WFC = Windows::Foundation::Collections;
00252             typedef Windows::Foundation::Collections::IKeyValuePair<Platform::String^, Platform::Object^> KVPair;
00253
00254             XmlDocument^ doc = ref new XmlDocument;
00255             doc->AppendChild(doc->CreateElement("items"));
00256             auto sessionState = SuspensionManager::SessionState();
00257
00258             std::for_each(WFC::begin(sessionState), WFC::end(sessionState), [doc](KVPair^ item)
00259             {
00260                 doc->DocumentElement->AppendChild(CreateXmlElementFromObject(doc, item->Key, item->Value));
00261             });
00262
00263             return concurrency::task<void>(doc->SaveToFileAsync(file));
00264         }
00265
00266         inline Windows::Foundation::PropertyType PropertyTypeFromString(Platform::String^ str)
00267         {
00268             int value = FromStringTo<int>(str);
00269             return (Windows::Foundation::PropertyType)value;
00270         }
00271
00272         inline concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file)
00273         {
00274             using namespace Platform;
00275             using namespace Windows::Foundation;
00276             using namespace Windows::Data::Xml::Dom;
00277             namespace WFC = Windows::Foundation::Collections;
00278
00279             concurrency::task<XmlDocument^> loadFileTask(XmlDocument::LoadFromFileAsync(file));
00280             return loadFileTask.then([=](concurrency::task<XmlDocument^> docTask)
00281             {
00282                 try
00283                 {
00284                     auto doc = docTask.get();
00285                     auto items = doc->SelectNodes("/items/item");
00286                     auto sessionState = SuspensionManager::SessionState();
00287
00288                     std::for_each(WFC::begin(items), WFC::end(items), [sessionState](IXmlNode^ node)
00289                     {
00290                         auto element = (IXmlElement^)node;
00291                         String^ name = element->GetAttribute("name");
00292                         String^ value = element->GetAttribute("value");
00293                         PropertyType type = PropertyTypeFromString(element->GetAttribute("type"));
00294
00295                         Object^ valueObject = ConvertStringToObject(type, value);
00296                         sessionState->Insert(name, valueObject);
00297                     });
00298
00299                 }
00300                 catch (Platform::Exception^)
00301                 {
00302                     // Restoring is best effort
00303                 }
00304             });
00305         }
00306     } // namespace Details
00307 } // namespace CppSamplesUtils
Generated on Sat Nov 23 2024 16:07:53 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Toast notifications/C#,C++/NotificationsExtensions/Common.cs Source File

  • Toast notifications
  • C#,C++
  • NotificationsExtensions

Common.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 System;
00009 using System.Collections.ObjectModel;
00010 using System.Runtime.InteropServices;
00011 using System.Text;
00012 #if !WINRT_NOT_PRESENT
00013 using Windows.Data.Xml.Dom;
00014 #endif
00015
00016 namespace NotificationsExtensions
00017 {
00018     internal sealed class NotificationContentText : INotificationContentText
00019     {
00020         internal NotificationContentText() { }
00021
00022         public string Text
00023         {
00024             get { return m_Text; }
00025             set { m_Text = value; }
00026         }
00027
00028         public string Lang
00029         {
00030             get { return m_Lang; }
00031             set { m_Lang = value; }
00032         }
00033
00034         private string m_Text;
00035         private string m_Lang;
00036     }
00037
00038     internal sealed class NotificationContentImage : INotificationContentImage
00039     {
00040         internal NotificationContentImage() { }
00041
00042         public string Src
00043         {
00044             get { return m_Src; }
00045             set { m_Src = value; }
00046         }
00047
00048         public string Alt
00049         {
00050             get { return m_Alt; }
00051             set { m_Alt = value; }
00052         }
00053
00054         public bool AddImageQuery
00055         {
00056             get
00057             {
00058                 if (m_AddImageQueryNullable == null || m_AddImageQueryNullable.Value == false)
00059                 {
00060                     return false;
00061                 }
00062                 else
00063                 {
00064                     return true;
00065                 }
00066             }
00067             set { m_AddImageQueryNullable = value; }
00068         }
00069
00070         public bool? AddImageQueryNullable
00071         {
00072             get { return m_AddImageQueryNullable; }
00073             set { m_AddImageQueryNullable = value; }
00074         }
00075
00076         private string m_Src;
00077         private string m_Alt;
00078         private bool? m_AddImageQueryNullable;
00079     }
00080
00081     internal static class Util
00082     {
00083         public const int NOTIFICATION_CONTENT_VERSION = 1;
00084
00085         public static string HttpEncode(string value)
00086         {
00087             return value.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("\"", "&quot;").Replace("'", "&apos;");
00088         }
00089     }
00090
00091     /// <summary>
00092     /// Base class for the notification content creation helper classes.
00093     /// </summary>
00094 #if !WINRT_NOT_PRESENT
00095     internal abstract class NotificationBase
00096 #else
00097     abstract partial class NotificationBase
00098 #endif
00099     {
00100         protected NotificationBase(string templateName, int imageCount, int textCount)
00101         {
00102             m_TemplateName = templateName;
00103
00104             m_Images = new NotificationContentImage[imageCount];
00105             for (int i = 0; i < m_Images.Length; i++)
00106             {
00107                 m_Images[i] = new NotificationContentImage();
00108             }
00109
00110             m_TextFields = new INotificationContentText[textCount];
00111             for (int i = 0; i < m_TextFields.Length; i++)
00112             {
00113                 m_TextFields[i] = new NotificationContentText();
00114             }
00115         }
00116
00117         public bool StrictValidation
00118         {
00119             get { return m_StrictValidation; }
00120             set { m_StrictValidation = value; }
00121         }
00122         public abstract string GetContent();
00123
00124         public override string ToString()
00125         {
00126             return GetContent();
00127         }
00128
00129 #if !WINRT_NOT_PRESENT
00130         public XmlDocument GetXml()
00131         {
00132             XmlDocument xml = new XmlDocument();
00133             xml.LoadXml(GetContent());
00134             return xml;
00135         }
00136 #endif
00137
00138         /// <summary>
00139         /// Retrieves the list of images that can be manipulated on the notification content.
00140         /// </summary>
00141         public INotificationContentImage[] Images
00142         {
00143             get { return m_Images; }
00144         }
00145
00146         /// <summary>
00147         /// Retrieves the list of text fields that can be manipulated on the notification content.
00148         /// </summary>
00149         public INotificationContentText[] TextFields
00150         {
00151             get { return m_TextFields; }
00152         }
00153
00154         /// <summary>
00155         /// The base Uri path that should be used for all image references in the notification.
00156         /// </summary>
00157         public string BaseUri
00158         {
00159             get { return m_BaseUri; }
00160             set
00161             {
00162                 if (this.StrictValidation && !String.IsNullOrEmpty(value))
00163                 {
00164                     Uri uri;
00165                     try
00166                     {
00167                         uri = new Uri(value);
00168                     }
00169                     catch (Exception e)
00170                     {
00171                         throw new ArgumentException("Invalid URI. Use a valid URI or turn off StrictValidation", e);
00172                     }
00173                     if (!(uri.Scheme.Equals("http", StringComparison.OrdinalIgnoreCase)
00174                         || uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase)
00175                         || uri.Scheme.Equals("ms-appx", StringComparison.OrdinalIgnoreCase)
00176                         || (uri.Scheme.Equals("ms-appdata", StringComparison.OrdinalIgnoreCase)
00177                             && (String.IsNullOrEmpty(uri.Authority)) // check to make sure the Uri isn't ms-appdata://foo/local
00178                             && (uri.AbsolutePath.StartsWith("/local/") || uri.AbsolutePath.StartsWith("local/"))))) // both ms-appdata:local/ and ms-appdata:/local/ are valid
00179                     {
00180                         throw new ArgumentException("The BaseUri must begin with http://, https://, ms-appx:///, or ms-appdata:///local/.", "value");
00181                     }
00182                 }
00183                 m_BaseUri = value;
00184             }
00185         }
00186
00187         public string Lang
00188         {
00189             get { return m_Lang; }
00190             set { m_Lang = value; }
00191         }
00192
00193         public bool AddImageQuery
00194         {
00195             get
00196             {
00197                 if (m_AddImageQueryNullable == null || m_AddImageQueryNullable.Value == false)
00198                 {
00199                     return false;
00200                 }
00201                 else
00202                 {
00203                     return true;
00204                 }
00205             }
00206             set { m_AddImageQueryNullable = value; }
00207         }
00208
00209         public bool? AddImageQueryNullable
00210         {
00211             get { return m_AddImageQueryNullable; }
00212             set { m_AddImageQueryNullable = value; }
00213         }
00214
00215         protected string SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery)
00216         {
00217             globalLang = (globalLang != null) ? globalLang : String.Empty;
00218             globalBaseUri = String.IsNullOrWhiteSpace(globalBaseUri) ? null : globalBaseUri;
00219
00220             StringBuilder builder = new StringBuilder(String.Empty);
00221             for (int i = 0; i < m_Images.Length; i++)
00222             {
00223                 if (!String.IsNullOrEmpty(m_Images[i].Src))
00224                 {
00225                     string escapedSrc = Util.HttpEncode(m_Images[i].Src);
00226                     if (!String.IsNullOrWhiteSpace(m_Images[i].Alt))
00227                     {
00228                         string escapedAlt = Util.HttpEncode(m_Images[i].Alt);
00229                         if (m_Images[i].AddImageQueryNullable == null || m_Images[i].AddImageQueryNullable == globalAddImageQuery)
00230                         {
00231                             builder.AppendFormat("<image id='{0}' src='{1}' alt='{2}'/>", i + 1, escapedSrc, escapedAlt);
00232                         }
00233                         else
00234                         {
00235                             builder.AppendFormat("<image addImageQuery='{0}' id='{1}' src='{2}' alt='{3}'/>", m_Images[i].AddImageQuery.ToString().ToLowerInvariant(), i + 1, escapedSrc, escapedAlt);
00236                         }
00237                     }
00238                     else
00239                     {
00240                         if (m_Images[i].AddImageQueryNullable == null || m_Images[i].AddImageQueryNullable == globalAddImageQuery)
00241                         {
00242                             builder.AppendFormat("<image id='{0}' src='{1}'/>", i + 1, escapedSrc);
00243                         }
00244                         else
00245                         {
00246                             builder.AppendFormat("<image addImageQuery='{0}' id='{1}' src='{2}'/>", m_Images[i].AddImageQuery.ToString().ToLowerInvariant(), i + 1, escapedSrc);
00247                         }
00248                     }
00249                 }
00250             }
00251
00252             for (int i = 0; i < m_TextFields.Length; i++)
00253             {
00254                 if (!String.IsNullOrWhiteSpace(m_TextFields[i].Text))
00255                 {
00256                     string escapedValue = Util.HttpEncode(m_TextFields[i].Text);
00257                     if (!String.IsNullOrWhiteSpace(m_TextFields[i].Lang) && !m_TextFields[i].Lang.Equals(globalLang))
00258                     {
00259                         string escapedLang = Util.HttpEncode(m_TextFields[i].Lang);
00260                         builder.AppendFormat("<text id='{0}' lang='{1}'>{2}</text>", i + 1, escapedLang, escapedValue);
00261                     }
00262                     else
00263                     {
00264                         builder.AppendFormat("<text id='{0}'>{1}</text>", i + 1, escapedValue);
00265                     }
00266                 }
00267             }
00268
00269             return builder.ToString();
00270         }
00271
00272         public string TemplateName { get { return m_TemplateName; } }
00273
00274         private bool m_StrictValidation = true;
00275         private NotificationContentImage[] m_Images;
00276         private INotificationContentText[] m_TextFields;
00277
00278         private string m_Lang;
00279         private string m_BaseUri;
00280         private string m_TemplateName;
00281         private bool? m_AddImageQueryNullable;
00282     }
00283
00284     /// <summary>
00285     /// Exception returned when invalid notification content is provided.
00286     /// </summary>
00287     internal sealed class NotificationContentValidationException : COMException
00288     {
00289         public NotificationContentValidationException(string message)
00290             : base(message, unchecked((int)0x80070057))
00291         {
00292         }
00293     }
00294 }
Generated on Sat Nov 23 2024 16:07:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAudio2 audio file playback/C++/DirectXBase.cpp Source File

  • XAudio2 audio file playback

DirectXBase.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 "DirectXBase.h"
00010
00011 using namespace Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::Graphics::Display;
00015 using namespace D2D1;
00016
00017 // Constructor.
00018 DirectXBase::DirectXBase() :
00019     m_windowSizeChangeInProgress(false),
00020     m_dpi(-1.0f)
00021 {
00022 }
00023
00024 // Initialize the DirectX resources required to run.
00025 void DirectXBase::Initialize(CoreWindow^ window, float dpi)
00026 {
00027     m_window = window;
00028
00029     CreateDeviceIndependentResources();
00030     CreateDeviceResources();
00031     SetDpi(dpi);
00032 }
00033
00034 // Recreate all device resources and set them back to the current state.
00035 void DirectXBase::HandleDeviceLost()
00036 {
00037     // Reset these member variables to ensure that SetDpi recreates all resources.
00038     float dpi = m_dpi;
00039     m_dpi = -1.0f;
00040     m_windowBounds.Width = 0;
00041     m_windowBounds.Height = 0;
00042     m_swapChain = nullptr;
00043
00044     CreateDeviceResources();
00045     SetDpi(dpi);
00046 }
00047
00048 // These are the resources required independent of the device.
00049 void DirectXBase::CreateDeviceIndependentResources()
00050 {
00051     D2D1_FACTORY_OPTIONS options;
00052     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00053
00054 #if defined(_DEBUG)
00055     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00056     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00057 #endif
00058
00059     DX::ThrowIfFailed(
00060         D2D1CreateFactory(
00061             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00062             __uuidof(ID2D1Factory1),
00063             &options,
00064             &m_d2dFactory
00065             )
00066         );
00067
00068     DX::ThrowIfFailed(
00069         DWriteCreateFactory(
00070             DWRITE_FACTORY_TYPE_SHARED,
00071             __uuidof(IDWriteFactory),
00072             &m_dwriteFactory
00073             )
00074         );
00075
00076     DX::ThrowIfFailed(
00077         CoCreateInstance(
00078             CLSID_WICImagingFactory,
00079             nullptr,
00080             CLSCTX_INPROC_SERVER,
00081             IID_PPV_ARGS(&m_wicFactory)
00082             )
00083         );
00084 }
00085
00086 // These are the resources that depend on the device.
00087 void DirectXBase::CreateDeviceResources()
00088 {
00089     // This flag adds support for surfaces with a different color channel ordering
00090     // than the API default. It is required for compatibility with Direct2D.
00091     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00092     ComPtr<IDXGIDevice> dxgiDevice;
00093
00094 #if defined(_DEBUG)
00095     // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00096     creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00097 #endif
00098
00099     // This array defines the set of DirectX hardware feature levels this app will support.
00100     // Note the ordering should be preserved.
00101     // Don't forget to declare your application's minimum required feature level in its
00102     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00103     D3D_FEATURE_LEVEL featureLevels[] =
00104     {
00105         D3D_FEATURE_LEVEL_11_1,
00106         D3D_FEATURE_LEVEL_11_0,
00107         D3D_FEATURE_LEVEL_10_1,
00108         D3D_FEATURE_LEVEL_10_0,
00109         D3D_FEATURE_LEVEL_9_3,
00110         D3D_FEATURE_LEVEL_9_2,
00111         D3D_FEATURE_LEVEL_9_1
00112     };
00113
00114     // Create the Direct3D 11 API device object and a corresponding context.
00115     ComPtr<ID3D11Device> device;
00116     ComPtr<ID3D11DeviceContext> context;
00117     DX::ThrowIfFailed(
00118         D3D11CreateDevice(
00119             nullptr,                    // Specify nullptr to use the default adapter.
00120             D3D_DRIVER_TYPE_HARDWARE,
00121             0,
00122             creationFlags,              // Set debug and Direct2D compatibility flags.
00123             featureLevels,              // List of feature levels this app can support.
00124             ARRAYSIZE(featureLevels),
00125             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Metro style apps.
00126             &device,                    // Returns the Direct3D device created.
00127             &m_featureLevel,            // Returns feature level of device created.
00128             &context                    // Returns the device immediate context.
00129             )
00130         );
00131
00132     // Get the Direct3D 11.1 API device and context interfaces.
00133     DX::ThrowIfFailed(
00134         device.As(&m_d3dDevice)
00135         );
00136
00137     DX::ThrowIfFailed(
00138         context.As(&m_d3dContext)
00139         );
00140
00141     // Get the underlying DXGI device of the Direct3D device.
00142     DX::ThrowIfFailed(
00143         m_d3dDevice.As(&dxgiDevice)
00144         );
00145
00146     // Create the Direct2D device object and a corresponding context.
00147     DX::ThrowIfFailed(
00148         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00149         );
00150
00151     DX::ThrowIfFailed(
00152         m_d2dDevice->CreateDeviceContext(
00153             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00154             &m_d2dContext
00155             )
00156         );
00157 }
00158
00159 // Helps track the DPI in the helper class.
00160 // This is called in the dpiChanged event handler in the view class.
00161 void DirectXBase::SetDpi(float dpi)
00162 {
00163     if (dpi != m_dpi)
00164     {
00165         // Save the DPI of this display in our class.
00166         m_dpi = dpi;
00167
00168         // Update Direct2D's stored DPI.
00169         m_d2dContext->SetDpi(m_dpi, m_dpi);
00170
00171         // Often a DPI change implies a window size change. In some cases Windows will issue
00172         // both a size changed event and a DPI changed event. In this case, the resulting bounds
00173         // will not change, and the window resize code will only be executed once.
00174         UpdateForWindowSizeChange();
00175     }
00176 }
00177
00178 // This routine is called in the event handler for the view SizeChanged event.
00179 void DirectXBase::UpdateForWindowSizeChange()
00180 {
00181     // Only handle window size changed if there is no pending DPI change.
00182     if (m_dpi != DisplayProperties::LogicalDpi)
00183     {
00184         return;
00185     }
00186
00187     if (m_window->Bounds.Width  != m_windowBounds.Width ||
00188         m_window->Bounds.Height != m_windowBounds.Height)
00189     {
00190         m_d2dContext->SetTarget(nullptr);
00191         m_d2dTargetBitmap = nullptr;
00192         m_d3dRenderTargetView = nullptr;
00193         m_d3dDepthStencilView = nullptr;
00194         m_windowSizeChangeInProgress = true;
00195         CreateWindowSizeDependentResources();
00196     }
00197 }
00198
00199 // Allocate all memory resources that change on a window SizeChanged event.
00200 void DirectXBase::CreateWindowSizeDependentResources()
00201 {
00202     // Store the window bounds so the next time we get a SizeChanged event we can
00203     // avoid rebuilding everything if the size is identical.
00204     m_windowBounds = m_window->Bounds;
00205
00206     if (m_swapChain != nullptr)
00207     {
00208         // If the swap chain already exists, resize it.
00209         HRESULT hr = m_swapChain->ResizeBuffers(2, 0, 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0);
00210
00211         if (hr == DXGI_ERROR_DEVICE_REMOVED)
00212         {
00213             // If the device was removed for any reason, a new device and swapchain will need to be created.
00214             HandleDeviceLost();
00215
00216             // Everything is set up now. Do not continue execution of this method.
00217             return;
00218         }
00219         else
00220         {
00221             DX::ThrowIfFailed(hr);
00222         }
00223     }
00224     else
00225     {
00226         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00227         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00228         swapChainDesc.Width = 0;                                     // Use automatic sizing.
00229         swapChainDesc.Height = 0;
00230         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;           // This is the most common swap chain format.
00231         swapChainDesc.Stereo = false;
00232         swapChainDesc.SampleDesc.Count = 1;                          // Don't use multi-sampling.
00233         swapChainDesc.SampleDesc.Quality = 0;
00234         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00235         swapChainDesc.BufferCount = 2;                               // Use double-buffering to minimize latency.
00236         swapChainDesc.Scaling = DXGI_SCALING_NONE;
00237         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Metro style apps must use this SwapEffect.
00238         swapChainDesc.Flags = 0;
00239
00240         ComPtr<IDXGIDevice1> dxgiDevice;
00241         DX::ThrowIfFailed(
00242             m_d3dDevice.As(&dxgiDevice)
00243             );
00244
00245         ComPtr<IDXGIAdapter> dxgiAdapter;
00246         DX::ThrowIfFailed(
00247             dxgiDevice->GetAdapter(&dxgiAdapter)
00248             );
00249
00250         ComPtr<IDXGIFactory2> dxgiFactory;
00251         DX::ThrowIfFailed(
00252             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00253             );
00254
00255         CoreWindow^ window = m_window.Get();
00256         DX::ThrowIfFailed(
00257             dxgiFactory->CreateSwapChainForCoreWindow(
00258                 m_d3dDevice.Get(),
00259                 reinterpret_cast<IUnknown*>(window),
00260                 &swapChainDesc,
00261                 nullptr,
00262                 &m_swapChain
00263                 )
00264             );
00265
00266         // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
00267         // ensures that the application will only render after each VSync, minimizing power consumption.
00268         DX::ThrowIfFailed(
00269             dxgiDevice->SetMaximumFrameLatency(1)
00270             );
00271     }
00272
00273     // Create a Direct3D render target view of the swap chain back buffer.
00274     ComPtr<ID3D11Texture2D> backBuffer;
00275     DX::ThrowIfFailed(
00276         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00277         );
00278
00279     DX::ThrowIfFailed(
00280         m_d3dDevice->CreateRenderTargetView(
00281             backBuffer.Get(),
00282             nullptr,
00283             &m_d3dRenderTargetView
00284             )
00285         );
00286
00287     // Cache the rendertarget dimensions in our helper class for convenient use.
00288     D3D11_TEXTURE2D_DESC backBufferDesc = {0};
00289     backBuffer->GetDesc(&backBufferDesc);
00290     m_renderTargetSize.Width  = static_cast<float>(backBufferDesc.Width);
00291     m_renderTargetSize.Height = static_cast<float>(backBufferDesc.Height);
00292
00293     // Create a depth stencil view for use with 3D rendering if needed.
00294     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00295         DXGI_FORMAT_D24_UNORM_S8_UINT,
00296         backBufferDesc.Width,
00297         backBufferDesc.Height,
00298         1,
00299         1,
00300         D3D11_BIND_DEPTH_STENCIL
00301         );
00302
00303     ComPtr<ID3D11Texture2D> depthStencil;
00304     DX::ThrowIfFailed(
00305         m_d3dDevice->CreateTexture2D(
00306             &depthStencilDesc,
00307             nullptr,
00308             &depthStencil
00309             )
00310         );
00311
00312     auto viewDesc = CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D);
00313     DX::ThrowIfFailed(
00314         m_d3dDevice->CreateDepthStencilView(
00315             depthStencil.Get(),
00316             &viewDesc,
00317             &m_d3dDepthStencilView
00318             )
00319         );
00320
00321     // Set the 3D rendering viewport to target the entire window.
00322     CD3D11_VIEWPORT viewport(
00323         0.0f,
00324         0.0f,
00325         static_cast<float>(backBufferDesc.Width),
00326         static_cast<float>(backBufferDesc.Height)
00327         );
00328
00329     m_d3dContext->RSSetViewports(1, &viewport);
00330
00331     // Create a Direct2D target bitmap associated with the
00332     // swap chain back buffer and set it as the current target.
00333     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00334         BitmapProperties1(
00335             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00336             PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00337             m_dpi,
00338             m_dpi
00339             );
00340
00341     ComPtr<IDXGISurface> dxgiBackBuffer;
00342     DX::ThrowIfFailed(
00343         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00344         );
00345
00346     DX::ThrowIfFailed(
00347         m_d2dContext->CreateBitmapFromDxgiSurface(
00348             dxgiBackBuffer.Get(),
00349             &bitmapProperties,
00350             &m_d2dTargetBitmap
00351             )
00352         );
00353
00354     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00355
00356     // Grayscale text anti-aliasing is recommended for all Metro style apps.
00357     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00358 }
00359
00360 // Method to deliver the final image to the display.
00361 void DirectXBase::Present()
00362 {
00363     // The application may optionally specify "dirty" or "scroll" rects to improve efficiency
00364     // in certain scenarios.  In this sample, however, we do not utilize those features.
00365     DXGI_PRESENT_PARAMETERS parameters = {0};
00366     parameters.DirtyRectsCount = 0;
00367     parameters.pDirtyRects = nullptr;
00368     parameters.pScrollRect = nullptr;
00369     parameters.pScrollOffset = nullptr;
00370
00371     // The first argument instructs DXGI to block until VSync, putting the application
00372     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00373     // frames that will never be displayed to the screen.
00374     HRESULT hr = m_swapChain->Present1(1, 0, &parameters);
00375
00376     // Discard the contents of the render target.
00377     // This is a valid operation only when the existing contents will be entirely
00378     // overwritten. If dirty or scroll rects are used, this call should be removed.
00379     m_d3dContext->DiscardView(m_d3dRenderTargetView.Get());
00380
00381     // Discard the contents of the depth stencil.
00382     m_d3dContext->DiscardView(m_d3dDepthStencilView.Get());
00383
00384     // If the device was removed either by a disconnect or a driver upgrade, we
00385     // must recreate all device resources.
00386     if (hr == DXGI_ERROR_DEVICE_REMOVED)
00387     {
00388         HandleDeviceLost();
00389     }
00390     else
00391     {
00392         DX::ThrowIfFailed(hr);
00393     }
00394
00395     if (m_windowSizeChangeInProgress)
00396     {
00397         // A window size change has been initiated and the app has just completed presenting
00398         // the first frame with the new size. Notify the resize manager so we can short
00399         // circuit any resize animation and prevent unnecessary delays.
00400         CoreWindowResizeManager::GetForCurrentView()->NotifyLayoutCompleted();
00401         m_windowSizeChangeInProgress = false;
00402     }
00403 }
00404
00405 void DirectXBase::ValidateDevice()
00406 {
00407     // The D3D Device is no longer valid if the default adapter changes or if
00408     // the device has been removed.
00409
00410     // First, get the information for the adapter related to the current device.
00411
00412     ComPtr<IDXGIDevice1> dxgiDevice;
00413     ComPtr<IDXGIAdapter> deviceAdapter;
00414     DXGI_ADAPTER_DESC deviceDesc;
00415     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00416     DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter));
00417     DX::ThrowIfFailed(deviceAdapter->GetDesc(&deviceDesc));
00418
00419     // Next, get the information for the default adapter.
00420
00421     ComPtr<IDXGIFactory2> dxgiFactory;
00422     ComPtr<IDXGIAdapter1> currentAdapter;
00423     DXGI_ADAPTER_DESC currentDesc;
00424     DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)));
00425     DX::ThrowIfFailed(dxgiFactory->EnumAdapters1(0, &currentAdapter));
00426     DX::ThrowIfFailed(currentAdapter->GetDesc(&currentDesc));
00427
00428     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00429     // a new D3D device must be created.
00430
00431     if ((deviceDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart) ||
00432         (deviceDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart) ||
00433         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00434     {
00435         // Release references to resources related to the old device.
00436         dxgiDevice = nullptr;
00437         deviceAdapter = nullptr;
00438
00439         // Create a new device and swap chain.
00440         HandleDeviceLost();
00441     }
00442 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/BasicReaderWriter.cpp Source File

  • Direct3D resource loading

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     m_locationPath = Platform::String::Concat(m_location->Path, "\\");
00023 }
00024
00025 BasicReaderWriter::BasicReaderWriter(
00026     _In_ Windows::Storage::StorageFolder^ folder
00027     )
00028 {
00029     m_location = folder;
00030     Platform::String^ path = m_location->Path;
00031     if (path->Length() == 0)
00032     {
00033         // Applications are not permitted to access certain
00034         // folders, such as the Documents folder, using this
00035         // code path.  In such cases, the Path property for
00036         // the folder will be an empty string.
00037         throw ref new Platform::FailureException();
00038     }
00039     m_locationPath = Platform::String::Concat(path, "\\");
00040 }
00041
00042 Platform::Array<byte>^ BasicReaderWriter::ReadData(
00043     _In_ Platform::String^ filename
00044     )
00045 {
00046     CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {0};
00047     extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
00048     extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
00049     extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN;
00050     extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
00051     extendedParams.lpSecurityAttributes = nullptr;
00052     extendedParams.hTemplateFile = nullptr;
00053
00054     Wrappers::FileHandle file(
00055         CreateFile2(
00056             Platform::String::Concat(m_locationPath, filename)->Data(),
00057             GENERIC_READ,
00058             FILE_SHARE_READ,
00059             OPEN_EXISTING,
00060             &extendedParams
00061             )
00062         );
00063     if (file.Get() == INVALID_HANDLE_VALUE)
00064     {
00065         throw ref new Platform::FailureException();
00066     }
00067
00068     FILE_STANDARD_INFO fileInfo = {0};
00069     if (!GetFileInformationByHandleEx(
00070         file.Get(),
00071         FileStandardInfo,
00072         &fileInfo,
00073         sizeof(fileInfo)
00074         ))
00075     {
00076         throw ref new Platform::FailureException();
00077     }
00078
00079     if (fileInfo.EndOfFile.HighPart != 0)
00080     {
00081         throw ref new Platform::OutOfMemoryException();
00082     }
00083
00084     Platform::Array<byte>^ fileData = ref new Platform::Array<byte>(fileInfo.EndOfFile.LowPart);
00085
00086     if (!ReadFile(
00087         file.Get(),
00088         fileData->Data,
00089         fileData->Length,
00090         nullptr,
00091         nullptr
00092         ))
00093     {
00094         throw ref new Platform::FailureException();
00095     }
00096
00097     return fileData;
00098 }
00099
00100 task<Platform::Array<byte>^> BasicReaderWriter::ReadDataAsync(
00101     _In_ Platform::String^ filename
00102     )
00103 {
00104     return task<StorageFile^>(m_location->GetFileAsync(filename)).then([=](StorageFile^ file)
00105     {
00106         return FileIO::ReadBufferAsync(file);
00107     }).then([=](IBuffer^ buffer)
00108     {
00109         auto fileData = ref new Platform::Array<byte>(buffer->Length);
00110         DataReader::FromBuffer(buffer)->ReadBytes(fileData);
00111         return fileData;
00112     });
00113 }
00114
00115 uint32 BasicReaderWriter::WriteData(
00116     _In_ Platform::String^ filename,
00117     _In_ const Platform::Array<byte>^ fileData
00118     )
00119 {
00120     CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {0};
00121     extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
00122     extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
00123     extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN;
00124     extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
00125     extendedParams.lpSecurityAttributes = nullptr;
00126     extendedParams.hTemplateFile = nullptr;
00127
00128     Wrappers::FileHandle file(
00129         CreateFile2(
00130             Platform::String::Concat(m_locationPath, filename)->Data(),
00131             GENERIC_WRITE,
00132             0,
00133             CREATE_ALWAYS,
00134             &extendedParams
00135             )
00136         );
00137     if (file.Get() == INVALID_HANDLE_VALUE)
00138     {
00139         throw ref new Platform::FailureException();
00140     }
00141
00142     DWORD numBytesWritten;
00143     if (
00144         !WriteFile(
00145             file.Get(),
00146             fileData->Data,
00147             fileData->Length,
00148             &numBytesWritten,
00149             nullptr
00150             ) ||
00151         numBytesWritten != fileData->Length
00152         )
00153     {
00154         throw ref new Platform::FailureException();
00155     }
00156
00157     return numBytesWritten;
00158 }
00159
00160 task<void> BasicReaderWriter::WriteDataAsync(
00161     _In_ Platform::String^ filename,
00162     _In_ const Platform::Array<byte>^ fileData
00163     )
00164 {
00165     return task<StorageFile^>(m_location->CreateFileAsync(filename, CreationCollisionOption::ReplaceExisting)).then([=](StorageFile^ file)
00166     {
00167         FileIO::WriteBytesAsync(file, fileData);
00168     });
00169 }
Generated on Sat Nov 23 2024 16:08:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: User domain name/C++/common/suspensionmanager.h Source File

  • User domain name
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-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< ID2D1DeviceContext > D2DDeviceContext, Microsoft::WRL::ComPtr< ID2D1SolidColorBrush > outlineBrush, Microsoft::WRL::ComPtr< ID2D1BitmapBrush > fillBrush) | CustomTextRenderer |
D2DDeviceContext | CustomTextRenderer | [private]
D2DFactory | CustomTextRenderer | [private]
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 |
fillBrush | CustomTextRenderer | [private]
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 |
outlineBrush | CustomTextRenderer | [private]
QueryInterface(IID const &riid, void **ppvObject) | CustomTextRenderer |
refCount | CustomTextRenderer | [private]
Generated on Sat Nov 23 2024 16:09:10 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application data/C++/Constants.h Source File

  • Application data

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"ApplicationData");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044
00045
00046 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/Material.h Source File

  • XAML DirectX 3D shooting game

Material.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 // Material:
00011 // This class maintains the properties that represent how an object will
00012 // look when it is rendered.  This includes the color of the object, the
00013 // texture used to render the object, and the vertex and pixel shader that
00014 // should be used for rendering.
00015 // The RenderSetup method sets the appropriate values into the constantBuffer
00016 // and calls the appropriate D3D11 context methods to set up the rendering pipeline
00017 // in the graphics hardware.
00018
00019 #include "ConstantBuffers.h"
00020
00021 ref class Material
00022 {
00023 internal:
00024     Material(
00025         DirectX::XMFLOAT4 meshColor,
00026         DirectX::XMFLOAT4 diffuseColor,
00027         DirectX::XMFLOAT4 specularColor,
00028         float specularExponent,
00029         _In_ ID3D11ShaderResourceView* textureResourceView,
00030         _In_ ID3D11VertexShader* vertexShader,
00031         _In_ ID3D11PixelShader* pixelShader
00032         );
00033
00034     void RenderSetup(
00035         _In_ ID3D11DeviceContext* context,
00036         _Inout_ ConstantBufferChangesEveryPrim* constantBuffer
00037         );
00038
00039     void SetTexture(_In_ ID3D11ShaderResourceView* textureResourceView)
00040     {
00041         m_textureRV = textureResourceView;
00042     }
00043
00044 protected private:
00045     DirectX::XMFLOAT4   m_meshColor;
00046     DirectX::XMFLOAT4   m_diffuseColor;
00047     DirectX::XMFLOAT4   m_hitColor;
00048     DirectX::XMFLOAT4   m_specularColor;
00049     float               m_specularExponent;
00050
00051     Microsoft::WRL::ComPtr<ID3D11VertexShader>       m_vertexShader;
00052     Microsoft::WRL::ComPtr<ID3D11PixelShader>        m_pixelShader;
00053     Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_textureRV;
00054 };
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::AtomPub::sealed Member List

This is the complete list of members for SDKSample::AtomPub::sealed, including all inherited members.
DeleteItem_Click(Object^sender, RoutedEventArgs^e) | SDKSample::AtomPub::sealed | [private]
DisplayItem() | SDKSample::AtomPub::sealed | [private]
DisplayItem() | SDKSample::AtomPub::sealed | [private]
DisplayItem() | SDKSample::AtomPub::sealed | [private]
feedIterator | SDKSample::AtomPub::sealed | [private]
FindEditUri(ServiceDocument^serviceDocument) | SDKSample::AtomPub::sealed | [private]
GetFeed_Click(Object^sender, RoutedEventArgs^e) | SDKSample::AtomPub::sealed | [private]
GetFeed_Click(Object^sender, RoutedEventArgs^e) | SDKSample::AtomPub::sealed | [private]
GetFeed_Click(Object^sender, RoutedEventArgs^e) | SDKSample::AtomPub::sealed | [private]
NextItem_Click(Object^sender, RoutedEventArgs^e) | SDKSample::AtomPub::sealed | [private]
NextItem_Click(Object^sender, RoutedEventArgs^e) | SDKSample::AtomPub::sealed | [private]
NextItem_Click(Object^sender, RoutedEventArgs^e) | SDKSample::AtomPub::sealed | [private]
OnNavigatedTo(NavigationEventArgs^e) override | SDKSample::AtomPub::sealed | [protected, virtual]
OnNavigatedTo(NavigationEventArgs^e) override | SDKSample::AtomPub::sealed | [protected, virtual]
OnNavigatedTo(NavigationEventArgs^e) override | SDKSample::AtomPub::sealed | [protected, virtual]
OnNavigatedTo(NavigationEventArgs^e) override | SDKSample::AtomPub::sealed | [protected, virtual]
OnNavigatingFrom(NavigatingCancelEventArgs^e) override | SDKSample::AtomPub::sealed | [protected, virtual]
OnNavigatingFrom(NavigatingCancelEventArgs^e) override | SDKSample::AtomPub::sealed | [protected, virtual]
OnNavigatingFrom(NavigatingCancelEventArgs^e) override | SDKSample::AtomPub::sealed | [protected, virtual]
OnNavigatingFrom(NavigatingCancelEventArgs^e) override | SDKSample::AtomPub::sealed | [protected, virtual]
PasswordField_PasswordChanged(Object^sender, RoutedEventArgs^e) | SDKSample::AtomPub::sealed | [private]
PasswordField_PasswordChanged(Object^sender, RoutedEventArgs^e) | SDKSample::AtomPub::sealed | [private]
PasswordField_PasswordChanged(Object^sender, RoutedEventArgs^e) | SDKSample::AtomPub::sealed | [private]
PasswordField_PasswordChanged(Object^sender, RoutedEventArgs^e) | SDKSample::AtomPub::sealed | [private]
PreviousItem_Click(Object^sender, RoutedEventArgs^e) | SDKSample::AtomPub::sealed | [private]
PreviousItem_Click(Object^sender, RoutedEventArgs^e) | SDKSample::AtomPub::sealed | [private]
PreviousItem_Click(Object^sender, RoutedEventArgs^e) | SDKSample::AtomPub::sealed | [private]
rootPage | SDKSample::AtomPub::sealed | [private]
Scenario1() | SDKSample::AtomPub::sealed |
Scenario2() | SDKSample::AtomPub::sealed |
Scenario3() | SDKSample::AtomPub::sealed |
Scenario4() | SDKSample::AtomPub::sealed |
SubmitItem_Click(Object^sender, RoutedEventArgs^e) | SDKSample::AtomPub::sealed | [private]
UpdateItem_Click(Object^sender, RoutedEventArgs^e) | SDKSample::AtomPub::sealed | [private]
UserNameField_TextChanged(Object^sender, TextChangedEventArgs^e) | SDKSample::AtomPub::sealed | [private]
UserNameField_TextChanged(Object^sender, TextChangedEventArgs^e) | SDKSample::AtomPub::sealed | [private]
UserNameField_TextChanged(Object^sender, TextChangedEventArgs^e) | SDKSample::AtomPub::sealed | [private]
UserNameField_TextChanged(Object^sender, TextChangedEventArgs^e) | SDKSample::AtomPub::sealed | [private]
Generated on Sat Nov 23 2024 16:09:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::Images::sealed Member List

This is the complete list of members for SDKSample::Images::sealed, including all inherited members.
decodePixelHeight | SDKSample::Images::sealed | [private]
decodePixelWidth | SDKSample::Images::sealed | [private]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Images::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Images::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Images::sealed | [protected, virtual]
rootPage | SDKSample::Images::sealed | [private]
Scenario1() | SDKSample::Images::sealed |
Scenario2() | SDKSample::Images::sealed |
Scenario2Button1_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Images::sealed | [private]
Scenario3() | SDKSample::Images::sealed |
Generated on Sat Nov 23 2024 16:09:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: SMS background task/C++/SmsBackgroundTask/pch.cpp Source File

  • SMS background task
  • SmsBackgroundTask

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application resources and localization/C++/Scenario10.xaml.cpp Source File

  • Application resources and localization

Scenario10.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 // Scenario10.xaml.cpp
00013 // Implementation of the Scenario10 class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario10.xaml.h"
00018
00019 using namespace SDKSample::ApplicationResources;
00020 using namespace Platform;
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
00026
00027 Scenario10::Scenario10()
00028 {
00029     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 void Scenario10::OnNavigatedTo(NavigationEventArgs^ e)
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     rootPage = MainPage::Current;
00042 }
00043
00044 void SDKSample::ApplicationResources::Scenario10::Scenario10Button_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 context = ref new ResourceContext();
00050
00051     auto selectedLanguage = Scenario10ComboBox_Language->SelectedValue;
00052         auto selectedScale = Scenario10ComboBox_Scale->SelectedValue;
00053         auto selectedContrast = Scenario10ComboBox_Contrast->SelectedValue;
00054         auto selectedHomeRegion = Scenario10ComboBox_HomeRegion->SelectedValue;
00055
00056         if (selectedLanguage != nullptr)
00057         {
00058       context->QualifierValues->Insert("language", selectedLanguage->ToString());
00059         }
00060         if (selectedScale != nullptr)
00061         {
00062             context->QualifierValues->Insert("scale", selectedScale->ToString());
00063         }
00064         if (selectedContrast != nullptr)
00065         {
00066             context->QualifierValues->Insert("contrast", selectedContrast->ToString());
00067         }
00068         if (selectedHomeRegion != nullptr)
00069         {
00070             context->QualifierValues->Insert("homeregion", selectedHomeRegion->ToString());
00071         }
00072
00073     Platform::Collections::Vector<String^>^ resourceIds = ref new Platform::Collections::Vector<String^>();
00074     //auto resourceIds = new list<String^>();
00075     resourceIds->Append("LanguageOnly");
00076     resourceIds->Append("ScaleOnly");
00077     resourceIds->Append("ContrastOnly");
00078     resourceIds->Append("HomeRegionOnly");
00079     resourceIds->Append("MultiDimensional");
00080         Scenario10_SearchMultipleResourceIds(context, resourceIds);
00081     }
00082 }
00083
00084
00085 void SDKSample::ApplicationResources::Scenario10::Scenario10_SearchMultipleResourceIds(ResourceContext^ context, Platform::Collections::Vector<String^>^ resourceIds)
00086 {
00087     Scenario10TextBlock->Text = "";
00088     auto dimensionMap = ResourceManager::Current->MainResourceMap->GetSubtree("dimensions");
00089
00090   for (unsigned int it = 0; it < resourceIds->Size; it++)
00091     {
00092     String^ id = resourceIds->GetAt(it);
00093     NamedResource^ namedResource = dimensionMap->Lookup(id);
00094         if (namedResource)
00095     {
00096       auto resourceCandidates = namedResource->ResolveAll(context);
00097       Scenario10_ShowCandidates(resourceIds->GetAt(it), resourceCandidates);
00098     }
00099     }
00100 }
00101
00102 void SDKSample::ApplicationResources::Scenario10::Scenario10_ShowCandidates(String^ resourceId, Windows::Foundation::Collections::IVectorView<ResourceCandidate^>^ resourceCandidates)
00103 {
00104     // print 'resourceId', 'found value', 'qualifer info', 'matching condition'
00105     String^ outText = "resourceId: dimensions\\" + resourceId + "\r\n";
00106
00107   for(unsigned int i =0; i < resourceCandidates->Size; i++)
00108     {
00109     ResourceCandidate^ candidate = resourceCandidates->GetAt(i);
00110     auto value = candidate->ValueAsString;
00111
00112         outText += "    Candidate " + i.ToString() + ":" + value + "\r\n";
00113     for (unsigned int j = 0; j < candidate->Qualifiers->Size; j++)
00114         {
00115       auto qualifier = candidate->Qualifiers->GetAt(j);
00116             auto qualifierName = qualifier->QualifierName;
00117             auto qualifierValue = qualifier->QualifierValue;
00118             outText += "        Qualifer: " + qualifierName + ": " + qualifierValue + "\r\n";
00119             outText += "        Matching: IsMatch (" + qualifier->IsMatch.ToString() + ")  " + "IsDefault (" + qualifier->IsDefault.ToString() + ")" + "\r\n";
00120         }
00121     }
00122
00123     this->Scenario10TextBlock->Text += outText + "\r\n";
00124
00125 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML data binding/C++/MainPage.xaml.h Source File

  • XAML data binding

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::TileContent::TileWideSmallImageAndText02 Member List

This is the complete list of members for NotificationsExtensions::TileContent::TileWideSmallImageAndText02, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
Branding | NotificationsExtensions::TileContent::TileNotificationBase |
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Image | NotificationsExtensions::TileContent::TileWideSmallImageAndText02 |
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
RequireSquareContent | NotificationsExtensions::TileContent::TileWideBase |
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SquareContent | NotificationsExtensions::TileContent::TileWideBase |
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextBody1 | NotificationsExtensions::TileContent::TileWideSmallImageAndText02 |
TextBody2 | NotificationsExtensions::TileContent::TileWideSmallImageAndText02 |
TextBody3 | NotificationsExtensions::TileContent::TileWideSmallImageAndText02 |
TextBody4 | NotificationsExtensions::TileContent::TileWideSmallImageAndText02 |
TextFields | NotificationsExtensions::NotificationBase |
TextHeading | NotificationsExtensions::TileContent::TileWideSmallImageAndText02 |
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWideSmallImageAndText02() | NotificationsExtensions::TileContent::TileWideSmallImageAndText02 | [inline]
TileWideSmallImageAndText02() | NotificationsExtensions::TileContent::TileWideSmallImageAndText02 | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:44 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Folder enumeration/C++/Constants.cpp Source File

  • Folder enumeration

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     { "Enumerate files and folders in the Pictures library",         "SDKSample.FolderEnumeration.Scenario1" },
00020     { "Enumerate files in the Pictures library, by groups",          "SDKSample.FolderEnumeration.Scenario2" },
00021     { "Enumerate files in the Pictures library with prefetch APIs",  "SDKSample.FolderEnumeration.Scenario3" },
00022 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D printing images and effects/C++/DirectXApp.cpp Source File

  • Direct2D printing images and effects

DirectXApp.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 "DirectXApp.h"
00010
00011 using namespace Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Windows::Graphics::Display;
00014 using namespace Windows::Graphics::Printing;
00015 using namespace Windows::ApplicationModel;
00016 using namespace Windows::ApplicationModel::Core;
00017 using namespace Windows::ApplicationModel::Activation;
00018 using namespace Windows::UI::ViewManagement;
00019
00020 DirectXApp::DirectXApp() :
00021     m_windowClosed(false),
00022     m_windowVisible(true)
00023 {
00024 }
00025
00026 void DirectXApp::Initialize(
00027     _In_ CoreApplicationView^ applicationView
00028     )
00029 {
00030     applicationView->Activated +=
00031         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &DirectXApp::OnActivated);
00032
00033     CoreApplication::Suspending +=
00034         ref new EventHandler<SuspendingEventArgs^>(this, &DirectXApp::OnSuspending);
00035
00036     CoreApplication::Resuming +=
00037         ref new EventHandler<Platform::Object^>(this, &DirectXApp::OnResuming);
00038
00039     m_renderer = ref new PageRenderer();
00040 }
00041
00042 void DirectXApp::SetWindow(
00043     _In_ CoreWindow^ window
00044     )
00045 {
00046     window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
00047
00048     window->SizeChanged +=
00049         ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &DirectXApp::OnWindowSizeChanged);
00050
00051     window->VisibilityChanged +=
00052         ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &DirectXApp::OnVisibilityChanged);
00053
00054     window->Closed +=
00055         ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &DirectXApp::OnWindowClosed);
00056
00057     DisplayProperties::LogicalDpiChanged +=
00058         ref new DisplayPropertiesEventHandler(this, &DirectXApp::OnLogicalDpiChanged);
00059
00060     m_renderer->Initialize(window, DisplayProperties::LogicalDpi);
00061     InitPrintManager();
00062 }
00063
00064 void DirectXApp::Load(
00065     _In_ Platform::String^ entryPoint
00066     )
00067 {
00068 }
00069
00070 void DirectXApp::Run()
00071 {
00072     while (!m_windowClosed)
00073     {
00074         if (m_windowVisible)
00075         {
00076             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(Windows::UI::Core::CoreProcessEventsOption::ProcessAllIfPresent);
00077             m_renderer->Render();
00078         }
00079         else
00080         {
00081             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(Windows::UI::Core::CoreProcessEventsOption::ProcessOneAndAllPending);
00082         }
00083     }
00084 }
00085
00086 void DirectXApp::Uninitialize()
00087 {
00088 }
00089
00090 void DirectXApp::OnWindowSizeChanged(
00091     _In_ Windows::UI::Core::CoreWindow^ sender,
00092     _In_ Windows::UI::Core::WindowSizeChangedEventArgs^ args
00093     )
00094 {
00095     m_renderer->SetSnappedMode(ApplicationView::Value == ApplicationViewState::Snapped);
00096     m_renderer->UpdateForWindowSizeChange();
00097 }
00098
00099 void DirectXApp::OnWindowClosed(
00100     _In_ CoreWindow^ sender,
00101     _In_ CoreWindowEventArgs^ args
00102     )
00103 {
00104     m_windowClosed = true;
00105 }
00106
00107 void DirectXApp::OnVisibilityChanged(
00108     _In_ CoreWindow^ sender,
00109     _In_ VisibilityChangedEventArgs^ args
00110     )
00111 {
00112     m_windowVisible = args->Visible;
00113 }
00114
00115 void DirectXApp::OnLogicalDpiChanged(_In_ Platform::Object^ sender)
00116 {
00117     m_renderer->SetDpi(DisplayProperties::LogicalDpi);
00118 }
00119
00120 void DirectXApp::OnActivated(
00121     _In_ CoreApplicationView^ applicationView,
00122     _In_ IActivatedEventArgs^ args
00123     )
00124 {
00125     CoreWindow::GetForCurrentThread()->Activate();
00126 }
00127
00128 void DirectXApp::OnSuspending(
00129     _In_ Platform::Object^ sender,
00130     _In_ SuspendingEventArgs^ args
00131     )
00132 {
00133 }
00134
00135 void DirectXApp::OnResuming(
00136     _In_ Platform::Object^ sender,
00137     _In_ Platform::Object^ args
00138     )
00139 {
00140 }
00141
00142 void DirectXApp::InitPrintManager()
00143 {
00144     // Call static method to get PrintManager object.
00145     m_printManager = Windows::Graphics::Printing::PrintManager::GetForCurrentView();
00146
00147     // Start print task event.
00148     m_printManager->PrintTaskRequested +=
00149         ref new TypedEventHandler<PrintManager^, PrintTaskRequestedEventArgs^>(this, &DirectXApp::SetPrintTask);
00150 }
00151
00152 void DirectXApp::SetPrintTask(
00153     _In_ PrintManager^ /*sender*/,
00154     _In_ PrintTaskRequestedEventArgs^ args
00155     )
00156 {
00157     PrintTaskSourceRequestedHandler^ sourceHandler =
00158         ref new PrintTaskSourceRequestedHandler([this](PrintTaskSourceRequestedArgs^ args)-> void{
00159             Microsoft::WRL::ComPtr<CDocumentSource> documentSource;
00160             DX::ThrowIfFailed(
00161                 Microsoft::WRL::MakeAndInitialize<CDocumentSource>(&documentSource, reinterpret_cast<IUnknown*>(m_renderer))
00162                 );
00163
00164             // Here CDocumentSource is inherited from IPrintDocumentSource, cast it back to an object.
00165             IPrintDocumentSource^ objSource(
00166                 reinterpret_cast<IPrintDocumentSource^>(documentSource.Get())
00167                 );
00168
00169             args->SetSource(objSource);
00170         });
00171
00172     // Request initializing print task.
00173     PrintTask^ printTask = args->Request->CreatePrintTask(
00174         L"Direct2D image and effect printing sample",
00175         sourceHandler
00176         );
00177 }
00178
00179 IFrameworkView^ DirectXAppSource::CreateView()
00180 {
00181     return ref new DirectXApp();
00182 }
00183
00184 [Platform::MTAThread]
00185 int main(Platform::Array<Platform::String^>^)
00186 {
00187     auto directXAppSource = ref new DirectXAppSource();
00188     CoreApplication::Run(directXAppSource);
00189     return 0;
00190 }
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application data/C++/Constants.cpp Source File

  • Application data

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
00021     { "Files",                  "SDKSample.ApplicationDataSample.Files" },
00022     { "Settings",               "SDKSample.ApplicationDataSample.Settings" },
00023     { "Setting Containers",     "SDKSample.ApplicationDataSample.SettingContainer" },
00024     { "Composite Settings",     "SDKSample.ApplicationDataSample.CompositeSettings" },
00025     { "DataChanged Event",      "SDKSample.ApplicationDataSample.DataChangedEvent" },
00026     { "Roaming: HighPriority",  "SDKSample.ApplicationDataSample.HighPriority" },
00027     { "ms-appdata:// Protocol", "SDKSample.ApplicationDataSample.Msappdata" },
00028     { "Clear",                  "SDKSample.ApplicationDataSample.ClearScenario" },
00029     { "SetVersion",             "SDKSample.ApplicationDataSample.SetVersion" },
00030 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: HttpClient/C++/common/suspensionmanager.h Source File

  • HttpClient
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Search contract/C++/common/suspensionmanager.h Source File

  • Search contract
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Push and periodic notifications client-side/C++/Scenario5.xaml.h Source File

  • Push and periodic notifications client-side

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 #pragma once
00012
00013 #include "pch.h"
00014 #include "Scenario5.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKSample
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       [Windows::Foundation::Metadata::WebHostHidden]
00025         public ref class Scenario5 sealed
00026         {
00027         public:
00028             Scenario5();
00029
00030         protected:
00031             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00032         private:
00033             MainPage^ rootPage;
00034             void StartBadgePolling_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00035         void StopBadgePolling_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00036         };
00037     }
00038 }
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Device auto rotation preferences/C++/pch.h Source File

  • Device auto rotation preferences

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: App tiles and badges/C#,C++/Globalization.xaml.cpp Source File

  • App tiles and badges
  • C#,C++

Globalization.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 // Globalization.xaml.cpp
00013 // Implementation of the Globalization class
00014 //
00015
00016 #include "pch.h"
00017 #include "Globalization.xaml.h"
00018
00019 using namespace SDKSample::Tiles;
00020
00021 using namespace Platform;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Navigation;
00025 using namespace Windows::UI::Notifications;
00026 using namespace NotificationsExtensions::TileContent;
00027 using namespace Windows::ApplicationModel::Resources::Core;
00028
00029 Globalization::Globalization()
00030 {
00031     InitializeComponent();
00032 }
00033
00034 void Globalization::OnNavigatedTo(NavigationEventArgs^ e)
00035 {
00036     rootPage = MainPage::Current;
00037 }
00038
00039 void Globalization::ViewCurrentResources_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00040 {
00041   String^ language = ResourceManager::Current->DefaultContext->QualifierValues->Lookup("Language");
00042
00043   String^ scale = ResourceManager::Current->DefaultContext->QualifierValues->Lookup("Scale");
00044
00045   String^ contrast = ResourceManager::Current->DefaultContext->QualifierValues->Lookup("Contrast");
00046
00047   OutputTextBlock->Text = "Your system is currently set to the following values: Application Language: " + language + ", Scale: " + scale + ", Contrast: " + contrast + ". If using web images and AddImageQuery, the following query string would be appened to the URL: ?ms-lang=" + language + "&ms-scale=" + scale + "&ms-contrast=" + contrast;
00048 }
00049
00050 void Globalization::SendTileNotificationWithQueryStrings_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00051 {
00052   auto tileContent = TileContentFactory::CreateTileWideImageAndText01();
00053   tileContent->TextCaptionWrap->Text = "This tile notification uses web images";
00054
00055   tileContent->Image->Src = ImageUrl->Text;
00056   tileContent->Image->Alt = "Web image";
00057
00058   // enable AddImageQuery on the notification
00059     tileContent->AddImageQuery = true;
00060
00061   auto squareContent = TileContentFactory::CreateTileSquareImage();
00062
00063   squareContent->Image->Src = ImageUrl->Text;
00064   squareContent->Image->Alt = "Web image";
00065
00066   // include the square template.
00067   tileContent->SquareContent = squareContent;
00068
00069   // Send the notification to the app's application tile
00070   TileUpdateManager::CreateTileUpdaterForApplication()->Update(tileContent->CreateNotification());
00071
00072   OutputTextBlock->Text = tileContent->GetContent();
00073 }
00074
00075 void Globalization::SendTileNotificationImage_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00076 {
00077   String^ scale = ResourceManager::Current->DefaultContext->QualifierValues->Lookup("Scale");
00078
00079   auto tileContent = TileContentFactory::CreateTileWideSmallImageAndText03();
00080
00081   tileContent->TextBodyWrap->Text = "graySquare.png in the xml is actually graySquare.scale-" + scale + ".png";
00082   tileContent->Image->Src = "ms-appx:///graySquare.png";
00083   tileContent->Image->Alt = "Gray square";
00084
00085   auto squaretileContent = TileContentFactory::CreateTileSquareImage();
00086   squaretileContent->Image->Src = "ms-appx:///graySquare.png";
00087   squaretileContent->Image->Alt = "Gray square";
00088   tileContent->SquareContent = squaretileContent;
00089
00090   TileUpdateManager::CreateTileUpdaterForApplication()->Update(tileContent->CreateNotification());
00091
00092   OutputTextBlock->Text = tileContent->GetContent();
00093 }
00094
00095 void Globalization::SendTileNotificationText_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00096 {
00097   auto tileContent = TileContentFactory::CreateTileWideText03();
00098   // check out /en-US/resources.resw to understand where this string will come from
00099   tileContent->TextHeadingWrap->Text = "ms-resource:greeting";
00100
00101   auto squareContent = TileContentFactory::CreateTileSquareText04();
00102   // check out /en-US/resources.resw to understand where this string will come from
00103   squareContent->TextBodyWrap->Text = "ms-resource:greeting";
00104   tileContent->SquareContent = squareContent;
00105
00106   TileUpdateManager::CreateTileUpdaterForApplication()->Update(tileContent->CreateNotification());
00107
00108   OutputTextBlock->Text = tileContent->GetContent();
00109 }
Generated on Sat Nov 23 2024 16:07:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C#,C++/MediaExtensions/Polar/PolarEffect.h Source File

  • Media extensions
  • C#,C++
  • MediaExtensions
  • Polar

PolarEffect.h

Go to the documentation of this file.
00001 // Defines the transform class.
00002 //
00003 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00004 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00005 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00006 // PARTICULAR PURPOSE.
00007 //
00008 // Copyright (c) Microsoft Corporation. All rights reserved.
00009
00010 #ifndef POLAREFFECT_H
00011 #define POLAREFFECT_H
00012
00013 #include <new>
00014 #include <mfapi.h>
00015 #include <mftransform.h>
00016 #include <mfidl.h>
00017 #include <mferror.h>
00018 #include <strsafe.h>
00019 #include <assert.h>
00020 #include <math.h>
00021
00022 // Note: The Direct2D helper library is included for its 2D matrix operations.
00023 #include <D2d1helper.h>
00024
00025 #include <wrl\implements.h>
00026 #include <wrl\module.h>
00027 #include <windows.media.h>
00028 #include <wrl\wrappers\corewrappers.h>
00029
00030 #include "PolarTransform.h"
00031
00032 using namespace Microsoft::WRL;
00033 using namespace Microsoft::WRL::Wrappers;
00034
00035 void DllAddRef();
00036 void DllRelease();
00037
00038 template <class T> void SafeRelease(T **ppT)
00039 {
00040     if (*ppT)
00041     {
00042         (*ppT)->Release();
00043         *ppT = NULL;
00044     }
00045 }
00046
00047 template <class T> void SafeArrayDelete(T **ppT)
00048 {
00049     if (*ppT)
00050     {
00051         delete [] (*ppT);
00052         *ppT = NULL;
00053     }
00054 }
00055
00056
00057 // Function pointer for the function that transforms the image.
00058 typedef void (*IMAGE_TRANSFORM_FN)(
00059     const UINT32*           pLookup,         // Lookup buffer.
00060     BYTE*                   pDest,           // Destination buffer.
00061     LONG                    lDestStride,     // Destination stride.
00062     const BYTE*             pSrc,            // Source buffer.
00063     LONG                    lSrcStride,      // Source stride.
00064     DWORD                   dwWidthInPixels, // Image width in pixels.
00065     DWORD                   dwHeightInPixels // Image height in pixels.
00066     );
00067
00068 typedef DOUBLE (*PolarTransformer)(DOUBLE, DOUBLE, DOUBLE);
00069
00070
00071 // CPolarEffect class:
00072 // Implements a polar transformation video effect.
00073
00074 class CPolarEffect
00075     : public Microsoft::WRL::RuntimeClass<
00076            Microsoft::WRL::RuntimeClassFlags< Microsoft::WRL::RuntimeClassType::WinRtClassicComMix >,
00077            ABI::Windows::Media::IMediaExtension,
00078            IMFTransform >
00079 {
00080     InspectableClass(RuntimeClass_PolarTransform_PolarEffect,BaseTrust)
00081
00082 public:
00083     CPolarEffect();
00084
00085     ~CPolarEffect();
00086
00087     __forceinline static DOUBLE DefaultRadius(DOUBLE r, DOUBLE R, DOUBLE theta) { return r; }
00088     __forceinline static DOUBLE DefaultTheta(DOUBLE r, DOUBLE R, DOUBLE theta) { return theta; };
00089
00090     __forceinline static DOUBLE PinchRadius(DOUBLE r, DOUBLE R, DOUBLE theta) { return sqrt(r*R); };
00091     __forceinline static DOUBLE FisheyeRadius(DOUBLE r, DOUBLE R, DOUBLE theta) { return (r*r)/R; };
00092     __forceinline static DOUBLE WarpTheta(DOUBLE r, DOUBLE R, DOUBLE theta) { return theta + r / R; };
00093
00094     STDMETHOD(RuntimeClassInitialize)();
00095
00096     // IMediaExtension
00097     STDMETHODIMP SetProperties(ABI::Windows::Foundation::Collections::IPropertySet *pConfiguration);
00098
00099     // IMFTransform
00100     STDMETHODIMP GetStreamLimits(
00101         DWORD   *pdwInputMinimum,
00102         DWORD   *pdwInputMaximum,
00103         DWORD   *pdwOutputMinimum,
00104         DWORD   *pdwOutputMaximum
00105     );
00106
00107     STDMETHODIMP GetStreamCount(
00108         DWORD   *pcInputStreams,
00109         DWORD   *pcOutputStreams
00110     );
00111
00112     STDMETHODIMP GetStreamIDs(
00113         DWORD   dwInputIDArraySize,
00114         DWORD   *pdwInputIDs,
00115         DWORD   dwOutputIDArraySize,
00116         DWORD   *pdwOutputIDs
00117     );
00118
00119     STDMETHODIMP GetInputStreamInfo(
00120         DWORD                     dwInputStreamID,
00121         MFT_INPUT_STREAM_INFO *   pStreamInfo
00122     );
00123
00124     STDMETHODIMP GetOutputStreamInfo(
00125         DWORD                     dwOutputStreamID,
00126         MFT_OUTPUT_STREAM_INFO *  pStreamInfo
00127     );
00128
00129     STDMETHODIMP GetAttributes(IMFAttributes** pAttributes);
00130
00131     STDMETHODIMP GetInputStreamAttributes(
00132         DWORD           dwInputStreamID,
00133         IMFAttributes   **ppAttributes
00134     );
00135
00136     STDMETHODIMP GetOutputStreamAttributes(
00137         DWORD           dwOutputStreamID,
00138         IMFAttributes   **ppAttributes
00139     );
00140
00141     STDMETHODIMP DeleteInputStream(DWORD dwStreamID);
00142
00143     STDMETHODIMP AddInputStreams(
00144         DWORD   cStreams,
00145         DWORD   *adwStreamIDs
00146     );
00147
00148     STDMETHODIMP GetInputAvailableType(
00149         DWORD           dwInputStreamID,
00150         DWORD           dwTypeIndex, // 0-based
00151         IMFMediaType    **ppType
00152     );
00153
00154     STDMETHODIMP GetOutputAvailableType(
00155         DWORD           dwOutputStreamID,
00156         DWORD           dwTypeIndex, // 0-based
00157         IMFMediaType    **ppType
00158     );
00159
00160     STDMETHODIMP SetInputType(
00161         DWORD           dwInputStreamID,
00162         IMFMediaType    *pType,
00163         DWORD           dwFlags
00164     );
00165
00166     STDMETHODIMP SetOutputType(
00167         DWORD           dwOutputStreamID,
00168         IMFMediaType    *pType,
00169         DWORD           dwFlags
00170     );
00171
00172     STDMETHODIMP GetInputCurrentType(
00173         DWORD           dwInputStreamID,
00174         IMFMediaType    **ppType
00175     );
00176
00177     STDMETHODIMP GetOutputCurrentType(
00178         DWORD           dwOutputStreamID,
00179         IMFMediaType    **ppType
00180     );
00181
00182     STDMETHODIMP GetInputStatus(
00183         DWORD           dwInputStreamID,
00184         DWORD           *pdwFlags
00185     );
00186
00187     STDMETHODIMP GetOutputStatus(DWORD *pdwFlags);
00188
00189     STDMETHODIMP SetOutputBounds(
00190         LONGLONG        hnsLowerBound,
00191         LONGLONG        hnsUpperBound
00192     );
00193
00194     STDMETHODIMP ProcessEvent(
00195         DWORD              dwInputStreamID,
00196         IMFMediaEvent      *pEvent
00197     );
00198
00199     STDMETHODIMP ProcessMessage(
00200         MFT_MESSAGE_TYPE    eMessage,
00201         ULONG_PTR           ulParam
00202     );
00203
00204     STDMETHODIMP ProcessInput(
00205         DWORD               dwInputStreamID,
00206         IMFSample           *pSample,
00207         DWORD               dwFlags
00208     );
00209
00210     STDMETHODIMP ProcessOutput(
00211         DWORD                   dwFlags,
00212         DWORD                   cOutputBufferCount,
00213         MFT_OUTPUT_DATA_BUFFER  *pOutputSamples, // one per stream
00214         DWORD                   *pdwStatus
00215     );
00216
00217
00218 private:
00219     // HasPendingOutput: Returns TRUE if the MFT is holding an input sample.
00220     BOOL HasPendingOutput() const { return m_pSample != NULL; }
00221
00222     // IsValidInputStream: Returns TRUE if dwInputStreamID is a valid input stream identifier.
00223     BOOL IsValidInputStream(DWORD dwInputStreamID) const
00224     {
00225         return dwInputStreamID == 0;
00226     }
00227
00228     // IsValidOutputStream: Returns TRUE if dwOutputStreamID is a valid output stream identifier.
00229     BOOL IsValidOutputStream(DWORD dwOutputStreamID) const
00230     {
00231         return dwOutputStreamID == 0;
00232     }
00233
00234     HRESULT OnGetPartialType(DWORD dwTypeIndex, IMFMediaType **ppmt);
00235     HRESULT OnCheckInputType(IMFMediaType *pmt);
00236     HRESULT OnCheckOutputType(IMFMediaType *pmt);
00237     HRESULT OnCheckMediaType(IMFMediaType *pmt);
00238     void    OnSetInputType(IMFMediaType *pmt);
00239     void    OnSetOutputType(IMFMediaType *pmt);
00240     HRESULT BeginStreaming();
00241     HRESULT EndStreaming();
00242     HRESULT OnProcessOutput(IMFMediaBuffer *pIn, IMFMediaBuffer *pOut);
00243     HRESULT OnFlush();
00244     HRESULT UpdateFormatInfo();
00245     void GeneratePolarLookup( UINT32 unWidth,
00246                                    UINT32 unHeight,
00247                                    UINT32 *pIndexLookup );
00248
00249
00250     CRITICAL_SECTION            m_critSec;
00251
00252     // Streaming
00253     bool                        m_bStreamingInitialized;
00254     IMFSample                   *m_pSample;                 // Input sample.
00255     IMFMediaType                *m_pInputType;              // Input media type.
00256     IMFMediaType                *m_pOutputType;             // Output media type.
00257
00258     // Fomat information
00259     UINT32                      m_imageWidthInPixels;
00260     UINT32                      m_imageHeightInPixels;
00261     DWORD                       m_cbImageSize;              // Image size, in bytes.
00262
00263     IMFAttributes               *m_pAttributes;
00264
00265     // Image transform function. (Changes based on the media type.)
00266     IMAGE_TRANSFORM_FN          m_pTransformFn;
00267
00268     // Lookup table to store the result of polar transformation
00269     UINT32                      *m_pIndexLookup;
00270
00271     // Polar transform function for specific effect
00272     PolarTransformer            m_pRadiusTransformFn;       // Radius transformation
00273     PolarTransformer            m_pThetaTransformFn;        // Angle transformation
00274 };
00275
00276 #endif
Generated on Sat Nov 23 2024 16:08:21 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Date and time formatting/C++/OverrideSettings.xaml.cpp Source File

  • Date and time formatting

OverrideSettings.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 // OverrideSettings.xaml.cpp
00013 // Implementation of the OverrideSettings class
00014 //
00015
00016 #include "pch.h"
00017 #include "OverrideSettings.xaml.h"
00018
00019 using namespace SDKSample::DateTimeFormatting;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024 using namespace Platform;
00025 using namespace Windows::Foundation;
00026 using namespace Windows::Foundation::Collections;
00027 using namespace Windows::Globalization;
00028 using namespace Windows::Globalization::DateTimeFormatting;
00029
00030 OverrideSettings::OverrideSettings()
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 void OverrideSettings::OnNavigatedTo(NavigationEventArgs^ e)
00041 {
00042     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00043     // as NotifyUser()
00044     rootPage = MainPage::Current;
00045 }
00046
00047 void OverrideSettings::Display_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00048 {
00049   // This scenario uses the Windows.Globalization.DateTimeFormatting.DateTimeFormatter class
00050   // to format a date/time by using a formatter that provides specific languages,
00051   // geographic region, calendar and clock
00052
00053   //Get the current default application context language
00054   String^ currentLanguage = ApplicationLanguages::Languages->GetAt(0);
00055
00056     // Array languages used by the test
00057     auto ja = ref new Platform::Collections::Vector<String^>();
00058     ja->Append("ja-JP");
00059     auto fr = ref new Platform::Collections::Vector<String^>();
00060     fr->Append("fr-FR");
00061     auto de = ref new Platform::Collections::Vector<String^>();
00062     de->Append("de-DE");
00063
00064     // Formatters for dates and times
00065     Array<DateTimeFormatter^> ^dateFormatters = {
00066     ref new DateTimeFormatter("longdate", ja, "JP", CalendarIdentifiers::Japanese, ClockIdentifiers::TwelveHour),
00067
00068         ref new DateTimeFormatter("month day", fr, "FR", CalendarIdentifiers::Gregorian, ClockIdentifiers::TwentyFourHour),
00069
00070         ref new DateTimeFormatter(
00071       YearFormat::Abbreviated,
00072       MonthFormat::Abbreviated,
00073       DayFormat::Default,
00074       DayOfWeekFormat::None,
00075       HourFormat::None,
00076       MinuteFormat::None,
00077       SecondFormat::None,
00078       de, "DE", CalendarIdentifiers::Gregorian, ClockIdentifiers::TwelveHour),
00079
00080     ref new DateTimeFormatter("longtime", ja, "JP", CalendarIdentifiers::Japanese, ClockIdentifiers::TwelveHour),
00081
00082         ref new DateTimeFormatter("hour minute", fr, "FR", CalendarIdentifiers::Gregorian, ClockIdentifiers::TwentyFourHour),
00083
00084         ref new DateTimeFormatter(
00085       YearFormat::None,
00086       MonthFormat::None,
00087       DayFormat::None,
00088       DayOfWeekFormat::None,
00089       HourFormat::Default,
00090       MinuteFormat::Default,
00091       SecondFormat::None,
00092       de, "DE", CalendarIdentifiers::Gregorian, ClockIdentifiers::TwelveHour)
00093     };
00094
00095   // Obtain the date that will be formatted.
00096   Windows::Globalization::Calendar^ cal = ref new Windows::Globalization::Calendar();
00097     Windows::Foundation::DateTime dateToFormat = cal->GetDateTime();
00098
00099     // Keep the results here
00100     String^ results = "";
00101   results = results + "Current default application context language: " + currentLanguage + "\n\n";
00102
00103   // Generate the results.
00104     for (unsigned int i = 0; i < dateFormatters->Length; i++)
00105     {
00106         // Perform the actual formatting.
00107         try
00108         {
00109       results = results + dateFormatters[i]->Template + ": (" + dateFormatters[i]->ResolvedLanguage + ") " + dateFormatters[i]->Format(dateToFormat) + "\n";
00110         }
00111         catch(Platform::Exception^)
00112         {
00113             // Retrieve and display formatter properties.
00114             results = results + "Unable to format using formatter with template: " +
00115                 dateFormatters[i]->Template + ", language: " +
00116                 dateFormatters[i]->Languages->GetAt(0) + ", region: " +
00117                 dateFormatters[i]->GeographicRegion + ", calendar: " +
00118                 dateFormatters[i]->Calendar + ", clock:" +
00119                 dateFormatters[i]->Clock + "\n";
00120         }
00121     }
00122
00123   // Display the results.
00124     rootPage->NotifyUser(results, NotifyType::StatusMessage);
00125 }
Generated on Sat Nov 23 2024 16:08:02 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/Level3.cpp Source File

  • XAML DirectX 3D shooting game

Level3.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 "Level3.h"
00010 #include "Face.h"
00011 #include "Animate.h"
00012
00013 using namespace DirectX;
00014
00015 //----------------------------------------------------------------------
00016
00017 Level3::Level3()
00018 {
00019     m_timeLimit = 30.0f;
00020     m_objective = "Hit each of the moving targets before time runs out.";
00021 }
00022
00023 //----------------------------------------------------------------------
00024
00025 void Level3::Initialize(std::vector<GameObject^> objects)
00026 {
00027     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     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     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     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     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     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     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.begin(); object != objects.end(); object++)
00090     {
00091         if (Face^ target = dynamic_cast<Face^>(*object))
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(ref new AnimateLineListPosition(4, LineList1, 10.0f, true));
00103                     break;
00104                 case 1:
00105                     target->AnimatePosition(ref new AnimateLineListPosition(6, LineList2, 15.0f, true));
00106                     break;
00107                 case 2:
00108                     target->AnimatePosition(ref new AnimateLineListPosition(4, LineList3, 15.0f, true));
00109                     break;
00110                 case 3:
00111                     target->AnimatePosition(ref new AnimateLineListPosition(5, LineList4, 15.0f, true));
00112                     break;
00113                 case 4:
00114                     target->AnimatePosition(ref new AnimateLineListPosition(6, LineList5, 15.0f, true));
00115                     break;
00116                 case 5:
00117                     target->AnimatePosition(ref new AnimateLineListPosition(5, LineList6, 15.0f, true));
00118                     break;
00119                 case 6:
00120                     target->AnimatePosition(
00121                         ref new 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                         ref new 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                         ref new 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 }
00171
00172 //----------------------------------------------------------------------
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/CartoonizeImageView.xaml.cpp Source File

  • Hilo C++
  • Hilo

CartoonizeImageView.xaml.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 #include "CartoonizeImageView.xaml.h"
00009
00010 using namespace Hilo;
00011
00012 // See http://go.microsoft.com/fwlink/?LinkId=267278 for info on how Hilo creates pages and navigates to pages.
00013
00014 CartoonizeImageView::CartoonizeImageView()
00015 {
00016     InitializeComponent();
00017 }
00018
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::EAS::sealed Member List

This is the complete list of members for SDKSample::EAS::sealed, including all inherited members.
Launch_Click1(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::EAS::sealed | [private]
Launch_Click2(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::EAS::sealed | [private]
Launch_Click3(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::EAS::sealed | [private]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::EAS::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::EAS::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::EAS::sealed | [protected, virtual]
Reset_Click1(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::EAS::sealed | [private]
Reset_Click2(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::EAS::sealed | [private]
Reset_Click3(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::EAS::sealed | [private]
rootPage | SDKSample::EAS::sealed | [private]
Scenario1() | SDKSample::EAS::sealed |
Scenario2() | SDKSample::EAS::sealed |
Scenario3() | SDKSample::EAS::sealed |
Generated on Sat Nov 23 2024 16:09:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Secondary tiles/C#,C++/SecondaryTileNotification.xaml.h Source File

  • Secondary tiles
  • C#,C++

SecondaryTileNotification.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 // SecondaryTileNotification.xaml.h
00013 // Declaration of the SecondaryTileNotification class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "SecondaryTileNotification.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SecondaryTiles
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 SecondaryTileNotification sealed
00029     {
00030     public:
00031         SecondaryTileNotification();
00032
00033     protected:
00034        virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00035        virtual void OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^ e) override;
00036     private:
00037         MainPage^ rootPage;
00038         Windows::UI::Xaml::Controls::AppBar^ appBar;
00039         void PinLiveTile_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         void SendTileNotification_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         void SendBadgeNotification_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00042         void SendTileNotificationWithStringManipulation_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00043         void SendBadgeNotificationWithStringManipulation_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00044         void ToggleButtons(bool isEnabled);
00045     };
00046 }
Generated on Sat Nov 23 2024 16:08:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D-Direct2D interop/C++/SampleOverlay.cpp Source File

  • Direct3D-Direct2D interop

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 Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::UI::ViewManagement;
00015 using namespace Windows::Graphics::Display;
00016 using namespace D2D1;
00017
00018 SampleOverlay::SampleOverlay() :
00019     m_drawOverlay(true)
00020 {
00021 }
00022
00023 void SampleOverlay::Initialize(
00024     _In_ ID2D1Device*         d2dDevice,
00025     _In_ ID2D1DeviceContext*  d2dContext,
00026     _In_ IWICImagingFactory*  wicFactory,
00027     _In_ IDWriteFactory*      dwriteFactory,
00028     _In_ Platform::String^    caption
00029     )
00030 {
00031     m_wicFactory = wicFactory;
00032     m_dwriteFactory = dwriteFactory;
00033     m_sampleName = caption;
00034     m_d2dDevice = d2dDevice;
00035     m_d2dContext = d2dContext;
00036     m_padding = 3.0f;
00037     m_textVerticalOffset = 5.0f;
00038     m_logoSize = D2D1::SizeF(0.0f, 0.0f);
00039     m_overlayWidth = 0.0f;
00040
00041     ComPtr<ID2D1Factory> factory;
00042     d2dDevice->GetFactory(&factory);
00043
00044     DX::ThrowIfFailed(
00045         factory.As(&m_d2dFactory)
00046         );
00047
00048     ResetDirectXResources();
00049 }
00050
00051 void SampleOverlay::ResetDirectXResources()
00052 {
00053     DX::ThrowIfFailed(
00054         m_d2dContext->CreateSolidColorBrush(ColorF(ColorF::White), &m_whiteBrush)
00055         );
00056
00057     ComPtr<IWICBitmapDecoder> wicBitmapDecoder;
00058     DX::ThrowIfFailed(
00059         m_wicFactory->CreateDecoderFromFilename(
00060             L"windowsbig-sdk.png",
00061             nullptr,
00062             GENERIC_READ,
00063             WICDecodeMetadataCacheOnDemand,
00064             &wicBitmapDecoder
00065             )
00066         );
00067
00068     ComPtr<IWICBitmapFrameDecode> wicBitmapFrame;
00069     DX::ThrowIfFailed(
00070         wicBitmapDecoder->GetFrame(0, &wicBitmapFrame)
00071         );
00072
00073     ComPtr<IWICFormatConverter> wicFormatConverter;
00074     DX::ThrowIfFailed(
00075         m_wicFactory->CreateFormatConverter(&wicFormatConverter)
00076         );
00077
00078     DX::ThrowIfFailed(
00079         wicFormatConverter->Initialize(
00080             wicBitmapFrame.Get(),
00081             GUID_WICPixelFormat32bppPBGRA,
00082             WICBitmapDitherTypeNone,
00083             nullptr,
00084             0.0,
00085             WICBitmapPaletteTypeCustom  // the BGRA format has no palette so this value is ignored
00086             )
00087         );
00088
00089     double dpiX = 96.0f;
00090     double dpiY = 96.0f;
00091     DX::ThrowIfFailed(
00092         wicFormatConverter->GetResolution(&dpiX, &dpiY)
00093         );
00094
00095     DX::ThrowIfFailed(
00096         m_d2dContext->CreateBitmapFromWicBitmap(
00097             wicFormatConverter.Get(),
00098             BitmapProperties(
00099                 PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00100                 static_cast<float>(dpiX),
00101                 static_cast<float>(dpiY)
00102                 ),
00103             &m_logoBitmap
00104             )
00105         );
00106
00107     m_logoSize = m_logoBitmap->GetSize();
00108
00109     ComPtr<IDWriteTextFormat> nameTextFormat;
00110     DX::ThrowIfFailed(
00111         m_dwriteFactory->CreateTextFormat(
00112             L"Segoe UI",
00113             nullptr,
00114             DWRITE_FONT_WEIGHT_LIGHT,
00115             DWRITE_FONT_STYLE_NORMAL,
00116             DWRITE_FONT_STRETCH_NORMAL,
00117             36.0f,
00118             L"en-US",
00119             &nameTextFormat
00120             )
00121         );
00122
00123     DX::ThrowIfFailed(
00124         nameTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)
00125         );
00126
00127     DX::ThrowIfFailed(
00128         nameTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)
00129         );
00130
00131     DX::ThrowIfFailed(
00132         m_dwriteFactory->CreateTextLayout(
00133             m_sampleName->Data(),
00134             m_sampleName->Length(),
00135             nameTextFormat.Get(),
00136             4096.0f,
00137             4096.0f,
00138             &m_textLayout
00139             )
00140         );
00141
00142     DWRITE_TEXT_METRICS metrics = {0};
00143     DX::ThrowIfFailed(
00144         m_textLayout->GetMetrics(&metrics)
00145         );
00146
00147     m_overlayWidth = m_padding * 3.0f + m_logoSize.width + metrics.width;
00148
00149     DX::ThrowIfFailed(
00150         m_d2dFactory->CreateDrawingStateBlock(&m_stateBlock)
00151         );
00152
00153     UpdateForWindowSizeChange();
00154 }
00155
00156 void SampleOverlay::UpdateForWindowSizeChange()
00157 {
00158     if (CoreWindow::GetForCurrentThread()->Bounds.Width < m_overlayWidth)
00159     {
00160         m_drawOverlay = false;
00161     }
00162     else
00163     {
00164         m_drawOverlay = true;
00165     }
00166 }
00167
00168 void SampleOverlay::Render()
00169 {
00170     if (m_drawOverlay)
00171     {
00172         m_d2dContext->SaveDrawingState(m_stateBlock.Get());
00173
00174         m_d2dContext->BeginDraw();
00175         m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00176         m_d2dContext->DrawBitmap(
00177             m_logoBitmap.Get(),
00178             D2D1::RectF(m_padding, 0.0f, m_logoSize.width + m_padding, m_logoSize.height)
00179             );
00180
00181         m_d2dContext->DrawTextLayout(
00182             Point2F(m_logoSize.width + 2.0f * m_padding, m_textVerticalOffset),
00183             m_textLayout.Get(),
00184             m_whiteBrush.Get()
00185             );
00186
00187         // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00188         // is lost. It will be handled during the next call to Present.
00189         HRESULT hr = m_d2dContext->EndDraw();
00190         if (hr != D2DERR_RECREATE_TARGET)
00191         {
00192             DX::ThrowIfFailed(hr);
00193         }
00194
00195         m_d2dContext->RestoreDrawingState(m_stateBlock.Get());
00196     }
00197 }
00198
00199 float SampleOverlay::GetTitleHeightInDips()
00200 {
00201     return m_logoSize.height;
00202 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: USSD message management/C++/RequestResponse.xaml.cpp Source File

  • USSD message management

RequestResponse.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 // RequestResponse.xaml.cpp
00013 // Implementation of the RequestResponse class
00014 //
00015
00016 #include "pch.h"
00017 #include "RequestResponse.xaml.h"
00018
00019 using namespace concurrency;
00020 using namespace Platform;
00021 using namespace Windows::Networking::NetworkOperators;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Navigation;
00025 using namespace SDKSample::UssdApi;
00026
00027 RequestResponse::RequestResponse()
00028 {
00029     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 void RequestResponse::OnNavigatedTo(NavigationEventArgs^ e)
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     rootPage = MainPage::Current;
00042 }
00043
00044 /// <summary>
00045 /// This is the click handler for the 'SendButton' button.
00046 /// </summary>
00047 /// <param name="sender"></param>
00048 /// <param name="e"></param>
00049 void SDKSample::UssdApi::RequestResponse::SendButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00050 {
00051     // Verify the USSD message text.
00052     if (MessageText->Text == L"")
00053     {
00054         rootPage->NotifyUser("Message cannot be empty", NotifyType::ErrorMessage);
00055         return;
00056     }
00057
00058     try
00059     {
00060         // Get the network account ID.
00061         auto networkAccIds = MobileBroadbandAccount::AvailableNetworkAccountIds;
00062         if (networkAccIds->Size == 0)
00063         {
00064             rootPage->NotifyUser("No network account ID found", NotifyType::ErrorMessage);
00065             return;
00066         }
00067         // For the sake of simplicity, assume we want to use the first account.
00068         // Refer to the MobileBroadbandAccount API's for how to select a specific account ID.
00069         auto networkAccountId = networkAccIds->GetAt(0);
00070
00071         SendButton->IsEnabled = false;
00072         rootPage->NotifyUser("Sending USSD request", NotifyType::StatusMessage);
00073
00074         // Create a USSD session for the specified network acccount ID.
00075         auto ussdSession = UssdSession::CreateFromNetworkAccountId(networkAccountId);
00076
00077         // Create a USSD message to be send to the network. This message is specific to
00078         // the network operator.
00079         auto message = ref new UssdMessage(MessageText->Text);
00080
00081         // Execute asynchronous operation as task
00082         task<UssdReply^> getUssdReply(ussdSession->SendMessageAndGetReplyAsync(message));
00083         getUssdReply.then([=](task<UssdReply^> replyTask)
00084         {
00085             try
00086             {
00087                 // Get will throw an exception if the task failed with an error.
00088                 auto reply = replyTask.get();
00089                 auto code = reply->ResultCode;
00090                 if (code == UssdResultCode::ActionRequired || code == UssdResultCode::NoActionRequired)
00091                 {
00092                     // If the actionRequired or noActionRequired ResultCode is returned, the reply contains
00093                     // a message from the network.
00094                     auto replyMessage = reply->Message;
00095                     auto payloadAsText = replyMessage->PayloadAsText;
00096                     if (payloadAsText != "")
00097                     {
00098                         // The message may be sent using various encodings. If Windows supports
00099                         // the encoding, the message can be accessed as text and will not be empty.
00100                         // Therefore, the test for an empty string is sufficient.
00101                         rootPage->NotifyUser("Response: " + payloadAsText, NotifyType::StatusMessage);
00102                     }
00103                     else
00104                     {
00105                         // If Windows does not support the encoding, the application may check
00106                         // the DataCodingScheme used for encoding and access the raw message
00107                         // through replyMessage->GetPayload()
00108                         wchar_t buf[100];
00109                         HRESULT hr = StringCchPrintf(buf, ARRAYSIZE(buf), L"Unsupported data coding scheme 0x%x", replyMessage->DataCodingScheme);
00110                         if (FAILED(hr))
00111                         {
00112                             throw Exception::CreateException(hr);
00113                         }
00114                         String^ s = ref new String(buf);
00115                         rootPage->NotifyUser(s, NotifyType::StatusMessage);
00116                     }
00117                 }
00118                 else
00119                 {
00120                     rootPage->NotifyUser("No response message", NotifyType::StatusMessage);
00121                 }
00122                 if (code == UssdResultCode::ActionRequired)
00123                 {
00124                     ussdSession->Close(); // Close the session from our end
00125                 }
00126             }
00127             catch (Platform::Exception^ ex)
00128             {
00129                 // Handle errors
00130                 rootPage->NotifyUser("An unexpected exception occured: " + ex->Message, NotifyType::ErrorMessage);
00131             }
00132             SendButton->IsEnabled = true;
00133         });
00134     }
00135     catch (Exception^ ex)
00136     {
00137         rootPage->NotifyUser("An unexpected exception occured: " + ex->Message, NotifyType::ErrorMessage);
00138         SendButton->IsEnabled = true;
00139     }
00140 }
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Network information/C++/common/LayoutAwarePage.h Source File

  • Network information
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Globalization preferences/C++/MainPage.xaml.cpp Source File

  • Globalization preferences

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:42 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Context menu/C++/MainPage.xaml.h Source File

  • Context menu

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Secondary tiles/C#,C++/UpdateAsync.xaml.h Source File

  • Secondary tiles
  • C#,C++

UpdateAsync.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 // UpdateAsync.xaml.h
00013 // Declaration of the UpdateAsync class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "UpdateAsync.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SecondaryTiles
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 UpdateAsync sealed
00029     {
00030     public:
00031         UpdateAsync();
00032
00033     protected:
00034         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00035         virtual void OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^ e) override;
00036     private:
00037         MainPage^ rootPage;
00038         Windows::UI::Xaml::Controls::AppBar^ appBar;
00039         void UpdateDefaultLogo_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040     };
00041 }
Generated on Sat Nov 23 2024 16:08:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: HttpClient/C++/MainPage.xaml.h Source File

  • HttpClient

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:46 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX postcard app/C++/DirectXSample.h Source File

  • DirectX postcard app

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
00010 // This header defines helper utilities to make DirectX APIs work with exceptions.
00011 namespace DX
00012 {
00013     inline void ThrowIfFailed(HRESULT hr)
00014     {
00015         if (FAILED(hr))
00016         {
00017             // Set a breakpoint on this line to catch DX API errors.
00018             throw Platform::Exception::CreateException(hr);
00019         }
00020     }
00021 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Audio Session (WASAPI)/C++/App.xaml.h Source File

  • Windows Audio Session (WASAPI)
  • C++

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application resources and localization/C++/Scenario6.xaml.cpp Source File

  • Application resources and localization

Scenario6.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.xaml.cpp
00013 // Implementation of the Scenario6 class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario6.xaml.h"
00018
00019 using namespace SDKSample::ApplicationResources;
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 using namespace AppResourceClassLibrary;
00026
00027 Scenario6::Scenario6()
00028 {
00029     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 void Scenario6::OnNavigatedTo(NavigationEventArgs^ e)
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     rootPage = MainPage::Current;
00042 }
00043
00044 void Scenario6::Scenario6Button_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 = ref new ResourceLoader("AppResourceClassLibrary/Resources");
00050         this->Scenario6TextBlock->Text = "Retrieved from app: " + resourceLoader->GetString("string1");
00051
00052     auto lib = ref new AppResourceClassLibrary::Class1();
00053     this->Scenario6TextBlock2->Text = "Retrieved from class library: " + lib->GetString();
00054     }
00055 }
00056
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Display orientation/C++/Scenario2.xaml.h Source File

  • Display orientation

Scenario2.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.xaml.h
00013 // Declaration of the Scenario2 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario2.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace DisplayOrientation
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 sealed
00031         {
00032         public:
00033             Scenario2();
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             void Scenario2Button_Click(
00041                 Platform::Object^ sender,
00042                 Windows::UI::Xaml::RoutedEventArgs^ e
00043                 );
00044
00045             void CalculateDeviceRotation(
00046                 Windows::Devices::Sensors::Accelerometer^ sender,
00047                 Windows::Devices::Sensors::AccelerometerReadingChangedEventArgs^ args
00048                 );
00049
00050             void UpdateArrowForRotation();
00051
00052             double rotationAngle;
00053             Windows::Devices::Sensors::Accelerometer^ accelerometer;
00054             Windows::Foundation::EventRegistrationToken readingChangedEventToken;
00055         };
00056     }
00057 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Search contract/C++/MainPage.xaml.cpp Source File

  • Search contract

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     LayoutRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160 }
00161
00162 /// <summary>
00163 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00164 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00165 /// and output sections into the respective UserControl on the main page.
00166 /// </summary>
00167 /// <param name="scenarioName"></param>
00168 void MainPage::LoadScenario(String^ scenarioName)
00169 {
00170     autoSizeInputSectionWhenSnapped = true;
00171
00172     // Load the ScenarioX.xaml file into the Frame.
00173     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00174     HiddenFrame->Navigate(scenarioType, this);
00175
00176     // Get the top element, the Page, so we can look up the elements
00177     // that represent the input and output sections of the ScenarioX file.
00178     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00179
00180     // Get each element.
00181     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00182     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00183
00184     if (input == nullptr)
00185     {
00186         // Malformed input section.
00187         NotifyUser("Cannot load scenario input section for " + scenarioName +
00188             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00189         return;
00190     }
00191
00192     if (output == nullptr)
00193     {
00194         // Malformed output section.
00195         NotifyUser("Cannot load scenario output section for " + scenarioName +
00196             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00197         return;
00198     }
00199
00200     // Find the LayoutRoot which parents the input and output sections in the main page.
00201     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00202
00203     if (panel != nullptr)
00204     {
00205         unsigned int index = 0;
00206         UIElementCollection^ collection = panel->Children;
00207
00208         // Get rid of the content that is currently in the intput and output sections.
00209         collection->IndexOf(input, &index);
00210         collection->RemoveAt(index);
00211
00212         collection->IndexOf(output, &index);
00213         collection->RemoveAt(index);
00214
00215         // Populate the input and output sections with the newly loaded content.
00216         InputSection->Content = input;
00217         OutputSection->Content = output;
00218
00219         ScenarioLoaded(this, nullptr);
00220     }
00221     else
00222     {
00223         // Malformed Scenario file.
00224         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00225             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00226     }
00227 }
00228
00229 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00230 {
00231     if (Scenarios->SelectedItem != nullptr)
00232     {
00233         NotifyUser("", NotifyType::StatusMessage);
00234
00235         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00236         InvalidateSize();
00237     }
00238 }
00239
00240 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00241 {
00242     switch (type)
00243     {
00244     case NotifyType::StatusMessage:
00245         // Use the status message style.
00246         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00247         break;
00248     case NotifyType::ErrorMessage:
00249         // Use the error message style.
00250         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00251         break;
00252     default:
00253         break;
00254     }
00255     StatusBlock->Text = strMessage;
00256
00257     // Collapsed the StatusBlock if it has no text to conserve real estate.
00258     if (StatusBlock->Text != "")
00259     {
00260         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00261     }
00262     else
00263     {
00264         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00265     }
00266 }
00267
00268 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00271     Windows::System::Launcher::LaunchUriAsync(uri);
00272 }
00273
00274
00275 /// <summary>
00276 /// Populates the page with content passed during navigation.  Any saved state is also
00277 /// provided when recreating a page from a prior session.
00278 /// </summary>
00279 /// <param name="navigationParameter">The parameter value passed to
00280 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00281 /// </param>
00282 /// <param name="pageState">A map of state preserved by this page during an earlier
00283 /// session.  This will be null the first time a page is visited.</param>
00284 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00285 {
00286     (void) navigationParameter;    // Unused parameter
00287
00288     PopulateScenarios();
00289
00290     // Starting scenario is the first or based upon a previous state.
00291     ListBoxItem^ startingScenario = nullptr;
00292     int startingScenarioIndex = -1;
00293
00294     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00295     {
00296         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00297     }
00298
00299     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00300
00301     InvalidateViewState();
00302 }
00303
00304 /// <summary>
00305 /// Preserves state associated with this page in case the application is suspended or the
00306 /// page is discarded from the navigation cache.  Values must conform to the serialization
00307 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00308 /// </summary>
00309 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00310 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00311 {
00312     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00313     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00314 }
Generated on Sat Nov 23 2024 16:07:43 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Credential picker/C++/ScenarioList.xaml.h Source File

  • Credential picker

ScenarioList.xaml.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 //
00009 // ScenarioList.xaml.h
00010 // Declaration of the ScenarioList class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioList.g.h"
00017 #include "MainPage.g.h"
00018
00019 namespace CredentialPickerCPP
00020 {
00021   [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class ScenarioList sealed
00023     {
00024     public:
00025         ScenarioList();
00026
00027     protected:
00028         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00029         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030
00031     private:
00032         ~ScenarioList();
00033
00034         MainPage^ rootPage;
00035     };
00036 }
Generated on Sat Nov 23 2024 16:07:57 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Portable device API/C++/pch.h Source File

  • Portable device API

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <windows.h>
00019 #include <vector>
00020 #include <memory>
00021 #include <collection.h>
00022 #include <shcore.h>
00023 #include <wrl\client.h>
00024 #include <PortableDevice.h>
00025 #include <PortableDeviceApi.h>
00026 #include <PortableDeviceTypes.h>
00027 #include <ppltasks.h>
00028
00029 #include "Common\LayoutAwarePage.h"
00030 #include "Common\SuspensionManager.h"
00031 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C#,C++/Sample-Utils/Constants.cs Source File

  • Media extensions
  • C#,C++
  • Sample-Utils

Constants.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 System;
00009 using System.Collections.Generic;
00010 using System.Linq;
00011 using System.Text;
00012 using System.Threading.Tasks;
00013
00014 namespace SDKTemplateCS
00015 {
00016     public partial class MainPage
00017     {
00018         public const string FEATURE_NAME = "Media Extensions";
00019     }
00020 }
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playback Manager Companion/C++/common/suspensionmanager.h Source File

  • Playback Manager Companion
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Sharing content source app/C++/ShareHtml.xaml.cpp Source File

  • Sharing content source app

ShareHtml.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 // ShareHtml.xaml.cpp
00013 // Implementation of the ShareHtml class
00014 //
00015
00016 #include "pch.h"
00017 #include "ShareHtml.xaml.h"
00018
00019 using namespace SDKSample::ShareSource;
00020 using namespace SDKSample::Common;
00021
00022 using namespace Platform;
00023 using namespace Windows::ApplicationModel::DataTransfer;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Windows::UI::Xaml;
00027 using namespace Windows::UI::Xaml::Controls;
00028 using namespace Windows::UI::Xaml::Navigation;
00029
00030 ShareHtml::ShareHtml()
00031 {
00032     InitializeComponent();
00033     ShareWebView->Navigate(ref new Uri("http://msdn.microsoft.com"));
00034 }
00035
00036 void ShareHtml::ShareWebView_LoadCompleted(Object^ sender, NavigationEventArgs^ e)
00037 {
00038     ShareWebView->Visibility = Windows::UI::Xaml::Visibility::Visible;
00039     BlockingRect->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00040     LoadingProgressRing->IsActive = false;
00041 }
00042
00043 bool ShareHtml::GetShareContent(DataRequest^ request)
00044 {
00045     bool succeeded = false;
00046
00047     // Get the user's selection from the WebView.
00048     auto requestData = ShareWebView->DataTransferPackage;
00049     auto dataPackageView = requestData->GetView();
00050
00051     if ((dataPackageView != nullptr) && (dataPackageView->AvailableFormats->Size > 0))
00052     {
00053         requestData->Properties->Title = "A web snippet for you";
00054         requestData->Properties->Description = "HTML selection from a WebView control"; // The description is optional.
00055         request->Data = requestData;
00056         succeeded = true;
00057     }
00058     else
00059     {
00060         request->FailWithDisplayText("Make a selection in the WebView control and try again.");
00061     }
00062     return succeeded;
00063 }
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML WebView control/C++/Scenario5.xaml.h Source File

  • XAML WebView control

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 SDKSample
00023 {
00024     namespace WebViewControl
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 Scenario5 sealed
00031         {
00032         public:
00033             Scenario5();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040             void Other_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         void WebView5_LoadCompleted(Platform::Object^ sender, Windows::UI::Xaml::Navigation::NavigationEventArgs^ e);
00042         void WebView5_ScriptNotify(Platform::Object^ sender, Windows::UI::Xaml::Controls::NotifyEventArgs^ e);
00043       };
00044     }
00045 }
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-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 |
key | PersistentState |
LoadBool(Platform::String^key, bool defaultValue) | PersistentState |
LoadBool(Platform::String^key, bool defaultValue) | PersistentState |
LoadBool(Platform::String^key, bool defaultValue) | PersistentState |
LoadBool(Platform::String^key, bool defaultValue) | PersistentState |
LoadInt32(Platform::String^key, int defaultValue) | PersistentState |
LoadInt32(Platform::String^key, int defaultValue) | PersistentState |
LoadInt32(Platform::String^key, int defaultValue) | PersistentState |
LoadInt32(Platform::String^key, int defaultValue) | PersistentState |
LoadSingle(Platform::String^key, float defaultValue) | PersistentState |
LoadSingle(Platform::String^key, float defaultValue) | PersistentState |
LoadSingle(Platform::String^key, float defaultValue) | PersistentState |
LoadSingle(Platform::String^key, float defaultValue) | PersistentState |
LoadString(Platform::String^key, Platform::String^defaultValue) | PersistentState |
LoadString(Platform::String^key, Platform::String^defaultValue) | PersistentState |
LoadString(Platform::String^key, Platform::String^defaultValue) | PersistentState |
LoadString(Platform::String^key, Platform::String^defaultValue) | PersistentState |
LoadXMFLOAT3(Platform::String^key, DirectX::XMFLOAT3 defaultValue) | PersistentState |
LoadXMFLOAT3(Platform::String^key, DirectX::XMFLOAT3 defaultValue) | PersistentState |
LoadXMFLOAT3(Platform::String^key, DirectX::XMFLOAT3 defaultValue) | PersistentState |
LoadXMFLOAT3(Platform::String^key, DirectX::XMFLOAT3 defaultValue) | PersistentState |
m_keyName | PersistentState | [private]
m_settingsValues | PersistentState | [private]
SaveBool(Platform::String^key, bool value) | PersistentState |
SaveBool(Platform::String^key, bool value) | PersistentState |
SaveBool(Platform::String^key, bool value) | PersistentState |
SaveBool(Platform::String^key, bool value) | PersistentState |
SaveInt32(Platform::String^key, int value) | PersistentState |
SaveInt32(Platform::String^key, int value) | PersistentState |
SaveInt32(Platform::String^key, int value) | PersistentState |
SaveInt32(Platform::String^key, int value) | PersistentState |
SaveSingle(Platform::String^key, float value) | PersistentState |
SaveSingle(Platform::String^key, float value) | PersistentState |
SaveSingle(Platform::String^key, float value) | PersistentState |
SaveSingle(Platform::String^key, float value) | PersistentState |
SaveString(Platform::String^key, Platform::String^string) | PersistentState |
SaveString(Platform::String^key, Platform::String^string) | PersistentState |
SaveString(Platform::String^key, Platform::String^string) | PersistentState |
SaveString(Platform::String^key, Platform::String^string) | PersistentState |
SaveXMFLOAT3(Platform::String^key, DirectX::XMFLOAT3 value) | PersistentState |
SaveXMFLOAT3(Platform::String^key, DirectX::XMFLOAT3 value) | PersistentState |
SaveXMFLOAT3(Platform::String^key, DirectX::XMFLOAT3 value) | PersistentState |
SaveXMFLOAT3(Platform::String^key, DirectX::XMFLOAT3 value) | PersistentState |
Generated on Sat Nov 23 2024 16:09:19 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML data binding/C++/Constants.cpp Source File

  • XAML data binding

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019   // The format here is the following:
00020   //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
00021   { "Binding modes", "SDKSample.DataBinding.Scenario1" },
00022   { "Value converters", "SDKSample.DataBinding.Scenario2" },
00023   { "Binding to a model", "SDKSample.DataBinding.Scenario3" },
00024   { "Indexers", "SDKSample.DataBinding.Scenario4" },
00025   { "Data templates", "SDKSample.DataBinding.Scenario5" },
00026   { "CollectionViewSource", "SDKSample.DataBinding.Scenario6" },
00027   { "Collection changes", "SDKSample.DataBinding.Scenario7" },
00028   { "Incremental Loading", "SDKSample.DataBinding.Scenario8" }
00029 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File picker contracts/C++/FileOpenPickerPage.xaml.cpp Source File

  • File picker contracts

FileOpenPickerPage.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 // FileOpenPickerPage.xaml.cpp
00013 // Implementation of the FileOpenPickerPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "FileOpenPickerPage.xaml.h"
00018 #include "Constants.h"
00019 #include "App.xaml.h"
00020 #include <collection.h>
00021
00022 using namespace SDKSample;
00023 using namespace SDKSample::Common;
00024 using namespace SDKSample::FilePickerContracts;
00025 using namespace Platform;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Graphics::Display;
00030 using namespace Windows::UI::ViewManagement;
00031 using namespace Windows::UI::Xaml;
00032 using namespace Windows::UI::Xaml::Controls;
00033 using namespace Windows::UI::Xaml::Interop;
00034 using namespace Windows::UI::Xaml::Navigation;
00035
00036 FileOpenPickerPage^ FileOpenPickerPage::Current = nullptr;
00037
00038 FileOpenPickerPage::FileOpenPickerPage()
00039 {
00040     InitializeComponent();
00041
00042     // This frame is hidden, meaning it is never shown.  It is simply used to load
00043     // each scenario page and then pluck out the input and output sections and
00044     // place them into the UserControls on the main page.
00045     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00046     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00047     LayoutRoot->Children->Append(HiddenFrame);
00048
00049     FeatureName->Text = FEATURE_NAME;
00050
00051     this->SizeChanged += ref new SizeChangedEventHandler(this, &FileOpenPickerPage::FileOpenPickerPage_SizeChanged);
00052     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &FileOpenPickerPage::Scenarios_SelectionChanged);
00053
00054     FileOpenPickerPage::Current = this;
00055     autoSizeInputSectionWhenSnapped = true;
00056 }
00057
00058 /// <summary>
00059 /// We need to handle SizeChanged so that we can make the sample layout property
00060 /// in the various layouts.
00061 /// </summary>
00062 /// <param name="sender"></param>
00063 /// <param name="e"></param>
00064 void FileOpenPickerPage::FileOpenPickerPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00065 {
00066     InvalidateSize();
00067     PageSizeChangedEventArgs^ args = ref new PageSizeChangedEventArgs();
00068     args->ViewState = ApplicationView::Value;
00069     PageResized(this, args);
00070 }
00071
00072 void FileOpenPickerPage::InvalidateSize()
00073 {
00074     // Get the window width
00075     double windowWidth = this->ActualWidth;
00076
00077     if (windowWidth != 0.0)
00078     {
00079         // Get the width of the ListBox.
00080         double listBoxWidth = Scenarios->ActualWidth;
00081
00082         // Is the ListBox using any margins that we need to consider?
00083         double listBoxMarginLeft = Scenarios->Margin.Left;
00084         double listBoxMarginRight = Scenarios->Margin.Right;
00085
00086         // Figure out how much room is left after considering the list box width
00087         double availableWidth = windowWidth - listBoxWidth;
00088
00089         // Is the top most child using margins?
00090         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00091         double layoutRootMarginRight = ContentRoot->Margin.Right;
00092
00093         // We have different widths to use depending on the view state
00094         if (ApplicationView::Value != ApplicationViewState::Snapped)
00095         {
00096             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00097             // and the LayoutRoot's margins
00098             InputSection->Width = ((availableWidth) -
00099                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00100         }
00101         else
00102         {
00103             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00104             if (autoSizeInputSectionWhenSnapped)
00105             {
00106                 InputSection->Width = windowWidth - (layoutRootMarginLeft + layoutRootMarginRight);
00107             }
00108         }
00109     }
00110     InvalidateViewState();
00111 }
00112
00113 void FileOpenPickerPage::InvalidateViewState()
00114 {
00115     // Are we going to snapped mode?
00116     if (ApplicationView::Value == ApplicationViewState::Snapped)
00117     {
00118         Grid::SetRow(DescriptionText, 3);
00119         Grid::SetColumn(DescriptionText, 0);
00120
00121         Grid::SetRow(InputSection, 4);
00122         Grid::SetColumn(InputSection, 0);
00123
00124         Grid::SetRow(FooterPanel, 2);
00125         Grid::SetColumn(FooterPanel, 0);
00126     }
00127     else
00128     {
00129         Grid::SetRow(DescriptionText, 1);
00130         Grid::SetColumn(DescriptionText, 1);
00131
00132         Grid::SetRow(InputSection, 2);
00133         Grid::SetColumn(InputSection, 1);
00134
00135         Grid::SetRow(FooterPanel, 1);
00136         Grid::SetColumn(FooterPanel, 1);
00137     }
00138
00139     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00140     // input and output sections from the page) we need to ensure that any VSM code used
00141     // by the scenario's input and output sections is fired.
00142     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00143     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00144 }
00145
00146 void FileOpenPickerPage::PopulateScenarios()
00147 {
00148     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00149
00150     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00151     for (unsigned int i = 0; i < scenarios->Length; ++i)
00152     {
00153         Scenario s = scenarios[i];
00154         ListBoxItem^ item = ref new ListBoxItem();
00155         item->Name = s.ClassName;
00156         item->Content = (i + 1).ToString() + ") " + s.Title;
00157         ScenarioList->Append(item);
00158     }
00159
00160     // Bind the ListBox to the scenario list.
00161     Scenarios->ItemsSource = ScenarioList;
00162 }
00163
00164 /// <summary>
00165 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00166 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00167 /// and output sections into the respective UserControl on the main page.
00168 /// </summary>
00169 /// <param name="scenarioName"></param>
00170 void FileOpenPickerPage::LoadScenario(String^ scenarioName)
00171 {
00172     autoSizeInputSectionWhenSnapped = true;
00173
00174     // Load the ScenarioX.xaml file into the Frame.
00175     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00176     HiddenFrame->Navigate(scenarioType, this);
00177
00178     // Get the top element, the Page, so we can look up the elements
00179     // that represent the input and output sections of the ScenarioX file.
00180     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00181
00182     // Get each element.
00183     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00184     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00185
00186     if (input == nullptr)
00187     {
00188         // Malformed input section.
00189         NotifyUser("Cannot load scenario input section for " + scenarioName +
00190             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00191         return;
00192     }
00193
00194     if (output == nullptr)
00195     {
00196         // Malformed output section.
00197         NotifyUser("Cannot load scenario output section for " + scenarioName +
00198             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00199         return;
00200     }
00201
00202     // Find the LayoutRoot which parents the input and output sections in the main page.
00203     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00204
00205     if (panel != nullptr)
00206     {
00207         unsigned int index = 0;
00208         UIElementCollection^ collection = panel->Children;
00209
00210         // Get rid of the content that is currently in the intput and output sections.
00211         collection->IndexOf(input, &index);
00212         collection->RemoveAt(index);
00213
00214         collection->IndexOf(output, &index);
00215         collection->RemoveAt(index);
00216
00217         // Populate the input and output sections with the newly loaded content.
00218         InputSection->Content = input;
00219         OutputSection->Content = output;
00220
00221         ScenarioLoaded(this, nullptr);
00222     }
00223     else
00224     {
00225         // Malformed Scenario file.
00226         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00227             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00228     }
00229 }
00230
00231 void FileOpenPickerPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00232 {
00233     if (Scenarios->SelectedItem != nullptr)
00234     {
00235         NotifyUser("", NotifyType::StatusMessage);
00236
00237         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00238         InvalidateSize();
00239     }
00240 }
00241
00242 void FileOpenPickerPage::NotifyUser(String^ strMessage, NotifyType type)
00243 {
00244     switch (type)
00245     {
00246     case NotifyType::StatusMessage:
00247         // Use the status message style.
00248         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00249         break;
00250     case NotifyType::ErrorMessage:
00251         // Use the error message style.
00252         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00253         break;
00254     default:
00255         break;
00256     }
00257     StatusBlock->Text = strMessage;
00258
00259     // Collapsed the StatusBlock if it has no text to conserve real estate.
00260     if (StatusBlock->Text != "")
00261     {
00262         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00263     }
00264     else
00265     {
00266         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00267     }
00268 }
00269
00270 void FileOpenPickerPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00271 {
00272     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00273     Windows::System::Launcher::LaunchUriAsync(uri);
00274 }
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void FileOpenPickerPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void FileOpenPickerPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
00316
00317 bool FileOpenPickerPage::EnsureUnsnapped()
00318 {
00319     // FilePicker APIs will not work if the application is in a snapped state.
00320     // If an app wants to show a FilePicker while snapped, it must attempt to unsnap first
00321     bool unsnapped = ((ApplicationView::Value != ApplicationViewState::Snapped) || ApplicationView::TryUnsnap());
00322     if (!unsnapped)
00323     {
00324         NotifyUser("Cannot unsnap the sample application", NotifyType::StatusMessage);
00325     }
00326
00327     return unsnapped;
00328 }
00329
00330 void FileOpenPickerPage::Activate(FileOpenPickerActivatedEventArgs^ args)
00331 {
00332     // cache FileOpenPickerUI
00333     fileOpenPickerUI = args->FileOpenPickerUI;
00334     Window::Current->Content = this;
00335     LoadState(nullptr, nullptr);
00336     Window::Current->Activate();
00337 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Programmatic file search/C++/common/LayoutAwarePage.cpp Source File

  • Programmatic file search
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:32 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML vector-based drawing/C++/Constants.h Source File

  • XAML vector-based drawing

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026     static Windows::UI::Color ConvertIndexToColor(int index)
00027     {
00028       // Converts between ComboBox indices and colors
00029         switch (index)
00030         {
00031           case 0:
00032             return Windows::UI::Colors::Red;
00033           case 1:
00034             return Windows::UI::Colors::Green;
00035           case 2:
00036             return Windows::UI::Colors::Blue;
00037           case 3:
00038             return Windows::UI::Colors::Gray;
00039           default:
00040             return Windows::UI::Colors::White;
00041         }
00042     }
00043         static property Platform::String^ FEATURE_NAME
00044         {
00045             Platform::String^ get()
00046             {
00047                 return ref new Platform::String(L"XAML Drawing Sample");
00048             }
00049         }
00050
00051         static property Platform::Array<Scenario>^ scenarios
00052         {
00053             Platform::Array<Scenario>^ get()
00054             {
00055                 return scenariosInner;
00056             }
00057         }
00058     private:
00059         static Platform::Array<Scenario>^ scenariosInner;
00060     };
00061 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/BasicCamera.h Source File

  • Direct3D resource loading

BasicCamera.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 camera class.
00011 ref class BasicCamera
00012 {
00013
00014 private:
00015     float3 m_position;      // the position of the camera
00016     float3 m_direction;     // the unit vector of the viewing direction
00017     float4x4 m_view;        // view matrix
00018     float4x4 m_projection;  // projection matrix
00019
00020 internal:
00021     void GetViewMatrix(_Out_ float4x4 *viewMatrix);
00022     void GetProjectionMatrix(_Out_ float4x4 *projectionMatrix);
00023
00024     // this method updates the view matrix based on new position and focus coordinates
00025     void SetViewParameters(
00026         _In_ float3 eyePosition,    // the position of the camera
00027         _In_ float3 lookPosition,   // the point the camera should look at
00028         _In_ float3 up              // the durection vector for up
00029         );
00030
00031     // this method updates the projection matrix based on new parameters
00032     void SetProjectionParameters(
00033         _In_ float minimumFieldOfView,  // the minimum horizontal or vertical field of view, in degrees
00034         _In_ float aspectRatio,         // the aspect ratio of the projection (width / height)
00035         _In_ float nearPlane,           // depth to map to 0
00036         _In_ float farPlane             // depth to map to 1
00037         );
00038 };
Generated on Sat Nov 23 2024 16:08:07 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D magazine app/C++/Text.cpp Source File

  • Direct2D magazine app

Text.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
00010 using namespace Microsoft::WRL;
00011 using namespace Windows::Data::Xml::Dom;
00012
00013 Text::Text() :
00014     Resource(),
00015     m_textLayout(nullptr),
00016     m_textPosition(),
00017     m_textLength()
00018 {
00019 }
00020
00021 bool Text::Initialize(
00022     _In_ Document^ document,
00023     _In_ XmlElement^ xmlElement
00024     )
00025 {
00026     if (!Resource::Initialize(document, xmlElement))
00027     {
00028         return false;
00029     }
00030
00031     float fontSize = 16.0f;
00032     DWRITE_FONT_WEIGHT fontWeight = DWRITE_FONT_WEIGHT_NORMAL;
00033     DWRITE_FONT_STYLE fontStyle = DWRITE_FONT_STYLE_NORMAL;
00034     DWRITE_FONT_STRETCH fontStretch = DWRITE_FONT_STRETCH_NORMAL;
00035
00036     Platform::String^ value = xmlElement->GetAttribute("font-size");
00037
00038     if (value != nullptr)
00039     {
00040         fontSize = static_cast<float>(_wtof(value->Data()));
00041     }
00042
00043     value = xmlElement->GetAttribute("font-weight");
00044
00045     if (value != nullptr)
00046     {
00047         fontWeight = static_cast<DWRITE_FONT_WEIGHT>(_wtol(value->Data()));
00048     }
00049
00050     value = xmlElement->GetAttribute("font-style");
00051
00052     if (value != nullptr)
00053     {
00054         fontStyle = static_cast<DWRITE_FONT_STYLE>(_wtol(value->Data()));
00055     }
00056
00057     value = xmlElement->GetAttribute("font-stretch");
00058
00059     if (value != nullptr)
00060     {
00061         fontStretch = static_cast<DWRITE_FONT_STRETCH>(_wtol(value->Data()));
00062     }
00063
00064     ComPtr<IDWriteFactory> dwriteFactory;
00065
00066     // Obtain DirectWrite factory from the current document
00067     document->GetDWriteFactory(&dwriteFactory);
00068
00069     value = xmlElement->GetAttribute("font-family");
00070
00071     if (value != nullptr)
00072     {
00073         // Creating and setting up text format and layout. This steps are
00074         // merely property setting. The actual work of laying out text is
00075         // deferred until the application asks for result or until the layout
00076         // is being drawn.
00077         ComPtr<IDWriteTextFormat> textFormat;
00078
00079         DX::ThrowIfFailed(
00080             dwriteFactory->CreateTextFormat(
00081                 value->Data(),
00082                 nullptr,    // Proper font collection will be set upon drawing
00083                 fontWeight,
00084                 fontStyle,
00085                 fontStretch,
00086                 fontSize,
00087                 L"en-US",
00088                 &textFormat
00089                 )
00090             );
00091
00092         // This call concatenates all text within this DOM element including
00093         // text inside each child element.
00094         Platform::String^ text = GetText(xmlElement);
00095         m_textLength = text->Length();
00096
00097         if (m_textLength != 0)
00098         {
00099             ComPtr<IDWriteTextLayout> textLayout;
00100
00101             DX::ThrowIfFailed(
00102                 dwriteFactory->CreateTextLayout(
00103                     text->Data(),
00104                     static_cast<uint32>(m_textLength),
00105                     textFormat.Get(),
00106                     FLT_MAX,
00107                     FLT_MAX,
00108                     &textLayout
00109                     )
00110                 );
00111
00112             textLayout.As(&m_textLayout);
00113
00114             ComPtr<IDWriteFontCollection> fontCollection;
00115             document->GetFontCollection(&fontCollection);
00116
00117             DWRITE_TEXT_RANGE range = {0};
00118             range.length = static_cast<uint32>(m_textLength);
00119
00120             DX::ThrowIfFailed(
00121                 m_textLayout->SetFontCollection(fontCollection.Get(), range)
00122                 );
00123         }
00124     }
00125
00126     return true;
00127 }
00128
00129 Platform::String^ Text::GetText(_In_ IXmlNode^ xmlNode)
00130 {
00131     if (xmlNode->NodeType == NodeType::TextNode)
00132     {
00133         return dynamic_cast<Platform::String^>(xmlNode->NodeValue);
00134     }
00135
00136     Platform::String^ text = nullptr;
00137
00138     if (xmlNode->HasChildNodes())
00139     {
00140         IXmlNode^ childXmlNode = xmlNode->FirstChild;
00141
00142         while (childXmlNode != nullptr)
00143         {
00144             text = Platform::String::Concat(text, GetText(childXmlNode));
00145
00146             childXmlNode = childXmlNode->NextSibling;
00147         }
00148     }
00149
00150     return text;
00151 }
00152
00153 bool Text::AcceptChildNode(
00154     _In_ Document^ document,
00155     _In_ IXmlNode^ childXmlNode
00156     )
00157 {
00158     if (childXmlNode->NodeType == NodeType::TextNode)
00159     {
00160         Platform::String^ text = GetText(childXmlNode);
00161
00162         if (text != nullptr)
00163         {
00164             // Since all text within child node is previously collected
00165             // when the text element is initialized, the text of the child
00166             // text node here isn't important. We only need to track proper
00167             // location of each span within the text element for formatting
00168             // purpose.
00169             m_textPosition += text->Length();
00170         }
00171     }
00172     else if (childXmlNode->NodeType == NodeType::ElementNode)
00173     {
00174         XmlElement^ xmlElement = dynamic_cast<XmlElement^>(childXmlNode);
00175
00176         if (xmlElement->TagName == "bold")
00177         {
00178             ComPtr<IDWriteFactory> dwriteFactory;
00179
00180             // Obtain DirectWrite factory from the current active document
00181             document->GetDWriteFactory(&dwriteFactory);
00182
00183             Platform::String^ spanText = GetText(childXmlNode);
00184
00185             DWRITE_TEXT_RANGE range = {0};
00186
00187             range.startPosition = static_cast<uint32>(m_textPosition);
00188             range.length = static_cast<uint32>(spanText->Length());
00189
00190             DX::ThrowIfFailed(
00191                 m_textLayout->SetFontWeight(
00192                     DWRITE_FONT_WEIGHT_BOLD,
00193                     range
00194                     )
00195                 );
00196
00197             m_textPosition += spanText->Length();
00198         }
00199     }
00200
00201     return true;
00202 }
00203
00204 void Text::GetTextLayout(_Outptr_ IDWriteTextLayout** textLayout)
00205 {
00206     *textLayout = ComPtr<IDWriteTextLayout>(m_textLayout).Detach();
00207 }
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Hilo::TileUpdateScheduler Member List

This is the complete list of members for Hilo::TileUpdateScheduler, including all inherited members.
TileUpdateScheduler() | Hilo::TileUpdateScheduler |
TileUpdateScheduler::ScheduleUpdateAsync(std::shared_ptr< Repository > repository, std::shared_ptr< ExceptionPolicy > exceptionPolicy) | Hilo::TileUpdateScheduler |
TileUpdateScheduler::UpdateTile(Windows::Foundation::Collections::IVector< Windows::Storage::StorageFile^>^files) | Hilo::TileUpdateScheduler | [private]
Generated on Sat Nov 23 2024 16:09:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D bump mapping/C++/DirectXBase.h Source File

  • Direct3D bump mapping

DirectXBase.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 "DirectXSample.h"
00011
00012 // Helper class that initializes DirectX APIs for both 2D and 3D rendering.
00013 // Some of the code in this class may be omitted if only 2D or only 3D rendering is being used.
00014 ref class DirectXBase abstract
00015 {
00016 internal:
00017     DirectXBase();
00018
00019     virtual void Initialize(Windows::UI::Core::CoreWindow^ window, float dpi);
00020     virtual void HandleDeviceLost();
00021     virtual void CreateDeviceIndependentResources();
00022     virtual void CreateDeviceResources();
00023     virtual void SetDpi(float dpi);
00024     virtual void UpdateForWindowSizeChange();
00025     virtual void CreateWindowSizeDependentResources();
00026     virtual void Render() = 0;
00027     virtual void Present();
00028     void ValidateDevice();
00029
00030 protected private:
00031     Platform::Agile<Windows::UI::Core::CoreWindow>  m_window;
00032
00033     // DirectWrite & Windows Imaging Component Objects.
00034     Microsoft::WRL::ComPtr<IDWriteFactory1>         m_dwriteFactory;
00035     Microsoft::WRL::ComPtr<IWICImagingFactory2>     m_wicFactory;
00036
00037     // DirectX Core Objects. Required for 2D and 3D.
00038     Microsoft::WRL::ComPtr<ID3D11Device1>           m_d3dDevice;
00039     Microsoft::WRL::ComPtr<ID3D11DeviceContext1>    m_d3dContext;
00040     Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00041     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00042
00043     // Direct2D Rendering Objects. Required for 2D.
00044     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00046     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00047     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmap;
00048
00049     // Direct3D Rendering Objects. Required for 3D.
00050     Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00051
00052     // Cached renderer properties.
00053     D3D_FEATURE_LEVEL                               m_featureLevel;
00054     Windows::Foundation::Size                       m_renderTargetSize;
00055     Windows::Foundation::Rect                       m_windowBounds;
00056     float                                           m_dpi;
00057     bool                                            m_windowSizeChangeInProgress;
00058 };
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playback Manager msAudioCategory/C++/MainPage.xaml.h Source File

  • Playback Manager msAudioCategory

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:46 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

D3DPostProcessing Member List

This is the complete list of members for D3DPostProcessing, including all inherited members.
__pad0__ | D3DPostProcessing |
BrightPassDownFilter() | D3DPostProcessing | [private]
CombineGlow() | D3DPostProcessing | [private]
CreateDeviceIndependentResources() override | D3DPostProcessing | [virtual]
CreateDeviceResources() override | D3DPostProcessing | [virtual]
CreateWindowSizeDependentResources() override | D3DPostProcessing | [virtual]
DrawQuad(ID3D11PixelShader *pixelShader, uint width, uint height) | D3DPostProcessing | [private]
HandleDeviceLost() override | D3DPostProcessing | [virtual]
m_brightPassConstantBuffer | D3DPostProcessing | [private]
m_brightPassTextureRenderTargetView | D3DPostProcessing | [private]
m_brightPassTextureShaderResourceView | D3DPostProcessing | [private]
m_camera | D3DPostProcessing | [private]
m_constantBuffer | D3DPostProcessing | [private]
m_constantBufferData | D3DPostProcessing | [private]
m_downScaleBrightPass9PixelShader | D3DPostProcessing | [private]
m_downScaleBrightPassPixelShader | D3DPostProcessing | [private]
m_finalPassPixelShader | D3DPostProcessing | [private]
m_glowConstantBuffer | D3DPostProcessing | [private]
m_glowPixelShader | D3DPostProcessing | [private]
m_glowTextureHeight | D3DPostProcessing | [private]
m_glowTextureRenderTargetViews | D3DPostProcessing | [private]
m_glowTextureShaderResourceViews | D3DPostProcessing | [private]
m_glowTextureWidth | D3DPostProcessing | [private]
m_indexBuffer | D3DPostProcessing | [private]
m_indexCount | D3DPostProcessing | [private]
m_inputLayout | D3DPostProcessing | [private]
m_intermediateRenderTargetHeight | D3DPostProcessing | [private]
m_intermediateRenderTargetWidth | D3DPostProcessing | [private]
m_intermediateTextureRenderTargetView | D3DPostProcessing | [private]
m_intermediateTextureShaderResourceView | D3DPostProcessing | [private]
m_linearSampler | D3DPostProcessing | [private]
m_pixelShader | D3DPostProcessing | [private]
m_pointSampler | D3DPostProcessing | [private]
m_quadLayout | D3DPostProcessing | [private]
m_quadVertexBuffer | D3DPostProcessing | [private]
m_quadVertexShader | D3DPostProcessing | [private]
m_sampleOverlay | D3DPostProcessing | [private]
m_sampler | D3DPostProcessing | [private]
m_texture | D3DPostProcessing | [private]
m_textureShaderResourceView | D3DPostProcessing | [private]
m_vertexBuffer | D3DPostProcessing | [private]
m_vertexShader | D3DPostProcessing | [private]
Render() override | D3DPostProcessing | [virtual]
RenderGlow() | D3DPostProcessing | [private]
Update(float timeTotal, float timeDelta) | D3DPostProcessing |
Generated on Sat Nov 23 2024 16:09:11 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/Level2.cpp Source File

  • XAML DirectX 3D shooting game

Level2.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 "Level2.h"
00010 #include "Face.h"
00011
00012 //----------------------------------------------------------------------
00013
00014 Level2::Level2()
00015 {
00016     m_timeLimit = 30.0f;
00017     m_objective = "Hit each of the targets in ORDER before time runs out.";
00018 }
00019
00020 //----------------------------------------------------------------------
00021
00022 void Level2::Initialize(std::vector<GameObject^> objects)
00023 {
00024     Level1::Initialize(objects);
00025
00026     int targetCount = 0;
00027     for (auto object = objects.begin(); object != objects.end(); object++)
00028     {
00029         if (Face^ target = dynamic_cast<Face^>(*object))
00030         {
00031             if (targetCount < 9)
00032             {
00033                 target->Target(targetCount == 0 ? true : false);
00034                 targetCount++;
00035             }
00036         }
00037     }
00038     m_nextId = 1;
00039 }
00040
00041 //----------------------------------------------------------------------
00042
00043 bool Level2::Update(
00044     float /* time */,
00045     float /* elapsedTime */,
00046     float /* timeRemaining */,
00047     std::vector<GameObject^> objects
00048     )
00049 {
00050     int left = 0;
00051     for (auto object = objects.begin(); object != objects.end(); object++)
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 //----------------------------------------------------------------------
00074
00075 void Level2::SaveState(PersistentState^ state)
00076 {
00077     state->SaveInt32(":NextTarget", m_nextId);
00078 }
00079
00080 //----------------------------------------------------------------------
00081
00082 void Level2::LoadState(PersistentState^ state)
00083 {
00084     m_nextId = state->LoadInt32(":NextTarget", 1);
00085 }
00086
00087 //----------------------------------------------------------------------
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Sharing content source app/C++/ShareDelayRenderedFiles.xaml.h Source File

  • Sharing content source app

ShareDelayRenderedFiles.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 // ShareDelayRenderedFiles.xaml.h
00013 // Declaration of the ShareDelayRenderedFiles class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "SharePage.h"
00020 #include "ShareDelayRenderedFiles.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKSample
00024 {
00025     namespace ShareSource
00026     {
00027         [Windows::Foundation::Metadata::WebHostHidden]
00028         public ref class ShareDelayRenderedFiles sealed
00029         {
00030         public:
00031             ShareDelayRenderedFiles();
00032
00033         protected:
00034             virtual bool GetShareContent(Windows::ApplicationModel::DataTransfer::DataRequest^ request) override;
00035
00036         private:
00037             MainPage^ rootPage;
00038             Windows::Storage::StorageFile^ imageFile;
00039
00040             void OnDeferredImageRequestedHandler(Windows::ApplicationModel::DataTransfer::DataProviderRequest^ request);
00041             void SelectImageButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00042         };
00043     }
00044 }
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::ToastContent::ToastText01 Member List

This is the complete list of members for NotificationsExtensions::ToastContent::ToastText01, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
Audio | NotificationsExtensions::ToastContent::ToastNotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
CreateNotification() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline]
Duration | NotificationsExtensions::ToastContent::ToastNotificationBase |
GetContent() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline, virtual]
GetContent() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline, virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
Launch | NotificationsExtensions::ToastContent::ToastNotificationBase |
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextBodyWrap | NotificationsExtensions::ToastContent::ToastText01 |
TextFields | NotificationsExtensions::NotificationBase |
ToastNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline]
ToastNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline]
ToastText01() | NotificationsExtensions::ToastContent::ToastText01 | [inline]
ToastText01() | NotificationsExtensions::ToastContent::ToastText01 | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application resources and localization/C++/Scenario3.xaml.h Source File

  • Application resources and localization

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 SDKSample
00023 {
00024     namespace ApplicationResources
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             void Scenario3StringLoad_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

GameHud Member List

This is the complete list of members for GameHud, including all inherited members.
__pad0__ | GameHud |
CreateDeviceIndependentResources(_In_ IDWriteFactory *dwriteFactory, _In_ IWICImagingFactory *wicFactory) | GameHud |
CreateDeviceIndependentResources(_In_ IDWriteFactory *dwriteFactory, _In_ IWICImagingFactory *wicFactory) | GameHud |
CreateDeviceResources(_In_ ID2D1DeviceContext *d2dContext) | GameHud |
CreateDeviceResources(_In_ ID2D1DeviceContext *d2dContext) | GameHud |
m_dwriteFactory | GameHud | [private]
m_logoBitmap | GameHud | [private]
m_logoSize | GameHud | [private]
m_maxTitleSize | GameHud | [private]
m_showTitle | GameHud | [private]
m_textBrush | GameHud | [private]
m_textBrushGrey | GameHud | [private]
m_textFormatBody | GameHud | [private]
m_textFormatBodySymbol | GameHud | [private]
m_textFormatTitleBody | GameHud | [private]
m_textFormatTitleHeader | GameHud | [private]
m_textFormatTitleLicense | GameHud | [private]
m_titleBody | GameHud | [private]
m_titleBodyLayout | GameHud | [private]
m_titleBodyVerticalOffset | GameHud | [private]
m_titleHeader | GameHud | [private]
m_titleHeaderLayout | GameHud | [private]
m_titleLicenseInfo | GameHud | [private]
m_titleLicenseInfoLayout | GameHud | [private]
m_titleLicenseVerticalOffset | GameHud | [private]
m_wicFactory | GameHud | [private]
Render(_In_ Simple3DGame^game, _In_ ID2D1DeviceContext *d2dContext, _In_ Windows::Foundation::Rect windowBounds) | GameHud |
Render(_In_ Simple3DGame^game, _In_ ID2D1DeviceContext *d2dContext, _In_ Windows::Foundation::Rect windowBounds) | GameHud |
SetLicenseInfo(_In_ Platform::String^licenseInfo) | GameHud |
titleBody | GameHud |
titleLicenseInfo | GameHud |
UpdateForWindowSizeChange(_In_ Windows::Foundation::Rect windowBounds) | GameHud |
UpdateForWindowSizeChange(_In_ Windows::Foundation::Rect windowBounds) | GameHud |
Generated on Sat Nov 23 2024 16:09:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application resources and localization/C++/CppSamplesUtils.h Source File

  • Application resources and localization

CppSamplesUtils.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 <string>
00014 #include <sstream>
00015 #include <algorithm>
00016 #include <collection.h>
00017 #include <ppltasks.h>
00018
00019 namespace CppSamplesUtils
00020 {
00021     namespace Details
00022     {
00023         static Windows::Foundation::Collections::PropertySet^ sessionState = nullptr;
00024         static Platform::String^ sessionStateFileName = ref new Platform::String(L"_cppSessionState.xml");
00025
00026         concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file);
00027         concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file);
00028     }
00029
00030     class SuspensionManager
00031     {
00032     public:
00033         static Windows::Foundation::Collections::PropertySet^ SessionState()
00034         {
00035             using namespace Windows::Foundation::Collections;
00036             using namespace Details;
00037
00038             if (sessionState == nullptr)
00039             {
00040                 sessionState = ref new PropertySet();
00041             }
00042             return sessionState;
00043         }
00044
00045         static concurrency::task<void> StartRestoreTask()
00046         {
00047             using namespace Windows::Foundation;
00048             using namespace Windows::Storage;
00049             using namespace Windows::Storage::Streams;
00050             using namespace Details;
00051
00052             auto state = SessionState();
00053             state->Clear();
00054
00055             concurrency::task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFileName));
00056             return getFileTask.then([=](StorageFile^ file)
00057             {
00058                 return DeserializeSessionState(file);
00059             });
00060         }
00061
00062         static concurrency::task<void> StartSaveTask()
00063         {
00064             using namespace Windows::Foundation;
00065             using namespace Windows::Storage;
00066             using namespace Windows::Storage::Streams;
00067             using namespace Details;
00068
00069             concurrency::task<StorageFile^> createFileTask(ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFileName, CreationCollisionOption::ReplaceExisting));
00070             return createFileTask.then([=](StorageFile^ file)
00071             {
00072                 return SerializeSessionState(file);
00073             });
00074         }
00075     };
00076
00077     namespace Details
00078     {
00079         template <class T>
00080         inline Platform::String^ ToString(T value)
00081         {
00082             std::wstringstream wss;
00083             wss << value;
00084             return ref new Platform::String(wss.str().c_str());
00085         }
00086
00087         template <class T>
00088         inline T FromStringTo(Platform::String^ str)
00089         {
00090             std::wistringstream wiss(str->Data());
00091             T value = 0;
00092             wiss >> value;
00093             return value;
00094         }
00095
00096         template <class T>
00097         inline T FromHexStringTo(Platform::String^ str)
00098         {
00099             std::wistringstream wiss(str->Data());
00100             T value = 0;
00101             wiss >> std::hex >> value;
00102             return value;
00103         }
00104
00105         template <>
00106         inline Platform::Guid FromStringTo<Platform::Guid>(Platform::String^ str)
00107         {
00108             using namespace Platform;
00109
00110             if (str->Length() != 38)
00111             {
00112                 throw ref new InvalidArgumentException;
00113             }
00114             std::wstring ws(str->Data());
00115             if (ws[0] != L'{' || ws[37] != L'}' || ws[9] != L'-' || ws[14] != L'-' || ws[19] != L'-' || ws[24] != L'-')
00116             {
00117                 throw ref new InvalidArgumentException;
00118             }
00119             ws[0] = ws[37] = ws[9] = ws[14] = ws[19] =ws[24] = L' ';
00120             std::wistringstream wiss(ws);
00121             unsigned int a = 0;
00122             unsigned short b = 0;
00123             unsigned short c = 0;
00124             unsigned short d = 0;
00125             unsigned long long e = 0;
00126             static_assert(sizeof(d) == sizeof(char) * 2, "sizeof(d) == sizeof(char) * 2");
00127             static_assert(sizeof(e) == sizeof(char) * 8, "sizeof(e) == sizeof(char) * 8");
00128             wiss >> std::hex >> a >> b >> c >> d >> e;
00129             unsigned char *ad = (unsigned char*)(&d);
00130             unsigned char *ae = (unsigned char*)(&e);
00131             return Platform::Guid(a, b, c, ad[1], ad[0], ae[5], ae[4], ae[3], ae[2], ae[1], ae[0]);
00132         }
00133
00134         inline Platform::Object^ ConvertStringToObject(Windows::Foundation::PropertyType type, Platform::String^ str)
00135         {
00136             using namespace Platform;
00137             using namespace Windows::Foundation;
00138
00139             if (type == PropertyType::String)
00140             {
00141                 return PropertyValue::CreateString(str);
00142             }
00143
00144             switch (type)
00145             {
00146             case PropertyType::UInt8:
00147                 return PropertyValue::CreateUInt8((unsigned char)FromStringTo<unsigned short>(str));
00148             case PropertyType::UInt16:
00149                 return PropertyValue::CreateUInt16(FromStringTo<unsigned short>(str));
00150             case PropertyType::UInt32:
00151                 return PropertyValue::CreateUInt32(FromStringTo<unsigned int>(str));
00152             case PropertyType::UInt64:
00153                 return PropertyValue::CreateUInt64(FromStringTo<unsigned long long>(str));
00154             case PropertyType::Int16:
00155                 return PropertyValue::CreateInt16(FromStringTo<short>(str));
00156             case PropertyType::Int32:
00157                 return PropertyValue::CreateInt32(FromStringTo<int>(str));
00158             case PropertyType::Int64:
00159                 return PropertyValue::CreateInt64(FromStringTo<long long>(str));
00160             case PropertyType::Single:
00161                 return PropertyValue::CreateSingle(FromStringTo<float>(str));
00162             case PropertyType::Double:
00163                 return PropertyValue::CreateDouble(FromStringTo<double>(str));
00164             case PropertyType::Boolean:
00165                 return PropertyValue::CreateBoolean(FromStringTo<bool>(str));
00166             case PropertyType::Char16:
00167                 return PropertyValue::CreateChar16(str->Data()[0]);
00168             case PropertyType::Guid:
00169                 return PropertyValue::CreateGuid(FromStringTo<Guid>(str));
00170             default:
00171                 throw ref new Platform::InvalidCastException;
00172             }
00173         }
00174
00175         inline Platform::String^ ConvertPropertyValueToString(Windows::Foundation::IPropertyValue^ pv)
00176         {
00177             using namespace Platform;
00178             using namespace Windows::Foundation;
00179
00180             String^ valueString;
00181
00182             switch (pv->Type)
00183             {
00184             case PropertyType::String:
00185                 valueString = pv->GetString();
00186                 break;
00187
00188             case PropertyType::UInt8:
00189             case PropertyType::UInt16:
00190             case PropertyType::UInt32:
00191             case PropertyType::UInt64:
00192                 valueString = ToString(pv->GetUInt64());
00193                 break;
00194
00195             case PropertyType::Int16:
00196             case PropertyType::Int32:
00197             case PropertyType::Int64:
00198                 valueString = ToString(pv->GetInt64());
00199                 break;
00200
00201             case PropertyType::Single:
00202                 valueString = ToString(pv->GetSingle());
00203                 break;
00204
00205             case PropertyType::Double:
00206                 valueString = ToString(pv->GetDouble());
00207                 break;
00208
00209             case PropertyType::Boolean:
00210                 valueString = ToString(pv->GetBoolean());
00211                 break;
00212
00213             case PropertyType::Char16:
00214                 wchar_t buffer[2];
00215                 buffer[0] = pv->GetChar16();
00216                 buffer[1] = 0;
00217                 valueString = ref new String(buffer);
00218                 break;
00219
00220             case PropertyType::Guid:
00221                 valueString = pv->GetGuid().ToString();
00222                 break;
00223
00224             default:
00225                 throw ref new InvalidCastException;
00226             }
00227
00228             return valueString;
00229         }
00230
00231         inline Windows::Data::Xml::Dom::XmlElement^ CreateXmlElementFromObject(Windows::Data::Xml::Dom::XmlDocument^ doc, Platform::String^ name, Platform::Object^ value)
00232         {
00233             using namespace Platform;
00234             using namespace Windows::Foundation;
00235             using namespace Windows::Data::Xml::Dom;
00236
00237             XmlElement^ element = doc->CreateElement("item");
00238             element->SetAttribute("name", name);
00239
00240             IPropertyValue^ pv = (IPropertyValue^)value;
00241             element->SetAttribute("type", ToString((int)pv->Type));
00242             element->SetAttribute("value", ConvertPropertyValueToString(pv));
00243
00244             return element;
00245         }
00246
00247         inline concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file)
00248         {
00249             using namespace Windows::Data::Xml::Dom;
00250             using namespace Windows::Foundation;
00251             namespace WFC = Windows::Foundation::Collections;
00252             typedef Windows::Foundation::Collections::IKeyValuePair<Platform::String^, Platform::Object^> KVPair;
00253
00254             XmlDocument^ doc = ref new XmlDocument;
00255             doc->AppendChild(doc->CreateElement("items"));
00256             auto sessionState = SuspensionManager::SessionState();
00257
00258             std::for_each(WFC::begin(sessionState), WFC::end(sessionState), [doc](KVPair^ item)
00259             {
00260                 doc->DocumentElement->AppendChild(CreateXmlElementFromObject(doc, item->Key, item->Value));
00261             });
00262
00263             return concurrency::task<void>(doc->SaveToFileAsync(file));
00264         }
00265
00266         inline Windows::Foundation::PropertyType PropertyTypeFromString(Platform::String^ str)
00267         {
00268             int value = FromStringTo<int>(str);
00269             return (Windows::Foundation::PropertyType)value;
00270         }
00271
00272         inline concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file)
00273         {
00274             using namespace Platform;
00275             using namespace Windows::Foundation;
00276             using namespace Windows::Data::Xml::Dom;
00277             namespace WFC = Windows::Foundation::Collections;
00278
00279             concurrency::task<XmlDocument^> loadFileTask(XmlDocument::LoadFromFileAsync(file));
00280             return loadFileTask.then([=](concurrency::task<XmlDocument^> docTask)
00281             {
00282                 try
00283                 {
00284                     auto doc = docTask.get();
00285                     auto items = doc->SelectNodes("/items/item");
00286                     auto sessionState = SuspensionManager::SessionState();
00287
00288                     std::for_each(WFC::begin(items), WFC::end(items), [sessionState](IXmlNode^ node)
00289                     {
00290                         auto element = (IXmlElement^)node;
00291                         String^ name = element->GetAttribute("name");
00292                         String^ value = element->GetAttribute("value");
00293                         PropertyType type = PropertyTypeFromString(element->GetAttribute("type"));
00294
00295                         Object^ valueObject = ConvertStringToObject(type, value);
00296                         sessionState->Insert(name, valueObject);
00297                     });
00298
00299                 }
00300                 catch (Platform::Exception^)
00301                 {
00302                     // Restoring is best effort
00303                 }
00304             });
00305         }
00306     } // namespace Details
00307 } // namespace CppSamplesUtils
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Gyrometer sensor/C++/pch.h Source File

  • Gyrometer sensor

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: StreamSocket/C++/Scenario1.xaml.h Source File

  • StreamSocket

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 using namespace Platform;
00023 using namespace Windows::Networking::Sockets;
00024 using namespace Windows::Storage::Streams;
00025
00026 namespace StreamSocketSample
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 Scenario1 sealed
00033     {
00034     public:
00035         Scenario1();
00036
00037     protected:
00038         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00039     private:
00040         MainPage^ rootPage;
00041         void StartListener_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00042     };
00043
00044     [Windows::Foundation::Metadata::WebHostHidden]
00045     public ref class ListenerContext sealed
00046     {
00047     public:
00048         ListenerContext(MainPage^ rootPage, StreamSocketListener^ listener);
00049         void OnConnection(StreamSocketListener^ listener, StreamSocketListenerConnectionReceivedEventArgs^ object);
00050
00051     private:
00052         MainPage^ rootPage;
00053         StreamSocketListener^ listener;
00054
00055         ~ListenerContext();
00056         void ReceiveStringLoop(DataReader^ reader, StreamSocket^ socket);
00057         void NotifyUserFromAsyncThread(String^ message, NotifyType type);
00058     };
00059 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C#,C++/ScenarioOutput2.xaml.cs Source File

  • Media extensions
  • C#,C++

ScenarioOutput2.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 System;
00009 using System.Linq;
00010 using System.Collections.Generic;
00011 using Windows.Foundation;
00012 using Windows.Foundation.Collections;
00013 using Windows.Graphics.Display;
00014 using Windows.UI.ViewManagement;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Controls.Primitives;
00018 using Windows.UI.Xaml.Data;
00019 using Windows.UI.Xaml.Input;
00020 using Windows.UI.Xaml.Media;
00021 using Windows.UI.Xaml.Navigation;
00022 using SDKTemplateCS;
00023
00024 namespace MediaExtensionsCS
00025 {
00026     public sealed partial class ScenarioOutput2 : Page
00027     {
00028         // A pointer back to the main page which is used to gain access to the input and output frames and their content.
00029         MainPage rootPage = null;
00030
00031         public ScenarioOutput2()
00032         {
00033             InitializeComponent();
00034         }
00035
00036         #region Template-Related Code - Do not remove
00037         protected override void OnNavigatedTo(NavigationEventArgs e)
00038         {
00039             // Get a pointer to our main page.
00040             rootPage = e.Parameter as MainPage;
00041
00042             Video.MediaFailed += new ExceptionRoutedEventHandler(rootPage.VideoOnError);
00043         }
00044
00045         protected override void OnNavigatedFrom(NavigationEventArgs e)
00046         {
00047             Video.MediaFailed -= new ExceptionRoutedEventHandler(rootPage.VideoOnError);
00048             Video.Source = null;
00049         }
00050         #endregion
00051     }
00052 }
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

ContactPicker::sealed Member List

This is the complete list of members for ContactPicker::sealed, including all inherited members.
__pad0__ | ContactPicker::sealed | [protected]
AddSampleContact(SampleContact sampleContact) | ContactPicker::sealed | [private]
autoSizeInputSectionWhenSnapped | ContactPicker::sealed | [private]
ContactList_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | ContactPicker::sealed | [private]
ContactPickerPage() | ContactPicker::sealed |
contactPickerUI | ContactPicker::sealed | [protected]
contactSet | ContactPicker::sealed | [private, static]
Footer_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | ContactPicker::sealed | [private]
Footer_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | ContactPicker::sealed | [private]
HiddenFrame | ContactPicker::sealed | [private]
InvalidateSize() | ContactPicker::sealed | [private]
InvalidateSize() | ContactPicker::sealed | [private]
InvalidateViewState() | ContactPicker::sealed | [private]
InvalidateViewState() | ContactPicker::sealed | [private]
LoadScenario(Platform::String^scenarioName) | ContactPicker::sealed |
LoadScenario(Platform::String^scenarioName) | ContactPicker::sealed |
MainPage() | ContactPicker::sealed |
MainPage_SizeChanged(Object^sender, Windows::UI::Xaml::SizeChangedEventArgs^e) | ContactPicker::sealed | [protected]
MainPagePicker() | ContactPicker::sealed |
MainPagePicker_SizeChanged(Object^sender, Windows::UI::Xaml::SizeChangedEventArgs^e) | ContactPicker::sealed | [protected]
MainPagePickerResized | ContactPicker::sealed |
MainPageResized | ContactPicker::sealed |
NotifyUser(Platform::String^strMessage, NotifyType type) | ContactPicker::sealed |
OnContactRemoved(Windows::ApplicationModel::Contacts::Provider::ContactPickerUI^sender, Windows::ApplicationModel::Contacts::Provider::ContactRemovedEventArgs^e) | ContactPicker::sealed | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ContactPicker::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ContactPicker::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ContactPicker::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ContactPicker::sealed | [protected, virtual]
PickAContactButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | ContactPicker::sealed | [private]
PickContactsButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | ContactPicker::sealed | [private]
PopulateScenarios() | ContactPicker::sealed | [private]
PopulateScenarios() | ContactPicker::sealed | [private]
ResolveSampleContact(Object^listBoxItem) | ContactPicker::sealed | [private]
ScenarioList | ContactPicker::sealed | [private]
ScenarioLoaded | ContactPicker::sealed |
ScenarioMultiple() | ContactPicker::sealed |
Scenarios_SelectionChanged(Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | ContactPicker::sealed | [protected]
Scenarios_SelectionChanged(Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | ContactPicker::sealed | [protected]
ScenarioSingle() | ContactPicker::sealed |
SetContactPicker(Platform::String^strFeature) | ContactPicker::sealed | [private]
SetContactPicker(Platform::String^strFeature) | ContactPicker::sealed | [private]
token | ContactPicker::sealed | [private]
~MainPage() | ContactPicker::sealed | [private]
~MainPagePicker() | ContactPicker::sealed | [private]
Generated on Sat Nov 23 2024 16:09:36 for Win8-Examples by doxygen 1.7.1


Win8-Examples: EAS policies for mail clients/C++/common/LayoutAwarePage.cpp Source File

  • EAS policies for mail clients
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:31 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Certificate enrollment/C++/common/LayoutAwarePage.h Source File

  • Certificate enrollment
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite paragraph text/C++/pch.cpp Source File

  • DirectWrite paragraph text

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML high contrast style/C++/Scenario3.xaml.h Source File

  • XAML high contrast style

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 SDKSample
00023 {
00024   namespace HighContrast
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::WebHostHiddenAttribute]
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       void Go_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040     };
00041   }
00042 }
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML user and custom controls/C++/common/suspensionmanager.cpp Source File

  • XAML user and custom controls
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D custom image effects/C++/PixelShader/SampleOverlay.h Source File

  • Direct2D custom image effects
  • PixelShader

SampleOverlay.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 "DirectXSample.h"
00011
00012 // This class is responsible for initializing and rendering the title overlay visible
00013 // at the top of the DirectX SDK samples.
00014 ref class SampleOverlay
00015 {
00016 internal:
00017     SampleOverlay();
00018
00019     void Initialize(
00020         _In_ ID2D1Device*         d2dDevice,
00021         _In_ ID2D1DeviceContext*  d2dContext,
00022         _In_ IWICImagingFactory*  wicFactory,
00023         _In_ IDWriteFactory*      dwriteFactory,
00024         _In_ Platform::String^    caption
00025         );
00026
00027     void ResetDirectXResources();
00028
00029     void UpdateForWindowSizeChange();
00030
00031     void Render();
00032
00033     float GetTitleHeightInDips();
00034
00035 private:
00036
00037     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00038     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00039     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00040     Microsoft::WRL::ComPtr<IDWriteFactory>          m_dwriteFactory;
00041     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_whiteBrush;
00042     Microsoft::WRL::ComPtr<ID2D1DrawingStateBlock>  m_stateBlock;
00043
00044     Microsoft::WRL::ComPtr<IWICImagingFactory>      m_wicFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Bitmap>             m_logoBitmap;
00046     Microsoft::WRL::ComPtr<IDWriteTextLayout>       m_textLayout;
00047
00048     UINT                                            m_idIncrement;
00049     bool                                            m_drawOverlay;
00050     Platform::String^                               m_sampleName;
00051     float                                           m_padding;
00052     float                                           m_textVerticalOffset;
00053     D2D1_SIZE_F                                     m_logoSize;
00054     float                                           m_overlayWidth;
00055 };
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

_SWITCH_STATE Member List

This is the complete list of members for _SWITCH_STATE, including all inherited members.
Switch1 | _SWITCH_STATE
Switch2 | _SWITCH_STATE
Switch3 | _SWITCH_STATE
Switch4 | _SWITCH_STATE
Switch5 | _SWITCH_STATE
Switch6 | _SWITCH_STATE
Switch7 | _SWITCH_STATE
Switch8 | _SWITCH_STATE
SwitchesAsUChar | _SWITCH_STATE
Generated on Sat Nov 23 2024 16:09:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/DesignTimeData.h Source File

  • Hilo C++
  • Hilo

DesignTimeData.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
00009 #include "IResizable.h"
00010
00011 namespace Hilo
00012 {
00013 #pragma region DesignTimePhoto Class
00014     [Windows::UI::Xaml::Data::Bindable]
00015     [Windows::Foundation::Metadata::WebHostHidden]
00016     public ref class DesignTimePhoto sealed : public IResizable
00017     {
00018     public:
00019         property Windows::UI::Xaml::Media::ImageSource^ Image
00020         {
00021             Windows::UI::Xaml::Media::ImageSource^ get();
00022         }
00023
00024         property Windows::UI::Xaml::Media::ImageSource^ Thumbnail
00025         {
00026             Windows::UI::Xaml::Media::ImageSource^ get();
00027         }
00028
00029         property Platform::String^ Name { Platform::String^ get(); }
00030         property Platform::String^ DisplayType { Platform::String^ get(); }
00031         property Platform::String^ Resolution { Platform::String^ get(); }
00032         property Platform::String^ FormattedDateTaken { Platform::String^ get(); }
00033         property Platform::String^ FormattedTimeTaken { Platform::String^ get(); }
00034         property uint64 FileSize { uint64 get(); }
00035         property Platform::String^ FormattedPath { Platform::String^ get(); }
00036
00037         property int ColumnSpan
00038         {
00039             virtual int get();
00040             virtual void set(int value);
00041         }
00042
00043         property int RowSpan
00044         {
00045             virtual int get();
00046             virtual void set(int value);
00047         }
00048
00049     private:
00050         int m_columnSpan;
00051         int m_rowSpan;
00052     };
00053 #pragma endregion
00054
00055 #pragma region DesignTimePhotoGroup Class
00056     [Windows::UI::Xaml::Data::Bindable]
00057     [Windows::Foundation::Metadata::WebHostHidden]
00058     public ref class DesignTimePhotoGroup sealed
00059     {
00060     public:
00061         DesignTimePhotoGroup(Platform::String^ title);
00062
00063         property Windows::Foundation::Collections::IObservableVector<DesignTimePhoto^>^ Items
00064         {
00065             Windows::Foundation::Collections::IObservableVector<DesignTimePhoto^>^ get();
00066         }
00067
00068         property Platform::String^ Title
00069         {
00070             Platform::String^ get();
00071         }
00072
00073     private:
00074         Platform::String^ m_title;
00075     };
00076 #pragma endregion
00077
00078 #pragma region DesignTimeMonthBlock Class
00079     ref class DesignTimeYearGroup;
00080
00081     [Windows::UI::Xaml::Data::Bindable]
00082     public ref class DesignTimeMonthBlock sealed
00083     {
00084     public:
00085         DesignTimeMonthBlock(bool hasPhotos);
00086
00087         property Platform::String^ Name
00088         {
00089             Platform::String^ get();
00090         }
00091
00092         property bool HasPhotos
00093         {
00094             bool get();
00095         }
00096
00097     private:
00098         bool m_hasPhotos;
00099
00100     };
00101 #pragma endregion
00102
00103 #pragma region DesignTimeYearGroup Class
00104     [Windows::UI::Xaml::Data::Bindable]
00105     public ref class DesignTimeYearGroup sealed
00106     {
00107     public:
00108         DesignTimeYearGroup(Platform::String^ title);
00109
00110         property Platform::String^ Title
00111         {
00112             Platform::String^ get();
00113         }
00114
00115         property Windows::Foundation::Collections::IObservableVector<DesignTimeMonthBlock^>^ Items
00116         {
00117             Windows::Foundation::Collections::IObservableVector<DesignTimeMonthBlock^>^ get();
00118         }
00119
00120     private:
00121         Platform::String^ m_title;
00122         Platform::Collections::Vector<DesignTimeMonthBlock^>^ m_months;
00123     };
00124 #pragma endregion
00125
00126 #pragma region DesignTimeData Class
00127     [Windows::UI::Xaml::Data::Bindable]
00128     [Windows::Foundation::Metadata::WebHostHidden]
00129     public ref class DesignTimeData sealed
00130     {
00131     public:
00132         DesignTimeData();
00133
00134         property Windows::UI::Xaml::Media::ImageSource^ Image
00135         {
00136             Windows::UI::Xaml::Media::ImageSource^ get();
00137         }
00138
00139         property Windows::Foundation::Collections::IObservableVector<DesignTimePhoto^>^ Photos
00140         {
00141             Windows::Foundation::Collections::IObservableVector<DesignTimePhoto^>^ get();
00142         }
00143
00144         property Windows::Foundation::Collections::IObservableVector<DesignTimePhotoGroup^>^ HubPhotosGroup
00145         {
00146             Windows::Foundation::Collections::IObservableVector<DesignTimePhotoGroup^>^ get();
00147         }
00148
00149         property Windows::Foundation::Collections::IObservableVector<DesignTimePhotoGroup^>^ MonthGroups
00150         {
00151             Windows::Foundation::Collections::IObservableVector<DesignTimePhotoGroup^>^ get();
00152         }
00153
00154         property Windows::Foundation::Collections::IObservableVector<DesignTimeYearGroup^>^ YearGroups
00155         {
00156             Windows::Foundation::Collections::IObservableVector<DesignTimeYearGroup^>^ get();
00157         }
00158
00159         property DesignTimePhoto^ Photo { DesignTimePhoto^ get(); }
00160         property DesignTimePhoto^ SelectedItem { DesignTimePhoto^ get(); }
00161         property Platform::String^ Coarseness { Platform::String^ get(); }
00162         property Platform::String^ Passes { Platform::String^ get(); }
00163         property Platform::String^ MonthAndYear { Platform::String^ get(); }
00164         property Platform::String^ AppName { Platform::String^ get(); }
00165         property Platform::String^ ImageBrowserPageTitle { Platform::String^ get(); }
00166
00167     private:
00168         DesignTimePhoto^ m_designTimePhoto;
00169     };
00170 #pragma endregion
00171 }
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D bump mapping/C++/BasicCamera.cpp Source File

  • Direct3D bump mapping

BasicCamera.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 "BasicCamera.h"
00010
00011 void BasicCamera::GetViewMatrix(_Out_ float4x4 *viewMatrix)
00012 {
00013     *viewMatrix = m_view;
00014 }
00015
00016 void BasicCamera::GetProjectionMatrix(_Out_ float4x4 *projectionMatrix)
00017 {
00018     *projectionMatrix = m_projection;
00019 }
00020
00021 // this method updates the view matrix based on new position and focus coordinates
00022 void BasicCamera::SetViewParameters(
00023     _In_ float3 eyePosition,    // the position of the camera
00024     _In_ float3 lookPosition,   // the point the camera should look at
00025     _In_ float3 up              // the durection vector for up
00026     )
00027 {
00028     m_position = eyePosition;
00029     m_direction = normalize(lookPosition - eyePosition);
00030     float3 zAxis = -m_direction;
00031     float3 xAxis = normalize(cross(up, zAxis));
00032     float3 yAxis = cross(zAxis, xAxis);
00033     float xOffset = -dot(xAxis, m_position);
00034     float yOffset = -dot(yAxis, m_position);
00035     float zOffset = -dot(zAxis, m_position);
00036     m_view = float4x4(
00037         xAxis.x, xAxis.y, xAxis.z, xOffset,
00038         yAxis.x, yAxis.y, yAxis.z, yOffset,
00039         zAxis.x, zAxis.y, zAxis.z, zOffset,
00040         0.0f,    0.0f,    0.0f,    1.0f
00041         );
00042 }
00043     // this method updates the projection matrix based on new parameters
00044 void BasicCamera::SetProjectionParameters(
00045     _In_ float minimumFieldOfView,  // the minimum horizontal or vertical field of view, in degrees
00046     _In_ float aspectRatio,         // the aspect ratio of the projection (width / height)
00047     _In_ float nearPlane,           // depth to map to 0
00048     _In_ float farPlane             // depth to map to 1
00049     )
00050 {
00051     float minScale = 1.0f / tan(minimumFieldOfView * PI_F / 360.0f);
00052     float xScale = 1.0f;
00053     float yScale = 1.0f;
00054     if (aspectRatio < 1.0f)
00055     {
00056         xScale = minScale;
00057         yScale = minScale * aspectRatio;
00058     }
00059     else
00060     {
00061         xScale = minScale / aspectRatio;
00062         yScale = minScale;
00063     }
00064     float zScale = farPlane / (farPlane - nearPlane);
00065     m_projection = float4x4(
00066         xScale, 0.0f,   0.0f,    0.0f,
00067         0.0f,   yScale, 0.0f,    0.0f,
00068         0.0f,   0.0f,   -zScale, -nearPlane*zScale,
00069         0.0f,   0.0f,   -1.0f,   0.0f
00070         );
00071 }
Generated on Sat Nov 23 2024 16:08:07 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C#,C++/MediaExtensions/Common/AsyncCB.h Source File

  • Media extensions
  • C#,C++
  • MediaExtensions
  • Common

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 Sat Nov 23 2024 16:08:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playback Manager msAudioCategory/C++/Constants.h Source File

  • Playback Manager msAudioCategory

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"Playback Manager");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044
00045
00046 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Web authentication broker/C++/common/suspensionmanager.cpp Source File

  • Web authentication broker
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:37 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File access/C++/common/suspensionmanager.cpp Source File

  • File access
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:36 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File access/C++/MainPage.xaml.h Source File

  • File access

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:46 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Scheduled notifications/C#,C++/ScenarioInput1.xaml.h Source File

  • Scheduled notifications
  • C#,C++

ScenarioInput1.xaml.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 // ScenarioInput1.xaml.h
00009 // Declaration of the ScenarioInput1 class.
00010 //
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "ScenarioInput1.g.h"
00016 #include "MainPage.xaml.h"
00017
00018 using namespace Windows::UI::Xaml;
00019
00020 namespace ScheduledNotificationsSampleCPP
00021 {
00022   [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class ScenarioInput1 sealed
00024     {
00025     public:
00026         ScenarioInput1();
00027
00028     protected:
00029   virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030
00031     private:
00032   MainPage^ rootPage;
00033   void Schedule_Click(Object^, Windows::UI::Xaml::RoutedEventArgs^ e);
00034   void ScheduleToast(Platform::String^ updateString, Windows::Foundation::DateTime dueTime, Platform::String^ idNumberString);
00035   void ScheduleTile(Platform::String^ updateString, Windows::Foundation::DateTime dueTime, Platform::String^ idNumberString);
00036   void ScheduleToastWithStringManipulation(Platform::String^ updateString, Windows::Foundation::DateTime dueTime, Platform::String^ idNumberString);
00037   void ScheduleTileWithStringManipulation(Platform::String^ updateString, Windows::Foundation::DateTime dueTime, Platform::String^ idNumberString);
00038     };
00039 }
Generated on Sat Nov 23 2024 16:07:59 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Certificate enrollment/C++/Scenario_Import.xaml.h Source File

  • Certificate enrollment

Scenario_Import.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 // Scenario_Import.xaml.h
00013 // Declaration of the Scenario_Import class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario_Import.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace CertificateEnrollment
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 Scenario_Import sealed
00031         {
00032         public:
00033             Scenario_Import();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void ImportPfx_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:07:58 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playback Manager Companion/C++/sample-utils/CppSamplesUtils.h Source File

  • Playback Manager Companion
  • sample-utils

CppSamplesUtils.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 <string>
00014 #include <sstream>
00015 #include <algorithm>
00016 #include <collection.h>
00017 #include <ppltasks.h>
00018
00019 namespace CppSamplesUtils
00020 {
00021     namespace Details
00022     {
00023         static Windows::Foundation::Collections::PropertySet^ sessionState = nullptr;
00024         static Platform::String^ sessionStateFileName = ref new Platform::String(L"_cppSessionState.xml");
00025
00026         concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file);
00027         concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file);
00028     }
00029
00030     class SuspensionManager
00031     {
00032     public:
00033         static Windows::Foundation::Collections::PropertySet^ SessionState()
00034         {
00035             using namespace Windows::Foundation::Collections;
00036             using namespace Details;
00037
00038             if (sessionState == nullptr)
00039             {
00040                 sessionState = ref new PropertySet();
00041             }
00042             return sessionState;
00043         }
00044
00045         static concurrency::task<void> StartRestoreTask()
00046         {
00047             using namespace Windows::Foundation;
00048             using namespace Windows::Storage;
00049             using namespace Windows::Storage::Streams;
00050             using namespace Details;
00051
00052             auto state = SessionState();
00053             state->Clear();
00054
00055             concurrency::task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFileName));
00056             return getFileTask.then([=](StorageFile^ file)
00057             {
00058                 return DeserializeSessionState(file);
00059             });
00060         }
00061
00062         static concurrency::task<void> StartSaveTask()
00063         {
00064             using namespace Windows::Foundation;
00065             using namespace Windows::Storage;
00066             using namespace Windows::Storage::Streams;
00067             using namespace Details;
00068
00069             concurrency::task<StorageFile^> createFileTask(ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFileName, CreationCollisionOption::ReplaceExisting));
00070             return createFileTask.then([=](StorageFile^ file)
00071             {
00072                 return SerializeSessionState(file);
00073             });
00074         }
00075     };
00076
00077     namespace Details
00078     {
00079         template <class T>
00080         inline Platform::String^ ToString(T value)
00081         {
00082             std::wstringstream wss;
00083             wss << value;
00084             return ref new Platform::String(wss.str().c_str());
00085         }
00086
00087         template <class T>
00088         inline T FromStringTo(Platform::String^ str)
00089         {
00090             std::wistringstream wiss(str->Data());
00091             T value = 0;
00092             wiss >> value;
00093             return value;
00094         }
00095
00096         template <class T>
00097         inline T FromHexStringTo(Platform::String^ str)
00098         {
00099             std::wistringstream wiss(str->Data());
00100             T value = 0;
00101             wiss >> std::hex >> value;
00102             return value;
00103         }
00104
00105         template <>
00106         inline Platform::Guid FromStringTo<Platform::Guid>(Platform::String^ str)
00107         {
00108             using namespace Platform;
00109
00110             if (str->Length() != 38)
00111             {
00112                 throw ref new InvalidArgumentException;
00113             }
00114             std::wstring ws(str->Data());
00115             if (ws[0] != L'{' || ws[37] != L'}' || ws[9] != L'-' || ws[14] != L'-' || ws[19] != L'-' || ws[24] != L'-')
00116             {
00117                 throw ref new InvalidArgumentException;
00118             }
00119             ws[0] = ws[37] = ws[9] = ws[14] = ws[19] =ws[24] = L' ';
00120             std::wistringstream wiss(ws);
00121             unsigned int a = 0;
00122             unsigned short b = 0;
00123             unsigned short c = 0;
00124             unsigned short d = 0;
00125             unsigned long long e = 0;
00126             static_assert(sizeof(d) == sizeof(char) * 2, "sizeof(d) == sizeof(char) * 2");
00127             static_assert(sizeof(e) == sizeof(char) * 8, "sizeof(e) == sizeof(char) * 8");
00128             wiss >> std::hex >> a >> b >> c >> d >> e;
00129             unsigned char *ad = (unsigned char*)(&d);
00130             unsigned char *ae = (unsigned char*)(&e);
00131             return Platform::Guid(a, b, c, ad[1], ad[0], ae[5], ae[4], ae[3], ae[2], ae[1], ae[0]);
00132         }
00133
00134         inline Platform::Object^ ConvertStringToObject(Windows::Foundation::PropertyType type, Platform::String^ str)
00135         {
00136             using namespace Platform;
00137             using namespace Windows::Foundation;
00138
00139             if (type == PropertyType::String)
00140             {
00141                 return PropertyValue::CreateString(str);
00142             }
00143
00144             switch (type)
00145             {
00146             case PropertyType::UInt8:
00147                 return PropertyValue::CreateUInt8((unsigned char)FromStringTo<unsigned short>(str));
00148             case PropertyType::UInt16:
00149                 return PropertyValue::CreateUInt16(FromStringTo<unsigned short>(str));
00150             case PropertyType::UInt32:
00151                 return PropertyValue::CreateUInt32(FromStringTo<unsigned int>(str));
00152             case PropertyType::UInt64:
00153                 return PropertyValue::CreateUInt64(FromStringTo<unsigned long long>(str));
00154             case PropertyType::Int16:
00155                 return PropertyValue::CreateInt16(FromStringTo<short>(str));
00156             case PropertyType::Int32:
00157                 return PropertyValue::CreateInt32(FromStringTo<int>(str));
00158             case PropertyType::Int64:
00159                 return PropertyValue::CreateInt64(FromStringTo<long long>(str));
00160             case PropertyType::Single:
00161                 return PropertyValue::CreateSingle(FromStringTo<float>(str));
00162             case PropertyType::Double:
00163                 return PropertyValue::CreateDouble(FromStringTo<double>(str));
00164             case PropertyType::Boolean:
00165                 return PropertyValue::CreateBoolean(FromStringTo<bool>(str));
00166             case PropertyType::Char16:
00167                 return PropertyValue::CreateChar16(str->Data()[0]);
00168             case PropertyType::Guid:
00169                 return PropertyValue::CreateGuid(FromStringTo<Guid>(str));
00170             default:
00171                 throw ref new Platform::InvalidCastException;
00172             }
00173         }
00174
00175         inline Platform::String^ ConvertPropertyValueToString(Windows::Foundation::IPropertyValue^ pv)
00176         {
00177             using namespace Platform;
00178             using namespace Windows::Foundation;
00179
00180             String^ valueString;
00181
00182             switch (pv->Type)
00183             {
00184             case PropertyType::String:
00185                 valueString = pv->GetString();
00186                 break;
00187
00188             case PropertyType::UInt8:
00189             case PropertyType::UInt16:
00190             case PropertyType::UInt32:
00191             case PropertyType::UInt64:
00192                 valueString = ToString(pv->GetUInt64());
00193                 break;
00194
00195             case PropertyType::Int16:
00196             case PropertyType::Int32:
00197             case PropertyType::Int64:
00198                 valueString = ToString(pv->GetInt64());
00199                 break;
00200
00201             case PropertyType::Single:
00202                 valueString = ToString(pv->GetSingle());
00203                 break;
00204
00205             case PropertyType::Double:
00206                 valueString = ToString(pv->GetDouble());
00207                 break;
00208
00209             case PropertyType::Boolean:
00210                 valueString = ToString(pv->GetBoolean());
00211                 break;
00212
00213             case PropertyType::Char16:
00214                 wchar_t buffer[2];
00215                 buffer[0] = pv->GetChar16();
00216                 buffer[1] = 0;
00217                 valueString = ref new String(buffer);
00218                 break;
00219
00220             case PropertyType::Guid:
00221                 valueString = pv->GetGuid().ToString();
00222                 break;
00223
00224             default:
00225                 throw ref new InvalidCastException;
00226             }
00227
00228             return valueString;
00229         }
00230
00231         inline Windows::Data::Xml::Dom::XmlElement^ CreateXmlElementFromObject(Windows::Data::Xml::Dom::XmlDocument^ doc, Platform::String^ name, Platform::Object^ value)
00232         {
00233             using namespace Platform;
00234             using namespace Windows::Foundation;
00235             using namespace Windows::Data::Xml::Dom;
00236
00237             XmlElement^ element = doc->CreateElement("item");
00238             element->SetAttribute("name", name);
00239
00240             IPropertyValue^ pv = (IPropertyValue^)value;
00241             element->SetAttribute("type", ToString((int)pv->Type));
00242             element->SetAttribute("value", ConvertPropertyValueToString(pv));
00243
00244             return element;
00245         }
00246
00247         inline concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file)
00248         {
00249             using namespace Windows::Data::Xml::Dom;
00250             using namespace Windows::Foundation;
00251             namespace WFC = Windows::Foundation::Collections;
00252             typedef Windows::Foundation::Collections::IKeyValuePair<Platform::String^, Platform::Object^> KVPair;
00253
00254             XmlDocument^ doc = ref new XmlDocument;
00255             doc->AppendChild(doc->CreateElement("items"));
00256             auto sessionState = SuspensionManager::SessionState();
00257
00258             std::for_each(WFC::begin(sessionState), WFC::end(sessionState), [doc](KVPair^ item)
00259             {
00260                 doc->DocumentElement->AppendChild(CreateXmlElementFromObject(doc, item->Key, item->Value));
00261             });
00262
00263             return concurrency::task<void>(doc->SaveToFileAsync(file));
00264         }
00265
00266         inline Windows::Foundation::PropertyType PropertyTypeFromString(Platform::String^ str)
00267         {
00268             int value = FromStringTo<int>(str);
00269             return (Windows::Foundation::PropertyType)value;
00270         }
00271
00272         inline concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file)
00273         {
00274             using namespace Platform;
00275             using namespace Windows::Foundation;
00276             using namespace Windows::Data::Xml::Dom;
00277             namespace WFC = Windows::Foundation::Collections;
00278
00279             concurrency::task<XmlDocument^> loadFileTask(XmlDocument::LoadFromFileAsync(file));
00280             return loadFileTask.then([=](concurrency::task<XmlDocument^> docTask)
00281             {
00282                 try
00283                 {
00284                     auto doc = docTask.get();
00285                     auto items = doc->SelectNodes("/items/item");
00286                     auto sessionState = SuspensionManager::SessionState();
00287
00288                     std::for_each(WFC::begin(items), WFC::end(items), [sessionState](IXmlNode^ node)
00289                     {
00290                         auto element = (IXmlElement^)node;
00291                         String^ name = element->GetAttribute("name");
00292                         String^ value = element->GetAttribute("value");
00293                         PropertyType type = PropertyTypeFromString(element->GetAttribute("type"));
00294
00295                         Object^ valueObject = ConvertStringToObject(type, value);
00296                         sessionState->Insert(name, valueObject);
00297                     });
00298
00299                 }
00300                 catch (Platform::Exception^)
00301                 {
00302                     // Restoring is best effort
00303                 }
00304             });
00305         }
00306     } // namespace Details
00307 } // namespace CppSamplesUtils
Generated on Sat Nov 23 2024 16:07:53 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Scheduled notifications/C#,C++/MainPage.xaml.cpp Source File

  • Scheduled notifications
  • C#,C++

MainPage.xaml.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 //
00009 // MainPage.xaml.cpp
00010 // Implementation of the MainPage.xaml class.
00011 //
00012
00013 #include "pch.h"
00014 #include "MainPage.xaml.h"
00015 #include "App.xaml.h"
00016
00017 using namespace Windows::UI::Xaml;
00018 using namespace Windows::UI::Xaml::Controls;
00019 using namespace Windows::UI::Xaml::Data;
00020 using namespace Windows::System;
00021 using namespace Windows::Foundation;
00022 using namespace Platform;
00023 using namespace ScheduledNotificationsSampleCPP;
00024 using namespace CppSamplesUtils;
00025 using namespace Windows::UI::Xaml::Navigation;
00026 using namespace Windows::UI::Xaml::Interop;
00027 using namespace Windows::Graphics::Display;
00028 using namespace Windows::UI::ViewManagement;
00029
00030 MainPage::MainPage()
00031 {
00032     InitializeComponent();
00033
00034     SetFeatureName("Scheduled Notifications");
00035
00036     _scenariosFrame = ScenarioList;
00037     _inputFrame = ScenarioInput;
00038     _outputFrame = ScenarioOutput;
00039
00040     _pageLoadedHandlerToken = Loaded += ref new RoutedEventHandler(this, &MainPage::Page_Loaded);
00041     _logicalDpiChangedToken = DisplayProperties::LogicalDpiChanged += ref new DisplayPropertiesEventHandler(this, &MainPage::DisplayProperties_LogicalDpiChanged);
00042     _resizeHandlerToken = Window::Current->SizeChanged += ref new Windows::UI::Xaml::WindowSizeChangedEventHandler(this, &MainPage::Page_SizeChanged);
00043 }
00044
00045 MainPage::~MainPage()
00046 {
00047 }
00048
00049 void MainPage::Page_Loaded(Object^ sender, RoutedEventArgs^ e)
00050 {
00051     // Load the ScenarioList page into the proper frame
00052     TypeName pageType = { "ScheduledNotificationsSampleCPP.ScenarioList", TypeKind::Custom };
00053     ScenarioList->Navigate(pageType, this);
00054
00055     // Figure out what resolution and orientation we are in and respond appropriately.
00056     CheckResolutionAndViewState();
00057 }
00058
00059 void MainPage::SetFeatureName(String^ strFeature)
00060 {
00061     FeatureName->Text = strFeature;
00062 }
00063
00064 void MainPage::DisplayProperties_LogicalDpiChanged(Object^ sender)
00065 {
00066     CheckResolutionAndViewState();
00067 }
00068
00069 void MainPage::CheckResolutionAndViewState()
00070 {
00071     ApplicationViewState state = ApplicationView::Value;
00072     String^ stateString = ConvertViewState(state);
00073
00074     ResolutionScale scale = DisplayProperties::ResolutionScale;
00075     String^ scaleString = ConvertResolution(scale);
00076
00077     VisualStateManager::GoToState(this, stateString + scaleString, false);
00078 }
00079
00080 String^ MainPage::ConvertViewState(ApplicationViewState state)
00081 {
00082     switch(state)
00083     {
00084     case ApplicationViewState::Filled:
00085         return "Filled";
00086     case ApplicationViewState::FullScreenLandscape:
00087         return "FullScreenLandscape";
00088     case ApplicationViewState::FullScreenPortrait:
00089         return "FullScreenPortrait";
00090     case ApplicationViewState::Snapped:
00091         return "Snapped";
00092     }
00093     return "";
00094 }
00095
00096 String^ MainPage::ConvertResolution(ResolutionScale scale)
00097 {
00098     switch(scale)
00099     {
00100     case ResolutionScale::Scale100Percent:
00101         return "Scale100Percent";
00102     case ResolutionScale::Scale140Percent:
00103         return "Scale140Percent";
00104     case ResolutionScale::Scale180Percent:
00105         return "Scale180Percent";
00106     }
00107     return "";
00108 }
00109
00110 void MainPage::DoNavigation(TypeName inPageType, Windows::UI::Xaml::Controls::Frame^ inFrame, TypeName outPageType, Windows::UI::Xaml::Controls::Frame^ outFrame)
00111 {
00112     inFrame->Navigate(inPageType, this);
00113     outFrame->Navigate(outPageType, this);
00114
00115     // Raise OutputFrameLoaded so downstream pages know that the output frame content has been loaded
00116     OutputFrameLoaded(this, nullptr);
00117     // Raise InputFrameLoaded so downstream pages know that the input frame content has been loaded
00118     InputFrameLoaded(this, nullptr);
00119 }
00120
00121 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00122 {
00123     switch (type)
00124     {
00125     case NotifyType::StatusMessage:
00126         StatusBlock->Style = dynamic_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00127         break;
00128     case NotifyType::ErrorMessage:
00129         StatusBlock->Style = dynamic_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00130         break;
00131     default:
00132         break;
00133     }
00134     StatusBlock->Text = strMessage;
00135 }
00136
00137 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00138 {
00139     auto _hyperlinkButton = (HyperlinkButton^)sender;
00140     auto uri = ref new Windows::Foundation::Uri((String^)_hyperlinkButton->Tag);
00141
00142     Windows::System::Launcher::LaunchUriAsync(uri);
00143 }
00144
00145 void MainPage::Page_SizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ args)
00146 {
00147     switch (Windows::UI::ViewManagement::ApplicationView::Value)
00148     {
00149     case ApplicationViewState::Filled:
00150         VisualStateManager::GoToState(this, "Filled", false);
00151         break;
00152     case ApplicationViewState::FullScreenLandscape:
00153         VisualStateManager::GoToState(this, "FullScreenLandscape", false);
00154         break;
00155     case ApplicationViewState::Snapped:
00156         VisualStateManager::GoToState(this, "Snapped", false);
00157         break;
00158     case ApplicationViewState::FullScreenPortrait:
00159         VisualStateManager::GoToState(this, "FullScreenPortrait", false);
00160         break;
00161     }
00162 }
Generated on Sat Nov 23 2024 16:07:43 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::ThreadPool::sealed Member List

This is the complete list of members for SDKSample::ThreadPool::sealed, including all inherited members.
CancelDelayTimer(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::ThreadPool::sealed | [private]
CancelPeriodicTimer(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::ThreadPool::sealed | [private]
CancelThreadPoolWorkItem(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::ThreadPool::sealed | [private]
CreateDelayTimer(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::ThreadPool::sealed | [private]
CreatePeriodicTimer(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::ThreadPool::sealed | [private]
CreateThreadPoolWorkItem(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::ThreadPool::sealed | [private]
DelayTimerScenario() | SDKSample::ThreadPool::sealed |
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::ThreadPool::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::ThreadPool::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::ThreadPool::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::ThreadPool::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::ThreadPool::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::ThreadPool::sealed | [protected, virtual]
PeriodicTimerScenario() | SDKSample::ThreadPool::sealed |
rootPage | SDKSample::ThreadPool::sealed | [private]
UpdateUI(ThreadPool::Status status) | SDKSample::ThreadPool::sealed |
UpdateUI(ThreadPool::Status status) | SDKSample::ThreadPool::sealed |
UpdateUI(ThreadPool::Status status) | SDKSample::ThreadPool::sealed |
UpdateWorkItemProgressUI(int percentComplete) | SDKSample::ThreadPool::sealed |
WorkItemScenario() | SDKSample::ThreadPool::sealed |
Generated on Sat Nov 23 2024 16:09:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Print/C++/ScenarioList.xaml.cpp Source File

  • Print

ScenarioList.xaml.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 //
00009 // ScenarioList.xaml.cpp
00010 // Implementation of the ScenarioList class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioList.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace PrintSample;
00018
00019 using namespace Platform;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Graphics::Display;
00023 using namespace Windows::UI::ViewManagement;
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 using namespace Windows::UI::Xaml::Interop;
00032
00033 ScenarioList::ScenarioList()
00034 {
00035     InitializeComponent();
00036 }
00037
00038 ScenarioList::~ScenarioList()
00039 {
00040 }
00041
00042 void ScenarioList::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00043 {
00044     if (Scenarios->SelectedItem != nullptr)
00045     {
00046         rootPage->NotifyUser("", NotifyType::StatusMessage);
00047
00048         ListBoxItem^ selectedListBoxItem = dynamic_cast<ListBoxItem^>(Scenarios->SelectedItem);
00049         SuspensionManager::SessionState()->Insert("SelectedScenario", selectedListBoxItem->Name);
00050
00051         if (rootPage->InputFrame != nullptr && rootPage->OutputFrame != nullptr)
00052         {
00053             //Load the input and output pages for the current scenario into their respective frames.
00054             TypeName inputPage = { "PrintSample" + "." + "ScenarioInput" + ((Scenarios->SelectedIndex + 1).ToString()), TypeKind::Custom };
00055             TypeName outputPage = { "PrintSample" + "." + "ScenarioOutput" + ((Scenarios->SelectedIndex + 1).ToString()), TypeKind::Custom };
00056             rootPage->DoNavigation(inputPage, rootPage->InputFrame);
00057             rootPage->DoNavigation(outputPage, rootPage->OutputFrame);
00058         }
00059     }
00060 }
00061
00062 void ScenarioList::OnNavigatedTo(NavigationEventArgs^ e)
00063 {
00064     rootPage = dynamic_cast<MainPage^>(e->Parameter);
00065
00066     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &ScenarioList::Scenarios_SelectionChanged);
00067     ListBoxItem^ startingScenario = nullptr;
00068
00069     auto ps = SuspensionManager::SessionState();
00070     if (ps->HasKey("SelectedScenario"))
00071     {
00072         PropertyValue^ pv;
00073         String^ item = dynamic_cast<String^>(ps->Lookup("SelectedScenario"));
00074         startingScenario = dynamic_cast<ListBoxItem^>(this->FindName(item));
00075     }
00076
00077     Scenarios->SelectedItem = startingScenario != nullptr ? startingScenario : Scenario1;
00078 }
Generated on Sat Nov 23 2024 16:07:57 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::TileContent::TileSquarePeekImageAndText04 Member List

This is the complete list of members for NotificationsExtensions::TileContent::TileSquarePeekImageAndText04, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
Branding | NotificationsExtensions::TileContent::TileNotificationBase |
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
NotificationsExtensions::GetContent() | NotificationsExtensions::TileContent::TileSquareBase | [inline]
NotificationsExtensions::GetContent() | NotificationsExtensions::TileContent::TileSquareBase | [inline]
NotificationsExtensions::TileContent::TileNotificationBase::GetContent() | NotificationsExtensions::NotificationBase | [pure virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Image | NotificationsExtensions::TileContent::TileSquarePeekImageAndText04 |
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeBinding(string globalLang, string globalBaseUri, TileBranding globalBranding, bool globalAddImageQuery) | NotificationsExtensions::TileContent::TileSquareBase | [inline]
SerializeBinding(string globalLang, string globalBaseUri, TileBranding globalBranding, bool globalAddImageQuery) | NotificationsExtensions::TileContent::TileSquareBase | [inline]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextBodyWrap | NotificationsExtensions::TileContent::TileSquarePeekImageAndText04 |
TextFields | NotificationsExtensions::NotificationBase |
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileSquareBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileSquareBase | [inline]
TileSquareBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileSquareBase | [inline]
TileSquarePeekImageAndText04() | NotificationsExtensions::TileContent::TileSquarePeekImageAndText04 | [inline]
TileSquarePeekImageAndText04() | NotificationsExtensions::TileContent::TileSquarePeekImageAndText04 | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:43 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Clipboard app/C++/CopyText.xaml.cpp Source File

  • Clipboard app

CopyText.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 // CopyText.xaml.cpp
00013 // Implementation of the CopyText class
00014 //
00015
00016 #include "pch.h"
00017 #include "CopyText.xaml.h"
00018
00019 using namespace Clipboard;
00020
00021 using namespace Platform;
00022 using namespace Windows::Foundation;
00023 using namespace Windows::Foundation::Collections;
00024 using namespace Windows::Storage::Streams;
00025 using namespace Windows::Graphics::Display;
00026 using namespace Windows::UI::ViewManagement;
00027 using namespace Windows::Data;
00028 using namespace Windows::Data::Html;
00029
00030 using namespace Windows::UI::Xaml;
00031 using namespace Windows::UI::Xaml::Controls;
00032 using namespace Windows::UI::Xaml::Navigation;
00033
00034 // App specific namespace references
00035 using namespace concurrency;
00036 using namespace Windows::ApplicationModel;
00037 using namespace Windows::ApplicationModel::DataTransfer;
00038
00039 CopyText::CopyText()
00040 {
00041     InitializeComponent();
00042
00043     imgSrc = "ms-appx-web:///assets/microsoft-sdk.png";
00044
00045     htmlDescription = "Use Clipboard to copy and paste text in different formats, including plain text, and formatted text (HTML).<br />"
00046         + "To <b>copy</b>, add text or HTML formats to a <i>DataPackage</i>, and then place <i>DataPackage</i> into the Clipboard.<br />"
00047         + "To handle local image files in the formatted text (such as the one below), use a resourceMap collection.<br />"
00048         + "<br /><img id=\"LocalImage\" src=\"" + imgSrc + "\" /><br /><br />"
00049         + "To <b>paste</b>, get <i>DataPackageView</i> from the Clipboard, and retrieve the content of the desired text format from it.<br />"
00050         + "The <i>DataPackage</i> class is also used to share or send content between applications. See the Share SDK sample for more information.";
00051
00052     CopyTextDescription->NavigateToString(htmlDescription);
00053
00054     textDescription = HtmlUtilities::ConvertToText(htmlDescription);
00055 }
00056
00057 void CopyText::OnNavigatedTo(NavigationEventArgs^ e)
00058 {
00059     // A pointer back to the main page. This is needed if you want to call methods in MainPage such
00060     // as NotifyUser()
00061     rootPage = MainPage::Current;
00062 }
00063
00064 #pragma region CopyText Click handlers
00065 void CopyText::CopyButton_Click(Object^ sender, RoutedEventArgs^ e)
00066 {
00067     OutputHtml->NavigateToString("<HTML></HTML>");
00068     ResourceMapText->Text = "";
00069     OutputText->Text = "";
00070
00071     auto dataPackage = ref new DataPackage();
00072     String^ htmlFormat = HtmlFormatHelper::CreateHtmlFormat(htmlDescription);
00073
00074     // Set the content as CF_HTML html format.
00075     dataPackage->SetHtmlFormat(htmlFormat);
00076
00077     // Set the content as CF_TEXT text format.
00078     dataPackage->SetText(textDescription);
00079
00080     // Populate resourceMap with StreamReference objects corresponding to local image files embedded in HTML
00081     auto imgUri = ref new Uri(imgSrc);
00082     auto imgRef = RandomAccessStreamReference::CreateFromUri(imgUri);
00083     dataPackage->ResourceMap->Insert(imgSrc, imgRef);
00084
00085     try
00086     {
00087         // Set the contents in the clipboard
00088         DataTransfer::Clipboard::SetContent(dataPackage);
00089         rootPage->NotifyUser("Text and HTML formats have been copied to clipboard. ", NotifyType::StatusMessage);
00090     }
00091     catch (Exception^ ex)
00092     {
00093         // Copying data to the Clipboard can potentially fail - for example, if another application is holding the Clipboard open
00094         rootPage->NotifyUser("Error copying Text and HTML formats to Clipboard: " + ex->Message + ".", NotifyType::ErrorMessage);
00095     }
00096 }
00097
00098 void CopyText::PasteButton_Click(Object^ sender, RoutedEventArgs^ e)
00099 {
00100     OutputHtml->NavigateToString("<HTML></HTML>");
00101     ResourceMapText->Text = "";
00102     OutputText->Text = "";
00103
00104     rootPage->NotifyUser("Clipboard content displayed below: ", NotifyType::StatusMessage);
00105
00106     DataPackageView^ dataPackageView = DataTransfer::Clipboard::GetContent();
00107
00108     if (dataPackageView->Contains(StandardDataFormats::Html))
00109     {
00110         create_task(dataPackageView->GetHtmlFormatAsync()).then(
00111             [this](task<String^> htmlTask)
00112             {
00113                 String^ htmlFormat;
00114                 try
00115                 {
00116                     htmlFormat = htmlTask.get();
00117                 }
00118                 catch (Exception^ ex)
00119                 {
00120                     rootPage->NotifyUserBackgroundThread("Failed GetHtmlFormatAsync - " + ex->Message, NotifyType::ErrorMessage);
00121                 }
00122
00123                 if (htmlFormat != nullptr)
00124                 {
00125                     String^ htmlFragment = HtmlFormatHelper::GetStaticFragment(htmlFormat);
00126
00127                     // Note: Metro Style apps may be unable to render some schemes (e.g., 'ms-clipboard-file') that reference local content.
00128                     // As a result, images may look broken. To learn the different URL schemes used by Metro style apps and how to use them
00129                     // to refer to content, see MSDN - http://msdn.microsoft.com/en-us/library/windows/apps/hh781215.aspx
00130                     OutputHtml->NavigateToString("HTML:<br />" + htmlFragment);
00131                 }
00132             });
00133
00134         // Note: this sample is not trying to resolve and render the HTML using resource map.
00135         // Please refer to the Clipboard JavaScript sample for an example of how to use resource map
00136         // for local images display within an HTML format. This sample will only demonstrate how to
00137         // get a resource map object and extract its key values
00138         create_task(dataPackageView->GetResourceMapAsync()).then(
00139             [this](task<IMapView<String^, RandomAccessStreamReference^>^> resourceMapTask)
00140             {
00141                 IMapView<String^, RandomAccessStreamReference^>^ resourceMap = resourceMapTask.get();
00142
00143                 // Check if there are any local images in the resource map.
00144                 if (resourceMap->Size > 0)
00145                 {
00146                     ResourceMapText->Text = "\n\nResource Map:";
00147                     std::for_each(begin(resourceMap), end(resourceMap),
00148                         [this](IKeyValuePair<String^, RandomAccessStreamReference^>^ item)
00149                         {
00150                             ResourceMapText->Text += "\n\tKey: " + item->Key;
00151                         });
00152                 }
00153                 else
00154                 {
00155                     rootPage->NotifyUserBackgroundThread("The resource map does not contain any file", NotifyType::StatusMessage);
00156                 }
00157             });
00158     }
00159     else
00160     {
00161         rootPage->NotifyUser("HTML format is not available in clipboard", NotifyType::StatusMessage);
00162     }
00163
00164     if (dataPackageView->Contains(StandardDataFormats::Text))
00165     {
00166         create_task(dataPackageView->GetTextAsync()).then(
00167             [this](task<String^> textTask)
00168             {
00169                 try
00170                 {
00171                     OutputText->Text = "\nText: \n" + textTask.get();
00172                 }
00173                 catch (Exception^ ex)
00174                 {
00175                     rootPage->NotifyUserBackgroundThread("Failed GetTextAsync - " + ex->Message, NotifyType::ErrorMessage);
00176                 }
00177             });
00178     }
00179     else
00180     {
00181         rootPage->NotifyUser("Text format is not available in clipboard", NotifyType::StatusMessage);
00182     }
00183 }
00184
00185 #pragma endregion
Generated on Sat Nov 23 2024 16:07:59 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

StreamSocketSample::App Member List

This is the complete list of members for StreamSocketSample::App, including all inherited members.
__pad0__ | StreamSocketSample::App |
OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^pArgs) override | StreamSocketSample::App | [virtual]
OnSuspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^pArgs) | StreamSocketSample::App | [virtual]
rootFrame | StreamSocketSample::App | [private]
Generated on Sat Nov 23 2024 16:09:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

AntSystem::Edge Member List

This is the complete list of members for AntSystem::Edge, including all inherited members.
Edge(std::shared_ptr< Node > pointA, std::shared_ptr< Node > pointB) | AntSystem::Edge | [inline, explicit]
Pheromone | AntSystem::Edge |
PointA | AntSystem::Edge |
PointB | AntSystem::Edge |
TravelDistance | AntSystem::Edge |
Generated on Sat Nov 23 2024 16:09:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D custom image effects/C++/VertexShader/pch.h Source File

  • Direct2D custom image effects
  • VertexShader

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 <d3d11_1.h>
00012 #include <d2d1_1.h>
00013 #include <d2d1effects.h>
00014 #include <dwrite_1.h>
00015 #include <wincodec.h>
00016 #include <agile.h>
00017 #include <math.h>
00018 #include <d2d1effectauthor.h>
00019 #include <d2d1effecthelpers.h>
00020
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Account picture name/C++/GetUserDisplayName.xaml.cpp Source File

  • Account picture name

GetUserDisplayName.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 // GetUserDisplayName.xaml.cpp
00013 // Implementation of the GetUserDisplayName class
00014 //
00015
00016 #include "pch.h"
00017 #include "GetUserDisplayName.xaml.h"
00018
00019 using namespace AccountPictureName;
00020 using namespace concurrency;
00021 using namespace Platform;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Navigation;
00025 using namespace Windows::System::UserProfile;
00026 using namespace Windows::Foundation;
00027 using namespace Microsoft::WRL;
00028 using namespace Microsoft::WRL::Wrappers;
00029
00030 GetUserDisplayName::GetUserDisplayName()
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 void GetUserDisplayName::OnNavigatedTo(NavigationEventArgs^ e)
00041 {
00042     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00043     // as NotifyUser()
00044     rootPage = MainPage::Current;
00045 }
00046
00047 void GetUserDisplayName::GetDisplayNameButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00048 {
00049     if (UserInformation::NameAccessAllowed)
00050     {
00051         create_task(UserInformation::GetDisplayNameAsync()).then([this](String^ displayName)
00052         {
00053             if (displayName != nullptr)
00054             {
00055                 rootPage->NotifyUser("Display name = " + displayName, NotifyType::StatusMessage);
00056             }
00057             else
00058             {
00059                 rootPage->NotifyUser("No display name returned for current user.", NotifyType::ErrorMessage);
00060             }
00061         });
00062     }
00063     else
00064     {
00065         rootPage->NotifyUser("Access to Name disabled by Privacy Setting or Group Policy", NotifyType::ErrorMessage);
00066     }
00067 }
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Touch hit testing/C++/DirectXSample.h Source File

  • Input Touch hit testing

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
00010 // This header defines helper utilities to make DirectX APIs work with exceptions.
00011 namespace DX
00012 {
00013     inline void ThrowIfFailed(HRESULT hr)
00014     {
00015         if (FAILED(hr))
00016         {
00017             // Set a breakpoint on this line to catch DX API errors.
00018             throw Platform::Exception::CreateException(hr);
00019         }
00020     }
00021 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Account picture name/C++/App.xaml.cpp Source File

  • Account picture name

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "App.xaml.h"
00018 #include "MainPage.xaml.h"
00019
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Controls;
00022 using namespace Windows::ApplicationModel;
00023 using namespace Windows::ApplicationModel::Activation;
00024 using namespace CppSamplesUtils;
00025 using namespace AccountPictureName;
00026 using namespace Windows::UI::Xaml::Interop;
00027
00028 App::App()
00029 {
00030     InitializeComponent();
00031     this->Suspending += ref new SuspendingEventHandler(this, &AccountPictureName::App::OnSuspending);
00032 }
00033
00034 void App::OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs)
00035 {
00036     auto deferral = pArgs->SuspendingOperation->GetDeferral();
00037     SuspensionManager::StartSaveTask().then([=]()
00038     {
00039         deferral->Complete();
00040     });
00041 }
00042
00043 void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs)
00044 {
00045     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Terminated)
00046     {
00047         SuspensionManager::StartRestoreTask().then([=](concurrency::task<void> restoreTask)
00048         {
00049             try
00050             {
00051                 restoreTask.get();
00052             }
00053             catch(Platform::Exception^)
00054             {
00055                 // If restore fails, the app should proceed as though there was no restored state.
00056             }
00057
00058             SetupWindowing(pArgs);
00059         });
00060     }
00061     else
00062     {
00063         SetupWindowing(pArgs);
00064     }
00065
00066 }
00067
00068 void App::SetupWindowing(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs)
00069 {
00070     if (Window::Current->Content == nullptr)
00071     {
00072         rootFrame = ref new Frame();
00073         TypeName pageType = { "AccountPictureName.MainPage", TypeKind::Custom };
00074         rootFrame->Navigate(pageType);
00075         Window::Current->Content = rootFrame;
00076     }
00077     MainPage^ p = safe_cast<MainPage^>(rootFrame->Content);
00078     p->LaunchArgs = pArgs;
00079     Window::Current->Activate();
00080 }
00081
00082 void App::OnActivated(IActivatedEventArgs^ args)
00083 {
00084     auto rootFrame = ref new Frame();
00085     TypeName pageType = { "AccountPictureName.MainPage", TypeKind::Custom };
00086     rootFrame->Navigate(pageType);
00087     Window::Current->Content = rootFrame;
00088
00089     // Check to see if the app was activated via a protocol
00090     if (args->Kind == ActivationKind::Protocol)
00091     {
00092         auto protocolArgs = safe_cast<ProtocolActivatedEventArgs^>(args);
00093         if (protocolArgs->Uri->SchemeName->Equals("ms-accountpictureprovider"))
00094         {
00095             auto rootPage = safe_cast<MainPage^>(rootFrame->Content);
00096             rootPage->ProtocolEvent = protocolArgs;
00097             MainPage::Current->LoadSetAccountPictureScenario();
00098         }
00099     }
00100     Window::Current->Activate();
00101 }
Generated on Sat Nov 23 2024 16:07:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playback Manager Companion/C++/StreamTypeAlert.xaml.cpp Source File

  • Playback Manager Companion

StreamTypeAlert.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 // StreamTypeAlert.xaml.cpp
00013 // Implementation of the StreamTypeAlert class
00014 //
00015
00016 #include "pch.h"
00017 #include "StreamTypeAlert.xaml.h"
00018
00019 using namespace SDKSample::PlaybackManager2;
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::UI::Xaml::Media;
00025
00026 StreamTypeAlert::StreamTypeAlert()
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 StreamTypeAlert::OnNavigatedTo(NavigationEventArgs^ e)
00037 {
00038     // Get a pointer to our main page.
00039     rootPage = MainPage::Current;
00040 }
00041
00042
00043 void StreamTypeAlert::Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00044 {
00045   Playback->SetAudioCategory(AudioCategory::Alerts);
00046     Playback->SelectFile();
00047 }
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2Dapp printing/C++/D2DPageRenderer.cpp Source File

  • Direct2Dapp printing

D2DPageRenderer.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 <math.h>
00010 #include "D2DPageRenderer.h"
00011 #include "D2DPageRendererContext.h"
00012
00013 using namespace Microsoft::WRL;
00014 using namespace Microsoft::WRL::Wrappers;
00015 using namespace Windows::Foundation;
00016 using namespace Windows::UI::Core;
00017 using namespace Windows::Graphics::Display;
00018
00019 PageRenderer::PageRenderer()
00020 : m_isSnapped(false)
00021 {
00022 }
00023
00024 void PageRenderer::CreateDeviceIndependentResources()
00025 {
00026     DirectXBase::CreateDeviceIndependentResources();
00027
00028     // Create a DirectWrite text format object for the sample's content.
00029     DX::ThrowIfFailed(
00030         m_dwriteFactory->CreateTextFormat(
00031             L"Segoe UI",
00032             nullptr,
00033             DWRITE_FONT_WEIGHT_NORMAL,
00034             DWRITE_FONT_STYLE_NORMAL,
00035             DWRITE_FONT_STRETCH_NORMAL,
00036             40.0f,
00037             L"en-us", // locale
00038             &m_textFormat
00039             )
00040         );
00041
00042     // Align the text horizontally.
00043     DX::ThrowIfFailed(
00044         m_textFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)
00045         );
00046
00047     // Center the text vertically.
00048     DX::ThrowIfFailed(
00049         m_textFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER)
00050         );
00051
00052     // Create a DirectWrite text format object for status messages.
00053     DX::ThrowIfFailed(
00054         m_dwriteFactory->CreateTextFormat(
00055             L"Segoe UI",
00056             nullptr,
00057             DWRITE_FONT_WEIGHT_NORMAL,
00058             DWRITE_FONT_STYLE_NORMAL,
00059             DWRITE_FONT_STRETCH_NORMAL,
00060             20.0f,
00061             L"en-us", // locale
00062             &m_messageFormat
00063             )
00064         );
00065
00066     // Center the text horizontally.
00067     DX::ThrowIfFailed(
00068         m_messageFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER)
00069         );
00070
00071     // Center the text vertically.
00072     DX::ThrowIfFailed(
00073         m_messageFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER)
00074         );
00075 }
00076
00077 void PageRenderer::CreateDeviceResources()
00078 {
00079     DirectXBase::CreateDeviceResources();
00080
00081     // Create and initialize sample overlay for sample title.
00082     m_sampleOverlay = ref new SampleOverlay();
00083     m_sampleOverlay->Initialize(
00084         m_d2dDevice.Get(),
00085         m_d2dContext.Get(),
00086         m_wicFactory.Get(),
00087         m_dwriteFactory.Get(),
00088         "Direct2D Windows Store app printing sample"
00089         );
00090
00091     D2D1_SIZE_F size = m_d2dContext->GetSize();
00092
00093     // Exclude sample title from imageable area for image drawing.
00094     float titleHeight = m_sampleOverlay->GetTitleHeightInDips();
00095
00096     // Create and initialize the page renderer context for display.
00097     m_displayPageRendererContext =
00098         ref new PageRendererContext(
00099             D2D1::RectF(0, titleHeight, size.width, size.height),
00100             m_d2dContext.Get(),
00101             DrawTypes::Rendering,
00102             this
00103             );
00104 }
00105
00106 void PageRenderer::UpdateForWindowSizeChange()
00107 {
00108     DirectXBase::UpdateForWindowSizeChange();
00109     m_sampleOverlay->UpdateForWindowSizeChange();
00110
00111     D2D1_SIZE_F size = m_d2dContext->GetSize();
00112
00113     // Exclude sample title from imageable area for image drawing.
00114     float titleHeight = m_sampleOverlay->GetTitleHeightInDips();
00115
00116     D2D1_RECT_F contentBox = D2D1::RectF(0, titleHeight, size.width, size.height);
00117     m_displayPageRendererContext->UpdateTargetBox(
00118         contentBox
00119         );
00120 }
00121
00122 // On-screen rendering.
00123 void PageRenderer::Render()
00124 {
00125     m_d2dContext->BeginDraw();
00126
00127     if (m_isSnapped)
00128     {
00129         m_displayPageRendererContext->DrawMessage("This sample does not support snapped view.");
00130     }
00131     else
00132     {
00133         // Render page context.
00134         m_displayPageRendererContext->Draw(1.0f);
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 = m_d2dContext->EndDraw();
00140     if (hr != D2DERR_RECREATE_TARGET)
00141     {
00142         DX::ThrowIfFailed(hr);
00143     }
00144
00145     // Render sample title.
00146     m_sampleOverlay->Render();
00147
00148     // We are accessing D3D resources directly in Present() without D2D's knowledge,
00149     // so we must manually acquire the D2D factory lock.
00150     //
00151     // Note: it's absolutely critical that the factory lock be released upon
00152     // exiting this function, or else the entire app will deadlock. This is
00153     // ensured via the following RAII class.
00154     {
00155         D2DFactoryLock factoryLock(m_d2dFactory.Get());
00156         Present();
00157     }
00158 }
00159
00160 void PageRenderer::SetSnappedMode(_In_ bool isSnapped)
00161 {
00162     m_isSnapped = isSnapped;
00163 }
00164
00165 void PageRenderer::DrawPreviewSurface(
00166     _In_  float                             width,
00167     _In_  float                             height,
00168     _In_  float                             scale,
00169     _In_  D2D1_RECT_F                       contentBox,
00170     _In_  uint32                            desiredJobPage,
00171     _In_  IPrintPreviewDxgiPackageTarget*   previewTarget
00172     )
00173 {
00174     // We are accessing D3D resources directly without D2D's knowledge, so we
00175     // must manually acquire the D2D factory lock.
00176     //
00177     // Note: it's absolutely critical that the factory lock be released upon
00178     // exiting this function, or else the entire app will deadlock. This is
00179     // ensured via the following RAII class.
00180     D2DFactoryLock factoryLock(m_d2dFactory.Get());
00181
00182     CD3D11_TEXTURE2D_DESC textureDesc(
00183         DXGI_FORMAT_B8G8R8A8_UNORM,
00184         static_cast<uint32>(ceil(width  * m_dpi / 96)),
00185         static_cast<uint32>(ceil(height * m_dpi / 96)),
00186         1,
00187         1,
00188         D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE
00189         );
00190
00191     ComPtr<ID3D11Texture2D> texture;
00192     DX::ThrowIfFailed(
00193         m_d3dDevice->CreateTexture2D(
00194             &textureDesc,
00195             nullptr,
00196             &texture
00197             )
00198         );
00199
00200     // Create a preview DXGI surface with given size.
00201     ComPtr<IDXGISurface> dxgiSurface;
00202     DX::ThrowIfFailed(
00203         texture.As<IDXGISurface>(&dxgiSurface)
00204         );
00205
00206     // Create a new D2D device context for rendering the preview surface. D2D
00207     // device contexts are stateful, and hence a unique device context must be
00208     // used on each thread.
00209     ComPtr<ID2D1DeviceContext> d2dContext;
00210     DX::ThrowIfFailed(
00211         m_d2dDevice->CreateDeviceContext(
00212             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00213             &d2dContext
00214             )
00215         );
00216
00217     // Update DPI for preview surface as well.
00218     d2dContext->SetDpi(m_dpi, m_dpi);
00219
00220     // Recommend using the screen DPI for better fidelity and better performance in the print preview.
00221     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00222         D2D1::BitmapProperties1(
00223             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00224             D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED)
00225             );
00226
00227     // Create surface bitmap on which page content is drawn.
00228     ComPtr<ID2D1Bitmap1> d2dSurfaceBitmap;
00229     DX::ThrowIfFailed(
00230         d2dContext->CreateBitmapFromDxgiSurface(
00231             dxgiSurface.Get(),
00232             &bitmapProperties,
00233             &d2dSurfaceBitmap
00234             )
00235         );
00236
00237     d2dContext->SetTarget(d2dSurfaceBitmap.Get());
00238
00239     // Create and initialize the page renderer context for preview.
00240     PageRendererContext^ previewPageRendererContext =
00241         ref new PageRendererContext(
00242             contentBox,
00243             d2dContext.Get(),
00244             DrawTypes::Preview,
00245             this
00246             );
00247
00248     d2dContext->BeginDraw();
00249
00250     // Draw page content on the preview surface.
00251     // Here contentBox is smaller than the real page size and the scale indicates the proportion.
00252     // It is faster to draw content on a smaller surface.
00253     previewPageRendererContext->Draw(scale);
00254
00255     // The document source handles D2DERR_RECREATETARGET, so it is okay to throw this error
00256     // here.
00257     DX::ThrowIfFailed(
00258         d2dContext->EndDraw()
00259         );
00260
00261     // Must pass the same DPI as used to create the DXGI surface for the correct print preview.
00262     DX::ThrowIfFailed(
00263         previewTarget->DrawPage(
00264             desiredJobPage,
00265             dxgiSurface.Get(),
00266             m_dpi,
00267             m_dpi
00268             )
00269         );
00270 }
00271
00272 void PageRenderer::CreatePrintControl(
00273     _In_  IPrintDocumentPackageTarget*      docPackageTarget,
00274     _In_  D2D1_PRINT_CONTROL_PROPERTIES*    printControlProperties
00275     )
00276 {
00277     // Explicitly release existing D2D print control.
00278     m_d2dPrintControl = nullptr;
00279
00280     DX::ThrowIfFailed(
00281         m_d2dDevice->CreatePrintControl(
00282             m_wicFactory.Get(),
00283             docPackageTarget,
00284             printControlProperties,
00285             &m_d2dPrintControl
00286             )
00287         );
00288 }
00289
00290 HRESULT PageRenderer::ClosePrintControl()
00291 {
00292     return (m_d2dPrintControl == nullptr) ? S_OK : m_d2dPrintControl->Close();
00293 }
00294
00295 // Print out one page, with the given print ticket.
00296 // This sample has only one page and we ignore pageNumber below.
00297 void PageRenderer::PrintPage(
00298     _In_ uint32                 /*pageNumber*/,
00299     _In_ D2D1_RECT_F            imageableArea,
00300     _In_ D2D1_SIZE_F            pageSize,
00301     _In_opt_ IStream*           pagePrintTicketStream
00302     )
00303 {
00304     // Create a new D2D device context for generating the print command list.
00305     // D2D device contexts are stateful, and hence a unique device context must
00306     // be used on each thread.
00307     ComPtr<ID2D1DeviceContext> d2dContext;
00308     DX::ThrowIfFailed(
00309         m_d2dDevice->CreateDeviceContext(
00310             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00311             &d2dContext
00312             )
00313         );
00314
00315     ComPtr<ID2D1CommandList> printCommandList;
00316     DX::ThrowIfFailed(
00317         d2dContext->CreateCommandList(&printCommandList)
00318         );
00319
00320     d2dContext->SetTarget(printCommandList.Get());
00321
00322     // Create and initialize the page renderer context for print.
00323     // In this case, we want to use the bitmap source that already has
00324     // the color context embedded in it. Thus, we pass NULL for the
00325     // color context parameter.
00326     PageRendererContext^ printPageRendererContext =
00327         ref new PageRendererContext(
00328             imageableArea,
00329             d2dContext.Get(),
00330             DrawTypes::Printing,
00331             this
00332             );
00333
00334     d2dContext->BeginDraw();
00335
00336     // Draw page content on a command list.
00337     // 1.0f below indicates that the printing content does not scale.
00338     // "DrawTypes::Printing" below indicates it is a printing case.
00339     printPageRendererContext->Draw(1.0f);
00340
00341     // The document source handles D2DERR_RECREATETARGET, so it is okay to throw this error
00342     // here.
00343     DX::ThrowIfFailed(
00344         d2dContext->EndDraw()
00345         );
00346
00347     DX::ThrowIfFailed(
00348         printCommandList->Close()
00349         );
00350
00351     DX::ThrowIfFailed(
00352         m_d2dPrintControl->AddPage(printCommandList.Get(), pageSize, pagePrintTicketStream)
00353         );
00354 }
00355
00356 IDWriteTextFormat* PageRenderer::GetTextFormatNoRef()
00357 {
00358     return m_textFormat.Get();
00359 }
00360
00361 IDWriteTextFormat* PageRenderer::GetMessageFormatNoRef()
00362 {
00363     return m_messageFormat.Get();
00364 }
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::TileContent::TileWideText11 Member List

This is the complete list of members for NotificationsExtensions::TileContent::TileWideText11, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
Branding | NotificationsExtensions::TileContent::TileNotificationBase |
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
RequireSquareContent | NotificationsExtensions::TileContent::TileWideBase |
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SquareContent | NotificationsExtensions::TileContent::TileWideBase |
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextColumn2Row1 | NotificationsExtensions::TileContent::TileWideText11 |
TextColumn2Row2 | NotificationsExtensions::TileContent::TileWideText11 |
TextColumn2Row3 | NotificationsExtensions::TileContent::TileWideText11 |
TextColumn2Row4 | NotificationsExtensions::TileContent::TileWideText11 |
TextColumn2Row5 | NotificationsExtensions::TileContent::TileWideText11 |
TextFields | NotificationsExtensions::NotificationBase |
TextPrefixColumn1Row1 | NotificationsExtensions::TileContent::TileWideText11 |
TextPrefixColumn1Row2 | NotificationsExtensions::TileContent::TileWideText11 |
TextPrefixColumn1Row3 | NotificationsExtensions::TileContent::TileWideText11 |
TextPrefixColumn1Row4 | NotificationsExtensions::TileContent::TileWideText11 |
TextPrefixColumn1Row5 | NotificationsExtensions::TileContent::TileWideText11 |
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWideText11() | NotificationsExtensions::TileContent::TileWideText11 | [inline]
TileWideText11() | NotificationsExtensions::TileContent::TileWideText11 | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX postcard app/C++/Extruder.cpp Source File

  • DirectX postcard app

Extruder.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 "Extruder.h"
00010
00011 using namespace Microsoft::WRL;
00012
00013 static const float FlatteningTolerance = 0.1f;
00014
00015 void Extruder::ExtrudeGeometry(ID2D1Geometry* pGeometry, float height, std::vector<SimpleVertex>* vertices)
00016 {
00017     //
00018     // The basic idea here is to generate the side faces by walking the
00019     // geometry and constructing quads, and use ID2D1Geometry::Tessellate
00020     // to generate the front and back faces.
00021     //
00022
00023     // Flatten our geometry first so we don't have to worry about stitching
00024     // together seams of Beziers.
00025     ComPtr<ID2D1Geometry> pFlattenedGeometry;
00026     D2DFlatten(pGeometry, FlatteningTolerance, &pFlattenedGeometry);
00027
00028     // D2DOutline will remove any self-intersections. This is important to
00029     // ensure that the tessellator doesn't introduce new vertices (which
00030     // can cause T-junctions).
00031     ComPtr<ID2D1Geometry> pOutlinedGeometry;
00032     D2DOutline(pFlattenedGeometry.Get(), &pOutlinedGeometry);
00033
00034     ComPtr<ID2D1Geometry> pSnappedGeometry;
00035     PointSnapper::SnapGeometry(pOutlinedGeometry.Get(), &pSnappedGeometry);
00036
00037     ComPtr<ExtrudingSink> helper;
00038     ExtrudingSink::CreateExtrudingSink(height, vertices, &helper);
00039
00040     DX::ThrowIfFailed(
00041         pSnappedGeometry->Tessellate(nullptr, helper.Get())
00042         );
00043
00044     // Simplify is a convenient API for extracting the data out of a geometry.
00045     DX::ThrowIfFailed(
00046         pOutlinedGeometry->Simplify(
00047             D2D1_GEOMETRY_SIMPLIFICATION_OPTION_LINES,
00048             nullptr, // world transform
00049             helper.Get()
00050             )
00051         );
00052
00053     // This Close() call is a little ambiguous, since it refers both to the
00054     // ID2D1TessellationSink and to the ID2D1SimplifiedGeometrySink.
00055     // Thankfully, it really doesn't matter with our ExtrudingSink.
00056     DX::ThrowIfFailed(
00057         helper->Close()
00058         );
00059 }
00060
00061 // Helper function for performing "flattening" -- transforming
00062 // a geometry with Beziers into one containing only line segments.
00063 void Extruder::D2DFlatten(ID2D1Geometry* pGeometry, float flatteningTolerance, ID2D1Geometry** ppGeometry)
00064 {
00065     ComPtr<ID2D1Factory> pFactory;
00066     pGeometry->GetFactory(&pFactory);
00067
00068     ComPtr<ID2D1PathGeometry> pPathGeometry;
00069     DX::ThrowIfFailed(
00070         pFactory->CreatePathGeometry(&pPathGeometry)
00071         );
00072
00073     ComPtr<ID2D1GeometrySink> pSink;
00074     DX::ThrowIfFailed(
00075         pPathGeometry->Open(&pSink)
00076         );
00077
00078     DX::ThrowIfFailed(
00079         pGeometry->Simplify(
00080             D2D1_GEOMETRY_SIMPLIFICATION_OPTION_LINES,
00081             nullptr, // world transform
00082             flatteningTolerance,
00083             pSink.Get()
00084             )
00085         );
00086
00087     DX::ThrowIfFailed(
00088         pSink->Close()
00089         );
00090
00091     *ppGeometry = pPathGeometry.Get();
00092     (*ppGeometry)->AddRef();
00093 }
00094
00095 // Helper function for performing "outlining" -- constructing an
00096 // equivalent geometry with no self-intersections. Note: This
00097 // uses the default flattening tolerance and hence should not be
00098 // used with very small geometries.
00099 void Extruder::D2DOutline(ID2D1Geometry* pGeometry, ID2D1Geometry** ppGeometry)
00100 {
00101     ComPtr<ID2D1Factory> pFactory;
00102     pGeometry->GetFactory(&pFactory);
00103
00104     ComPtr<ID2D1PathGeometry> pPathGeometry;
00105     DX::ThrowIfFailed(
00106         pFactory->CreatePathGeometry(&pPathGeometry)
00107         );
00108
00109     ComPtr<ID2D1GeometrySink> pSink;
00110     DX::ThrowIfFailed(
00111         pPathGeometry->Open(&pSink)
00112         );
00113
00114     DX::ThrowIfFailed(
00115         pGeometry->Outline(nullptr, pSink.Get())
00116         );
00117
00118     DX::ThrowIfFailed(
00119         pSink->Close()
00120         );
00121
00122     *ppGeometry = pPathGeometry.Get();
00123     (*ppGeometry)->AddRef();
00124 }
00125
00126 // Internal sink used to implement Extruder.
00127 // Note: This class makes certain assumptions about its usage
00128 // (e.g. no Beziers), which is why it's a private class.
00129 // Note 2: Both ID2D1SimplifiedGeometrySink and
00130 // ID2D1TessellationSink define a Close() method, which is
00131 // bending the rules a bit. This is another reason why we are
00132 // significantly limiting its usage.
00133 void Extruder::ExtrudingSink::CreateExtrudingSink(
00134     float height,
00135     _In_ std::vector<SimpleVertex>* pVertices,
00136     _Outptr_ ExtrudingSink** ppExtrudingSink
00137     )
00138 {
00139     *ppExtrudingSink = new ExtrudingSink(height, pVertices);
00140     (*ppExtrudingSink)->AddRef();
00141 }
00142
00143 Extruder::ExtrudingSink::ExtrudingSink(float height, _In_ std::vector<SimpleVertex>* pVertices) :
00144     m_height(height),
00145     m_vertices(pVertices),
00146     m_ref(0)
00147 {
00148 }
00149
00150 void Extruder::ExtrudingSink::AddBeziers(const D2D1_BEZIER_SEGMENT* /*beziers*/, UINT /*beziersCount*/)
00151 {
00152     //
00153     // ExtrudingSink only handles line segments. Users should flatten
00154     // their geometry prior to passing through an ExtrudingSink.
00155     //
00156 }
00157
00158 void Extruder::ExtrudingSink::AddLines(const D2D1_POINT_2F* points, UINT pointsCount)
00159 {
00160     for (UINT i = 0; i < pointsCount; ++i)
00161     {
00162         Vertex2D v;
00163
00164         v.pt = float2(points[i].x, points[i].y);
00165
00166         //
00167         // Take care to ignore degenerate segments, as we will be
00168         // unable to compute proper normals for them.
00169         //
00170         // Note: This doesn't handle near-degenerate segments, which
00171         // should probably also be removed. The one complication here
00172         // is that the segments should be removed from both the outline
00173         // and the front/back tessellations.
00174         //
00175         if ((m_figureVertices.size() == 0) ||
00176             (v.pt.x != m_figureVertices.back().pt.x) ||
00177             (v.pt.y != m_figureVertices.back().pt.y)
00178             )
00179         {
00180             m_figureVertices.push_back(v);
00181         }
00182     }
00183 }
00184
00185 void Extruder::ExtrudingSink::BeginFigure(D2D1_POINT_2F startPoint, D2D1_FIGURE_BEGIN /*figureBegin*/)
00186 {
00187     m_figureVertices.clear();
00188
00189     Vertex2D v = {
00190         float2(startPoint.x, startPoint.y),
00191         float2(0, 0), // dummy
00192         float2(0, 0), // dummy
00193         float2(0, 0) // dummy
00194     };
00195
00196     m_figureVertices.push_back(v);
00197 }
00198
00199 HRESULT Extruder::ExtrudingSink::Close()
00200 {
00201     return S_OK;
00202 }
00203
00204 void Extruder::ExtrudingSink::EndFigure(D2D1_FIGURE_END /*figureEnd*/)
00205 {
00206     float2 front =  m_figureVertices.front().pt;
00207     float2 back =  m_figureVertices.back().pt;
00208
00209     if (front.x == back.x && front.y == back.y)
00210     {
00211         m_figureVertices.pop_back();
00212     }
00213
00214     // If we only have one vertex, then there is nothing to draw!
00215     if (m_figureVertices.size() > 1)
00216     {
00217         //
00218         // We construct the triangles corresponding to the sides of
00219         // the extruded object in 3 steps:
00220         //
00221
00222         //
00223         // Step 1:
00224         //
00225         // Snap vertices and calculate normals.
00226         //
00227         //
00228         // Note: it is important that we compute normals *before*
00229         // snapping the vertices, otherwise, the normals will become
00230         // discretized, which will manifest itself as faceting.
00231         //
00232         for (UINT i = 0; i < m_figureVertices.size(); ++i)
00233         {
00234             m_figureVertices[i].norm = GetNormal(i);
00235             m_figureVertices[i].pt = PointSnapper::SnapPoint(m_figureVertices[i].pt);
00236         }
00237
00238         //
00239         // Step 2:
00240         //
00241         // Interpolate normals as appropriate.
00242         //
00243         for (UINT i = 0; i < m_figureVertices.size(); ++i)
00244         {
00245             UINT h = (i+m_figureVertices.size()-1)%m_figureVertices.size();
00246
00247             float2 n1 =  m_figureVertices[h].norm;
00248             float2 n2 =  m_figureVertices[i].norm;
00249
00250             //
00251             // Take a dot-product to determine if the angle between
00252             // the normals is small. If it is, then average them so we
00253             // get a smooth transition from one face to the next.
00254             //
00255             if ((n1.x * n2.x + n1.y * n2.y) > 0.5f)
00256             {
00257                 float2 sum = m_figureVertices[i].norm + m_figureVertices[h].norm;
00258
00259                 m_figureVertices[i].interpNorm1 = m_figureVertices[i].interpNorm2 = Normalize(sum);
00260             }
00261             else
00262             {
00263                 m_figureVertices[i].interpNorm1 = m_figureVertices[h].norm;
00264                 m_figureVertices[i].interpNorm2 = m_figureVertices[i].norm;
00265             }
00266         }
00267
00268         //
00269         // Step 3:
00270         //
00271         // Output the triangles.
00272         //
00273
00274         // interpNorm1 == end normal of previous segment
00275         // interpNorm2 == begin normal of next segment
00276         for (UINT i = 0; i < m_figureVertices.size(); ++i)
00277         {
00278             UINT j = (i+1) % m_figureVertices.size();
00279
00280             float2 pt =  m_figureVertices[i].pt;
00281             float2 nextPt = m_figureVertices[j].pt;
00282
00283             float2 ptNorm3 =  m_figureVertices[i].interpNorm2;
00284             float2 nextPtNorm2 =  m_figureVertices[j].interpNorm1;
00285
00286             //
00287             // These 6 vertices define two adjacent triangles that
00288             // together form a quad.
00289             //
00290             SimpleVertex newVertices[6] =
00291             {
00292                 {float3(pt.x, pt.y, m_height/2), float3(ptNorm3.x, ptNorm3.y, 0.0f)},
00293                 {float3(pt.x, pt.y, -m_height/2), float3(ptNorm3.x, ptNorm3.y, 0.0f)},
00294                 {float3(nextPt.x, nextPt.y, -m_height/2), float3(nextPtNorm2.x, nextPtNorm2.y, 0.0f)},
00295                 {float3(nextPt.x, nextPt.y, -m_height/2), float3(nextPtNorm2.x, nextPtNorm2.y, 0.0f)},
00296                 {float3(nextPt.x, nextPt.y, m_height/2), float3(nextPtNorm2.x, nextPtNorm2.y, 0.0f)},
00297                 {float3(pt.x, pt.y, m_height/2), float3(ptNorm3.x, ptNorm3.y, 0.0f)},
00298             };
00299
00300             for (UINT n = 0; n < ARRAYSIZE(newVertices); ++n)
00301             {
00302                 m_vertices->push_back(newVertices[n]);
00303             }
00304         }
00305     }
00306 }
00307
00308 void Extruder::ExtrudingSink::SetFillMode(D2D1_FILL_MODE /*fillMode*/)
00309 {
00310     // Do nothing
00311 }
00312
00313 void Extruder::ExtrudingSink::SetSegmentFlags(D2D1_PATH_SEGMENT /*vertexFlags*/)
00314 {
00315     // Do nothing
00316 }
00317
00318 void Extruder::ExtrudingSink::AddTriangles(const D2D1_TRIANGLE* triangles, UINT trianglesCount)
00319 {
00320     //
00321     // These triangles reprent the front and back faces of the extrusion.
00322     //
00323     for (UINT i = 0; i < trianglesCount; ++i)
00324     {
00325         D2D1_TRIANGLE tri = triangles[i];
00326
00327         D2D1_POINT_2F d1 = {tri.point2.x - tri.point1.x, tri.point2.y - tri.point1.y};
00328         D2D1_POINT_2F d2 = {tri.point3.x - tri.point2.x, tri.point3.y - tri.point2.y};
00329
00330         tri.point1 = PointSnapper::SnapPoint(tri.point1);
00331         tri.point2 = PointSnapper::SnapPoint(tri.point2);
00332         tri.point3 = PointSnapper::SnapPoint(tri.point3);
00333
00334         //
00335         // Currently, Tessellate does not guarantee the orientation
00336         // of the triangles it produces, so we must check here.
00337         //
00338
00339         float cross = d1.x * d2.y - d1.y*d2.x;
00340         if (cross < 0)
00341         {
00342             D2D1_POINT_2F tmp = tri.point1;
00343
00344             tri.point1 = tri.point2;
00345             tri.point2 = tmp;
00346         }
00347
00348         SimpleVertex newVertices[] =
00349         {
00350             {float3(tri.point1.x, tri.point1.y, m_height/2), float3(0.0f, 0.0f, 1.0f)},
00351             {float3(tri.point2.x, tri.point2.y, m_height/2), float3(0.0f, 0.0f, 1.0f)},
00352             {float3(tri.point3.x, tri.point3.y, m_height/2), float3(0.0f, 0.0f, 1.0f)},
00353
00354             //
00355             // Note: these points are listed in a different order since the orientation of the back
00356             // face should be the opposite of the front face.
00357             //
00358             {float3(tri.point2.x, tri.point2.y, -m_height/2), float3(0.0f, 0.0f, -1.0f)},
00359             {float3(tri.point1.x, tri.point1.y, -m_height/2), float3(0.0f, 0.0f, -1.0f)},
00360             {float3(tri.point3.x, tri.point3.y, -m_height/2), float3(0.0f, 0.0f, -1.0f)},
00361         };
00362
00363         for (UINT i = 0; i < ARRAYSIZE(newVertices); ++i)
00364         {
00365             m_vertices->push_back(newVertices[i]);
00366         }
00367     }
00368 }
00369
00370 float2 Extruder::ExtrudingSink::GetNormal(uint32 i)
00371 {
00372     uint32 j = (i+1) % m_figureVertices.size();
00373
00374     float2 pti = m_figureVertices[i].pt;
00375     float2 ptj = m_figureVertices[j].pt;
00376     float2 vecij = ptj - pti;
00377
00378     return Normalize(float2(vecij.y, vecij.x));
00379 }
00380
00381 float2 Extruder::ExtrudingSink::Normalize(float2 pt)
00382 {
00383     return pt / sqrtf(pt.x*pt.x+pt.y*pt.y);
00384 }
00385
00386 //
00387 // IUnknown methods
00388 //
00389 // These use a basic, non-thread-safe implementation of the
00390 // standard reference-counting logic.
00391 //
00392 HRESULT Extruder::ExtrudingSink::QueryInterface(REFIID riid, _Outptr_ void** object)
00393 {
00394     *object = nullptr;
00395     return E_NOTIMPL;
00396 }
00397
00398 ULONG Extruder::ExtrudingSink::AddRef()
00399 {
00400     m_ref++;
00401     return m_ref;
00402 }
00403
00404 ULONG Extruder::ExtrudingSink::Release()
00405 {
00406     m_ref--;
00407
00408     if (m_ref == 0)
00409     {
00410         delete this;
00411         return 0;
00412     }
00413
00414     return m_ref;
00415 }
Generated on Sat Nov 23 2024 16:08:15 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Portable device API/C++/Constants.h Source File

  • Portable device API

Constants.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 #define NUM_OBJECTS_TO_REQUEST 10
00016
00017 namespace SDKSample
00018 {
00019     public value struct Scenario
00020     {
00021         Platform::String^ Title;
00022         Platform::String^ ClassName;
00023     };
00024
00025     partial ref class MainPage
00026     {
00027     public:
00028         static property Platform::String^ FEATURE_NAME
00029         {
00030             Platform::String^ get()
00031             {
00032                 return ref new Platform::String(L"PortableDevice");
00033             }
00034         }
00035
00036         static property Platform::Array<Scenario>^ scenarios
00037         {
00038             Platform::Array<Scenario>^ get()
00039             {
00040                 return scenariosInner;
00041             }
00042         }
00043
00044         void DispatcherNotifyUser(Platform::String^ message, NotifyType type);
00045
00046     private:
00047         static Platform::Array<Scenario>^ scenariosInner;
00048     };
00049
00050     // RAII wrapper for CoTaskMemAlloc'ed resources
00051     struct CoTaskMemFreeStruct
00052     {
00053         void operator() (void* ptr) const
00054         {
00055             CoTaskMemFree(ptr);
00056         }
00057     };
00058     typedef std::unique_ptr<wchar_t, CoTaskMemFreeStruct> CoTaskMemString;
00059
00060     // RAII wrapper for Propvariants
00061     struct PropVariantClearStruct
00062     {
00063         void operator() (PROPVARIANT* pvPtr) const
00064         {
00065             PropVariantClear(pvPtr);
00066         }
00067     };
00068     typedef std::unique_ptr<PROPVARIANT, PropVariantClearStruct> PropVariantPtr;
00069
00070     // RAII wrapper for an array of CoTaskMemAlloc'ed resiyrces
00071     class CoTaskMemFreeArray
00072     {
00073     public:
00074         CoTaskMemFreeArray(_Inout_updates_(count) void** ptr, size_t count) :
00075           _ptr(ptr), _count(count)
00076         {
00077         }
00078
00079         ~CoTaskMemFreeArray()
00080         {
00081             for (size_t i=0; i<_count; i++)
00082             {
00083                 CoTaskMemFree(_ptr[i]);
00084             }
00085         }
00086
00087         void** _ptr;
00088         size_t _count;
00089     };
00090
00091     // Common helper functions
00092     Microsoft::WRL::ComPtr<IPortableDeviceValues> GetClientInfo();
00093     Platform::String^ GetFirstStorageId(_In_ IPortableDevice* device);
00094     ULONGLONG StreamCopy(_In_ IStream* destStream, _In_ IStream* sourceStream, DWORD transferSizeBytes);
00095
00096     inline void ThrowIfFailed(HRESULT hr)
00097     {
00098         if (FAILED(hr))
00099         {
00100             // Set a breakpoint on the line below to catch errors from the Portable Device APIs.
00101             throw Platform::Exception::CreateException(hr);
00102         }
00103     }
00104 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML data binding/C++/Scenario7.xaml.cpp Source File

  • XAML data binding

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 #include "Team.h"
00019
00020 using namespace SDKSample::DataBinding;
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::ViewManagement;
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
00034 Scenario7::Scenario7()
00035 {
00036     InitializeComponent();
00037   btnRemoveTeam->Click += ref new RoutedEventHandler(this, &Scenario7::BtnRemoveTeam_Click);
00038   Scenario7Reset(nullptr,nullptr);
00039 }
00040
00041
00042 void SDKSample::DataBinding::Scenario7::Scenario7Reset(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00043 {
00044     auto teams = ref new Teams();
00045   teams->Items->VectorChanged += ref new VectorChangedEventHandler<Object^>(this, &Scenario7::VectorChanged);
00046   _observableTeams = teams;
00047   teamsCVS->Source = _observableTeams->Items;
00048   tbCollectionChangeStatus->Text = "";
00049
00050 }
00051
00052 void SDKSample::DataBinding::Scenario7::BtnRemoveTeam_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00053 {
00054     if (_observableTeams->Items->Size > 0)
00055     {
00056     int index=0;
00057     if(lvTeams->SelectedItem != nullptr)
00058     {
00059       index = lvTeams->SelectedIndex;
00060     }
00061     _observableTeams->Items->RemoveAt(index);
00062     }
00063 }
00064
00065 void SDKSample::DataBinding::Scenario7::VectorChanged(IObservableVector<Object^>^ sender, IVectorChangedEventArgs^ e)
00066 {
00067   tbCollectionChangeStatus->Text = "Collection was changed. Count = " + _observableTeams->Items->Size.ToString();
00068 }
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Toast notifications/C#,C++/ScenarioOutput1.xaml.h Source File

  • Toast notifications
  • C#,C++

ScenarioOutput1.xaml.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 //
00009 // Scenario1Output.xaml.h
00010 // Declaration of the Scenario1Output class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioOutput1.g.h"
00017 #include "MainPage.xaml.h"
00018
00019 namespace ToastsSampleCPP
00020 {
00021   [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class ScenarioOutput1 sealed
00023     {
00024     public:
00025         ScenarioOutput1();
00026
00027     protected:
00028         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030
00031     private:
00032         ~ScenarioOutput1();
00033
00034     MainPage^ rootPage;
00035         void rootPage_InputFrameLoaded(Object^ sender, Object^ e);
00036         Windows::Foundation::EventRegistrationToken _frameLoadedToken;
00037     };
00038 }
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/Common/BindableBase.cpp Source File

  • Hilo C++
  • Hilo
  • Common

BindableBase.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 #include "BindableBase.h"
00009
00010 using namespace Hilo::Common;
00011
00012 using namespace Platform;
00013 using namespace Windows::UI::Xaml::Data;
00014
00015 /// <summary>
00016 /// Notifies listeners that a property value has changed.
00017 /// </summary>
00018 /// <param name="propertyName">Name of the property used to notify listeners.</param>
00019 void BindableBase::OnPropertyChanged(String^ propertyName)
00020 {
00021     PropertyChanged(this, ref new PropertyChangedEventArgs(propertyName));
00022 }
00023
00024 Windows::UI::Xaml::Data::ICustomProperty^ BindableBase::GetCustomProperty(Platform::String^ name)
00025 {
00026     return nullptr;
00027 }
00028
00029 Windows::UI::Xaml::Data::ICustomProperty^ BindableBase::GetIndexedProperty(Platform::String^ name, Windows::UI::Xaml::Interop::TypeName type)
00030 {
00031     return nullptr;
00032 }
00033
00034 Platform::String^ BindableBase::GetStringRepresentation()
00035 {
00036     return this->ToString();
00037 }
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::ApplicationDataSample::sealed Member List

This is the complete list of members for SDKSample::ApplicationDataSample::sealed, including all inherited members.
appData | SDKSample::ApplicationDataSample::sealed | [private]
applicationData | SDKSample::ApplicationDataSample::sealed | [private]
Clear_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::ApplicationDataSample::sealed | [private]
ClearScenario() | SDKSample::ApplicationDataSample::sealed |
CompositeSettings() | SDKSample::ApplicationDataSample::sealed |
CopyFile(Windows::Foundation::Uri^sourceUri, Windows::Storage::StorageFolder^destFolder, Platform::String^destFilename) | SDKSample::ApplicationDataSample::sealed | [private]
counter | SDKSample::ApplicationDataSample::sealed | [private]
CreateContainer_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::ApplicationDataSample::sealed | [private]
DataChangedEvent() | SDKSample::ApplicationDataSample::sealed |
DataChangedHandler(Windows::Storage::ApplicationData^appData, Object^) | SDKSample::ApplicationDataSample::sealed | [private]
DataChangedHandler(Windows::Storage::ApplicationData^appData, Object^) | SDKSample::ApplicationDataSample::sealed | [private]
DeleteCompositeSetting_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::ApplicationDataSample::sealed | [private]
DeleteContainer_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::ApplicationDataSample::sealed | [private]
DeleteSetting_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::ApplicationDataSample::sealed | [private]
DeleteSetting_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::ApplicationDataSample::sealed | [private]
DisplayOutput() | SDKSample::ApplicationDataSample::sealed | [private]
DisplayOutput() | SDKSample::ApplicationDataSample::sealed | [private]
DisplayOutput() | SDKSample::ApplicationDataSample::sealed | [private]
DisplayOutput(bool remoteUpdate) | SDKSample::ApplicationDataSample::sealed | [private]
DisplayOutput() | SDKSample::ApplicationDataSample::sealed | [private]
DisplayOutput() | SDKSample::ApplicationDataSample::sealed | [private]
DisplayOutput() | SDKSample::ApplicationDataSample::sealed | [private]
Files() | SDKSample::ApplicationDataSample::sealed |
HighPriority() | SDKSample::ApplicationDataSample::sealed |
Increment_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::ApplicationDataSample::sealed | [private]
IncrementHighPriority_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::ApplicationDataSample::sealed | [private]
localSettings | SDKSample::ApplicationDataSample::sealed | [private]
Msappdata() | SDKSample::ApplicationDataSample::sealed |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::ApplicationDataSample::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::ApplicationDataSample::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::ApplicationDataSample::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::ApplicationDataSample::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::ApplicationDataSample::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::ApplicationDataSample::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::ApplicationDataSample::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::ApplicationDataSample::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::ApplicationDataSample::sealed | [protected, virtual]
OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^e) override | SDKSample::ApplicationDataSample::sealed | [protected, virtual]
ReadCounter() | SDKSample::ApplicationDataSample::sealed | [private]
roamingFolder | SDKSample::ApplicationDataSample::sealed | [private]
roamingSettings | SDKSample::ApplicationDataSample::sealed | [private]
rootPage | SDKSample::ApplicationDataSample::sealed | [private]
SettingContainer() | SDKSample::ApplicationDataSample::sealed |
Settings() | SDKSample::ApplicationDataSample::sealed |
SetVersion() | SDKSample::ApplicationDataSample::sealed |
SetVersion0_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::ApplicationDataSample::sealed | [private]
SetVersion1_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::ApplicationDataSample::sealed | [private]
SetVersionHandler0(Windows::Storage::SetVersionRequest^request) | SDKSample::ApplicationDataSample::sealed | [private]
SetVersionHandler1(Windows::Storage::SetVersionRequest^request) | SDKSample::ApplicationDataSample::sealed | [private]
SimulateRoaming_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::ApplicationDataSample::sealed | [private]
WriteCompositeSetting_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::ApplicationDataSample::sealed | [private]
WriteOutputText() | SDKSample::ApplicationDataSample::sealed | [private]
WriteSetting_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::ApplicationDataSample::sealed | [private]
WriteSetting_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::ApplicationDataSample::sealed | [private]
Generated on Sat Nov 23 2024 16:09:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Check if current session is remote/C++/App.xaml.cpp Source File

  • Check if current session is remote

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:26 for Win8-Examples by doxygen 1.7.1


Win8-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.
g | Vector2< T > |
operator[](unsigned int index) | Vector2< T > | [inline]
operator[](unsigned int index) | Vector2< T > | [inline]
operator[](unsigned int index) | Vector2< T > | [inline]
operator[](unsigned int index) | Vector2< T > | [inline]
operator[](unsigned int index) | Vector2< T > | [inline]
operator[](unsigned int index) | Vector2< T > | [inline]
operator[](unsigned int index) | Vector2< T > | [inline]
operator[](unsigned int index) | Vector2< T > | [inline]
operator[](unsigned int index) | Vector2< T > | [inline]
operator[](unsigned int index) | Vector2< T > | [inline]
operator[](unsigned int index) | Vector2< T > | [inline]
operator[](unsigned int index) | Vector2< T > | [inline]
operator[](unsigned int index) | Vector2< T > | [inline]
operator[](unsigned int index) | Vector2< T > | [inline]
operator[](unsigned int index) | Vector2< T > | [inline]
operator[](unsigned int index) | Vector2< T > | [inline]
operator[](unsigned int index) | Vector2< T > | [inline]
operator[](unsigned int index) | Vector2< T > | [inline]
operator[](unsigned int index) | Vector2< T > | [inline]
operator[](unsigned int index) | Vector2< T > | [inline]
operator[](unsigned int index) | Vector2< T > | [inline]
operator[](unsigned int index) | Vector2< T > | [inline]
r | 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]
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]
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]
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]
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]
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]
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]
Vector2(T _x=0, T _y=0) | Vector2< T > | [inline]
x | Vector2< T > |
y | Vector2< T > |
Generated on Sat Nov 23 2024 16:09:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File and folder thumbnail/C++/Scenario1.xaml.h Source File

  • File and folder thumbnail

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 SDKSample
00023 {
00024     namespace FileThumbnails
00025     {
00026         [Windows::Foundation::Metadata::WebHostHidden]
00027         public ref class Scenario1 sealed
00028         {
00029         public:
00030             Scenario1();
00031
00032         protected:
00033             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00034
00035         private:
00036             MainPage^ rootPage;
00037
00038             void GetThumbnailButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039         };
00040     }
00041 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/Sphere.h Source File

  • DirectX 3D shooting game

Sphere.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 // Sphere:
00011 // This class is a specialization of GameObject that represents a sphere primitive.
00012 // The sphere is defined by a 'position' and radius.
00013
00014 #include "GameObject.h"
00015
00016 ref class Sphere: public GameObject
00017 {
00018 internal:
00019     Sphere();
00020     Sphere(DirectX::XMFLOAT3 pos, float radius);
00021
00022     void Position(DirectX::XMFLOAT3 position);
00023     void Position(DirectX::XMVECTOR position);
00024     void Radius(float radius);
00025     float Radius();
00026
00027     virtual bool IsTouching(
00028         DirectX::XMFLOAT3 point,
00029         float radius,
00030         _Out_ DirectX::XMFLOAT3 *contact,
00031         _Out_ DirectX::XMFLOAT3 *normal
00032         ) override;
00033
00034 private:
00035     void Update();
00036
00037     float m_radius;
00038 };
00039
00040
00041 __forceinline void Sphere::Position(DirectX::XMFLOAT3 position)
00042 {
00043     m_position = position;
00044     Update();
00045 }
00046
00047 __forceinline void Sphere::Position(DirectX::XMVECTOR position)
00048 {
00049     DirectX::XMStoreFloat3(&m_position, position);
00050     Update();
00051 }
00052
00053 __forceinline void Sphere::Radius(float radius)
00054 {
00055     m_radius = radius;
00056     Update();
00057 }
00058
00059 __forceinline float Sphere::Radius()
00060 {
00061     return m_radius;
00062 }
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Device auto rotation preferences/C++/Portrait.xaml.h Source File

  • Device auto rotation preferences

Portrait.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 // Portrait.xaml.h
00013 // Declaration of the Portrait class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Portrait.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace Rotation
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 Portrait sealed
00031         {
00032         public:
00033             Portrait();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void SetPortrait_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:08:02 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D save to image file/C++/pch.h Source File

  • Direct2D save to image file

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 <d3d11_1.h>
00012 #include <d2d1_1.h>
00013 #include <d2d1effects.h>
00014 #include <d2d1_1helper.h>
00015 #include <dwrite_1.h>
00016 #include <wincodec.h>
00017 #include <shcore.h>
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include <agile.h>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/GameTimer.cpp Source File

  • DirectX 3D shooting game

GameTimer.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 "GameTimer.h"
00010
00011 GameTimer::GameTimer():
00012     m_active(false)
00013 {
00014     LARGE_INTEGER frequency;
00015     if (!QueryPerformanceFrequency(&frequency))
00016     {
00017         throw ref new Platform::FailureException();
00018     }
00019     m_secondsPerCount = 1.0f / static_cast<float>(frequency.QuadPart);
00020
00021     Reset();
00022 }
00023
00024 // Returns the total time elapsed since Reset() was called, NOT counting any
00025 // time when the clock is stopped.
00026 float GameTimer::PlayingTime()
00027 {
00028     if (m_active)
00029     {
00030         // The distance m_currentTime - m_baseTime includes paused time,
00031         // which we do not want to count.  To correct this, we can subtract
00032         // the paused time from m_currentTime:
00033         return static_cast<float>(((m_currentTime.QuadPart - m_pausedTime.QuadPart) - m_baseTime.QuadPart)*m_secondsPerCount);
00034     }
00035     else
00036     {
00037         // The clock is currently not running so don't count the time since
00038         // the clock was stopped
00039         return static_cast<float>(((m_stopTime.QuadPart - m_pausedTime.QuadPart) - m_baseTime.QuadPart)*m_secondsPerCount);
00040     }
00041 }
00042
00043
00044 void GameTimer::PlayingTime(float time)
00045 {
00046     // Reset the internal state to reflect a PlayingTime of 'time'
00047     // Offset the baseTime by this 'time'.
00048     m_active = false;
00049     m_stopTime = m_currentTime;
00050     m_pausedTime.QuadPart = 0;
00051
00052     m_baseTime.QuadPart = m_stopTime.QuadPart - static_cast<__int64>(time / m_secondsPerCount);
00053 }
00054
00055
00056 float GameTimer::DeltaTime()
00057 {
00058     return m_deltaTime;
00059 }
00060
00061 void GameTimer::Reset()
00062 {
00063     LARGE_INTEGER currentTime;
00064     if (!QueryPerformanceCounter(&currentTime))
00065     {
00066         throw ref new Platform::FailureException();
00067     }
00068     m_baseTime = currentTime;
00069     m_previousTime = currentTime;
00070     m_stopTime = currentTime;
00071     m_currentTime = currentTime;
00072     m_pausedTime.QuadPart = 0;
00073     m_active = false;
00074 }
00075
00076 void GameTimer::Start()
00077 {
00078     LARGE_INTEGER startTime;
00079     if (!QueryPerformanceCounter(&startTime))
00080     {
00081         throw ref new Platform::FailureException();
00082     }
00083     if (!m_active)
00084     {
00085         // Accumulate the time elapsed between stop and start pairs.
00086         m_pausedTime.QuadPart += (startTime.QuadPart - m_stopTime.QuadPart);
00087
00088         m_previousTime = startTime;
00089         m_stopTime.QuadPart = 0;
00090         m_active = true;
00091     }
00092 }
00093
00094 void GameTimer::Stop()
00095 {
00096     if (m_active)
00097     {
00098         // Set the stop time to the time of the last update.
00099         m_stopTime = m_currentTime;
00100         m_active = false;
00101     }
00102 }
00103
00104 void GameTimer::Update()
00105 {
00106     if (!m_active)
00107     {
00108         m_deltaTime = 0.0;
00109         return;
00110     }
00111
00112     LARGE_INTEGER currentTime;
00113     if (!QueryPerformanceCounter(&currentTime))
00114     {
00115         throw ref new Platform::FailureException();
00116     }
00117     m_currentTime = currentTime;
00118
00119     m_deltaTime = (m_currentTime.QuadPart - m_previousTime.QuadPart)*m_secondsPerCount;
00120     m_previousTime = m_currentTime;
00121
00122     if (m_deltaTime < 0.0)
00123     {
00124         m_deltaTime = 0.0;
00125     }
00126 }
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text editing/C++/Common/suspensionmanager.cpp Source File

  • XAML text editing
  • Common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CameraCaptureUI/C++/common/LayoutAwarePage.cpp Source File

  • CameraCaptureUI
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:30 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Credential picker/C++/ScenarioOutput3.xaml.cpp Source File

  • Credential picker

ScenarioOutput3.xaml.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 //
00009 // Scenario3Output.xaml.cpp
00010 // Implementation of the Scenario3Output class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioOutput3.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace CredentialPickerCPP;
00018
00019 using namespace Platform;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Graphics::Display;
00023 using namespace Windows::UI::ViewManagement;
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 using namespace Windows::UI::ViewManagement;
00032
00033 ScenarioOutput3::ScenarioOutput3()
00034 {
00035     InitializeComponent();
00036
00037 #pragma region ViewState and Resolution change code for THIS page - Remove unless you need it
00038     Loaded += ref new RoutedEventHandler(this, &ScenarioOutput3::Page_Loaded);
00039
00040     Window::Current->SizeChanged += ref new Windows::UI::Xaml::WindowSizeChangedEventHandler(this, &ScenarioOutput3::Page_SizeChanged);
00041     DisplayProperties::LogicalDpiChanged += ref new DisplayPropertiesEventHandler(this, &ScenarioOutput3::DisplayProperties_LogicalDpiChanged);
00042 #pragma endregion
00043 }
00044
00045 #pragma region ViewState and Resolution change code for THIS page - Remove unless you need it
00046 ScenarioOutput3::~ScenarioOutput3()
00047 {
00048 }
00049
00050 void ScenarioOutput3::Page_Loaded(Object^ sender, RoutedEventArgs^ e)
00051 {
00052 }
00053
00054 void ScenarioOutput3::Page_SizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00055 {
00056     CheckResolutionAndViewState();
00057 }
00058
00059 void ScenarioOutput3::DisplayProperties_LogicalDpiChanged(Object^ sender)
00060 {
00061     CheckResolutionAndViewState();
00062 }
00063
00064 void ScenarioOutput3::CheckResolutionAndViewState()
00065 {
00066     ApplicationViewState state = ApplicationView::Value;
00067     String^ stateString = rootPage->ConvertViewState(state);
00068
00069     ResolutionScale scale = DisplayProperties::ResolutionScale;
00070     String^ scaleString = rootPage->ConvertResolution(scale);
00071
00072     VisualStateManager::GoToState(this, stateString + scaleString, false);
00073 }
00074
00075 #pragma endregion
00076
00077 #pragma region Template-Related Code - Do not remove
00078 void ScenarioOutput3::OnNavigatedTo(NavigationEventArgs^ e)
00079 {
00080     // Get a pointer to our main page.
00081     rootPage = dynamic_cast<MainPage^>(e->Parameter);
00082
00083     // We want to be notified with the OutputFrame is loaded so we can get to the content.
00084     _frameLoadedToken = rootPage->InputFrameLoaded += ref new Windows::Foundation::EventHandler<Platform::Object^>(this, &ScenarioOutput3::rootPage_InputFrameLoaded);
00085 }
00086
00087 void ScenarioOutput3::OnNavigatedFrom(NavigationEventArgs^ e)
00088 {
00089     rootPage->InputFrameLoaded -= _frameLoadedToken;
00090 }
00091
00092 #pragma endregion
00093
00094 #pragma region Use this code if you need access to elements in the input frame - otherwise deletea
00095 void ScenarioOutput3::rootPage_InputFrameLoaded(Object^ sender, Object^ e)
00096 {
00097     // Get a pointer to the content within the OutputFrame.
00098     Page^ inputFrame = dynamic_cast<Page^>(rootPage->InputFrame->Content);
00099
00100     // Go find the elements that we need for this scenario
00101     // ex: flipView1 = dynamic_cast<FlipView^>(inputFrame->FindName("FlipView1"));
00102 }
00103
00104 #pragma endregion
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playback Manager msAudioCategory/C++/StreamTypeOther.xaml.cpp Source File

  • Playback Manager msAudioCategory

StreamTypeOther.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 // StreamTypeOther.xaml.cpp
00013 // Implementation of the StreamTypeOther class
00014 //
00015
00016 #include "pch.h"
00017 #include "StreamTypeOther.xaml.h"
00018
00019 using namespace SDKSample::PlaybackManager;
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::UI::Xaml::Media;
00025
00026 StreamTypeOther::StreamTypeOther()
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 StreamTypeOther::OnNavigatedTo(NavigationEventArgs^ e)
00037 {
00038     // Get a pointer to our main page.
00039     rootPage = MainPage::Current;
00040 }
00041
00042
00043 void StreamTypeOther::Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00044 {
00045   Playback->SetAudioCategory(AudioCategory::Other);
00046     Playback->SelectFile();
00047 }
00048
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Print/C++/ScenarioOutput6.xaml.cpp Source File

  • Print

ScenarioOutput6.xaml.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 //
00009 // ScenarioOutput6.xaml.cpp
00010 // Implementation of the ScenarioOutput6 class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioOutput6.xaml.h"
00015
00016 using namespace PrintSample;
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 ScenarioOutput6::ScenarioOutput6()
00030 {
00031     InitializeComponent();
00032 }
00033
00034 ScenarioOutput6::~ScenarioOutput6()
00035 {
00036 }
Generated on Sat Nov 23 2024 16:08:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::FolderEnumeration::sealed Member List

This is the complete list of members for SDKSample::FolderEnumeration::sealed, including all inherited members.
ColorSpaceProperty | SDKSample::FolderEnumeration::sealed | [private, static]
CopyrightProperty | SDKSample::FolderEnumeration::sealed | [private, static]
CreateHeaderTextBlock(Platform::String^contents) | SDKSample::FolderEnumeration::sealed | [private]
CreateHeaderTextBlock(Platform::String^contents) | SDKSample::FolderEnumeration::sealed | [protected]
CreateLineItemTextBlock(Platform::String^contents) | SDKSample::FolderEnumeration::sealed | [private]
CreateLineItemTextBlock() | SDKSample::FolderEnumeration::sealed | [protected]
GetFilesAndFolderButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::FolderEnumeration::sealed | [private]
GetFilesButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::FolderEnumeration::sealed | [protected]
GetPropertyDisplayValue(Platform::Object^property) | SDKSample::FolderEnumeration::sealed | [protected]
GroupByHelper(Windows::Storage::Search::QueryOptions^queryOptions) | SDKSample::FolderEnumeration::sealed | [private]
GroupByMonthButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::FolderEnumeration::sealed | [private]
GroupByRatingButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::FolderEnumeration::sealed | [private]
GroupByTagButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::FolderEnumeration::sealed | [private]
Scenario1() | SDKSample::FolderEnumeration::sealed |
Scenario2() | SDKSample::FolderEnumeration::sealed |
Scenario3() | SDKSample::FolderEnumeration::sealed |
Generated on Sat Nov 23 2024 16:09:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Audio Session (WASAPI)/C++/pch.h Source File

  • Windows Audio Session (WASAPI)
  • C++

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common.h"
00021 #include "Common\LayoutAwarePage.h"
00022 #include "Common\SuspensionManager.h"
00023 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Device auto rotation preferences/C++/common/LayoutAwarePage.cpp Source File

  • Device auto rotation preferences
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:31 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Custom driver access/C++/app_cpp/Scenario4_DeviceAsync.xaml.cpp Source File

  • Custom driver access
  • app_cpp

Scenario4_DeviceAsync.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 // DeviceAsync.xaml.cpp
00013 // Implementation of the DeviceAsync class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario4_DeviceAsync.xaml.h"
00018
00019 using namespace SDKSample::CustomDeviceAccess;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 DeviceAsync::DeviceAsync()
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 DeviceAsync::OnNavigatedTo(NavigationEventArgs^ /* e */)
00036 {
00037     // Get a pointer to our main page.
00038     rootPage = MainPage::Current;
00039 }
00040
00041
00042 void SDKSample::CustomDeviceAccess::DeviceAsync::deviceAsyncSet_Click_1(Platform::Object^ /* sender */, Windows::UI::Xaml::RoutedEventArgs^ /* e */)
00043 {
00044     if (DeviceList::Current->Fx2Device == nullptr) {
00045         rootPage->NotifyUser("Fx2 device not connected or accessible", NotifyType::ErrorMessage);
00046         return;
00047     }
00048
00049     // Get the selector element
00050     unsigned int val = barGraphInput->SelectedIndex;
00051     auto barGraphArray = ref new Platform::Array<bool>(8);
00052
00053     for (unsigned int i = 0; i < barGraphArray->Length; i += 1) {
00054         barGraphArray[i] = i < val;
00055     }
00056
00057     try {
00058         DeviceList::Current->Fx2Device->SetBarGraphDisplay(barGraphArray);
00059     }
00060     catch (Platform::Exception^ exception) {
00061         rootPage->NotifyUser(exception->ToString(), NotifyType::ErrorMessage);
00062         return;
00063     }
00064
00065     this->ClearBarGraphTable();
00066     rootPage->NotifyUser("Bar Graph Set to " + val, NotifyType::StatusMessage);
00067 }
00068
00069 void SDKSample::CustomDeviceAccess::DeviceAsync::deviceAsyncGet_Click_1(Platform::Object^ /* sender */, Windows::UI::Xaml::RoutedEventArgs^ /* e */)
00070 {
00071     if (DeviceList::Current->Fx2Device == nullptr) {
00072         rootPage->NotifyUser("Fx2 device not connected or accessible", NotifyType::ErrorMessage);
00073         return;
00074     }
00075
00076     rootPage->NotifyUser("Getting Fx2 Bars", NotifyType::StatusMessage);
00077
00078     // Start the async operation to retrieve the LEDs
00079     auto async = DeviceList::Current->Fx2Device->GetBarGraphDisplayAsync();
00080
00081     // Create a task around the async operation we got back
00082     concurrency::task<Samples::Devices::Fx2::BarGraphDisplayResult^> result(async);
00083
00084     // On completion handle either success or failure
00085     result.then(
00086         [this](concurrency::task<Samples::Devices::Fx2::BarGraphDisplayResult^> Result) {
00087             try {
00088                 // get the result.  This throws if the async operation failed
00089                 auto result = Result.get();
00090                 UpdateBarGraphTable(result->BarGraphDisplay);
00091                 rootPage->NotifyUser("Got bars value", NotifyType::StatusMessage);
00092             } catch (Platform::Exception^ exception) {
00093                 rootPage->NotifyUser(exception->Message, NotifyType::ErrorMessage);
00094             }
00095         }
00096         );
00097 }
00098
00099 void SDKSample::CustomDeviceAccess::DeviceAsync::ClearBarGraphTable(void)
00100 {
00101     barGraphOutput->Inlines->Clear();
00102 }
00103
00104 void SDKSample::CustomDeviceAccess::DeviceAsync::UpdateBarGraphTable(Platform::Array<bool>^ BarGraphArray)
00105 {
00106     auto output = barGraphOutput;
00107
00108     DeviceList::CreateBooleanTable(
00109         output->Inlines,
00110         BarGraphArray,
00111         nullptr,
00112         "Bar Number",
00113         "Bar State",
00114         "Lit",
00115         "Not Lit"
00116         );
00117 }
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-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]
operator!=(const POSITION &p) const | List< T >::POSITION | [inline]
operator==(const POSITION &p) const | List< T >::POSITION | [inline]
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]
POSITION() | List< T >::POSITION | [inline]
POSITION(Node *p) | List< T >::POSITION | [inline, private]
POSITION() | List< T >::POSITION | [inline]
POSITION(Node *p) | List< T >::POSITION | [inline, private]
Generated on Sat Nov 23 2024 16:09:15 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Sharing content target app/C++/pch.h Source File

  • Sharing content target app

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017 #include "Sample-Utils\CppSamplesUtils.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D sprite/C++/SampleOverlay.h Source File

  • Direct3D sprite

SampleOverlay.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 "DirectXSample.h"
00011
00012 // This class is responsible for initializing and rendering the title overlay visible
00013 // at the top of the DirectX SDK samples.
00014 ref class SampleOverlay
00015 {
00016 internal:
00017     SampleOverlay();
00018
00019     void Initialize(
00020         _In_ ID2D1Device*         d2dDevice,
00021         _In_ ID2D1DeviceContext*  d2dContext,
00022         _In_ IWICImagingFactory*  wicFactory,
00023         _In_ IDWriteFactory*      dwriteFactory,
00024         _In_ Platform::String^    caption
00025         );
00026
00027     void ResetDirectXResources();
00028
00029     void UpdateForWindowSizeChange();
00030
00031     void Render();
00032
00033     float GetTitleHeightInDips();
00034
00035 private:
00036
00037     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00038     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00039     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00040     Microsoft::WRL::ComPtr<IDWriteFactory>          m_dwriteFactory;
00041     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_whiteBrush;
00042     Microsoft::WRL::ComPtr<ID2D1DrawingStateBlock>  m_stateBlock;
00043
00044     Microsoft::WRL::ComPtr<IWICImagingFactory>      m_wicFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Bitmap>             m_logoBitmap;
00046     Microsoft::WRL::ComPtr<IDWriteTextLayout>       m_textLayout;
00047
00048     UINT                                            m_idIncrement;
00049     bool                                            m_drawOverlay;
00050     Platform::String^                               m_sampleName;
00051     float                                           m_padding;
00052     float                                           m_textVerticalOffset;
00053     D2D1_SIZE_F                                     m_logoSize;
00054     float                                           m_overlayWidth;
00055 };
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite hit testing/C++/pch.cpp Source File

  • DirectWrite hit testing

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-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.
__pad0__ | SoundEffect |
Initialize(_In_ IXAudio2 *masteringEngine, _In_ WAVEFORMATEX *sourceFormat, _In_ Platform::Array< byte >^soundData) | SoundEffect |
Initialize(_In_ IXAudio2 *masteringEngine, _In_ WAVEFORMATEX *sourceFormat, _In_ Platform::Array< byte >^soundData) | SoundEffect |
m_audioAvailable | SoundEffect | [private]
m_soundData | SoundEffect | [private]
m_sourceVoice | SoundEffect | [private]
PlaySound(_In_ float volume) | SoundEffect |
PlaySound(_In_ float volume) | SoundEffect |
Generated on Sat Nov 23 2024 16:09:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

AppBarControl::Common::LayoutAwarePage Member List

This is the complete list of members for AppBarControl::Common::LayoutAwarePage, including all inherited members.
__pad0__ | AppBarControl::Common::LayoutAwarePage |
_defaultViewModel | AppBarControl::Common::LayoutAwarePage | [private]
_layoutAwareControls | AppBarControl::Common::LayoutAwarePage | [private]
_windowSizeEventToken | AppBarControl::Common::LayoutAwarePage | [private]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | AppBarControl::Common::LayoutAwarePage | [virtual]
GoBack(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | AppBarControl::Common::LayoutAwarePage | [virtual]
InvalidateVisualState() | AppBarControl::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | AppBarControl::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | AppBarControl::Common::LayoutAwarePage |
WindowSizeChanged(Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | AppBarControl::Common::LayoutAwarePage | [private]
Generated on Sat Nov 23 2024 16:09:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DeviceAppForPrinters::App Member List

This is the complete list of members for DeviceAppForPrinters::App, including all inherited members.
__pad0__ | DeviceAppForPrinters::App |
OnActivated(Windows::ApplicationModel::Activation::IActivatedEventArgs^pArgs) override | DeviceAppForPrinters::App | [virtual]
OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^pArgs) override | DeviceAppForPrinters::App | [virtual]
OnSuspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^pArgs) | DeviceAppForPrinters::App | [virtual]
rootFrame | DeviceAppForPrinters::App | [private]
SetupWindowing(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^pArgs) | DeviceAppForPrinters::App | [private]
Generated on Sat Nov 23 2024 16:09:37 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Splash screen/C++/common/LayoutAwarePage.h Source File

  • Splash screen
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML accessibility/C++/Constants.h Source File

  • XAML accessibility

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"XAML Accessibility Sample");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CryptoWinRT/C++/pch.h Source File

  • CryptoWinRT

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Splash screen/C++/pch.cpp Source File

  • Splash screen

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Portable device API/C++/S3_SendToDevice.xaml.h Source File

  • Portable device API

S3_SendToDevice.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 // S3_SendToDevice.xaml.h
00013 // Declaration of the S3_SendToDevice class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "S3_SendToDevice.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace PortableDeviceCPP
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 S3_SendToDevice sealed
00031         {
00032         public:
00033             S3_SendToDevice();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037
00038         private:
00039             void Run_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040             void ShowDeviceSelectorAsync();
00041             void DeviceList_Tapped(Platform::Object^ sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^ e);
00042             void SendContentToDeviceAsync(Windows::Devices::Enumeration::DeviceInformation^ deviceInfoElement);
00043             void TransferFileToDeviceAsync(Windows::Storage::StorageFile^ file, _In_ IPortableDevice* device);
00044             Microsoft::WRL::ComPtr<IPortableDeviceValues> FillInPropertiesForImage(
00045                 Windows::Storage::StorageFile^ file, Platform::String^ parentId, ULONGLONG size);
00046
00047             MainPage^ rootPage;
00048             // Contains the device information used for populating the device selection list
00049             Windows::Devices::Enumeration::DeviceInformationCollection^ _deviceInfoCollection;
00050         };
00051     }
00052 }
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

HighScoreEntry Member List

This is the complete list of members for HighScoreEntry, including all inherited members.
elapsedTime | HighScoreEntry
levelCompleted | HighScoreEntry
tag | HighScoreEntry
totalHits | HighScoreEntry
totalShots | HighScoreEntry
wasJustAdded | HighScoreEntry
Generated on Sat Nov 23 2024 16:09:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/App.xaml.h Source File

  • Media extensions

App.xaml.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 //
00009 // App.xaml.h
00010 // Declaration of the App.xaml class.
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "App.g.h"
00017
00018 namespace MediaExtensionsCPP
00019 {
00020     ref class App
00021     {
00022     internal:
00023         App();
00024
00025     public:
00026         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00027         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00028     };
00029 }
00030
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Toast notifications/C#,C++/App.xaml.h Source File

  • Toast notifications
  • C#,C++

App.xaml.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 //
00009 // App.xaml.h
00010 // Declaration of the App.xaml class.
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "App.g.h"
00017
00018 namespace ToastsSampleCPP
00019 {
00020     [Windows::Foundation::Metadata::WebHostHidden]
00021     ref class App sealed
00022     {
00023     public:
00024         App();
00025         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ args) override;
00026         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00027     };
00028 }
00029
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/BasicLoader.h Source File

  • Direct3D resource loading

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 Sat Nov 23 2024 16:08:08 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Account picture name/C++/GetAccountPicture.xaml.cpp Source File

  • Account picture name

GetAccountPicture.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 // GetAccountPicture.xaml.cpp
00013 // Implementation of the GetAccountPicture class
00014 //
00015
00016 #include "pch.h"
00017 #include "GetAccountPicture.xaml.h"
00018
00019 using namespace AccountPictureName;
00020 using namespace concurrency;
00021 using namespace Platform;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Navigation;
00025 using namespace Windows::UI::Xaml::Media::Imaging;
00026 using namespace Windows::System::UserProfile;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::ApplicationModel;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::Streams;
00031 using namespace Microsoft::WRL;
00032 using namespace Microsoft::WRL::Wrappers;
00033
00034 GetAccountPicture::GetAccountPicture()
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 GetAccountPicture::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 void GetAccountPicture::GetSmallImageButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00052 {
00053     HideImageAndVideoControls();
00054
00055     if (!UserInformation::NameAccessAllowed)
00056     {
00057         rootPage->NotifyUser("Access to account picture disabled by Privacy Setting or Group Policy", NotifyType::ErrorMessage);
00058     }
00059     else
00060     {
00061         auto smallImageFile = UserInformation::GetAccountPicture(AccountPictureKind::SmallImage);
00062         if (smallImageFile != nullptr)
00063         {
00064             rootPage->NotifyUser("Path: " + smallImageFile->Path, NotifyType::StatusMessage);
00065             create_task(smallImageFile->OpenReadAsync()).then(
00066                 [this](task<IRandomAccessStreamWithContentType^> imageStreamTask)
00067                 {
00068                     try
00069                     {
00070                         auto imageStream = imageStreamTask.get();
00071                         auto bitmapImage = ref new BitmapImage();
00072                         bitmapImage->SetSource(imageStream);
00073                         AccountPictureImage->Source = bitmapImage;
00074                         AccountPictureImage->Visibility = Windows::UI::Xaml::Visibility::Visible;
00075                     }
00076                     catch (Exception^ Ex)
00077                     {
00078                         rootPage->NotifyUser("No large account picture image returned for current user.", NotifyType::ErrorMessage);
00079                     }
00080                 });
00081         }
00082         else
00083         {
00084             rootPage->NotifyUser("No small account picture image returned for current user.", NotifyType::ErrorMessage);
00085         }
00086     }
00087 }
00088
00089 void GetAccountPicture::GetLargeImageButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00090 {
00091     HideImageAndVideoControls();
00092
00093     if (!UserInformation::NameAccessAllowed)
00094     {
00095         rootPage->NotifyUser("Access to account picture disabled by Privacy Setting or Group Policy", NotifyType::ErrorMessage);
00096     }
00097     else
00098     {
00099         auto largeImageFile = UserInformation::GetAccountPicture(AccountPictureKind::LargeImage);
00100         if (largeImageFile != nullptr)
00101         {
00102             rootPage->NotifyUser("Path: " + largeImageFile->Path, NotifyType::StatusMessage);
00103             create_task(largeImageFile->OpenReadAsync()).then(
00104                 [this](task<IRandomAccessStreamWithContentType^> imageStreamTask)
00105                 {
00106                     try
00107                     {
00108                         auto imageStream = imageStreamTask.get();
00109                         auto bitmapImage = ref new BitmapImage();
00110                         bitmapImage->SetSource(imageStream);
00111                         AccountPictureImage->Source = bitmapImage;
00112                         AccountPictureImage->Visibility = Windows::UI::Xaml::Visibility::Visible;
00113                     }
00114                     catch (Exception^ ex)
00115                     {
00116                         rootPage->NotifyUser("Failed to read from stream. " + ex->Message, NotifyType::ErrorMessage);
00117                     }
00118                 });
00119         }
00120         else
00121         {
00122             rootPage->NotifyUser("No large account picture image returned for current user.", NotifyType::ErrorMessage);
00123         }
00124     }
00125 }
00126
00127 void GetAccountPicture::GetVideoButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00128 {
00129     HideImageAndVideoControls();
00130
00131     if (!UserInformation::NameAccessAllowed)
00132     {
00133         rootPage->NotifyUser("Access to account picture disabled by Privacy Setting or Group Policy", NotifyType::ErrorMessage);
00134     }
00135     else
00136     {
00137         auto videoFile = UserInformation::GetAccountPicture(AccountPictureKind::Video);
00138         if (videoFile != nullptr)
00139         {
00140             rootPage->NotifyUser("Path: " + videoFile->Path, NotifyType::StatusMessage);
00141             create_task(videoFile->OpenReadAsync()).then(
00142                 [this](task<IRandomAccessStreamWithContentType^> videoStreamTask)
00143                 {
00144                     try
00145                     {
00146                         auto videoStream = videoStreamTask.get();
00147                         AccountPictureVideo->SetSource(videoStream, "video/mp4");
00148                         AccountPictureVideo->Visibility = Windows::UI::Xaml::Visibility::Visible;
00149                     }
00150                     catch (Exception^ Ex)
00151                     {
00152                         rootPage->NotifyUser("No large account picture image returned for current user.", NotifyType::ErrorMessage);
00153                     }
00154                 });
00155         }
00156         else
00157         {
00158             rootPage->NotifyUser("No video account picture returned for current user.", NotifyType::ErrorMessage);
00159         }
00160     }
00161 }
00162
00163 void GetAccountPicture::HideImageAndVideoControls()
00164 {
00165     AccountPictureImage->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00166     AccountPictureVideo->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00167 }
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::WebViewControl::sealed Member List

This is the complete list of members for SDKSample::WebViewControl::sealed, including all inherited members.
Address_KeyUp(Platform::Object^sender, Windows::UI::Xaml::Input::KeyRoutedEventArgs^e) | SDKSample::WebViewControl::sealed | [private]
BottomAppBar_Closed(Platform::Object^sender, Platform::Object^obj) | SDKSample::WebViewControl::sealed | [private]
BottomAppBar_Opened(Platform::Object^sender, Platform::Object^obj) | SDKSample::WebViewControl::sealed | [private]
ComboBox1_DropDownClosed(Platform::Object^sender, Platform::Object^e) | SDKSample::WebViewControl::sealed | [private]
ComboBox1_DropDownOpened(Platform::Object^sender, Platform::Object^e) | SDKSample::WebViewControl::sealed | [private]
dataRequestedToken | SDKSample::WebViewControl::sealed | [private]
dataTransferManager | SDKSample::WebViewControl::sealed | [private]
dataTransferManager_DataRequested(Windows::ApplicationModel::DataTransfer::DataTransferManager^sender, Windows::ApplicationModel::DataTransfer::DataRequestedEventArgs^args) | SDKSample::WebViewControl::sealed | [private]
Default_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::WebViewControl::sealed | [private]
Default_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::WebViewControl::sealed | [private]
Default_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::WebViewControl::sealed | [private]
DoSomething_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::WebViewControl::sealed | [private]
FireScript_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::WebViewControl::sealed | [private]
Go_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::WebViewControl::sealed | [private]
Home_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::WebViewControl::sealed | [private]
Load_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::WebViewControl::sealed | [private]
Load_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::WebViewControl::sealed | [private]
Nav_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::WebViewControl::sealed | [private]
NavigateButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::WebViewControl::sealed | [private]
NavToString_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::WebViewControl::sealed | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::WebViewControl::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::WebViewControl::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::WebViewControl::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::WebViewControl::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::WebViewControl::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::WebViewControl::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::WebViewControl::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::WebViewControl::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::WebViewControl::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::WebViewControl::sealed | [protected, virtual]
Other_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::WebViewControl::sealed | [private]
Other_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::WebViewControl::sealed | [private]
Other_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::WebViewControl::sealed | [private]
PageWithAppBar() | SDKSample::WebViewControl::sealed |
rootPage | SDKSample::WebViewControl::sealed | [private]
Scenario1() | SDKSample::WebViewControl::sealed |
Scenario2() | SDKSample::WebViewControl::sealed |
Scenario3() | SDKSample::WebViewControl::sealed |
Scenario4() | SDKSample::WebViewControl::sealed |
Scenario5() | SDKSample::WebViewControl::sealed |
Scenario6() | SDKSample::WebViewControl::sealed |
Scenario7() | SDKSample::WebViewControl::sealed |
Scenario8() | SDKSample::WebViewControl::sealed |
Script_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::WebViewControl::sealed | [private]
Share_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::WebViewControl::sealed | [private]
ShowMe_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::WebViewControl::sealed | [private]
Solution_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::WebViewControl::sealed | [private]
WebView1_LoadCompleted(Platform::Object^sender, Windows::UI::Xaml::Navigation::NavigationEventArgs^e) | SDKSample::WebViewControl::sealed | [private]
WebView4_ScriptNotify(Platform::Object^sender, Windows::UI::Xaml::Controls::NotifyEventArgs^e) | SDKSample::WebViewControl::sealed | [private]
WebView5_LoadCompleted(Platform::Object^sender, Windows::UI::Xaml::Navigation::NavigationEventArgs^e) | SDKSample::WebViewControl::sealed | [private]
WebView5_ScriptNotify(Platform::Object^sender, Windows::UI::Xaml::Controls::NotifyEventArgs^e) | SDKSample::WebViewControl::sealed | [private]
WebView7_LoadCompleted(Platform::Object^sender, Windows::UI::Xaml::Navigation::NavigationEventArgs^e) | SDKSample::WebViewControl::sealed | [private]
Generated on Sat Nov 23 2024 16:09:53 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D stereoscopic 3D/C++/SampleOverlay.cpp Source File

  • Direct3D stereoscopic 3D

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 Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::UI::ViewManagement;
00015 using namespace Windows::Graphics::Display;
00016 using namespace D2D1;
00017
00018 SampleOverlay::SampleOverlay() :
00019     m_drawOverlay(true)
00020 {
00021 }
00022
00023 void SampleOverlay::Initialize(
00024     _In_ ID2D1Device*         d2dDevice,
00025     _In_ ID2D1DeviceContext*  d2dContext,
00026     _In_ IWICImagingFactory*  wicFactory,
00027     _In_ IDWriteFactory*      dwriteFactory,
00028     _In_ Platform::String^    caption
00029     )
00030 {
00031     m_wicFactory = wicFactory;
00032     m_dwriteFactory = dwriteFactory;
00033     m_sampleName = caption;
00034     m_d2dDevice = d2dDevice;
00035     m_d2dContext = d2dContext;
00036     m_padding = 3.0f;
00037     m_textVerticalOffset = 5.0f;
00038     m_logoSize = D2D1::SizeF(0.0f, 0.0f);
00039     m_overlayWidth = 0.0f;
00040
00041     ComPtr<ID2D1Factory> factory;
00042     d2dDevice->GetFactory(&factory);
00043
00044     DX::ThrowIfFailed(
00045         factory.As(&m_d2dFactory)
00046         );
00047
00048     ResetDirectXResources();
00049 }
00050
00051 void SampleOverlay::ResetDirectXResources()
00052 {
00053     DX::ThrowIfFailed(
00054         m_d2dContext->CreateSolidColorBrush(ColorF(ColorF::White), &m_whiteBrush)
00055         );
00056
00057     ComPtr<IWICBitmapDecoder> wicBitmapDecoder;
00058     DX::ThrowIfFailed(
00059         m_wicFactory->CreateDecoderFromFilename(
00060             L"windowsbig-sdk.png",
00061             nullptr,
00062             GENERIC_READ,
00063             WICDecodeMetadataCacheOnDemand,
00064             &wicBitmapDecoder
00065             )
00066         );
00067
00068     ComPtr<IWICBitmapFrameDecode> wicBitmapFrame;
00069     DX::ThrowIfFailed(
00070         wicBitmapDecoder->GetFrame(0, &wicBitmapFrame)
00071         );
00072
00073     ComPtr<IWICFormatConverter> wicFormatConverter;
00074     DX::ThrowIfFailed(
00075         m_wicFactory->CreateFormatConverter(&wicFormatConverter)
00076         );
00077
00078     DX::ThrowIfFailed(
00079         wicFormatConverter->Initialize(
00080             wicBitmapFrame.Get(),
00081             GUID_WICPixelFormat32bppPBGRA,
00082             WICBitmapDitherTypeNone,
00083             nullptr,
00084             0.0,
00085             WICBitmapPaletteTypeCustom  // the BGRA format has no palette so this value is ignored
00086             )
00087         );
00088
00089     double dpiX = 96.0f;
00090     double dpiY = 96.0f;
00091     DX::ThrowIfFailed(
00092         wicFormatConverter->GetResolution(&dpiX, &dpiY)
00093         );
00094
00095     DX::ThrowIfFailed(
00096         m_d2dContext->CreateBitmapFromWicBitmap(
00097             wicFormatConverter.Get(),
00098             BitmapProperties(
00099                 PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00100                 static_cast<float>(dpiX),
00101                 static_cast<float>(dpiY)
00102                 ),
00103             &m_logoBitmap
00104             )
00105         );
00106
00107     m_logoSize = m_logoBitmap->GetSize();
00108
00109     ComPtr<IDWriteTextFormat> nameTextFormat;
00110     DX::ThrowIfFailed(
00111         m_dwriteFactory->CreateTextFormat(
00112             L"Segoe UI",
00113             nullptr,
00114             DWRITE_FONT_WEIGHT_LIGHT,
00115             DWRITE_FONT_STYLE_NORMAL,
00116             DWRITE_FONT_STRETCH_NORMAL,
00117             36.0f,
00118             L"en-US",
00119             &nameTextFormat
00120             )
00121         );
00122
00123     DX::ThrowIfFailed(
00124         nameTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)
00125         );
00126
00127     DX::ThrowIfFailed(
00128         nameTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)
00129         );
00130
00131     DX::ThrowIfFailed(
00132         m_dwriteFactory->CreateTextLayout(
00133             m_sampleName->Data(),
00134             m_sampleName->Length(),
00135             nameTextFormat.Get(),
00136             4096.0f,
00137             4096.0f,
00138             &m_textLayout
00139             )
00140         );
00141
00142     DWRITE_TEXT_METRICS metrics = {0};
00143     DX::ThrowIfFailed(
00144         m_textLayout->GetMetrics(&metrics)
00145         );
00146
00147     m_overlayWidth = m_padding * 3.0f + m_logoSize.width + metrics.width;
00148
00149     DX::ThrowIfFailed(
00150         m_d2dFactory->CreateDrawingStateBlock(&m_stateBlock)
00151         );
00152
00153     UpdateForWindowSizeChange();
00154 }
00155
00156 void SampleOverlay::UpdateForWindowSizeChange()
00157 {
00158     if (CoreWindow::GetForCurrentThread()->Bounds.Width < m_overlayWidth)
00159     {
00160         m_drawOverlay = false;
00161     }
00162     else
00163     {
00164         m_drawOverlay = true;
00165     }
00166 }
00167
00168 void SampleOverlay::Render()
00169 {
00170     if (m_drawOverlay)
00171     {
00172         m_d2dContext->SaveDrawingState(m_stateBlock.Get());
00173
00174         m_d2dContext->BeginDraw();
00175         m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00176         m_d2dContext->DrawBitmap(
00177             m_logoBitmap.Get(),
00178             D2D1::RectF(m_padding, 0.0f, m_logoSize.width + m_padding, m_logoSize.height)
00179             );
00180
00181         m_d2dContext->DrawTextLayout(
00182             Point2F(m_logoSize.width + 2.0f * m_padding, m_textVerticalOffset),
00183             m_textLayout.Get(),
00184             m_whiteBrush.Get()
00185             );
00186
00187         // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00188         // is lost. It will be handled during the next call to Present.
00189         HRESULT hr = m_d2dContext->EndDraw();
00190         if (hr != D2DERR_RECREATE_TARGET)
00191         {
00192             DX::ThrowIfFailed(hr);
00193         }
00194
00195         m_d2dContext->RestoreDrawingState(m_stateBlock.Get());
00196     }
00197 }
00198
00199 float SampleOverlay::GetTitleHeightInDips()
00200 {
00201     return m_logoSize.height;
00202 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/pch.cpp Source File

  • DirectX 3D shooting game

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: HomeGroup app/C++/Constants.cpp Source File

  • HomeGroup app

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016 using namespace Windows::UI::ViewManagement;
00017
00018 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00019 {
00020     { "Open the file picker at HomeGroup",    "SDKSample.HomeGroup.HomeGroupPicker" },
00021     { "Search HomeGroup",                     "SDKSample.HomeGroup.SearchHomeGroup" },
00022     { "Stream video from Homegroup",          "SDKSample.HomeGroup.HomeGroupVideoStream" },
00023     { "Advanced search",                      "SDKSample.HomeGroup.HomeGroupAdvancedSearch"}
00024 };
00025
00026 bool MainPage::EnsureUnsnapped()
00027 {
00028     // FilePicker APIs will not work if the application is in a snapped state. If an app wants to show a FilePicker while snapped,
00029     // it must attempt to unsnap first.
00030     bool unsnapped = ((ApplicationView::Value != ApplicationViewState::Snapped) || ApplicationView::TryUnsnap());
00031     if (!unsnapped)
00032     {
00033         NotifyUser("Cannot unsnap the sample application.", NotifyType::StatusMessage);
00034     }
00035
00036     return unsnapped;
00037 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Device auto rotation preferences/C++/None.xaml.cpp Source File

  • Device auto rotation preferences

None.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 // None.xaml.cpp
00013 // Implementation of the None class
00014 //
00015
00016 #include "pch.h"
00017 #include "None.xaml.h"
00018
00019 using namespace SDKSample::Rotation;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 None::None()
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 None::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 SDKSample::Rotation::None::ClearPreference_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00043 {
00044     Button^ b = safe_cast<Button^>(sender);
00045     if (b != nullptr)
00046     {
00047         Windows::Graphics::Display::DisplayProperties::AutoRotationPreferences = Windows::Graphics::Display::DisplayOrientations::None;
00048
00049         if (Windows::Graphics::Display::DisplayProperties::AutoRotationPreferences == Windows::Graphics::Display::DisplayOrientations::None)
00050         {
00051             rootPage->NotifyUser("Succeeded: All preferences cleared.", NotifyType::StatusMessage);
00052         }
00053         else
00054         {
00055             rootPage->NotifyUser("Error: Failed to set the preference.", NotifyType::StatusMessage);
00056         }
00057     }
00058 }
Generated on Sat Nov 23 2024 16:08:02 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Print/C++/ScenarioInput1.xaml.h Source File

  • Print

ScenarioInput1.xaml.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 // ScenarioInput1.xaml.h
00009 // Declaration of the ScenarioInput1 class.
00010 //
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "ScenarioInput1.g.h"
00016 #include "MainPage.xaml.h"
00017
00018 using namespace Windows::UI::Xaml;
00019 using namespace Windows::UI::Xaml::Printing;
00020
00021 namespace PrintSample
00022 {
00023     /// <summary>
00024     /// Basic scenario for modern printing (how to register)
00025     /// </summary>
00026     [Windows::Foundation::Metadata::WebHostHidden]
00027     public ref class ScenarioInput1 sealed
00028     {
00029     public:
00030         ScenarioInput1();
00031
00032     protected:
00033         virtual void PreparetPrintContent() override;
00034
00035     private:
00036         /// <summary>
00037         /// Register for print button handler
00038         /// </summary>
00039         void RegisterForPrintingButtonClick(Object^ sender, RoutedEventArgs^ e);
00040     };
00041 }
Generated on Sat Nov 23 2024 16:07:59 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite hit testing/C++/SampleOverlay.cpp Source File

  • DirectWrite hit testing

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 Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::UI::ViewManagement;
00015 using namespace Windows::Graphics::Display;
00016 using namespace D2D1;
00017
00018 SampleOverlay::SampleOverlay() :
00019     m_drawOverlay(true)
00020 {
00021 }
00022
00023 void SampleOverlay::Initialize(
00024     _In_ ID2D1Device*         d2dDevice,
00025     _In_ ID2D1DeviceContext*  d2dContext,
00026     _In_ IWICImagingFactory*  wicFactory,
00027     _In_ IDWriteFactory*      dwriteFactory,
00028     _In_ Platform::String^    caption
00029     )
00030 {
00031     m_wicFactory = wicFactory;
00032     m_dwriteFactory = dwriteFactory;
00033     m_sampleName = caption;
00034     m_d2dDevice = d2dDevice;
00035     m_d2dContext = d2dContext;
00036     m_padding = 3.0f;
00037     m_textVerticalOffset = 5.0f;
00038     m_logoSize = D2D1::SizeF(0.0f, 0.0f);
00039     m_overlayWidth = 0.0f;
00040
00041     ComPtr<ID2D1Factory> factory;
00042     d2dDevice->GetFactory(&factory);
00043
00044     DX::ThrowIfFailed(
00045         factory.As(&m_d2dFactory)
00046         );
00047
00048     ResetDirectXResources();
00049 }
00050
00051 void SampleOverlay::ResetDirectXResources()
00052 {
00053     DX::ThrowIfFailed(
00054         m_d2dContext->CreateSolidColorBrush(ColorF(ColorF::White), &m_whiteBrush)
00055         );
00056
00057     ComPtr<IWICBitmapDecoder> wicBitmapDecoder;
00058     DX::ThrowIfFailed(
00059         m_wicFactory->CreateDecoderFromFilename(
00060             L"windowsbig-sdk.png",
00061             nullptr,
00062             GENERIC_READ,
00063             WICDecodeMetadataCacheOnDemand,
00064             &wicBitmapDecoder
00065             )
00066         );
00067
00068     ComPtr<IWICBitmapFrameDecode> wicBitmapFrame;
00069     DX::ThrowIfFailed(
00070         wicBitmapDecoder->GetFrame(0, &wicBitmapFrame)
00071         );
00072
00073     ComPtr<IWICFormatConverter> wicFormatConverter;
00074     DX::ThrowIfFailed(
00075         m_wicFactory->CreateFormatConverter(&wicFormatConverter)
00076         );
00077
00078     DX::ThrowIfFailed(
00079         wicFormatConverter->Initialize(
00080             wicBitmapFrame.Get(),
00081             GUID_WICPixelFormat32bppPBGRA,
00082             WICBitmapDitherTypeNone,
00083             nullptr,
00084             0.0,
00085             WICBitmapPaletteTypeCustom  // the BGRA format has no palette so this value is ignored
00086             )
00087         );
00088
00089     double dpiX = 96.0f;
00090     double dpiY = 96.0f;
00091     DX::ThrowIfFailed(
00092         wicFormatConverter->GetResolution(&dpiX, &dpiY)
00093         );
00094
00095     DX::ThrowIfFailed(
00096         m_d2dContext->CreateBitmapFromWicBitmap(
00097             wicFormatConverter.Get(),
00098             BitmapProperties(
00099                 PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00100                 static_cast<float>(dpiX),
00101                 static_cast<float>(dpiY)
00102                 ),
00103             &m_logoBitmap
00104             )
00105         );
00106
00107     m_logoSize = m_logoBitmap->GetSize();
00108
00109     ComPtr<IDWriteTextFormat> nameTextFormat;
00110     DX::ThrowIfFailed(
00111         m_dwriteFactory->CreateTextFormat(
00112             L"Segoe UI",
00113             nullptr,
00114             DWRITE_FONT_WEIGHT_LIGHT,
00115             DWRITE_FONT_STYLE_NORMAL,
00116             DWRITE_FONT_STRETCH_NORMAL,
00117             36.0f,
00118             L"en-US",
00119             &nameTextFormat
00120             )
00121         );
00122
00123     DX::ThrowIfFailed(
00124         nameTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)
00125         );
00126
00127     DX::ThrowIfFailed(
00128         nameTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)
00129         );
00130
00131     DX::ThrowIfFailed(
00132         m_dwriteFactory->CreateTextLayout(
00133             m_sampleName->Data(),
00134             m_sampleName->Length(),
00135             nameTextFormat.Get(),
00136             4096.0f,
00137             4096.0f,
00138             &m_textLayout
00139             )
00140         );
00141
00142     DWRITE_TEXT_METRICS metrics = {0};
00143     DX::ThrowIfFailed(
00144         m_textLayout->GetMetrics(&metrics)
00145         );
00146
00147     m_overlayWidth = m_padding * 3.0f + m_logoSize.width + metrics.width;
00148
00149     DX::ThrowIfFailed(
00150         m_d2dFactory->CreateDrawingStateBlock(&m_stateBlock)
00151         );
00152
00153     UpdateForWindowSizeChange();
00154 }
00155
00156 void SampleOverlay::UpdateForWindowSizeChange()
00157 {
00158     if (CoreWindow::GetForCurrentThread()->Bounds.Width < m_overlayWidth)
00159     {
00160         m_drawOverlay = false;
00161     }
00162     else
00163     {
00164         m_drawOverlay = true;
00165     }
00166 }
00167
00168 void SampleOverlay::Render()
00169 {
00170     if (m_drawOverlay)
00171     {
00172         m_d2dContext->SaveDrawingState(m_stateBlock.Get());
00173
00174         m_d2dContext->BeginDraw();
00175         m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00176         m_d2dContext->DrawBitmap(
00177             m_logoBitmap.Get(),
00178             D2D1::RectF(m_padding, 0.0f, m_logoSize.width + m_padding, m_logoSize.height)
00179             );
00180
00181         m_d2dContext->DrawTextLayout(
00182             Point2F(m_logoSize.width + 2.0f * m_padding, m_textVerticalOffset),
00183             m_textLayout.Get(),
00184             m_whiteBrush.Get()
00185             );
00186
00187         // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00188         // is lost. It will be handled during the next call to Present.
00189         HRESULT hr = m_d2dContext->EndDraw();
00190         if (hr != D2DERR_RECREATE_TARGET)
00191         {
00192             DX::ThrowIfFailed(hr);
00193         }
00194
00195         m_d2dContext->RestoreDrawingState(m_stateBlock.Get());
00196     }
00197 }
00198
00199 float SampleOverlay::GetTitleHeightInDips()
00200 {
00201     return m_logoSize.height;
00202 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX touch input/C++/pch.cpp Source File

  • DirectX touch input

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows account authorization/C++/pch.h Source File

  • Windows account authorization

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <msxml6.h>
00019 #include <collection.h>
00020 #include <ppltasks.h>
00021 #include <wrl.h>
00022 #include "Common\LayoutAwarePage.h"
00023 #include "Common\SuspensionManager.h"
00024 #include "App.xaml.h"
00025 #include <sstream>
00026
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML data binding/C++/S2Formatter.h Source File

  • XAML data binding

S2Formatter.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 //
00009 // S2Formatter.h
00010 // Declaration of the S2Formatter class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016
00017 using namespace Platform;
00018 using namespace Windows::UI::Xaml::Data;
00019 using namespace Windows::UI::Xaml::Interop;
00020
00021
00022 namespace SDKSample
00023 {
00024     namespace DataBinding
00025     {
00026     // This value converter is used in Scenario 2. For more information on Value Converters, see http://go.microsoft.com/fwlink/?LinkId=254639#data_conversions
00027       [Windows::Foundation::Metadata::WebHostHidden]
00028       public ref class S2Formatter sealed : Windows::UI::Xaml::Data::IValueConverter
00029       {
00030       public:
00031         S2Formatter();
00032         virtual Object^ Convert(Object^ value, TypeName targetType, Object^ parameter, String^ language);
00033         virtual Object^ ConvertBack(Object^ value, TypeName targetType, Object^ parameter, String^ language);
00034       private:
00035         ~S2Formatter();
00036       };
00037     }
00038 }
Generated on Sat Nov 23 2024 16:08:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File access/C++/Scenario2.xaml.cpp Source File

  • File access

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 SDKSample::FileAccess;
00020
00021 using namespace concurrency;
00022 using namespace Platform;
00023 using namespace Windows::Storage;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Controls;
00026 using namespace Windows::UI::Xaml::Navigation;
00027
00028 Scenario2::Scenario2()
00029 {
00030     InitializeComponent();
00031     rootPage = MainPage::Current;
00032     WriteTextButton->Click += ref new RoutedEventHandler(this, &Scenario2::WriteTextButton_Click);
00033     ReadTextButton->Click  += ref new RoutedEventHandler(this, &Scenario2::ReadTextButton_Click);
00034 }
00035
00036 void Scenario2::WriteTextButton_Click(Object^ sender, RoutedEventArgs^ e)
00037 {
00038     rootPage->ResetScenarioOutput(OutputTextBlock);
00039     StorageFile^ file = rootPage->SampleFile;
00040     if (file != nullptr)
00041     {
00042         String^ userContent = InputTextBox->Text;
00043         if (userContent != nullptr && !userContent->IsEmpty())
00044         {
00045             create_task(FileIO::WriteTextAsync(file, userContent)).then([this, file, userContent](task<void> task)
00046             {
00047                 try
00048                 {
00049                     task.get();
00050                     OutputTextBlock->Text = "The following text was written to '" + file->Name + "':\n\n" + userContent;
00051                 }
00052                 catch(COMException^ ex)
00053                 {
00054                     rootPage->HandleFileNotFoundException(ex);
00055                 }
00056             });
00057         }
00058         else
00059         {
00060             OutputTextBlock->Text = "The text box is empty, please write something and then click 'Write' again.";
00061         }
00062     }
00063 }
00064
00065 void Scenario2::ReadTextButton_Click(Object^ sender, RoutedEventArgs^ e)
00066 {
00067     rootPage->ResetScenarioOutput(OutputTextBlock);
00068     StorageFile^ file = rootPage->SampleFile;
00069     if (file != nullptr)
00070     {
00071         create_task(FileIO::ReadTextAsync(file)).then([this, file](task<String^> task)
00072         {
00073             try
00074             {
00075                 String^ fileContent = task.get();
00076                 OutputTextBlock->Text = "The following text was read from '" + file->Name + "':\n\n" + fileContent;
00077             }
00078             catch(COMException^ ex)
00079             {
00080                 rootPage->HandleFileNotFoundException(ex);
00081             }
00082         });
00083     }
00084 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: AtomPub/C++/Scenario2.xaml.h Source File

  • AtomPub

Scenario2.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.xaml.h
00013 // Declaration of the Scenario2 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario2.g.h"
00020 #include "MainPage.xaml.h"
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::Foundation;
00026 using namespace Platform;
00027
00028 namespace SDKSample
00029 {
00030     namespace AtomPub
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 Scenario2 sealed
00037         {
00038         public:
00039             Scenario2();
00040
00041         protected:
00042             virtual void OnNavigatedTo(NavigationEventArgs^ e) override;
00043             virtual void OnNavigatingFrom(NavigatingCancelEventArgs^ e) override;
00044
00045         private:
00046             MainPage^ rootPage;
00047             void SubmitItem_Click(Object^ sender, RoutedEventArgs^ e);
00048             Uri^ FindEditUri(ServiceDocument^ serviceDocument);
00049             void UserNameField_TextChanged(Object^ sender, TextChangedEventArgs^ e);
00050             void PasswordField_PasswordChanged(Object^ sender, RoutedEventArgs^ e);
00051         };
00052     }
00053 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Device auto rotation preferences/C++/App.xaml.cpp Source File

  • Device auto rotation preferences

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML images/C++/Scenario2.xaml.h Source File

  • XAML images

Scenario2.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.xaml.h
00013 // Declaration of the Scenario2 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario2.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace Images
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 sealed
00031         {
00032         public:
00033             Scenario2();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038         int decodePixelHeight;
00039         int decodePixelWidth;
00040             MainPage^ rootPage;
00041         void Scenario2Button1_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00042       };
00043     }
00044 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Account picture name/C++/sample-utils/CppSamplesUtils.h Source File

  • Account picture name
  • sample-utils

CppSamplesUtils.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 <string>
00014 #include <sstream>
00015 #include <algorithm>
00016 #include <collection.h>
00017 #include <ppltasks.h>
00018
00019 namespace CppSamplesUtils
00020 {
00021     namespace Details
00022     {
00023         static Windows::Foundation::Collections::PropertySet^ sessionState = nullptr;
00024         static Platform::String^ sessionStateFileName = ref new Platform::String(L"_cppSessionState.xml");
00025
00026         concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file);
00027         concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file);
00028     }
00029
00030     class SuspensionManager
00031     {
00032     public:
00033         static Windows::Foundation::Collections::PropertySet^ SessionState()
00034         {
00035             using namespace Windows::Foundation::Collections;
00036             using namespace Details;
00037
00038             if (sessionState == nullptr)
00039             {
00040                 sessionState = ref new PropertySet();
00041             }
00042             return sessionState;
00043         }
00044
00045         static concurrency::task<void> StartRestoreTask()
00046         {
00047             using namespace Windows::Foundation;
00048             using namespace Windows::Storage;
00049             using namespace Windows::Storage::Streams;
00050             using namespace Details;
00051
00052             auto state = SessionState();
00053             state->Clear();
00054
00055             concurrency::task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFileName));
00056             return getFileTask.then([=](StorageFile^ file)
00057             {
00058                 return DeserializeSessionState(file);
00059             });
00060         }
00061
00062         static concurrency::task<void> StartSaveTask()
00063         {
00064             using namespace Windows::Foundation;
00065             using namespace Windows::Storage;
00066             using namespace Windows::Storage::Streams;
00067             using namespace Details;
00068
00069             concurrency::task<StorageFile^> createFileTask(ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFileName, CreationCollisionOption::ReplaceExisting));
00070             return createFileTask.then([=](StorageFile^ file)
00071             {
00072                 return SerializeSessionState(file);
00073             });
00074         }
00075     };
00076
00077     namespace Details
00078     {
00079         template <class T>
00080         inline Platform::String^ ToString(T value)
00081         {
00082             std::wstringstream wss;
00083             wss << value;
00084             return ref new Platform::String(wss.str().c_str());
00085         }
00086
00087         template <class T>
00088         inline T FromStringTo(Platform::String^ str)
00089         {
00090             std::wistringstream wiss(str->Data());
00091             T value = 0;
00092             wiss >> value;
00093             return value;
00094         }
00095
00096         template <class T>
00097         inline T FromHexStringTo(Platform::String^ str)
00098         {
00099             std::wistringstream wiss(str->Data());
00100             T value = 0;
00101             wiss >> std::hex >> value;
00102             return value;
00103         }
00104
00105         template <>
00106         inline Platform::Guid FromStringTo<Platform::Guid>(Platform::String^ str)
00107         {
00108             using namespace Platform;
00109
00110             if (str->Length() != 38)
00111             {
00112                 throw ref new InvalidArgumentException;
00113             }
00114             std::wstring ws(str->Data());
00115             if (ws[0] != L'{' || ws[37] != L'}' || ws[9] != L'-' || ws[14] != L'-' || ws[19] != L'-' || ws[24] != L'-')
00116             {
00117                 throw ref new InvalidArgumentException;
00118             }
00119             ws[0] = ws[37] = ws[9] = ws[14] = ws[19] =ws[24] = L' ';
00120             std::wistringstream wiss(ws);
00121             unsigned int a = 0;
00122             unsigned short b = 0;
00123             unsigned short c = 0;
00124             unsigned short d = 0;
00125             unsigned long long e = 0;
00126             static_assert(sizeof(d) == sizeof(char) * 2, "sizeof(d) == sizeof(char) * 2");
00127             static_assert(sizeof(e) == sizeof(char) * 8, "sizeof(e) == sizeof(char) * 8");
00128             wiss >> std::hex >> a >> b >> c >> d >> e;
00129             unsigned char *ad = (unsigned char*)(&d);
00130             unsigned char *ae = (unsigned char*)(&e);
00131             return Platform::Guid(a, b, c, ad[1], ad[0], ae[5], ae[4], ae[3], ae[2], ae[1], ae[0]);
00132         }
00133
00134         inline Platform::Object^ ConvertStringToObject(Windows::Foundation::PropertyType type, Platform::String^ str)
00135         {
00136             using namespace Platform;
00137             using namespace Windows::Foundation;
00138
00139             if (type == PropertyType::String)
00140             {
00141                 return PropertyValue::CreateString(str);
00142             }
00143
00144             switch (type)
00145             {
00146             case PropertyType::UInt8:
00147                 return PropertyValue::CreateUInt8((unsigned char)FromStringTo<unsigned short>(str));
00148             case PropertyType::UInt16:
00149                 return PropertyValue::CreateUInt16(FromStringTo<unsigned short>(str));
00150             case PropertyType::UInt32:
00151                 return PropertyValue::CreateUInt32(FromStringTo<unsigned int>(str));
00152             case PropertyType::UInt64:
00153                 return PropertyValue::CreateUInt64(FromStringTo<unsigned long long>(str));
00154             case PropertyType::Int16:
00155                 return PropertyValue::CreateInt16(FromStringTo<short>(str));
00156             case PropertyType::Int32:
00157                 return PropertyValue::CreateInt32(FromStringTo<int>(str));
00158             case PropertyType::Int64:
00159                 return PropertyValue::CreateInt64(FromStringTo<long long>(str));
00160             case PropertyType::Single:
00161                 return PropertyValue::CreateSingle(FromStringTo<float>(str));
00162             case PropertyType::Double:
00163                 return PropertyValue::CreateDouble(FromStringTo<double>(str));
00164             case PropertyType::Boolean:
00165                 return PropertyValue::CreateBoolean(FromStringTo<bool>(str));
00166             case PropertyType::Char16:
00167                 return PropertyValue::CreateChar16(str->Data()[0]);
00168             case PropertyType::Guid:
00169                 return PropertyValue::CreateGuid(FromStringTo<Guid>(str));
00170             default:
00171                 throw ref new Platform::InvalidCastException;
00172             }
00173         }
00174
00175         inline Platform::String^ ConvertPropertyValueToString(Windows::Foundation::IPropertyValue^ pv)
00176         {
00177             using namespace Platform;
00178             using namespace Windows::Foundation;
00179
00180             String^ valueString;
00181
00182             switch (pv->Type)
00183             {
00184             case PropertyType::String:
00185                 valueString = pv->GetString();
00186                 break;
00187
00188             case PropertyType::UInt8:
00189             case PropertyType::UInt16:
00190             case PropertyType::UInt32:
00191             case PropertyType::UInt64:
00192                 valueString = ToString(pv->GetUInt64());
00193                 break;
00194
00195             case PropertyType::Int16:
00196             case PropertyType::Int32:
00197             case PropertyType::Int64:
00198                 valueString = ToString(pv->GetInt64());
00199                 break;
00200
00201             case PropertyType::Single:
00202                 valueString = ToString(pv->GetSingle());
00203                 break;
00204
00205             case PropertyType::Double:
00206                 valueString = ToString(pv->GetDouble());
00207                 break;
00208
00209             case PropertyType::Boolean:
00210                 valueString = ToString(pv->GetBoolean());
00211                 break;
00212
00213             case PropertyType::Char16:
00214                 wchar_t buffer[2];
00215                 buffer[0] = pv->GetChar16();
00216                 buffer[1] = 0;
00217                 valueString = ref new String(buffer);
00218                 break;
00219
00220             case PropertyType::Guid:
00221                 valueString = pv->GetGuid().ToString();
00222                 break;
00223
00224             default:
00225                 throw ref new InvalidCastException;
00226             }
00227
00228             return valueString;
00229         }
00230
00231         inline Windows::Data::Xml::Dom::XmlElement^ CreateXmlElementFromObject(Windows::Data::Xml::Dom::XmlDocument^ doc, Platform::String^ name, Platform::Object^ value)
00232         {
00233             using namespace Platform;
00234             using namespace Windows::Foundation;
00235             using namespace Windows::Data::Xml::Dom;
00236
00237             XmlElement^ element = doc->CreateElement("item");
00238             element->SetAttribute("name", name);
00239
00240             IPropertyValue^ pv = (IPropertyValue^)value;
00241             element->SetAttribute("type", ToString((int)pv->Type));
00242             element->SetAttribute("value", ConvertPropertyValueToString(pv));
00243
00244             return element;
00245         }
00246
00247         inline concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file)
00248         {
00249             using namespace Windows::Data::Xml::Dom;
00250             using namespace Windows::Foundation;
00251             namespace WFC = Windows::Foundation::Collections;
00252             typedef Windows::Foundation::Collections::IKeyValuePair<Platform::String^, Platform::Object^> KVPair;
00253
00254             XmlDocument^ doc = ref new XmlDocument;
00255             doc->AppendChild(doc->CreateElement("items"));
00256             auto sessionState = SuspensionManager::SessionState();
00257
00258             std::for_each(WFC::begin(sessionState), WFC::end(sessionState), [doc](KVPair^ item)
00259             {
00260                 doc->DocumentElement->AppendChild(CreateXmlElementFromObject(doc, item->Key, item->Value));
00261             });
00262
00263             return concurrency::task<void>(doc->SaveToFileAsync(file));
00264         }
00265
00266         inline Windows::Foundation::PropertyType PropertyTypeFromString(Platform::String^ str)
00267         {
00268             int value = FromStringTo<int>(str);
00269             return (Windows::Foundation::PropertyType)value;
00270         }
00271
00272         inline concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file)
00273         {
00274             using namespace Platform;
00275             using namespace Windows::Foundation;
00276             using namespace Windows::Data::Xml::Dom;
00277             namespace WFC = Windows::Foundation::Collections;
00278
00279             concurrency::task<XmlDocument^> loadFileTask(XmlDocument::LoadFromFileAsync(file));
00280             return loadFileTask.then([=](concurrency::task<XmlDocument^> docTask)
00281             {
00282                 try
00283                 {
00284                     auto doc = docTask.get();
00285                     auto items = doc->SelectNodes("/items/item");
00286                     auto sessionState = SuspensionManager::SessionState();
00287
00288                     std::for_each(WFC::begin(items), WFC::end(items), [sessionState](IXmlNode^ node)
00289                     {
00290                         auto element = (IXmlElement^)node;
00291                         String^ name = element->GetAttribute("name");
00292                         String^ value = element->GetAttribute("value");
00293                         PropertyType type = PropertyTypeFromString(element->GetAttribute("type"));
00294
00295                         Object^ valueObject = ConvertStringToObject(type, value);
00296                         sessionState->Insert(name, valueObject);
00297                     });
00298
00299                 }
00300                 catch (Platform::Exception^)
00301                 {
00302                     // Restoring is best effort
00303                 }
00304             });
00305         }
00306     } // namespace Details
00307 } // namespace CppSamplesUtils
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Clipboard::sealed Member List

This is the complete list of members for Clipboard::sealed, including all inherited members.
__pad0__ | Clipboard::sealed | [protected]
autoSizeInputSectionWhenSnapped | Clipboard::sealed | [private]
ClearOutput() | Clipboard::sealed | [private]
ClearOutputButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Clipboard::sealed | [private]
contentChangedToken | Clipboard::sealed | [private, static]
CopyBitmap(bool useDelayedRendering) | Clipboard::sealed | [private]
CopyButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Clipboard::sealed | [private]
CopyButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Clipboard::sealed | [private]
CopyButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Clipboard::sealed | [private]
CopyFiles() | Clipboard::sealed |
CopyImage() | Clipboard::sealed |
CopyText() | Clipboard::sealed |
CopyWithDelayedRenderingButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Clipboard::sealed | [private]
DisplayFormats(Windows::ApplicationModel::DataTransfer::DataPackageView^dataPackageView) | Clipboard::sealed | [private]
EmptyClipboardButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Clipboard::sealed | [private]
Footer_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Clipboard::sealed | [private]
HandleClipboardChanged() | Clipboard::sealed | [private]
HiddenFrame | Clipboard::sealed | [private]
htmlDescription | Clipboard::sealed | [private]
imgSrc | Clipboard::sealed | [private]
imgStreamRef | Clipboard::sealed | [private]
InvalidateSize() | Clipboard::sealed | [private]
InvalidateViewState() | Clipboard::sealed | [private]
LoadScenario(Platform::String^scenarioName) | Clipboard::sealed |
MainPage() | Clipboard::sealed |
MainPage_SizeChanged(Object^sender, Windows::UI::Xaml::SizeChangedEventArgs^e) | Clipboard::sealed | [protected]
MainPageResized | Clipboard::sealed |
needToPrintClipboardFormat | Clipboard::sealed | [private, static]
NotifyUser(Platform::String^strMessage, NotifyType type) | Clipboard::sealed |
NotifyUserBackgroundThread(Platform::String^message, NotifyType type) | Clipboard::sealed |
OnClipboardChanged(Platform::Object^sender, Platform::Object^e) | Clipboard::sealed | [private]
OnDeferredImageRequestedHandler(Windows::ApplicationModel::DataTransfer::DataProviderRequest^request) | Clipboard::sealed | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | Clipboard::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | Clipboard::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | Clipboard::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | Clipboard::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | Clipboard::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | Clipboard::sealed | [protected, virtual]
OnVisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | Clipboard::sealed | [private]
Others() | Clipboard::sealed |
PasteButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Clipboard::sealed | [private]
PasteButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Clipboard::sealed | [private]
PasteButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Clipboard::sealed | [private]
PopulateScenarios() | Clipboard::sealed | [private]
RegisterClipboardContentChanged_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Clipboard::sealed | [private]
registerContentChanged | Clipboard::sealed | [private, static]
rootPage | Clipboard::sealed | [private]
ScenarioList | Clipboard::sealed | [private]
ScenarioLoaded | Clipboard::sealed |
Scenarios_SelectionChanged(Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | Clipboard::sealed | [protected]
SetFeatureName(Platform::String^strFeature) | Clipboard::sealed | [private]
ShowFormatButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Clipboard::sealed | [private]
textDescription | Clipboard::sealed | [private]
visibilityChangedToken | Clipboard::sealed | [private, static]
windowVisible | Clipboard::sealed | [private, static]
~MainPage() | Clipboard::sealed | [private]
Generated on Sat Nov 23 2024 16:09:36 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Sharing content target app/C++/pch.cpp Source File

  • Sharing content target app

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C#,C++/ScenarioOutput4.xaml.cs Source File

  • Media extensions
  • C#,C++

ScenarioOutput4.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 System;
00009 using System.Linq;
00010 using System.Collections.Generic;
00011 using Windows.Foundation;
00012 using Windows.Foundation.Collections;
00013 using Windows.Graphics.Display;
00014 using Windows.UI.ViewManagement;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Controls.Primitives;
00018 using Windows.UI.Xaml.Data;
00019 using Windows.UI.Xaml.Input;
00020 using Windows.UI.Xaml.Media;
00021 using Windows.UI.Xaml.Navigation;
00022 using SDKTemplateCS;
00023
00024 namespace MediaExtensionsCS
00025 {
00026     public sealed partial class ScenarioOutput4 : Page
00027     {
00028         // A pointer back to the main page which is used to gain access to the input and output frames and their content.
00029         MainPage rootPage = null;
00030
00031         public ScenarioOutput4()
00032         {
00033             InitializeComponent();
00034         }
00035
00036         #region Template-Related Code - Do not remove
00037         protected override void OnNavigatedTo(NavigationEventArgs e)
00038         {
00039             // Get a pointer to our main page.
00040             rootPage = e.Parameter as MainPage;
00041
00042             Video.MediaFailed += new ExceptionRoutedEventHandler(rootPage.VideoOnError);
00043         }
00044
00045         protected override void OnNavigatedFrom(NavigationEventArgs e)
00046         {
00047             Video.MediaFailed -= new ExceptionRoutedEventHandler(rootPage.VideoOnError);
00048             Video.Source = null;
00049         }
00050         #endregion
00051     }
00052 }
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

CollisionInfo Member List

This is the complete list of members for CollisionInfo, including all inherited members.
elasticCollision | CollisionInfo
isRollingOnFloor | CollisionInfo
maxCollisionSpeed | CollisionInfo
maxRollingSpeed | CollisionInfo
Generated on Sat Nov 23 2024 16:09:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX postcard app/C++/BasicLoader.cpp Source File

  • DirectX postcard app

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 Sat Nov 23 2024 16:08:07 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C#,C++/MediaExtensions/Grayscale/dllmain.cpp Source File

  • Media extensions
  • C#,C++
  • MediaExtensions
  • Grayscale

dllmain.cpp

Go to the documentation of this file.
00001 //////////////////////////////////////////////////////////////////////////
00002 //
00003 // dllmain.cpp
00004 //
00005 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00007 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00008 // PARTICULAR PURPOSE.
00009 //
00010 // Copyright (c) Microsoft Corporation. All rights reserved.
00011 //
00012 //////////////////////////////////////////////////////////////////////////
00013
00014 #include <initguid.h>
00015 #include "Grayscale.h"
00016
00017 using namespace Microsoft::WRL;
00018
00019 namespace Microsoft { namespace Samples {
00020     ActivatableClass(CGrayscale);
00021 }}
00022
00023 BOOL WINAPI DllMain( _In_ HINSTANCE hInstance, _In_ DWORD dwReason, _In_opt_ LPVOID lpReserved )
00024 {
00025     if( DLL_PROCESS_ATTACH == dwReason )
00026     {
00027         //
00028         //  Don't need per-thread callbacks
00029         //
00030         DisableThreadLibraryCalls( hInstance );
00031
00032         Module<InProc>::GetModule().Create();
00033     }
00034     else if( DLL_PROCESS_DETACH == dwReason )
00035     {
00036         Module<InProc>::GetModule().Terminate();
00037     }
00038
00039     return TRUE;
00040 }
00041
00042 HRESULT WINAPI DllGetActivationFactory( _In_ HSTRING activatibleClassId, _Outptr_ IActivationFactory** factory )
00043 {
00044     auto &module = Microsoft::WRL::Module< Microsoft::WRL::InProc >::GetModule();
00045     return module.GetActivationFactory( activatibleClassId, factory );
00046 }
00047
00048 HRESULT WINAPI DllCanUnloadNow()
00049 {
00050     auto &module = Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule();
00051     return (module.Terminate()) ? S_OK : S_FALSE;
00052 }
00053
00054 STDAPI DllGetClassObject( _In_ REFCLSID rclsid, _In_ REFIID riid, _Outptr_ LPVOID FAR* ppv )
00055 {
00056     auto &module = Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule();
00057     return module.GetClassObject( rclsid, riid, ppv );
00058 }
Generated on Sat Nov 23 2024 16:08:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKMESH_SUBSET Member List

This is the complete list of members for SDKMESH_SUBSET, including all inherited members.
IndexCount | SDKMESH_SUBSET
IndexStart | SDKMESH_SUBSET
MaterialID | SDKMESH_SUBSET
Name | SDKMESH_SUBSET
PrimitiveType | SDKMESH_SUBSET
VertexCount | SDKMESH_SUBSET
VertexStart | SDKMESH_SUBSET
Generated on Sat Nov 23 2024 16:09:21 for Win8-Examples by doxygen 1.7.1


Win8-Examples: AtomPub/C++/App.xaml.h Source File

  • AtomPub

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Programmatic file search/C++/pch.h Source File

  • Programmatic file search

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D sprite/C++/BasicTimer.cpp Source File

  • Direct3D sprite

BasicTimer.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 "BasicTimer.h"
00010
00011 BasicTimer::BasicTimer()
00012 {
00013     if (!QueryPerformanceFrequency(&m_frequency))
00014     {
00015         throw ref new Platform::FailureException();
00016     }
00017     Reset();
00018 }
00019
00020 void BasicTimer::Reset()
00021 {
00022     Update();
00023     m_startTime = m_currentTime;
00024     m_total = 0.0f;
00025     m_delta = 1.0f / 60.0f;
00026 }
00027
00028 void BasicTimer::Update()
00029 {
00030     if (!QueryPerformanceCounter(&m_currentTime))
00031     {
00032         throw ref new Platform::FailureException();
00033     }
00034
00035     m_total = static_cast<float>(
00036         static_cast<double>(m_currentTime.QuadPart-m_startTime.QuadPart) /
00037         static_cast<double>(m_frequency.QuadPart)
00038         );
00039
00040     if (m_lastTime.QuadPart == m_startTime.QuadPart)
00041     {
00042         // If the timer was just reset, report a time delta equivalent to 60Hz frame time.
00043         m_delta = 1.0f / 60.0f;
00044     }
00045     else
00046     {
00047         m_delta = static_cast<float>(
00048             static_cast<double>(m_currentTime.QuadPart-m_lastTime.QuadPart) /
00049             static_cast<double>(m_frequency.QuadPart)
00050             );
00051     }
00052
00053     m_lastTime = m_currentTime;
00054 }
00055
00056 float BasicTimer::Total::get()
00057 {
00058     return m_total;
00059 }
00060
00061 float BasicTimer::Delta::get()
00062 {
00063     return m_delta;
00064 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite vertical text/C++/FlowSource.cpp Source File

  • DirectWrite vertical text

FlowSource.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 // Contents:    Tells a flow layout where text is allowed to flow.
00009 //
00010 //----------------------------------------------------------------------------
00011 #include "pch.h"
00012 #include "TextAnalysis.h"
00013 #include "FlowSource.h"
00014
00015 void FlowLayoutSource::Reset()
00016 {
00017     m_currentV = 0;
00018     m_currentU = 0;
00019 }
00020
00021 void FlowLayoutSource::SetSize(
00022     float width,
00023     float height
00024     )
00025 {
00026     m_width  = width;
00027     m_height = height;
00028 }
00029
00030 bool FlowLayoutSource::GetNextRect(
00031     float fontHeight,
00032     ReadingDirection readingDirection,
00033     _Out_ RectF* nextRect
00034     )
00035 {
00036     RectF& rect = *nextRect;
00037
00038     // Set defaults.
00039     RectF zeroRect = {};
00040     rect = zeroRect;
00041
00042     if (m_height <= 0 || m_width <= 0)
00043     {
00044         return 1; // Do nothing if empty.
00045     }
00046
00047     bool const isVertical           = (readingDirection & ReadingDirectionPrimaryAxis) != 0;
00048     bool const isReversedPrimary    = (readingDirection & ReadingDirectionPrimaryProgression) != 0;
00049     bool const isReversedSecondary  = (readingDirection & ReadingDirectionSecondaryProgression) != 0;
00050
00051     float const uSize     = isVertical ? m_height : m_width;
00052     float const vSize     = isVertical ? m_width  : m_height;
00053     float const uSizeHalf = uSize / 2;
00054     float const vSizeHalf = vSize / 2;
00055
00056     if (m_currentV >= vSize)
00057     {
00058         return 1; // Crop any further lines.
00059     }
00060
00061     // Initially set to entire size.
00062     rect.left   = 0;
00063     rect.top    = 0;
00064     rect.right  = uSize;
00065     rect.bottom = vSize;
00066
00067     // Advance to the next row/column.
00068     float u = m_currentU;
00069     float v = m_currentV;
00070
00071     m_currentV += fontHeight;
00072
00073     float minSizeHalf = min(uSizeHalf, vSizeHalf);
00074     float adjustedV = (v + fontHeight/2) - vSizeHalf;
00075
00076     // Determine x from y using circle formula d^2 = (x^2 + y^2).
00077     float d2    = (minSizeHalf * minSizeHalf) - (adjustedV * adjustedV);
00078     u           = (d2 > 0) ? sqrt(d2) : -1;
00079     rect.top    = v;
00080     rect.bottom = v + fontHeight;
00081     rect.left   = uSizeHalf - u;
00082     rect.right  = uSizeHalf + u;
00083
00084     // Reorient rect according to reading direction.
00085     if (isReversedPrimary)
00086     {
00087         std::swap(rect.left, rect.right);
00088         rect.left  = uSize - rect.left;
00089         rect.right = uSize - rect.right;
00090     }
00091     if (isReversedSecondary)
00092     {
00093         std::swap(rect.top, rect.bottom);
00094         rect.top    = vSize - rect.top;
00095         rect.bottom = vSize - rect.bottom;
00096     }
00097     if (isVertical)
00098     {
00099         std::swap(rect.left, rect.top);
00100         std::swap(rect.right, rect.bottom);
00101     }
00102
00103     return 1;
00104 }
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playback Manager msAudioCategory/C++/common/LayoutAwarePage.h Source File

  • Playback Manager msAudioCategory
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Credential picker/C++/ScenarioInput3.xaml.h Source File

  • Credential picker

ScenarioInput3.xaml.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 //
00009 // Scenario3Input.xaml.h
00010 // Declaration of the Scenario3Input class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioInput3.g.h"
00017 #include "MainPage.g.h"
00018
00019 namespace CredentialPickerCPP
00020 {
00021   [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class ScenarioInput3 sealed
00023     {
00024     public:
00025         ScenarioInput3();
00026
00027     protected:
00028         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030
00031     private:
00032         MainPage^ rootPage;
00033         void rootPage_OutputFrameLoaded(Object^ sender, Object^ e);
00034         void Launch_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00035         Windows::Foundation::EventRegistrationToken _frameLoadedToken;
00036         void SetError(Platform::String^ errorText);
00037         void SetResult(Windows::Security::Credentials::UI::CredentialPickerResults^ res);
00038         void SetPasswordExplainVisibility(bool isShown);
00039         void Protocol_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00040          ~ScenarioInput3();
00041     };
00042 }
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/CppSamplesUtils.h Source File

  • Media extensions

CppSamplesUtils.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 <string>
00014 #include <sstream>
00015 #include <algorithm>
00016 #include <collection.h>
00017 #include <ppltasks.h>
00018
00019 namespace CppSamplesUtils
00020 {
00021     namespace Details
00022     {
00023         static Windows::Foundation::Collections::PropertySet^ sessionState = nullptr;
00024         static Platform::String^ sessionStateFileName = ref new Platform::String(L"_cppSessionState.xml");
00025
00026         concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file);
00027         concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file);
00028     }
00029
00030     class SuspensionManager
00031     {
00032     public:
00033         static Windows::Foundation::Collections::PropertySet^ SessionState()
00034         {
00035             using namespace Windows::Foundation::Collections;
00036             using namespace Details;
00037
00038             if (sessionState == nullptr)
00039             {
00040                 sessionState = ref new PropertySet();
00041             }
00042             return sessionState;
00043         }
00044
00045         static concurrency::task<void> StartRestoreTask()
00046         {
00047             using namespace Windows::Foundation;
00048             using namespace Windows::Storage;
00049             using namespace Windows::Storage::Streams;
00050             using namespace Details;
00051
00052             auto state = SessionState();
00053             state->Clear();
00054
00055             concurrency::task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFileName));
00056             return getFileTask.then([=](StorageFile^ file)
00057             {
00058                 return DeserializeSessionState(file);
00059             });
00060         }
00061
00062         static concurrency::task<void> StartSaveTask()
00063         {
00064             using namespace Windows::Foundation;
00065             using namespace Windows::Storage;
00066             using namespace Windows::Storage::Streams;
00067             using namespace Details;
00068
00069             concurrency::task<StorageFile^> createFileTask(ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFileName, CreationCollisionOption::ReplaceExisting));
00070             return createFileTask.then([=](StorageFile^ file)
00071             {
00072                 return SerializeSessionState(file);
00073             });
00074         }
00075     };
00076
00077     namespace Details
00078     {
00079         template <class T>
00080         inline Platform::String^ ToString(T value)
00081         {
00082             std::wstringstream wss;
00083             wss << value;
00084             return ref new Platform::String(wss.str().c_str());
00085         }
00086
00087         template <class T>
00088         inline T FromStringTo(Platform::String^ str)
00089         {
00090             std::wistringstream wiss(str->Data());
00091             T value = 0;
00092             wiss >> value;
00093             return value;
00094         }
00095
00096         template <class T>
00097         inline T FromHexStringTo(Platform::String^ str)
00098         {
00099             std::wistringstream wiss(str->Data());
00100             T value = 0;
00101             wiss >> std::hex >> value;
00102             return value;
00103         }
00104
00105         template <>
00106         inline Platform::Guid FromStringTo<Platform::Guid>(Platform::String^ str)
00107         {
00108             using namespace Platform;
00109
00110             if (str->Length() != 38)
00111             {
00112                 throw ref new InvalidArgumentException;
00113             }
00114             std::wstring ws(str->Data());
00115             if (ws[0] != L'{' || ws[37] != L'}' || ws[9] != L'-' || ws[14] != L'-' || ws[19] != L'-' || ws[24] != L'-')
00116             {
00117                 throw ref new InvalidArgumentException;
00118             }
00119             ws[0] = ws[37] = ws[9] = ws[14] = ws[19] =ws[24] = L' ';
00120             std::wistringstream wiss(ws);
00121             unsigned int a = 0;
00122             unsigned short b = 0;
00123             unsigned short c = 0;
00124             unsigned short d = 0;
00125             unsigned long long e = 0;
00126             static_assert(sizeof(d) == sizeof(char) * 2, "sizeof(d) == sizeof(char) * 2");
00127             static_assert(sizeof(e) == sizeof(char) * 8, "sizeof(e) == sizeof(char) * 8");
00128             wiss >> std::hex >> a >> b >> c >> d >> e;
00129             unsigned char *ad = (unsigned char*)(&d);
00130             unsigned char *ae = (unsigned char*)(&e);
00131             return Platform::Guid(a, b, c, ad[1], ad[0], ae[5], ae[4], ae[3], ae[2], ae[1], ae[0]);
00132         }
00133
00134         inline Platform::Object^ ConvertStringToObject(Windows::Foundation::PropertyType type, Platform::String^ str)
00135         {
00136             using namespace Platform;
00137             using namespace Windows::Foundation;
00138
00139             if (type == PropertyType::String)
00140             {
00141                 return PropertyValue::CreateString(str);
00142             }
00143
00144             switch (type)
00145             {
00146             case PropertyType::UInt8:
00147                 return PropertyValue::CreateUInt8((unsigned char)FromStringTo<unsigned short>(str));
00148             case PropertyType::UInt16:
00149                 return PropertyValue::CreateUInt16(FromStringTo<unsigned short>(str));
00150             case PropertyType::UInt32:
00151                 return PropertyValue::CreateUInt32(FromStringTo<unsigned int>(str));
00152             case PropertyType::UInt64:
00153                 return PropertyValue::CreateUInt64(FromStringTo<unsigned long long>(str));
00154             case PropertyType::Int16:
00155                 return PropertyValue::CreateInt16(FromStringTo<short>(str));
00156             case PropertyType::Int32:
00157                 return PropertyValue::CreateInt32(FromStringTo<int>(str));
00158             case PropertyType::Int64:
00159                 return PropertyValue::CreateInt64(FromStringTo<long long>(str));
00160             case PropertyType::Single:
00161                 return PropertyValue::CreateSingle(FromStringTo<float>(str));
00162             case PropertyType::Double:
00163                 return PropertyValue::CreateDouble(FromStringTo<double>(str));
00164             case PropertyType::Boolean:
00165                 return PropertyValue::CreateBoolean(FromStringTo<bool>(str));
00166             case PropertyType::Char16:
00167                 return PropertyValue::CreateChar16(str->Data()[0]);
00168             case PropertyType::Guid:
00169                 return PropertyValue::CreateGuid(FromStringTo<Guid>(str));
00170             default:
00171                 throw ref new Platform::InvalidCastException;
00172             }
00173         }
00174
00175         inline Platform::String^ ConvertPropertyValueToString(Windows::Foundation::IPropertyValue^ pv)
00176         {
00177             using namespace Platform;
00178             using namespace Windows::Foundation;
00179
00180             String^ valueString;
00181
00182             switch (pv->Type)
00183             {
00184             case PropertyType::String:
00185                 valueString = pv->GetString();
00186                 break;
00187
00188             case PropertyType::UInt8:
00189             case PropertyType::UInt16:
00190             case PropertyType::UInt32:
00191             case PropertyType::UInt64:
00192                 valueString = ToString(pv->GetUInt64());
00193                 break;
00194
00195             case PropertyType::Int16:
00196             case PropertyType::Int32:
00197             case PropertyType::Int64:
00198                 valueString = ToString(pv->GetInt64());
00199                 break;
00200
00201             case PropertyType::Single:
00202                 valueString = ToString(pv->GetSingle());
00203                 break;
00204
00205             case PropertyType::Double:
00206                 valueString = ToString(pv->GetDouble());
00207                 break;
00208
00209             case PropertyType::Boolean:
00210                 valueString = ToString(pv->GetBoolean());
00211                 break;
00212
00213             case PropertyType::Char16:
00214                 wchar_t buffer[2];
00215                 buffer[0] = pv->GetChar16();
00216                 buffer[1] = 0;
00217                 valueString = ref new String(buffer);
00218                 break;
00219
00220             case PropertyType::Guid:
00221                 valueString = pv->GetGuid().ToString();
00222                 break;
00223
00224             default:
00225                 throw ref new InvalidCastException;
00226             }
00227
00228             return valueString;
00229         }
00230
00231         inline Windows::Data::Xml::Dom::XmlElement^ CreateXmlElementFromObject(Windows::Data::Xml::Dom::XmlDocument^ doc, Platform::String^ name, Platform::Object^ value)
00232         {
00233             using namespace Platform;
00234             using namespace Windows::Foundation;
00235             using namespace Windows::Data::Xml::Dom;
00236
00237             XmlElement^ element = doc->CreateElement("item");
00238             element->SetAttribute("name", name);
00239
00240             IPropertyValue^ pv = (IPropertyValue^)value;
00241             element->SetAttribute("type", ToString((int)pv->Type));
00242             element->SetAttribute("value", ConvertPropertyValueToString(pv));
00243
00244             return element;
00245         }
00246
00247         inline concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file)
00248         {
00249             using namespace Windows::Data::Xml::Dom;
00250             using namespace Windows::Foundation;
00251             namespace WFC = Windows::Foundation::Collections;
00252             typedef Windows::Foundation::Collections::IKeyValuePair<Platform::String^, Platform::Object^> KVPair;
00253
00254             XmlDocument^ doc = ref new XmlDocument;
00255             doc->AppendChild(doc->CreateElement("items"));
00256             auto sessionState = SuspensionManager::SessionState();
00257
00258             std::for_each(WFC::begin(sessionState), WFC::end(sessionState), [doc](KVPair^ item)
00259             {
00260                 doc->DocumentElement->AppendChild(CreateXmlElementFromObject(doc, item->Key, item->Value));
00261             });
00262
00263             return concurrency::task<void>(doc->SaveToFileAsync(file));
00264         }
00265
00266         inline Windows::Foundation::PropertyType PropertyTypeFromString(Platform::String^ str)
00267         {
00268             int value = FromStringTo<int>(str);
00269             return (Windows::Foundation::PropertyType)value;
00270         }
00271
00272         inline concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file)
00273         {
00274             using namespace Platform;
00275             using namespace Windows::Foundation;
00276             using namespace Windows::Data::Xml::Dom;
00277             namespace WFC = Windows::Foundation::Collections;
00278
00279             concurrency::task<XmlDocument^> loadFileTask(XmlDocument::LoadFromFileAsync(file));
00280             return loadFileTask.then([=](concurrency::task<XmlDocument^> docTask)
00281             {
00282                 try
00283                 {
00284                     auto doc = docTask.get();
00285                     auto items = doc->SelectNodes("/items/item");
00286                     auto sessionState = SuspensionManager::SessionState();
00287
00288                     std::for_each(WFC::begin(items), WFC::end(items), [sessionState](IXmlNode^ node)
00289                     {
00290                         auto element = (IXmlElement^)node;
00291                         String^ name = element->GetAttribute("name");
00292                         String^ value = element->GetAttribute("value");
00293                         PropertyType type = PropertyTypeFromString(element->GetAttribute("type"));
00294
00295                         Object^ valueObject = ConvertStringToObject(type, value);
00296                         sessionState->Insert(name, valueObject);
00297                     });
00298
00299                 }
00300                 catch (Platform::Exception^)
00301                 {
00302                     // Restoring is best effort
00303                 }
00304             });
00305         }
00306     } // namespace Details
00307 } // namespace CppSamplesUtils
Generated on Sat Nov 23 2024 16:07:53 for Win8-Examples by doxygen 1.7.1


Win8-Examples: EAS policies for mail clients/C++/Scenario3.xaml.cpp Source File

  • EAS policies for mail clients

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 SDKSample::EAS;
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::ViewManagement;
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::Security::ExchangeActiveSyncProvisioning;
00034 using namespace concurrency;
00035 using namespace Windows::UI::Core;
00036
00037 Scenario3::Scenario3()
00038 {
00039     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 void Scenario3::OnNavigatedTo(NavigationEventArgs^ e)
00048 {
00049     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00050     // as NotifyUser()
00051     rootPage = MainPage::Current;
00052 }
00053
00054
00055
00056 void SDKSample::EAS::Scenario3::Launch_Click3(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00057 {
00058   try
00059   {
00060
00061     EasClientSecurityPolicy^ RequestedPolicy = ref new EasClientSecurityPolicy;
00062
00063
00064     if (RequireEncryptionValue2 == nullptr)
00065     {
00066       RequestedPolicy->RequireEncryption=false;
00067     }
00068     else
00069     {
00070       if (RequireEncryptionValue2->IsChecked)
00071         RequestedPolicy->RequireEncryption=true;
00072       else
00073       {
00074         RequestedPolicy->RequireEncryption=false;
00075       }
00076
00077     }
00078
00079     if (MinPasswordLengthValue2==nullptr||MinPasswordLengthValue2->Text=="")
00080       RequestedPolicy->MinPasswordLength = 0;
00081     else
00082     {
00083       RequestedPolicy->MinPasswordLength = _wtoi(MinPasswordLengthValue2->Text->Data());
00084     }
00085
00086     if (DisallowConvenienceLogonValue2 == nullptr)
00087     {
00088       RequestedPolicy->DisallowConvenienceLogon=false;
00089     }
00090     else
00091     {
00092       if (DisallowConvenienceLogonValue2->IsChecked)
00093         RequestedPolicy->DisallowConvenienceLogon=true;
00094       else
00095       {
00096         RequestedPolicy->DisallowConvenienceLogon=false;
00097       }
00098
00099     }
00100
00101     if (MinPasswordComplexCharactersValue2==nullptr||MinPasswordComplexCharactersValue2->Text=="")
00102       RequestedPolicy->MinPasswordComplexCharacters = 0;
00103     else
00104     {
00105       RequestedPolicy->MinPasswordComplexCharacters = _wtoi(MinPasswordComplexCharactersValue2->Text->Data());
00106     }
00107
00108     TimeSpan ExpirationDays;
00109     if (PasswordExpirationValue2==nullptr||PasswordExpirationValue2->Text=="")
00110     {
00111       ExpirationDays.Duration = 0;
00112       RequestedPolicy->PasswordExpiration = ExpirationDays;
00113     }
00114     else
00115     {
00116       ExpirationDays.Duration = _wtoi(PasswordExpirationValue2->Text->Data())*86400000;
00117       RequestedPolicy->PasswordExpiration = ExpirationDays;
00118     }
00119
00120     if (PasswordHistoryValue2==nullptr||PasswordHistoryValue2->Text=="")
00121       RequestedPolicy->PasswordHistory = 0;
00122     else
00123     {
00124       RequestedPolicy->PasswordHistory = _wtoi(PasswordHistoryValue2->Text->Data());
00125     }
00126
00127     if (MaxPasswordFailedAttemptsValue2==nullptr||MaxPasswordFailedAttemptsValue2->Text=="")
00128       RequestedPolicy->MaxPasswordFailedAttempts = 0;
00129     else
00130     {
00131       RequestedPolicy->MaxPasswordFailedAttempts = _wtoi(MaxPasswordFailedAttemptsValue2->Text->Data());
00132     }
00133
00134     TimeSpan Inactiveseconds;
00135     if (MaxInactivityTimeLockValue2==nullptr||MaxInactivityTimeLockValue2->Text=="")
00136     {
00137       Inactiveseconds.Duration=0;
00138       RequestedPolicy->MaxInactivityTimeLock = Inactiveseconds;
00139     }
00140     else
00141     {
00142       Inactiveseconds.Duration=_wtoi(MaxInactivityTimeLockValue2->Text->Data())*1000;
00143       RequestedPolicy->MaxInactivityTimeLock = Inactiveseconds;
00144     }
00145
00146   task<EasComplianceResults^> ApplyOp(RequestedPolicy->ApplyAsync());
00147         ApplyOp.then([=](task<EasComplianceResults^> resultTask)
00148         {
00149             try
00150             {
00151       auto results = resultTask.get();
00152
00153       RequireEncryptionResult2->Text = results->RequireEncryptionResult.ToString();
00154       MinPasswordLengthResult2->Text = results->MinPasswordLengthResult.ToString();
00155       DisallowConvenienceLogonResult2->Text = results->DisallowConvenienceLogonResult.ToString();
00156       MinPasswordComplexCharactersResult2->Text = results->MinPasswordComplexCharactersResult.ToString();
00157       PasswordExpirationResult2->Text = results->PasswordExpirationResult.ToString();
00158       PasswordHistoryResult2->Text = results->PasswordHistoryResult.ToString();
00159       MaxPasswordFailedAttemptsResult2->Text = results->MaxPasswordFailedAttemptsResult.ToString();
00160       MaxInactivityTimeLockResult2->Text = results->MaxInactivityTimeLockResult.ToString();
00161       }
00162       catch(Platform::Exception^ ex)
00163       {
00164         // ignore that 0x800704C7 exception
00165         if(ex->HResult!=0x800704C7)
00166           DebugArea->Text += "Error: " +ex->Message;
00167       }
00168     });
00169
00170   }
00171
00172   catch (Platform::Exception^ ex)
00173   {
00174
00175     DebugArea->Text += "Error: " +ex->Message;
00176   }
00177
00178 }
00179
00180 void SDKSample::EAS::Scenario3::Reset_Click3(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00181 {
00182   try
00183   {
00184     RequireEncryptionValue2->IsChecked=false;
00185     MinPasswordLengthValue2->Text="";
00186     DisallowConvenienceLogonValue2->IsChecked=false;
00187     MinPasswordComplexCharactersValue2->Text="";
00188     PasswordExpirationValue2->Text="";
00189     PasswordHistoryValue2->Text="";
00190     MaxPasswordFailedAttemptsValue2->Text="";
00191     MaxInactivityTimeLockValue2->Text="";
00192
00193     RequireEncryptionResult2->Text = "";
00194     MinPasswordLengthResult2->Text = "";
00195     DisallowConvenienceLogonResult2->Text = "";
00196     MinPasswordComplexCharactersResult2->Text = "";
00197     PasswordExpirationResult2->Text = "";
00198     PasswordHistoryResult2->Text = "";
00199     MaxPasswordFailedAttemptsResult2->Text = "";
00200     MaxInactivityTimeLockResult2->Text = "";
00201
00202     DebugArea->Text = "";
00203   }
00204   catch(Platform::Exception^ ex)
00205   {
00206     DebugArea->Text += "Error: " +ex->Message;
00207   }
00208 }
00209
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

AntSystem::LatLong Member List

This is the complete list of members for AntSystem::LatLong, including all inherited members.
Latitude | AntSystem::LatLong |
LatLong(double latitude, double longitude) | AntSystem::LatLong | [inline, explicit]
Longitude | AntSystem::LatLong |
Generated on Sat Nov 23 2024 16:09:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Audio Session (WASAPI)/C++/pch.cpp Source File

  • Windows Audio Session (WASAPI)
  • C++

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Print/C++/ScenarioOutput5.xaml.h Source File

  • Print

ScenarioOutput5.xaml.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 //
00009 // ScenarioOutput5.xaml.h
00010 // Declaration of the ScenarioOutput5 class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioOutput5.g.h"
00017 #include "MainPage.xaml.h"
00018
00019 namespace PrintSample
00020 {
00021     /// <summary>
00022     /// An empty page that can be used on its own or navigated to within a Frame.
00023     /// </summary>
00024     [Windows::Foundation::Metadata::WebHostHidden]
00025     public ref class ScenarioOutput5 sealed
00026     {
00027     public:
00028         ScenarioOutput5();
00029
00030         property Platform::String^ SelectedText
00031         {
00032             Platform::String^ get()
00033             {
00034                 return textContent->SelectedText;
00035             }
00036         }
00037     private:
00038         ~ScenarioOutput5();
00039     };
00040 }
Generated on Sat Nov 23 2024 16:08:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Secondary tiles/C#,C++/Constants.cpp Source File

  • Secondary tiles
  • C#,C++

Constants.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 "Constants.h"
00014
00015 using namespace SecondaryTiles;
00016 using namespace Windows::Foundation;
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     { "Pin Tile",                           "SecondaryTiles.PinTile" },
00023     { "Unpin Tile",                         "SecondaryTiles.UnpinTile" },
00024     { "Enumerate Tiles",                    "SecondaryTiles.EnumerateTiles" },
00025     { "Is Tile Pinned?",                    "SecondaryTiles.TilePinned" },
00026     { "Show Activation Arguments",          "SecondaryTiles.LaunchedFromSecondaryTile" },
00027     { "Secondary Tile Notifications",       "SecondaryTiles.SecondaryTileNotification" },
00028     { "Pin/Unpin Through Appbar",           "SecondaryTiles.PinFromAppbar" },
00029     { "Update Secondary Tile Default Logo", "SecondaryTiles.UpdateAsync" }
00030 };
00031
00032 Rect MainPage::GetElementRect(FrameworkElement^ element)
00033 {
00034     Windows::UI::Xaml::Media::GeneralTransform^ buttonTransform = element->TransformToVisual(nullptr);
00035     const Point pointOrig(0, 0);
00036     const Point pointTransformed = buttonTransform->TransformPoint(pointOrig);
00037     const Rect rect(pointTransformed.X,
00038                     pointTransformed.Y,
00039                     safe_cast<float>(element->ActualWidth),
00040                     safe_cast<float>(element->ActualHeight));
00041
00042     return rect;
00043 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Animation metrics/C++/Constants.cpp Source File

  • Animation metrics

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
00021     { "Retrieving Animation Metrics", "SDKSample.AnimationMetrics.Scenario1" },
00022 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/MediaExtensions/Mpeg1Decoder/dll.cpp Source File

  • Media extensions
  • MediaExtensions
  • Mpeg1Decoder

dll.cpp

Go to the documentation of this file.
00001 //////////////////////////////////////////////////////////////////////////
00002 //
00003 // dllmain.cpp
00004 //
00005 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00007 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00008 // PARTICULAR PURPOSE.
00009 //
00010 // Copyright (c) Microsoft Corporation. All rights reserved.
00011 //
00012 //////////////////////////////////////////////////////////////////////////
00013
00014 #include <wrl\module.h>
00015 #include "Decoder.h"
00016
00017 using namespace Microsoft::WRL;
00018
00019 namespace Microsoft { namespace Samples {
00020     ActivatableClass(CDecoder);
00021 }}
00022
00023 BOOL WINAPI DllMain( _In_ HINSTANCE hInstance, _In_ DWORD dwReason, _In_opt_ LPVOID lpReserved )
00024 {
00025     if( DLL_PROCESS_ATTACH == dwReason )
00026     {
00027         //
00028         //  Don't need per-thread callbacks
00029         //
00030         DisableThreadLibraryCalls( hInstance );
00031
00032         Module<InProc>::GetModule().Create();
00033     }
00034     else if( DLL_PROCESS_DETACH == dwReason )
00035     {
00036         Module<InProc>::GetModule().Terminate();
00037     }
00038
00039     return TRUE;
00040 }
00041
00042 HRESULT WINAPI DllGetActivationFactory( _In_ HSTRING activatibleClassId, _Outptr_ IActivationFactory** factory )
00043 {
00044     auto &module = Microsoft::WRL::Module< Microsoft::WRL::InProc >::GetModule();
00045     return module.GetActivationFactory( activatibleClassId, factory );
00046 }
00047
00048 HRESULT WINAPI DllCanUnloadNow()
00049 {
00050     auto &module = Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule();
00051     return (module.Terminate()) ? S_OK : S_FALSE;
00052 }
00053
00054 STDAPI DllGetClassObject( _In_ REFCLSID rclsid, _In_ REFIID riid, _Outptr_ LPVOID FAR* ppv )
00055 {
00056     auto &module = Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule();
00057     return module.GetClassObject( rclsid, riid, ppv );
00058 }
Generated on Sat Nov 23 2024 16:08:21 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Raw notifications/C++/MainAppSample/ScenarioOutput1.xaml.h Source File

  • Raw notifications
  • MainAppSample

ScenarioOutput1.xaml.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 //
00009 // Scenario1Output.xaml.h
00010 // Declaration of the Scenario1Output class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioOutput1.g.h"
00017 #include "MainPage.xaml.h"
00018
00019 namespace RawNotificationsSampleCPP
00020 {
00021   [Windows::Foundation::Metadata::WebHostHidden]
00022   public ref class ScenarioOutput1 sealed
00023   {
00024   public:
00025     ScenarioOutput1();
00026
00027   protected:
00028     virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029     virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030
00031   private:
00032     ~ScenarioOutput1();
00033     MainPage^ rootPage;
00034     void rootPage_InputFrameLoaded(Object^ sender, Object^ e);
00035     Windows::Foundation::EventRegistrationToken _frameLoadedToken;
00036   };
00037 }
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/StereoProjection.h Source File

  • DirectX 3D shooting game

StereoProjection.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 typedef struct STEREO_PARAMETERS
00011 {
00012     float viewerDistanceInches;
00013     float displaySizeInches;
00014     float pixelResolutionWidth;
00015     float pixelResolutionHeight;
00016     float stereoSeparationFactor;
00017     float stereoExaggerationFactor;
00018 } STEREO_PARAMETERS;
00019
00020 // Enumeration for stereo channels (left and right).
00021 typedef enum class STEREO_CHANNEL
00022 {
00023     LEFT = 0,
00024     RIGHT
00025 } STEREO_CHANNEL;
00026
00027 // Enumeration for stereo mode (normal or inverted).
00028 typedef enum class STEREO_MODE
00029 {
00030     NORMAL = 0,
00031     INVERTED,
00032 } STEREO_MODE;
00033
00034 void StereoCreateDefaultParameters(_Out_ STEREO_PARAMETERS* pStereoParameters);
00035
00036 DirectX::XMMATRIX MatrixStereoProjectionFovLH(
00037     _In_opt_ const STEREO_PARAMETERS* stereoParameters,
00038     STEREO_CHANNEL channel,
00039     float fovAngleY,
00040     float aspectHByW,
00041     float nearZ,
00042     float farZ,
00043     STEREO_MODE stereoMode
00044     );
00045
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::InclinometerCPP::sealed Member List

This is the complete list of members for SDKSample::InclinometerCPP::sealed, including all inherited members.
desiredReportInterval | SDKSample::InclinometerCPP::sealed | [private]
dispatcher | SDKSample::InclinometerCPP::sealed | [private]
dispatcherTimer | SDKSample::InclinometerCPP::sealed | [private]
DisplayCurrentReading(Platform::Object^sender, Platform::Object^e) | SDKSample::InclinometerCPP::sealed | [private]
inclinometer | SDKSample::InclinometerCPP::sealed | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::InclinometerCPP::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::InclinometerCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::InclinometerCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::InclinometerCPP::sealed | [protected, virtual]
ReadingChanged(Windows::Devices::Sensors::Inclinometer^sender, Windows::Devices::Sensors::InclinometerReadingChangedEventArgs^e) | SDKSample::InclinometerCPP::sealed | [private]
readingToken | SDKSample::InclinometerCPP::sealed | [private]
rootPage | SDKSample::InclinometerCPP::sealed | [private]
Scenario1() | SDKSample::InclinometerCPP::sealed |
Scenario2() | SDKSample::InclinometerCPP::sealed |
ScenarioDisable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::InclinometerCPP::sealed | [private]
ScenarioDisable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::InclinometerCPP::sealed | [private]
ScenarioEnable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::InclinometerCPP::sealed | [private]
ScenarioEnable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::InclinometerCPP::sealed | [private]
VisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | SDKSample::InclinometerCPP::sealed | [private]
VisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | SDKSample::InclinometerCPP::sealed | [private]
visibilityToken | SDKSample::InclinometerCPP::sealed | [private]
Generated on Sat Nov 23 2024 16:09:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::ToastContent::ToastText03 Member List

This is the complete list of members for NotificationsExtensions::ToastContent::ToastText03, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
Audio | NotificationsExtensions::ToastContent::ToastNotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
CreateNotification() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline]
Duration | NotificationsExtensions::ToastContent::ToastNotificationBase |
GetContent() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline, virtual]
GetContent() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline, virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
Launch | NotificationsExtensions::ToastContent::ToastNotificationBase |
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextBody | NotificationsExtensions::ToastContent::ToastText03 |
TextFields | NotificationsExtensions::NotificationBase |
TextHeadingWrap | NotificationsExtensions::ToastContent::ToastText03 |
ToastNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline]
ToastNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline]
ToastText03() | NotificationsExtensions::ToastContent::ToastText03 | [inline]
ToastText03() | NotificationsExtensions::ToastContent::ToastText03 | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Globalization preferences/C++/CurrentInputLanguage.xaml.h Source File

  • Globalization preferences

CurrentInputLanguage.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 // CurrentInputLanguageScenario.xaml.h
00013 // Declaration of the CurrentInputLanguage class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "CurrentInputLanguage.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace GlobalizationPreferencesSample
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 CurrentInputLanguage sealed
00031         {
00032         public:
00033             CurrentInputLanguage();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void Display_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DWriteParagraphText Member List

This is the complete list of members for DWriteParagraphText, including all inherited members.
__pad0__ | DWriteParagraphText |
ApplyJustificationSettings() | DWriteParagraphText | [private]
ApplySpacingSettings() | DWriteParagraphText | [private]
CreateDeviceIndependentResources() override | DWriteParagraphText | [virtual]
CreateDeviceResources() override | DWriteParagraphText | [virtual]
CreateWindowSizeDependentResources() override | DWriteParagraphText | [virtual]
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | DWriteParagraphText | [virtual]
Load(_In_ Platform::String^entryPoint) | DWriteParagraphText | [virtual]
m_blackBrush | DWriteParagraphText | [private]
m_gestureRecognizer | DWriteParagraphText | [private]
m_isIncreasedSpacing | DWriteParagraphText | [private]
m_isJustified | DWriteParagraphText | [private]
m_sampleOverlay | DWriteParagraphText | [private]
m_textFormat | DWriteParagraphText | [private]
m_textLayout1 | DWriteParagraphText | [private]
m_textRange | DWriteParagraphText | [private]
m_textTypography | DWriteParagraphText | [private]
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | DWriteParagraphText | [private]
OnDisplayContentsInvalidated(_In_ Platform::Object^sender) | DWriteParagraphText | [private]
OnHolding(_In_ Windows::UI::Input::GestureRecognizer^recognizer, _In_ Windows::UI::Input::HoldingEventArgs^args) | DWriteParagraphText | [private]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | DWriteParagraphText | [private]
OnPointerMoved(_In_ Windows::UI::Core::CoreWindow^window, _In_ Windows::UI::Core::PointerEventArgs^args) | DWriteParagraphText | [private]
OnPointerPressed(_In_ Windows::UI::Core::CoreWindow^window, _In_ Windows::UI::Core::PointerEventArgs^args) | DWriteParagraphText | [private]
OnPointerReleased(_In_ Windows::UI::Core::CoreWindow^window, _In_ Windows::UI::Core::PointerEventArgs^args) | DWriteParagraphText | [private]
OnResuming(_In_ Platform::Object^sender, _In_ Platform::Object^args) | DWriteParagraphText | [private]
OnSuspending(_In_ Platform::Object^sender, _In_ Windows::ApplicationModel::SuspendingEventArgs^args) | DWriteParagraphText | [private]
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | DWriteParagraphText | [private]
Render() override | DWriteParagraphText | [virtual]
Run() | DWriteParagraphText | [virtual]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | DWriteParagraphText | [virtual]
ShowMenu(Windows::Foundation::Point position) | DWriteParagraphText | [private]
Uninitialize() | DWriteParagraphText | [virtual]
UpdateCharacterSpacing(Windows::UI::Popups::IUICommand^command) | DWriteParagraphText | [private]
UpdateJustification(Windows::UI::Popups::IUICommand^command) | DWriteParagraphText | [private]
Generated on Sat Nov 23 2024 16:09:12 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::TileContent::TileWidePeekImage05 Member List

This is the complete list of members for NotificationsExtensions::TileContent::TileWidePeekImage05, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
Branding | NotificationsExtensions::TileContent::TileNotificationBase |
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
ImageMain | NotificationsExtensions::TileContent::TileWidePeekImage05 |
Images | NotificationsExtensions::NotificationBase |
ImageSecondary | NotificationsExtensions::TileContent::TileWidePeekImage05 |
Lang | NotificationsExtensions::NotificationBase |
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
RequireSquareContent | NotificationsExtensions::TileContent::TileWideBase |
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SquareContent | NotificationsExtensions::TileContent::TileWideBase |
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextBodyWrap | NotificationsExtensions::TileContent::TileWidePeekImage05 |
TextFields | NotificationsExtensions::NotificationBase |
TextHeading | NotificationsExtensions::TileContent::TileWidePeekImage05 |
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWidePeekImage05() | NotificationsExtensions::TileContent::TileWidePeekImage05 | [inline]
TileWidePeekImage05() | NotificationsExtensions::TileContent::TileWidePeekImage05 | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:44 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SaveAsImageFile Member List

This is the complete list of members for SaveAsImageFile, including all inherited members.
__pad0__ | SaveAsImageFile |
CreateDeviceIndependentResources() override | SaveAsImageFile | [virtual]
CreateDeviceResources() override | SaveAsImageFile | [virtual]
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | SaveAsImageFile | [virtual]
Load(_In_ Platform::String^entryPoint) | SaveAsImageFile | [virtual]
m_blackBrush | SaveAsImageFile | [private]
m_imageFileName | SaveAsImageFile | [private]
m_isSnapped | SaveAsImageFile | [private]
m_sampleOverlay | SaveAsImageFile | [private]
m_screenSavingState | SaveAsImageFile | [private]
m_snappedViewFormat | SaveAsImageFile | [private]
m_textFormat | SaveAsImageFile | [private]
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | SaveAsImageFile | [private]
OnDisplayContentsInvalidated(_In_ Platform::Object^sender) | SaveAsImageFile | [private]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | SaveAsImageFile | [private]
OnPointerPressed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | SaveAsImageFile | [private]
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | SaveAsImageFile | [private]
Render() override | SaveAsImageFile | [virtual]
Run() | SaveAsImageFile | [virtual]
SaveBitmapToFile() | SaveAsImageFile | [private]
SaveBitmapToStream(_In_ Microsoft::WRL::ComPtr< ID2D1Bitmap1 > d2dBitmap, _In_ Microsoft::WRL::ComPtr< IWICImagingFactory2 > wicFactory2, _In_ Microsoft::WRL::ComPtr< ID2D1DeviceContext > d2dContext, _In_ REFGUID wicFormat, _In_ IStream *stream) | SaveAsImageFile | [private, static]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | SaveAsImageFile | [virtual]
Uninitialize() | SaveAsImageFile | [virtual]
Generated on Sat Nov 23 2024 16:09:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::ApplicationResources::sealed Member List

This is the complete list of members for SDKSample::ApplicationResources::sealed, including all inherited members.
ContextChanged(Windows::Foundation::Collections::IObservableMap< Platform::String^, Platform::String^>^sender, Windows::Foundation::Collections::IMapChangedEventArgs< Platform::String^>^eventArg) | SDKSample::ApplicationResources::sealed | [private]
eventToken | SDKSample::ApplicationResources::sealed | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::ApplicationResources::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::ApplicationResources::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::ApplicationResources::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::ApplicationResources::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::ApplicationResources::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::ApplicationResources::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::ApplicationResources::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::ApplicationResources::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::ApplicationResources::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::ApplicationResources::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::ApplicationResources::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::ApplicationResources::sealed | [protected, virtual]
rootPage | SDKSample::ApplicationResources::sealed | [private]
Scenario1() | SDKSample::ApplicationResources::sealed |
Scenario10() | SDKSample::ApplicationResources::sealed |
Scenario10_SearchMultipleResourceIds(Windows::ApplicationModel::Resources::Core::ResourceContext^context, Platform::Collections::Vector< Platform::String^>^resourceIds) | SDKSample::ApplicationResources::sealed | [private]
Scenario10_ShowCandidates(Platform::String^resourceId, Windows::Foundation::Collections::IVectorView< Windows::ApplicationModel::Resources::Core::ResourceCandidate^>^resourceCandidates) | SDKSample::ApplicationResources::sealed | [private]
Scenario10Button_Show_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::ApplicationResources::sealed | [private]
Scenario11() | SDKSample::ApplicationResources::sealed |
Scenario11Button_Show_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::ApplicationResources::sealed | [private]
Scenario2() | SDKSample::ApplicationResources::sealed |
Scenario3() | SDKSample::ApplicationResources::sealed |
Scenario3StringLoad_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::ApplicationResources::sealed | [private]
Scenario4() | SDKSample::ApplicationResources::sealed |
Scenario5() | SDKSample::ApplicationResources::sealed |
Scenario5Button_Show_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::ApplicationResources::sealed | [private]
Scenario6() | SDKSample::ApplicationResources::sealed |
Scenario6Button_Show_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::ApplicationResources::sealed | [private]
Scenario7() | SDKSample::ApplicationResources::sealed |
Scenario7Button_Show_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::ApplicationResources::sealed | [private]
Scenario8() | SDKSample::ApplicationResources::sealed |
Scenario8Button_Show_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::ApplicationResources::sealed | [private]
Scenario9() | SDKSample::ApplicationResources::sealed |
Scenario9Button_Show_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::ApplicationResources::sealed | [private]
Generated on Sat Nov 23 2024 16:09:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Globalization preferences/C++/pch.cpp Source File

  • Globalization preferences

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite custom text renderer/C++/pch.cpp Source File

  • DirectWrite custom text renderer

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D post-processing effects/C++/BasicTimer.h Source File

  • Direct3D post-processing effects

BasicTimer.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 timer class used to drive the render loop of the actively-animated
00011 // DirectX SDK samples. Uses the QueryPerformanceCounter function to retrieve
00012 // high-resolution timing information.
00013 ref class BasicTimer
00014 {
00015 private:
00016     LARGE_INTEGER m_frequency;
00017     LARGE_INTEGER m_currentTime;
00018     LARGE_INTEGER m_startTime;
00019     LARGE_INTEGER m_lastTime;
00020     float m_total;
00021     float m_delta;
00022
00023 internal:
00024     BasicTimer();
00025     void Reset();
00026     void Update();
00027     property float Total
00028     {
00029         float get();
00030     }
00031     property float Delta
00032     {
00033         float get();
00034     }
00035 };
Generated on Sat Nov 23 2024 16:08:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Toast notifications/C#,C++/ScenarioInput2.xaml.h Source File

  • Toast notifications
  • C#,C++

ScenarioInput2.xaml.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 //
00009 // Scenario2Input.xaml.h
00010 // Declaration of the Scenario2Input class.
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioInput2.g.h"
00017 #include "MainPage.g.h"
00018
00019 namespace ToastsSampleCPP
00020 {
00021   [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class ScenarioInput2 sealed
00023     {
00024     public:
00025         ScenarioInput2();
00026
00027     protected:
00028         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030
00031     private:
00032         ~ScenarioInput2();
00033
00034     MainPage^ rootPage;
00035         void OutputText(Platform::String^ text);
00036         void Scenario2DisplayToast(Windows::UI::Notifications::ToastTemplateType templateType);
00037         void Scenario2DisplayToastWithStringManipulation(Windows::UI::Notifications::ToastTemplateType templateType);
00038
00039         Windows::UI::Xaml::Controls::TextBlock^ outputText;
00040     };
00041 }
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

QiListSelf< InterfaceName, InterfaceChain > Member List

This is the complete list of members for QiListSelf< InterfaceName, InterfaceChain >, including all inherited members.
QueryInterfaceInternal(IID const &iid, OUT void **ppObject) QiListSelf< InterfaceName, InterfaceChain > [inline]
Generated on Sat Nov 23 2024 16:09:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Configure keys for media/C++/App.xaml.h Source File

  • Configure keys for media

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Network information/C++/NetworkStatusChange.xaml.cpp Source File

  • Network information

NetworkStatusChange.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 // NetworkStatusChange.xaml.cpp
00013 // Implementation of the NetworkStatusChange class
00014 //
00015
00016 #include "pch.h"
00017 #include "NetworkStatusChange.xaml.h"
00018
00019 using namespace SDKSample::NetworkInformationApi;
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::System;
00025 using namespace Windows::Foundation;
00026 using namespace Platform;
00027 using namespace Windows::Networking;
00028 using namespace Windows::Networking::Connectivity;
00029
00030 NetworkStatusChange::NetworkStatusChange()
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 void NetworkStatusChange::OnNavigatedTo(NavigationEventArgs^ e)
00041 {
00042     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00043     // as NotifyUser()
00044     rootPage = MainPage::Current;
00045
00046     //create handler for network status changed event
00047     networkStatusCallback = ref new NetworkStatusChangedEventHandler(this, &NetworkStatusChange::OnNetworkStatusChange, CallbackContext::Same);
00048 }
00049
00050 // Get Connection Cost based suggestions
00051 String^ NetworkStatusChange::GetCostBasedSuggestions(ConnectionCost^ connectionCost)
00052 {
00053     String^ strRet = "";
00054
00055     strRet = L"Cost Based Suggestions: \n";
00056     if (connectionCost->Roaming)
00057     {
00058         strRet += L"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";
00059     }
00060     else if (connectionCost->NetworkCostType == NetworkCostType::Variable)
00061     {
00062         strRet += L"Connection cost is variable, and the connection is charged based on usage, so application can implement the Conservative behavior\n";
00063     }
00064     else if (connectionCost->NetworkCostType == NetworkCostType::Fixed)
00065     {
00066         if (connectionCost->OverDataLimit || connectionCost->ApproachingDataLimit)
00067         {
00068             strRet += L"Connection has exceeded the usage cap limit or is approaching the datalimit, and the application can implement High Cost behavior in this scenario\n";
00069         }
00070         else
00071         {
00072             strRet += L"Application can implemement the Conservative behavior\n";
00073         }
00074     }
00075     else
00076     {
00077         strRet += L"Application can implement the Standard behavior\n";
00078     }
00079
00080     return strRet;
00081 }
00082
00083 // Get Connection Cost information
00084 String^ NetworkStatusChange::GetConnectionCostInfo(ConnectionCost^ connectionCost)
00085 {
00086     String^ strRet = "";
00087
00088     if (connectionCost == nullptr)
00089     {
00090         return strRet;
00091     }
00092
00093     strRet = L"Connection Cost Information: \n";
00094     strRet += L"====================\n";
00095     switch(connectionCost->NetworkCostType)
00096     {
00097         case NetworkCostType::Unrestricted:
00098             strRet += L"Cost: Unrestricted\n";
00099             break;
00100         case NetworkCostType::Fixed:
00101             strRet += L"Cost: Fixed\n";
00102             break;
00103         case NetworkCostType::Variable:
00104             strRet += L"Cost: Variable\n";
00105             break;
00106         case NetworkCostType::Unknown:
00107             strRet += L"Cost: Unknown\n";
00108             break;
00109         default:
00110             strRet += L"Cost: Error\n";
00111             break;
00112     }
00113
00114     if (connectionCost->Roaming)
00115     {
00116         strRet += L"Roaming    : Yes\n";
00117     }
00118     else
00119     {
00120         strRet += L"Roaming    : No\n";
00121     }
00122
00123     if (connectionCost->OverDataLimit)
00124     {
00125         strRet += L"OverDataLimit    : Yes\n";
00126     }
00127     else
00128     {
00129         strRet += L"OverDataLimit    : No\n";
00130     }
00131
00132     if (connectionCost->ApproachingDataLimit)
00133     {
00134         strRet += L"ApproachingDataLimit    : Yes\n";
00135     }
00136     else
00137     {
00138         strRet += L"ApproachingDataLimit    : No\n";
00139     }
00140
00141     //Get cost based suggestions
00142     strRet += GetCostBasedSuggestions(connectionCost);
00143     return strRet;
00144 }
00145
00146 // Get Dataplan Status Information
00147 String^ NetworkStatusChange::GetDataPlanStatusInfo(DataPlanStatus^ dataPlan)
00148 {
00149     String ^strRet = "";
00150
00151     if (dataPlan == nullptr)
00152     {
00153         return strRet;
00154     }
00155
00156     strRet = L"Dataplan Status Information: \n";
00157     strRet += L"====================\n";
00158
00159     if (dataPlan->DataPlanUsage != nullptr)
00160     {
00161         auto lastSyncTime = dataPlan->DataPlanUsage->LastSyncTime;
00162         ULARGE_INTEGER lst;
00163         lst.QuadPart = lastSyncTime.UniversalTime;
00164         FILETIME ftLastSyncTime;
00165         SYSTEMTIME stLastSyncTime;
00166
00167         //get FILETIME from lastSyncTime, convert FILETIME to SYSTEMTIME and display
00168         ftLastSyncTime.dwLowDateTime = lst.LowPart;
00169         ftLastSyncTime.dwHighDateTime = lst.HighPart;
00170         FileTimeToSystemTime(&ftLastSyncTime, &stLastSyncTime);
00171         strRet += L"Usage In Megabytes : " + dataPlan->DataPlanUsage->MegabytesUsed.ToString() + "\n";
00172         strRet += L"LastSyncTime: " + stLastSyncTime.wMonth.ToString() + "/" + stLastSyncTime.wDay.ToString() + "/" + stLastSyncTime.wYear.ToString() + " " + stLastSyncTime.wHour.ToString() + ":" + stLastSyncTime.wMinute.ToString() + ":"+ stLastSyncTime.wSecond.ToString() + "\n";
00173     }
00174     else
00175     {
00176         strRet += L"DataPlan Usage : Not Defined\n";
00177     }
00178
00179     if (dataPlan->InboundBitsPerSecond != nullptr)
00180     {
00181         auto inboundBandwidth = dataPlan->InboundBitsPerSecond->Value;
00182         strRet += L"InboundBitsPerSecond : " + inboundBandwidth.ToString() + "\n";
00183     }
00184     else
00185     {
00186         strRet += L"InboundBitsPerSecond : Not Defined\n";
00187     }
00188
00189     if (dataPlan->OutboundBitsPerSecond != nullptr)
00190     {
00191         auto outboundBandwidth = dataPlan->OutboundBitsPerSecond->Value;
00192         strRet += L"OutboundBitsPerSecond : " + outboundBandwidth.ToString() + "\n";
00193     }
00194     else
00195     {
00196         strRet += L"OutboundBitsPerSecond : Not Defined\n";
00197     }
00198
00199     if (dataPlan->DataLimitInMegabytes != nullptr)
00200     {
00201         auto dataLimit = dataPlan->DataLimitInMegabytes->Value;
00202         strRet += L"DataLimitInMegabytes : " + dataLimit.ToString() + "\n";
00203
00204     }
00205     else
00206     {
00207         strRet += L"DataLimitInMegabytes : Not Defined\n";
00208     }
00209
00210     if (dataPlan->NextBillingCycle != nullptr)
00211     {
00212         auto nextBillingCycle = dataPlan->NextBillingCycle->Value;
00213         ULARGE_INTEGER nbc;
00214         nbc.QuadPart = nextBillingCycle.UniversalTime;
00215         FILETIME ftNextBillingCycle;
00216         SYSTEMTIME stNextBillingCycle;
00217
00218         //get FILETIME from NextBillingCycle, convert to FILETIME to SYSTEMTIME and display
00219         ftNextBillingCycle.dwLowDateTime = nbc.LowPart;
00220         ftNextBillingCycle.dwHighDateTime = nbc.HighPart;
00221         FileTimeToSystemTime(&ftNextBillingCycle, &stNextBillingCycle);
00222         strRet += L"NextBillingCycle: " + stNextBillingCycle.wMonth.ToString() + "/" + stNextBillingCycle.wDay.ToString() + "/" + stNextBillingCycle.wYear.ToString() + " " + stNextBillingCycle.wHour.ToString() + ":" + stNextBillingCycle.wMinute.ToString() + ":" + stNextBillingCycle.wSecond.ToString() + "\n";
00223     }
00224     else
00225     {
00226         strRet += L"NextBillingCycle : Not Defined\n";
00227     }
00228
00229     if (dataPlan->MaxTransferSizeInMegabytes != nullptr)
00230     {
00231         auto transferSize = dataPlan->MaxTransferSizeInMegabytes->Value;
00232         strRet += L"MaxTransferSizeInMegabytes : " + transferSize.ToString() + "\n";
00233     }
00234     else
00235     {
00236         strRet += L"MaxTransferSizeInMegabytes : Not Defined\n";
00237     }
00238
00239     return strRet;
00240 }
00241
00242
00243 // Get Network Security Settings information
00244 String^ NetworkStatusChange::GetNetworkSecuritySettingsInfo(NetworkSecuritySettings^ netSecuritySettings)
00245 {
00246     String^ networkSecurity = "";
00247     networkSecurity += L"Network Security Settings: \n";
00248     networkSecurity += L"====================\n";
00249
00250     if (netSecuritySettings == nullptr)
00251     {
00252         networkSecurity += L"Network Security Settings not available\n";
00253         return networkSecurity;
00254     }
00255
00256     //NetworkAuthenticationType
00257     switch (netSecuritySettings->NetworkAuthenticationType)
00258     {
00259         case NetworkAuthenticationType::None:
00260             networkSecurity += L"NetworkAuthenticationType: None";
00261             break;
00262         case NetworkAuthenticationType::Unknown:
00263             networkSecurity += L"NetworkAuthenticationType: Unknown";
00264             break;
00265         case NetworkAuthenticationType::Open80211:
00266             networkSecurity += L"NetworkAuthenticationType: Open80211";
00267             break;
00268         case NetworkAuthenticationType::SharedKey80211:
00269             networkSecurity += L"NetworkAuthenticationType: SharedKey80211";
00270             break;
00271         case NetworkAuthenticationType::Wpa:
00272             networkSecurity += L"NetworkAuthenticationType: Wpa";
00273             break;
00274         case NetworkAuthenticationType::WpaPsk:
00275             networkSecurity += L"NetworkAuthenticationType: WpaPsk";
00276             break;
00277         case NetworkAuthenticationType::WpaNone:
00278             networkSecurity += L"NetworkAuthenticationType: WpaNone";
00279             break;
00280         case NetworkAuthenticationType::Rsna:
00281             networkSecurity += L"NetworkAuthenticationType: Rsna";
00282             break;
00283         case NetworkAuthenticationType::RsnaPsk:
00284             networkSecurity += L"NetworkAuthenticationType: RsnaPsk";
00285             break;
00286         default:
00287             networkSecurity += L"NetworkAuthenticationType: Error";
00288             break;
00289     }
00290     networkSecurity += L"\n";
00291
00292     //NetworkEncryptionType
00293     switch (netSecuritySettings->NetworkEncryptionType)
00294     {
00295         case NetworkEncryptionType::None:
00296             networkSecurity += L"NetworkEncryptionType: None";
00297             break;
00298         case NetworkEncryptionType::Unknown:
00299             networkSecurity += L"NetworkEncryptionType: Unknown";
00300             break;
00301         case NetworkEncryptionType::Wep:
00302             networkSecurity += L"NetworkEncryptionType: Wep";
00303             break;
00304         case NetworkEncryptionType::Wep40:
00305             networkSecurity += L"NetworkEncryptionType: Wep40";
00306             break;
00307         case NetworkEncryptionType::Wep104:
00308             networkSecurity += L"NetworkEncryptionType: Wep104";
00309             break;
00310         case NetworkEncryptionType::Tkip:
00311             networkSecurity += L"NetworkEncryptionType: Tkip";
00312             break;
00313         case NetworkEncryptionType::Ccmp:
00314             networkSecurity += L"NetworkEncryptionType: Ccmp";
00315             break;
00316         case NetworkEncryptionType::WpaUseGroup:
00317             networkSecurity += L"NetworkEncryptionType: WpaUseGroup";
00318             break;
00319         case NetworkEncryptionType::RsnUseGroup:
00320             networkSecurity += L"NetworkEncryptionType: RsnUseGroup";
00321             break;
00322         default:
00323             networkSecurity += L"NetworkEncryptionType: Error";
00324             break;
00325     }
00326     networkSecurity += L"\n";
00327     return networkSecurity;
00328 }
00329
00330
00331 // Get Connection Profile Information
00332 String^ NetworkStatusChange::GetConnectionProfile(ConnectionProfile^ connectionProfile)
00333 {
00334     String^ strProfileInfo = "";
00335
00336     switch (connectionProfile->GetNetworkConnectivityLevel())
00337     {
00338         case NetworkConnectivityLevel::None:
00339             strProfileInfo += "Connectivity Level : None\n";
00340             break;
00341         case NetworkConnectivityLevel::LocalAccess:
00342             strProfileInfo += "Connectivity Level : Local Access\n";
00343             break;
00344         case NetworkConnectivityLevel::ConstrainedInternetAccess:
00345             strProfileInfo += "Connectivity Level : Constrained Internet Access\n";
00346             break;
00347         case NetworkConnectivityLevel::InternetAccess:
00348             strProfileInfo += "Connectivity Level : Internet Access\n";
00349             break;
00350     }
00351
00352     //Get Connection Cost information
00353     ConnectionCost^ connectionCost = connectionProfile->GetConnectionCost();
00354     strProfileInfo += GetConnectionCostInfo(connectionCost);
00355
00356     //Get Dataplan Status information
00357     DataPlanStatus^ dataPlan = connectionProfile->GetDataPlanStatus();
00358     strProfileInfo += GetDataPlanStatusInfo(dataPlan);
00359
00360     //Get Network Security Settings
00361     NetworkSecuritySettings^ netSecuritySettings = connectionProfile->NetworkSecuritySettings;
00362     strProfileInfo += GetNetworkSecuritySettingsInfo(netSecuritySettings);
00363
00364     return strProfileInfo;
00365 }
00366
00367 // Register for Network Status Change notifications
00368 void NetworkStatusChange::NetworkStatusChange_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00369 {
00370     try
00371     {
00372         // register for network status change notifications
00373         if (!registeredNetworkStatusNotif)
00374         {
00375             cookie = NetworkInformation::NetworkStatusChanged += networkStatusCallback;
00376             registeredNetworkStatusNotif = true;
00377         }
00378         if (internetProfileInfo == "")
00379         {
00380             rootPage->NotifyUser(L"No network status change. ", NotifyType::StatusMessage);
00381         }
00382         else
00383         {
00384             rootPage->NotifyUser(internetProfileInfo, NotifyType::StatusMessage);
00385         }
00386     }
00387
00388     catch (Exception^ ex)
00389     {
00390         rootPage->NotifyUser("An unexpected exception occured: " + ex->Message, NotifyType::ErrorMessage);
00391     }
00392 }
00393
00394 // Event handler for Network Status Change event
00395 void NetworkStatusChange::OnNetworkStatusChange(Object^ sender)
00396 {
00397     try
00398     {
00399         //network status changed
00400         internetProfileInfo = "Network Status Changed: \n";
00401
00402         // Display new Interent Connection profile information
00403         ConnectionProfile^ internetConnectionProfile = NetworkInformation::GetInternetConnectionProfile();
00404         if (internetConnectionProfile == nullptr)
00405         {
00406             rootPage->NotifyUser(L"Not connected to Internet\n", NotifyType::StatusMessage);
00407         }
00408         else
00409         {
00410             String^ connectionProfileInfo = L"Profile Name : " + internetConnectionProfile->ProfileName + L"\n" + GetConnectionProfile(internetConnectionProfile);
00411             rootPage->NotifyUser(connectionProfileInfo, NotifyType::StatusMessage);
00412         }
00413         internetProfileInfo = "";
00414     }
00415
00416     catch (Exception^ ex)
00417     {
00418         rootPage->NotifyUser("An unexpected exception occured: " + ex->Message, NotifyType::ErrorMessage);
00419     }
00420 }
00421
00422 // Unregister Network Status Change notifications
00423 void NetworkStatusChange::UnRegisterForNetworkStatusChangeNotif ()
00424 {
00425     try
00426     {
00427         NetworkInformation::NetworkStatusChanged -= cookie;
00428         internetProfileInfo = "";
00429         registeredNetworkStatusNotif = false;
00430     }
00431     catch (Exception^ ex)
00432     {
00433         rootPage->NotifyUser("An unexpected exception occured: " + ex->Message, NotifyType::ErrorMessage);
00434     }
00435 }
00436
00437 void NetworkStatusChange::OnNavigatedFrom(NavigationEventArgs^ e)
00438 {
00439     //on scenario change, unregister from Network Status Change notifications if registerd
00440     if (registeredNetworkStatusNotif)
00441     {
00442         UnRegisterForNetworkStatusChangeNotif ();
00443         registeredNetworkStatusNotif = false;
00444     }
00445 }
00446
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Extended Linguistic Services (ELS)/C++/ScriptDetection.xaml.h Source File

  • Extended Linguistic Services (ELS)
  • C++

ScriptDetection.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 // ScriptDetection.xaml.h
00013 // Declaration of the ScriptDetection class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "ScriptDetection.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace ELS
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 ScriptDetection sealed
00031         {
00032         public:
00033             ScriptDetection();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037
00038         private:
00039             MainPage^ rootPage;
00040             void Go_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         };
00042     }
00043 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media Server client/C++/common/LayoutAwarePage.h Source File

  • Media Server client
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/Level5.h Source File

  • DirectX 3D shooting game

Level5.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 // Level5:
00011 // This class defines the fifth level of the game.  It derives from the
00012 // third level.  This level introduces obstacles that move into place
00013 // during game play.  The targets may be hit in any order.
00014
00015 #include "Level3.h"
00016
00017 ref class Level5: public Level3
00018 {
00019 internal:
00020     Level5();
00021     virtual void Initialize(std::vector<GameObject^> objects) override;
00022 };
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Globalization preferences/C++/Utilities.cpp Source File

  • Globalization preferences

Utilities.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 // UserPreferences.xaml.cpp
00013 // Implementation of the UserPreferences class
00014 //
00015
00016 #include "pch.h"
00017 #include "Utilities.h"
00018
00019 using namespace SDKSample::GlobalizationPreferencesSample;
00020
00021 using namespace Platform;
00022 using namespace Windows::Foundation;
00023
00024 /// <summary>
00025 /// Converts vector view of strings into a single string.
00026 /// </summary>
00027 Platform::String^ Utilities::VectorViewToString(Windows::Foundation::Collections::IVectorView<Platform::String^>^ data)
00028 {
00029     // Initial value is empty
00030     String^ value = "";
00031
00032     // Iterate throgh the elements in the vector view and add them to the string
00033     for (unsigned int i = 0; i < data->Size; i++)
00034         value = value + data->GetAt(i) + " ";
00035
00036     // Return the string
00037     return value;
00038 }
00039
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Web authentication broker/C++/App.xaml.cpp Source File

  • Web authentication broker

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:28 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML AppBar control/C++/Scenario4.xaml.h Source File

  • XAML AppBar control

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
00022 namespace AppBarControl
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 Scenario4 sealed
00029     {
00030     public:
00031         Scenario4();
00032
00033     protected:
00034         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00035     private:
00036         MainPage^ rootPage;
00037         void ShowMe_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038     };
00039 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D HLSL fractal generator/C++/DirectXSample.h Source File

  • Direct3D HLSL fractal generator

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
00010 // This header defines helper utilities to make DirectX APIs work with exceptions.
00011 namespace DX
00012 {
00013     inline void ThrowIfFailed(HRESULT hr)
00014     {
00015         if (FAILED(hr))
00016         {
00017             // Set a breakpoint on this line to catch DX API errors.
00018             throw Platform::Exception::CreateException(hr);
00019         }
00020     }
00021 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Accelerometer sensor/C++/MainPage.xaml.cpp Source File

  • Accelerometer sensor

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DatagramSocketSample::Scenario Member List

This is the complete list of members for DatagramSocketSample::Scenario, including all inherited members.
ClassName | DatagramSocketSample::Scenario
Title | DatagramSocketSample::Scenario
Generated on Sat Nov 23 2024 16:09:37 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media Server client/C++/App.xaml.h Source File

  • Media Server client

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

D2DTextAnimation Member List

This is the complete list of members for D2DTextAnimation, including all inherited members.
__pad0__ | D2DTextAnimation |
CalculateCenterPosition() | D2DTextAnimation | [private]
CreateDeviceIndependentResources() override | D2DTextAnimation | [virtual]
CreateDeviceResources() override | D2DTextAnimation | [virtual]
CreateOpacityMask() | D2DTextAnimation |
DrawTextLayout(float x, float y) | D2DTextAnimation | [private]
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | D2DTextAnimation | [virtual]
Load(_In_ Platform::String^entryPoint) | D2DTextAnimation | [virtual]
m_animating | D2DTextAnimation | [private]
m_blackBrush | D2DTextAnimation | [private]
m_firstRun | D2DTextAnimation | [private]
m_gestureRecognizer | D2DTextAnimation | [private]
m_opacityBitmap | D2DTextAnimation | [private]
m_sampleOverlay | D2DTextAnimation | [private]
m_textFormat | D2DTextAnimation | [private]
m_textLayout | D2DTextAnimation | [private]
m_textMetrics | D2DTextAnimation | [private]
m_viewPosition | D2DTextAnimation | [private]
m_zoom | D2DTextAnimation | [private]
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | D2DTextAnimation | [private]
OnDisplayContentsInvalidated(_In_ Platform::Object^sender) | D2DTextAnimation | [private]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | D2DTextAnimation | [private]
OnManipulationCompleted(_In_ Windows::UI::Input::GestureRecognizer^recognizer, _In_ Windows::UI::Input::ManipulationCompletedEventArgs^args) | D2DTextAnimation | [private]
OnManipulationUpdated(_In_ Windows::UI::Input::GestureRecognizer^recognizer, _In_ Windows::UI::Input::ManipulationUpdatedEventArgs^args) | D2DTextAnimation | [private]
OnPointerMoved(_In_ Windows::UI::Core::CoreWindow^window, _In_ Windows::UI::Core::PointerEventArgs^args) | D2DTextAnimation | [private]
OnPointerPressed(_In_ Windows::UI::Core::CoreWindow^window, _In_ Windows::UI::Core::PointerEventArgs^args) | D2DTextAnimation | [private]
OnPointerReleased(_In_ Windows::UI::Core::CoreWindow^window, _In_ Windows::UI::Core::PointerEventArgs^args) | D2DTextAnimation | [private]
OnPointerWheelChanged(_In_ Windows::UI::Core::CoreWindow^window, _In_ Windows::UI::Core::PointerEventArgs^args) | D2DTextAnimation | [private]
OnSuspending(_In_ Platform::Object^sender, _In_ Windows::ApplicationModel::SuspendingEventArgs^args) | D2DTextAnimation | [private]
OnTapped(_In_ Windows::UI::Input::GestureRecognizer^recognizer, _In_ Windows::UI::Input::TappedEventArgs^args) | D2DTextAnimation | [private]
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | D2DTextAnimation | [private]
Render() override | D2DTextAnimation | [virtual]
Run() | D2DTextAnimation | [virtual]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | D2DTextAnimation | [virtual]
Uninitialize() | D2DTextAnimation | [virtual]
Generated on Sat Nov 23 2024 16:09:11 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D perspective transform/C++/SampleOverlay.cpp Source File

  • Direct2D perspective transform

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 Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::UI::ViewManagement;
00015 using namespace Windows::Graphics::Display;
00016 using namespace D2D1;
00017
00018 SampleOverlay::SampleOverlay() :
00019     m_drawOverlay(true)
00020 {
00021 }
00022
00023 void SampleOverlay::Initialize(
00024     _In_ ID2D1Device*         d2dDevice,
00025     _In_ ID2D1DeviceContext*  d2dContext,
00026     _In_ IWICImagingFactory*  wicFactory,
00027     _In_ IDWriteFactory*      dwriteFactory,
00028     _In_ Platform::String^    caption
00029     )
00030 {
00031     m_wicFactory = wicFactory;
00032     m_dwriteFactory = dwriteFactory;
00033     m_sampleName = caption;
00034     m_d2dDevice = d2dDevice;
00035     m_d2dContext = d2dContext;
00036     m_padding = 3.0f;
00037     m_textVerticalOffset = 5.0f;
00038     m_logoSize = D2D1::SizeF(0.0f, 0.0f);
00039     m_overlayWidth = 0.0f;
00040
00041     ComPtr<ID2D1Factory> factory;
00042     d2dDevice->GetFactory(&factory);
00043
00044     DX::ThrowIfFailed(
00045         factory.As(&m_d2dFactory)
00046         );
00047
00048     ResetDirectXResources();
00049 }
00050
00051 void SampleOverlay::ResetDirectXResources()
00052 {
00053     DX::ThrowIfFailed(
00054         m_d2dContext->CreateSolidColorBrush(ColorF(ColorF::White), &m_whiteBrush)
00055         );
00056
00057     ComPtr<IWICBitmapDecoder> wicBitmapDecoder;
00058     DX::ThrowIfFailed(
00059         m_wicFactory->CreateDecoderFromFilename(
00060             L"windowsbig-sdk.png",
00061             nullptr,
00062             GENERIC_READ,
00063             WICDecodeMetadataCacheOnDemand,
00064             &wicBitmapDecoder
00065             )
00066         );
00067
00068     ComPtr<IWICBitmapFrameDecode> wicBitmapFrame;
00069     DX::ThrowIfFailed(
00070         wicBitmapDecoder->GetFrame(0, &wicBitmapFrame)
00071         );
00072
00073     ComPtr<IWICFormatConverter> wicFormatConverter;
00074     DX::ThrowIfFailed(
00075         m_wicFactory->CreateFormatConverter(&wicFormatConverter)
00076         );
00077
00078     DX::ThrowIfFailed(
00079         wicFormatConverter->Initialize(
00080             wicBitmapFrame.Get(),
00081             GUID_WICPixelFormat32bppPBGRA,
00082             WICBitmapDitherTypeNone,
00083             nullptr,
00084             0.0,
00085             WICBitmapPaletteTypeCustom  // the BGRA format has no palette so this value is ignored
00086             )
00087         );
00088
00089     double dpiX = 96.0f;
00090     double dpiY = 96.0f;
00091     DX::ThrowIfFailed(
00092         wicFormatConverter->GetResolution(&dpiX, &dpiY)
00093         );
00094
00095     DX::ThrowIfFailed(
00096         m_d2dContext->CreateBitmapFromWicBitmap(
00097             wicFormatConverter.Get(),
00098             BitmapProperties(
00099                 PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00100                 static_cast<float>(dpiX),
00101                 static_cast<float>(dpiY)
00102                 ),
00103             &m_logoBitmap
00104             )
00105         );
00106
00107     m_logoSize = m_logoBitmap->GetSize();
00108
00109     ComPtr<IDWriteTextFormat> nameTextFormat;
00110     DX::ThrowIfFailed(
00111         m_dwriteFactory->CreateTextFormat(
00112             L"Segoe UI",
00113             nullptr,
00114             DWRITE_FONT_WEIGHT_LIGHT,
00115             DWRITE_FONT_STYLE_NORMAL,
00116             DWRITE_FONT_STRETCH_NORMAL,
00117             36.0f,
00118             L"en-US",
00119             &nameTextFormat
00120             )
00121         );
00122
00123     DX::ThrowIfFailed(
00124         nameTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)
00125         );
00126
00127     DX::ThrowIfFailed(
00128         nameTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)
00129         );
00130
00131     DX::ThrowIfFailed(
00132         m_dwriteFactory->CreateTextLayout(
00133             m_sampleName->Data(),
00134             m_sampleName->Length(),
00135             nameTextFormat.Get(),
00136             4096.0f,
00137             4096.0f,
00138             &m_textLayout
00139             )
00140         );
00141
00142     DWRITE_TEXT_METRICS metrics = {0};
00143     DX::ThrowIfFailed(
00144         m_textLayout->GetMetrics(&metrics)
00145         );
00146
00147     m_overlayWidth = m_padding * 3.0f + m_logoSize.width + metrics.width;
00148
00149     DX::ThrowIfFailed(
00150         m_d2dFactory->CreateDrawingStateBlock(&m_stateBlock)
00151         );
00152
00153     UpdateForWindowSizeChange();
00154 }
00155
00156 void SampleOverlay::UpdateForWindowSizeChange()
00157 {
00158     if (CoreWindow::GetForCurrentThread()->Bounds.Width < m_overlayWidth)
00159     {
00160         m_drawOverlay = false;
00161     }
00162     else
00163     {
00164         m_drawOverlay = true;
00165     }
00166 }
00167
00168 void SampleOverlay::Render()
00169 {
00170     if (m_drawOverlay)
00171     {
00172         m_d2dContext->SaveDrawingState(m_stateBlock.Get());
00173
00174         m_d2dContext->BeginDraw();
00175         m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00176         m_d2dContext->DrawBitmap(
00177             m_logoBitmap.Get(),
00178             D2D1::RectF(m_padding, 0.0f, m_logoSize.width + m_padding, m_logoSize.height)
00179             );
00180
00181         m_d2dContext->DrawTextLayout(
00182             Point2F(m_logoSize.width + 2.0f * m_padding, m_textVerticalOffset),
00183             m_textLayout.Get(),
00184             m_whiteBrush.Get()
00185             );
00186
00187         // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00188         // is lost. It will be handled during the next call to Present.
00189         HRESULT hr = m_d2dContext->EndDraw();
00190         if (hr != D2DERR_RECREATE_TARGET)
00191         {
00192             DX::ThrowIfFailed(hr);
00193         }
00194
00195         m_d2dContext->RestoreDrawingState(m_stateBlock.Get());
00196     }
00197 }
00198
00199 float SampleOverlay::GetTitleHeightInDips()
00200 {
00201     return m_logoSize.height;
00202 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

PostcardRenderer Member List

This is the complete list of members for PostcardRenderer, including all inherited members.
__pad0__ | PostcardRenderer |
AddPaper() | PostcardRenderer |
CreateDeviceIndependentResources() override | PostcardRenderer | [virtual]
CreateDeviceResources() override | PostcardRenderer | [virtual]
CreateWindowSizeDependentResources() override | PostcardRenderer | [virtual]
LoadImage(Windows::Storage::Streams::IRandomAccessStream^randomAccessStream) | PostcardRenderer |
m_extrudedTextRenderer | PostcardRenderer | [private]
m_imageRenderer | PostcardRenderer | [private]
m_inkRenderer | PostcardRenderer | [private]
m_paperRenderer | PostcardRenderer | [private]
m_sampleMode | PostcardRenderer | [private]
m_swapChainPanel | PostcardRenderer | [private]
m_windowState | PostcardRenderer | [private]
MovePaper() | PostcardRenderer |
OnDataRequested(_In_ Windows::ApplicationModel::DataTransfer::DataTransferManager^sender, _In_ Windows::ApplicationModel::DataTransfer::DataRequestedEventArgs^args) | PostcardRenderer |
OnManipulationCompleted(_In_ Platform::Object^, _In_ Windows::UI::Xaml::Input::ManipulationCompletedRoutedEventArgs^args) | PostcardRenderer |
OnManipulationDelta(_In_ Platform::Object^, _In_ Windows::UI::Xaml::Input::ManipulationDeltaRoutedEventArgs^args) | PostcardRenderer |
OnManipulationStarted(_In_ Platform::Object^, _In_ Windows::UI::Xaml::Input::ManipulationStartedRoutedEventArgs^args) | PostcardRenderer |
OnPointerMoved(_In_ Platform::Object^, _In_ Windows::UI::Xaml::Input::PointerRoutedEventArgs^args) | PostcardRenderer |
OnPointerPressed(_In_ Platform::Object^, _In_ Windows::UI::Xaml::Input::PointerRoutedEventArgs^args) | PostcardRenderer |
OnPointerReleased(_In_ Platform::Object^, _In_ Windows::UI::Xaml::Input::PointerRoutedEventArgs^args) | PostcardRenderer |
OnTapped(_In_ Platform::Object^, _In_ Windows::UI::Xaml::Input::TappedRoutedEventArgs^args) | PostcardRenderer |
RemovePaper() | PostcardRenderer |
Render() override | PostcardRenderer | [virtual]
ResetPostcard() | PostcardRenderer |
ResetSignature() | PostcardRenderer |
SaveBitmapToStream(_In_ ID2D1Bitmap1 *d2dBitmap, _In_ IWICImagingFactory2 *wicFactory2, _In_ ID2D1DeviceContext *d2dContext, _In_ REFGUID wicFormat, _In_ IStream *stream) | PostcardRenderer | [private]
SavePostcard(Windows::Storage::Streams::IRandomAccessStream^randomAccessStream, GUID wicFormat) | PostcardRenderer |
SetEffectIntensity(float value) | PostcardRenderer |
SetExtrudedText(Platform::String^text) | PostcardRenderer |
SetSampleMode(SampleMode mode) | PostcardRenderer |
StampPaper() | PostcardRenderer |
StartSignature() | PostcardRenderer |
UpdateForViewStateChanged(Windows::UI::ViewManagement::ApplicationViewState state) | PostcardRenderer |
UpdateForWindowSizeChange() override | PostcardRenderer | [virtual]
Generated on Sat Nov 23 2024 16:09:19 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/SoundEffect.cpp Source File

  • XAML DirectX 3D shooting game

SoundEffect.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 "SoundEffect.h"
00010 #include "DirectXSample.h"
00011
00012 SoundEffect::SoundEffect():
00013     m_audioAvailable(false)
00014 {
00015 }
00016
00017 //----------------------------------------------------------------------
00018
00019 void SoundEffect::Initialize(
00020     _In_ IXAudio2 *masteringEngine,
00021     _In_ WAVEFORMATEX *sourceFormat,
00022     _In_ Platform::Array<byte>^ soundData)
00023 {
00024     m_soundData = soundData;
00025
00026     if (masteringEngine == nullptr)
00027     {
00028         // Audio is not available so just return.
00029         m_audioAvailable = false;
00030         return;
00031     }
00032
00033     // Create a source voice for this sound effect.
00034     DX::ThrowIfFailed(
00035         masteringEngine->CreateSourceVoice(
00036             &m_sourceVoice,
00037             sourceFormat
00038             )
00039         );
00040     m_audioAvailable = true;
00041 }
00042
00043 //----------------------------------------------------------------------
00044
00045 void SoundEffect::PlaySound(_In_ float volume)
00046 {
00047     XAUDIO2_BUFFER buffer = {0};
00048
00049     if (!m_audioAvailable)
00050     {
00051         // Audio is not available so just return.
00052         return;
00053     }
00054
00055     // Interrupt sound effect if it is currently playing.
00056     DX::ThrowIfFailed(
00057         m_sourceVoice->Stop()
00058         );
00059     DX::ThrowIfFailed(
00060         m_sourceVoice->FlushSourceBuffers()
00061         );
00062
00063     // Queue the memory buffer for playback and start the voice.
00064     buffer.AudioBytes = m_soundData->Length;
00065     buffer.pAudioData = m_soundData->Data;
00066     buffer.Flags = XAUDIO2_END_OF_STREAM;
00067
00068     DX::ThrowIfFailed(
00069         m_sourceVoice->SetVolume(volume)
00070         );
00071     DX::ThrowIfFailed(
00072         m_sourceVoice->SubmitSourceBuffer(&buffer)
00073         );
00074     DX::ThrowIfFailed(
00075         m_sourceVoice->Start()
00076         );
00077 }
00078
00079 //----------------------------------------------------------------------
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::Rotation::sealed Member List

This is the complete list of members for SDKSample::Rotation::sealed, including all inherited members.
ClearPreference_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Rotation::sealed | [private]
Landscape() | SDKSample::Rotation::sealed |
LandscapeFlipped() | SDKSample::Rotation::sealed |
None() | SDKSample::Rotation::sealed |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Rotation::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Rotation::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Rotation::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Rotation::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Rotation::sealed | [protected, virtual]
Portrait() | SDKSample::Rotation::sealed |
PortraitFlipped() | SDKSample::Rotation::sealed |
rootPage | SDKSample::Rotation::sealed | [private]
SetLandscape_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Rotation::sealed | [private]
SetLandscapeFlipped_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Rotation::sealed | [private]
SetPortrait_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Rotation::sealed | [private]
SetPortraitFlipped_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Rotation::sealed | [private]
Generated on Sat Nov 23 2024 16:09:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Transcoding media/C++/pch.h Source File

  • Transcoding media

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Inclinometer sensor/C++/common/suspensionmanager.h Source File

  • Inclinometer sensor
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SecondaryTiles::Scenario Member List

This is the complete list of members for SecondaryTiles::Scenario, including all inherited members.
className | SecondaryTiles::Scenario
title | SecondaryTiles::Scenario
Generated on Sat Nov 23 2024 16:09:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: AtomPub/C++/Scenario1.xaml.h Source File

  • AtomPub

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 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Navigation;
00024 using namespace Platform;
00025
00026 namespace SDKSample
00027 {
00028     namespace AtomPub
00029     {
00030         /// <summary>
00031         /// An empty page that can be used on its own or navigated to within a Frame.
00032         /// </summary>
00033       [Windows::Foundation::Metadata::WebHostHidden]
00034         public ref class Scenario1 sealed
00035         {
00036         public:
00037             Scenario1();
00038
00039         protected:
00040             virtual void OnNavigatedTo(NavigationEventArgs^ e) override;
00041             virtual void OnNavigatingFrom(NavigatingCancelEventArgs^ e) override;
00042
00043         private:
00044             MainPage^ rootPage;
00045             SyndicationItemIterator^ feedIterator;
00046
00047             void GetFeed_Click(Object^ sender, RoutedEventArgs^ e);
00048             void PreviousItem_Click(Object^ sender, RoutedEventArgs^ e);
00049             void NextItem_Click(Object^ sender, RoutedEventArgs^ e);
00050             void UserNameField_TextChanged(Object^ sender, TextChangedEventArgs^ e);
00051             void PasswordField_PasswordChanged(Object^ sender, RoutedEventArgs^ e);
00052             void DisplayItem();
00053         };
00054     }
00055 }
Generated on Sat Nov 23 2024 16:07:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media Server client/C++/App.xaml.cpp Source File

  • Media Server client

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Message dialog/C++/CustomCommand.xaml.cpp Source File

  • Message dialog

CustomCommand.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 "CustomCommand.xaml.h"
00018
00019 using namespace SDKSample::MessageDialogSample;
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 CustomCommand::CustomCommand()
00027 {
00028     InitializeComponent();
00029 }
00030
00031 void CustomCommand::OnNavigatedTo(NavigationEventArgs^ e)
00032 {
00033     rootPage = MainPage::Current;
00034 }
00035
00036 /// <summary>
00037 /// Click handler for the 'CustomCommandButton' button.
00038 /// Demonstrates the use of a message dialog with custom commands, command callbacks, and a default command.
00039 /// A message will be displayed indicating which command was invoked on the dialog.
00040 /// In this scenario, 'Install updates' is selected as the default choice.
00041 /// </summary>
00042 /// <param name="sender">The Object that caused this event to be fired.</param>
00043 /// <param name="e">State information and event data associated with the routed event.</param>
00044 void SDKSample::MessageDialogSample::CustomCommand::CustomCommandButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00045 {
00046     // Create the message dialog and set its content and title
00047     auto messageDialog = ref new MessageDialog("New updates have been found for this program. Would you like to install the new updates?", "Updates available");
00048
00049     // Add commands and set their callbacks
00050     messageDialog->Commands->Append(ref new UICommand("Don't install", ref new UICommandInvokedHandler([this](IUICommand^ command)
00051     {
00052         rootPage->NotifyUser("The 'Don't install' command has been selected.", NotifyType::StatusMessage);
00053     })));
00054     messageDialog->Commands->Append(ref new UICommand("Install updates", ref new UICommandInvokedHandler([this](IUICommand^ command)
00055     {
00056         rootPage->NotifyUser("The 'Install updates' command has been selected.", NotifyType::StatusMessage);
00057     })));
00058
00059     // Set the command that will be invoked by default
00060     messageDialog->DefaultCommandIndex = 1;
00061
00062     // Show the message dialog
00063     messageDialog->ShowAsync();
00064 }
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SphereMesh Member List

This is the complete list of members for SphereMesh, including all inherited members.
__pad0__ | SphereMesh
segments | SphereMesh
Generated on Sat Nov 23 2024 16:09:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DirectX::D3DX_BC6H Member List

This is the complete list of members for DirectX::D3DX_BC6H, including all inherited members.
AssignIndices(_In_ const EncodeParams *pEP, _In_reads_(BC6H_MAX_REGIONS) const INTEndPntPair aEndPts[], _Out_writes_(NUM_PIXELS_PER_BLOCK) size_t aIndices[], _Out_writes_(BC6H_MAX_REGIONS) float aTotErr[]) const | DirectX::D3DX_BC6H | [private]
BW enum value | DirectX::D3DX_BC6H | [private]
BX enum value | DirectX::D3DX_BC6H | [private]
BY enum value | DirectX::D3DX_BC6H | [private]
BZ enum value | DirectX::D3DX_BC6H | [private]
D enum value | DirectX::D3DX_BC6H | [private]
Decode(_In_ bool bSigned, _Out_writes_(NUM_PIXELS_PER_BLOCK) HDRColorA *pOut) const | DirectX::D3DX_BC6H |
EField enum name | DirectX::D3DX_BC6H | [private]
EmitBlock(_In_ const EncodeParams *pEP, _In_reads_(BC6H_MAX_REGIONS) const INTEndPntPair aEndPts[], _In_reads_(NUM_PIXELS_PER_BLOCK) const size_t aIndices[]) | DirectX::D3DX_BC6H | [private]
Encode(_In_ bool bSigned, _In_reads_(NUM_PIXELS_PER_BLOCK) const HDRColorA *const pIn) | DirectX::D3DX_BC6H |
EndPointsFit(_In_ const EncodeParams *pEP, _In_reads_(BC6H_MAX_REGIONS) const INTEndPntPair aEndPts[]) | DirectX::D3DX_BC6H | [private, static]
FinishUnquantize(_In_ int comp, _In_ bool bSigned) | DirectX::D3DX_BC6H | [private, static]
GeneratePaletteQuantized(_In_ const EncodeParams *pEP, _In_ const INTEndPntPair &endPts, _Out_writes_(BC6H_MAX_INDICES) INTColor aPalette[]) const | DirectX::D3DX_BC6H | [private]
GeneratePaletteUnquantized(_In_ const EncodeParams *pEP, _In_ size_t uRegion, _Out_writes_(BC6H_MAX_INDICES) INTColor aPalette[]) | DirectX::D3DX_BC6H | [private, static]
GetBit(_Inout_ size_t &uStartBit) const | DirectX::CBits< 16 > | [inline, private]
GetBits(_Inout_ size_t &uStartBit, _In_ size_t uNumBits) const | DirectX::CBits< 16 > | [inline, private]
GW enum value | DirectX::D3DX_BC6H | [private]
GX enum value | DirectX::D3DX_BC6H | [private]
GY enum value | DirectX::D3DX_BC6H | [private]
GZ enum value | DirectX::D3DX_BC6H | [private]
M enum value | DirectX::D3DX_BC6H | [private]
MapColors(_In_ const EncodeParams *pEP, _In_ size_t uRegion, _In_ size_t np, _In_reads_(np) const size_t *auIndex) const | DirectX::D3DX_BC6H | [private]
MapColorsQuantized(_In_ const EncodeParams *pEP, _In_reads_(np) const INTColor aColors[], _In_ size_t np, _In_ const INTEndPntPair &endPts) const | DirectX::D3DX_BC6H | [private]
ms_aDesc | DirectX::D3DX_BC6H | [private, static]
ms_aInfo | DirectX::D3DX_BC6H | [private, static]
ms_aModeToInfo | DirectX::D3DX_BC6H | [private, static]
NA enum value | DirectX::D3DX_BC6H | [private]
OptimizeEndPoints(_In_ const EncodeParams *pEP, _In_reads_(BC6H_MAX_REGIONS) const float aOrgErr[], _In_reads_(BC6H_MAX_REGIONS) const INTEndPntPair aOrgEndPts[], _Inout_updates_all_(BC6H_MAX_REGIONS) INTEndPntPair aOptEndPts[]) const | DirectX::D3DX_BC6H | [private]
OptimizeOne(_In_ const EncodeParams *pEP, _In_reads_(np) const INTColor aColors[], _In_ size_t np, _In_ float aOrgErr, _In_ const INTEndPntPair &aOrgEndPts, _Out_ INTEndPntPair &aOptEndPts) const | DirectX::D3DX_BC6H | [private]
PerturbOne(_In_ const EncodeParams *pEP, _In_reads_(np) const INTColor aColors[], _In_ size_t np, _In_ uint8_t ch, _In_ const INTEndPntPair &oldEndPts, _Out_ INTEndPntPair &newEndPts, _In_ float fOldErr, _In_ int do_b) const | DirectX::D3DX_BC6H | [private]
Quantize(_In_ int iValue, _In_ int prec, _In_ bool bSigned) | DirectX::D3DX_BC6H | [private, static]
QuantizeEndPts(_In_ const EncodeParams *pEP, _Out_writes_(BC6H_MAX_REGIONS) INTEndPntPair *qQntEndPts) const | DirectX::D3DX_BC6H | [private]
Refine(_Inout_ EncodeParams *pEP) | DirectX::D3DX_BC6H | [private]
RoughMSE(_Inout_ EncodeParams *pEP) const | DirectX::D3DX_BC6H | [private]
RW enum value | DirectX::D3DX_BC6H | [private]
RX enum value | DirectX::D3DX_BC6H | [private]
RY enum value | DirectX::D3DX_BC6H | [private]
RZ enum value | DirectX::D3DX_BC6H | [private]
SetBit(_Inout_ size_t &uStartBit, _In_ uint8_t uValue) | DirectX::CBits< 16 > | [inline, private]
SetBits(_Inout_ size_t &uStartBit, _In_ size_t uNumBits, _In_ uint8_t uValue) | DirectX::CBits< 16 > | [inline, private]
SwapIndices(_In_ const EncodeParams *pEP, _Inout_updates_all_(BC6H_MAX_REGIONS) INTEndPntPair aEndPts[], _In_reads_(NUM_PIXELS_PER_BLOCK) size_t aIndices[]) | DirectX::D3DX_BC6H | [private, static]
Unquantize(_In_ int comp, _In_ uint8_t uBitsPerComp, _In_ bool bSigned) | DirectX::D3DX_BC6H | [private, static]
Generated on Sat Nov 23 2024 16:09:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Sharing content source app/C++/ShareImage.xaml.h Source File

  • Sharing content source app

ShareImage.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 // ShareImage.xaml.h
00013 // Declaration of the ShareImage class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "SharePage.h"
00020 #include "ShareImage.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKSample
00024 {
00025     namespace ShareSource
00026     {
00027         [Windows::Foundation::Metadata::WebHostHidden]
00028         public ref class ShareImage sealed
00029         {
00030         public:
00031             ShareImage();
00032
00033         protected:
00034             virtual bool GetShareContent(Windows::ApplicationModel::DataTransfer::DataRequest^ request) override;
00035
00036         private:
00037             MainPage^ rootPage;
00038             Windows::Storage::StorageFile^ imageFile;
00039
00040             void SelectImageButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         };
00042     }
00043 }
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: AtomPub/C++/pch.cpp Source File

  • AtomPub

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 Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/ResourceLoading.cpp Source File

  • Direct3D resource loading

ResourceLoading.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 "ResourceLoading.h"
00010 #include "BasicShapes.h"
00011 #include "BasicLoader.h"
00012
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::Foundation;
00015 using namespace Windows::Foundation::Collections;
00016 using namespace Windows::UI::Core;
00017
00018 ResourceLoading::ResourceLoading()
00019 {
00020 }
00021
00022 void ResourceLoading::CreateDeviceIndependentResources()
00023 {
00024     DirectXBase::CreateDeviceIndependentResources();
00025
00026     m_camera = ref new BasicCamera();
00027
00028     m_controller = ref new LonLatController();
00029     m_controller->Initialize(m_window.Get());
00030     m_controller->SetPosition(float3(0.7f, 0.7f, 0.7f));
00031 }
00032
00033 void ResourceLoading::CreateDeviceResources()
00034 {
00035     DirectXBase::CreateDeviceResources();
00036
00037     // Create the SampleOverlay, which synchronously loads its required resources.
00038     m_sampleOverlay = ref new SampleOverlay();
00039
00040     m_sampleOverlay->Initialize(
00041         m_d2dDevice.Get(),
00042         m_d2dContext.Get(),
00043         m_wicFactory.Get(),
00044         m_dwriteFactory.Get(),
00045         "Direct3D resource loading sample"
00046         );
00047
00048     // This flag will keep track of whether or not all application
00049     // resources have been loaded.  Until all resources are loaded,
00050     // only the sample overlay will be drawn on the screen.
00051     m_loadingComplete = false;
00052
00053     // Create a BasicLoader, and use it to asynchronously load all
00054     // application resources.  When an output value becomes non-null,
00055     // this indicates that the asynchronous operation has completed.
00056     BasicLoader^ loader = ref new BasicLoader(m_d3dDevice.Get());
00057
00058     auto loadVertexShaderTask = loader->LoadShaderAsync(
00059         "SimpleVertexShader.cso",
00060         nullptr,
00061         0,
00062         &m_vertexShader,
00063         &m_inputLayout
00064         );
00065
00066     auto loadPixelShaderTask = loader->LoadShaderAsync(
00067         "SimplePixelShader.cso",
00068         &m_pixelShader
00069         );
00070
00071     auto loadTextureTask = loader->LoadTextureAsync(
00072         "reftexture.dds",
00073         nullptr,
00074         &m_textureSRV
00075         );
00076
00077     auto loadMeshTask = loader->LoadMeshAsync(
00078         "refmesh.vbo",
00079         &m_vertexBuffer,
00080         &m_indexBuffer,
00081         nullptr,
00082         &m_indexCount
00083         );
00084
00085     // The && operator can be used to create a single task that represents
00086     // a group of multiple tasks. The new task's completed handler will only
00087     // be called once all associated tasks have completed. In this case, the
00088     // new task represents a task to load various assets from the package.
00089     (loadVertexShaderTask && loadPixelShaderTask && loadTextureTask && loadMeshTask).then([=]()
00090     {
00091         m_loadingComplete = true;
00092     });
00093
00094     CD3D11_BUFFER_DESC constantBufferDesc(sizeof(ConstantBuffer), D3D11_BIND_CONSTANT_BUFFER);
00095     DX::ThrowIfFailed(
00096         m_d3dDevice->CreateBuffer(
00097             &constantBufferDesc,
00098             nullptr,
00099             &m_constantBuffer
00100             )
00101         );
00102
00103     CD3D11_SAMPLER_DESC samplerDesc(
00104         D3D11_FILTER_ANISOTROPIC,
00105         D3D11_TEXTURE_ADDRESS_WRAP,
00106         D3D11_TEXTURE_ADDRESS_WRAP,
00107         D3D11_TEXTURE_ADDRESS_WRAP,
00108         0.0f,
00109         m_featureLevel > D3D_FEATURE_LEVEL_9_1 ? 4 : 2,
00110         D3D11_COMPARISON_NEVER,
00111         nullptr,
00112         0,
00113         D3D11_FLOAT32_MAX
00114         );
00115     DX::ThrowIfFailed(
00116         m_d3dDevice->CreateSamplerState(
00117             &samplerDesc,
00118             &m_sampler
00119             )
00120         );
00121
00122     m_constantBufferData.model = identity();
00123 }
00124
00125 void ResourceLoading::CreateWindowSizeDependentResources()
00126 {
00127     DirectXBase::CreateWindowSizeDependentResources();
00128
00129     m_camera->SetProjectionParameters(
00130         70.0f,
00131         m_renderTargetSize.Width / m_renderTargetSize.Height,
00132         0.01f,
00133         100.0f
00134         );
00135
00136     m_camera->GetProjectionMatrix(&m_constantBufferData.projection);
00137
00138     m_sampleOverlay->UpdateForWindowSizeChange();
00139 }
00140
00141 void ResourceLoading::Update(float timeTotal, float timeDelta)
00142 {
00143     m_controller->Update();
00144
00145     m_camera->SetViewParameters(
00146         m_controller->get_Position(),
00147         m_controller->get_LookPoint(),
00148         float3(0, 1, 0)
00149         );
00150
00151     m_camera->GetViewMatrix(&m_constantBufferData.view);
00152 }
00153
00154 void ResourceLoading::Render()
00155 {
00156     m_d3dContext->OMSetRenderTargets(
00157         1,
00158         m_d3dRenderTargetView.GetAddressOf(),
00159         m_d3dDepthStencilView.Get()
00160         );
00161
00162     const float clearColor[4] = { 0.071f, 0.040f, 0.561f, 1.0f };
00163
00164     m_d3dContext->ClearRenderTargetView(
00165         m_d3dRenderTargetView.Get(),
00166         clearColor
00167         );
00168
00169     m_d3dContext->ClearDepthStencilView(
00170         m_d3dDepthStencilView.Get(),
00171         D3D11_CLEAR_DEPTH,
00172         1.0f,
00173         0
00174         );
00175
00176     // Only render objects if all required resources have been loaded.
00177     if (m_loadingComplete)
00178     {
00179         m_d3dContext->UpdateSubresource(
00180             m_constantBuffer.Get(),
00181             0,
00182             nullptr,
00183             &m_constantBufferData,
00184             0,
00185             0
00186             );
00187
00188         UINT stride = sizeof(BasicVertex);
00189         UINT offset = 0;
00190         m_d3dContext->IASetVertexBuffers(
00191             0,
00192             1,
00193             m_vertexBuffer.GetAddressOf(),
00194             &stride,
00195             &offset
00196             );
00197
00198         m_d3dContext->IASetIndexBuffer(
00199             m_indexBuffer.Get(),
00200             DXGI_FORMAT_R16_UINT,
00201             0
00202             );
00203
00204         m_d3dContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
00205
00206         m_d3dContext->IASetInputLayout(m_inputLayout.Get());
00207
00208         m_d3dContext->VSSetShader(
00209             m_vertexShader.Get(),
00210             nullptr,
00211             0
00212             );
00213
00214         m_d3dContext->VSSetConstantBuffers(
00215             0,
00216             1,
00217             m_constantBuffer.GetAddressOf()
00218             );
00219
00220         m_d3dContext->PSSetShader(
00221             m_pixelShader.Get(),
00222             nullptr,
00223             0
00224             );
00225
00226         m_d3dContext->PSSetShaderResources(
00227             0,
00228             1,
00229             m_textureSRV.GetAddressOf()
00230             );
00231
00232         m_d3dContext->PSSetSamplers(
00233             0,
00234             1,
00235             m_sampler.GetAddressOf()
00236             );
00237
00238         m_d3dContext->DrawIndexed(
00239             m_indexCount,
00240             0,
00241             0
00242             );
00243     }
00244
00245     m_sampleOverlay->Render();
00246 }
00247
00248 void ResourceLoading::SaveInternalState(_In_ IPropertySet^ state)
00249 {
00250     m_controller->SaveInternalState(state);
00251 }
00252
00253 void ResourceLoading::LoadInternalState(_In_ IPropertySet^ state)
00254 {
00255     m_controller->LoadInternalState(state);
00256 }
Generated on Sat Nov 23 2024 16:08:11 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text display/C++/Constants.h Source File

  • XAML text display

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"XAML text display sample");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX postcard app/C++/ImageRenderer.h Source File

  • DirectX postcard app

ImageRenderer.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 ref class ImageRenderer
00010 {
00011 internal:
00012     void CreateDeviceIndependentResources(Microsoft::WRL::ComPtr<IWICImagingFactory2> wicFactory);
00013     void CreateDeviceResources(Microsoft::WRL::ComPtr<ID2D1DeviceContext> d2dContext);
00014     void CreateWindowSizeDependentResources(float dpi);
00015
00016     void DrawImageAndEffects();
00017
00018     void LoadImage(Windows::Storage::Streams::IRandomAccessStream^ randomAccessStream);
00019     void SetEffectIntensity(float value);
00020     void Reset();
00021
00022 private:
00023     void UpdateImageZoom();
00024
00025     // Resources shared with PostcardRenderer.
00026     Microsoft::WRL::ComPtr<IWICImagingFactory2>             m_wicFactory;
00027     Microsoft::WRL::ComPtr<ID2D1DeviceContext>              m_d2dContext;
00028     float                                                   m_dpi;
00029
00030     // Resources specific to this renderer.
00031     Microsoft::WRL::ComPtr<ID2D1Effect>                     m_bitmapSourceEffect;
00032     D2D1_SIZE_U                                             m_imagePixelSize;
00033     D2D1_SIZE_F                                             m_imageSizeDips;
00034     float                                                   m_imageZoomFactor;
00035
00036     Microsoft::WRL::ComPtr<ID2D1Effect>                     m_saturationEffect;
00037 };
00038
Generated on Sat Nov 23 2024 16:08:15 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Message dialog/C++/Constants.cpp Source File

  • Message dialog

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     { "Use custom commands", "SDKSample.MessageDialogSample.CustomCommand" },
00020     { "Use default close command", "SDKSample.MessageDialogSample.DefaultCloseCommand" },
00021     { "Use completed callback", "SDKSample.MessageDialogSample.CompletedCallback" },
00022     { "Use cancel command", "SDKSample.MessageDialogSample.CancelCommand" }
00023 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Manipulations and gestures (C++)/C++/DirectXBase.cpp Source File

  • Input Manipulations and gestures (C++)
  • C++

DirectXBase.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 "DirectXBase.h"
00010
00011 using namespace Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::Graphics::Display;
00015 using namespace D2D1;
00016
00017 // Constructor.
00018 DirectXBase::DirectXBase() :
00019     m_windowSizeChangeInProgress(false),
00020     m_dpi(-1.0f)
00021 {
00022 }
00023
00024 // Initialize the DirectX resources required to run.
00025 void DirectXBase::Initialize(CoreWindow^ window, float dpi)
00026 {
00027     m_window = window;
00028
00029     CreateDeviceIndependentResources();
00030     CreateDeviceResources();
00031     SetDpi(dpi);
00032 }
00033
00034 // Recreate all device resources and set them back to the current state.
00035 void DirectXBase::HandleDeviceLost()
00036 {
00037     // Reset these member variables to ensure that SetDpi recreates all resources.
00038     float dpi = m_dpi;
00039     m_dpi = -1.0f;
00040     m_windowBounds.Width = 0;
00041     m_windowBounds.Height = 0;
00042     m_swapChain = nullptr;
00043
00044     CreateDeviceResources();
00045     SetDpi(dpi);
00046 }
00047
00048 // These are the resources required independent of the device.
00049 void DirectXBase::CreateDeviceIndependentResources()
00050 {
00051     D2D1_FACTORY_OPTIONS options;
00052     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00053
00054 #if defined(_DEBUG)
00055     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00056     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00057 #endif
00058
00059     DX::ThrowIfFailed(
00060         D2D1CreateFactory(
00061             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00062             __uuidof(ID2D1Factory1),
00063             &options,
00064             &m_d2dFactory
00065             )
00066         );
00067
00068     DX::ThrowIfFailed(
00069         DWriteCreateFactory(
00070             DWRITE_FACTORY_TYPE_SHARED,
00071             __uuidof(IDWriteFactory),
00072             &m_dwriteFactory
00073             )
00074         );
00075
00076     DX::ThrowIfFailed(
00077         CoCreateInstance(
00078             CLSID_WICImagingFactory,
00079             nullptr,
00080             CLSCTX_INPROC_SERVER,
00081             IID_PPV_ARGS(&m_wicFactory)
00082             )
00083         );
00084 }
00085
00086 // These are the resources that depend on the device.
00087 void DirectXBase::CreateDeviceResources()
00088 {
00089     // This flag adds support for surfaces with a different color channel ordering
00090     // than the API default. It is required for compatibility with Direct2D.
00091     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00092     ComPtr<IDXGIDevice> dxgiDevice;
00093
00094 #if defined(_DEBUG)
00095     // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00096     creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00097 #endif
00098
00099     // This array defines the set of DirectX hardware feature levels this app will support.
00100     // Note the ordering should be preserved.
00101     // Don't forget to declare your application's minimum required feature level in its
00102     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00103     D3D_FEATURE_LEVEL featureLevels[] =
00104     {
00105         D3D_FEATURE_LEVEL_11_1,
00106         D3D_FEATURE_LEVEL_11_0,
00107         D3D_FEATURE_LEVEL_10_1,
00108         D3D_FEATURE_LEVEL_10_0,
00109         D3D_FEATURE_LEVEL_9_3,
00110         D3D_FEATURE_LEVEL_9_2,
00111         D3D_FEATURE_LEVEL_9_1
00112     };
00113
00114     // Create the Direct3D 11 API device object and a corresponding context.
00115     ComPtr<ID3D11Device> device;
00116     ComPtr<ID3D11DeviceContext> context;
00117     DX::ThrowIfFailed(
00118         D3D11CreateDevice(
00119             nullptr,                    // Specify nullptr to use the default adapter.
00120             D3D_DRIVER_TYPE_HARDWARE,
00121             0,
00122             creationFlags,              // Set debug and Direct2D compatibility flags.
00123             featureLevels,              // List of feature levels this app can support.
00124             ARRAYSIZE(featureLevels),
00125             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Store apps.
00126             &device,                    // Returns the Direct3D device created.
00127             &m_featureLevel,            // Returns feature level of device created.
00128             &context                    // Returns the device immediate context.
00129             )
00130         );
00131
00132     // Get the Direct3D 11.1 API device and context interfaces.
00133     DX::ThrowIfFailed(
00134         device.As(&m_d3dDevice)
00135         );
00136
00137     DX::ThrowIfFailed(
00138         context.As(&m_d3dContext)
00139         );
00140
00141     // Get the underlying DXGI device of the Direct3D device.
00142     DX::ThrowIfFailed(
00143         m_d3dDevice.As(&dxgiDevice)
00144         );
00145
00146     // Create the Direct2D device object and a corresponding context.
00147     DX::ThrowIfFailed(
00148         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00149         );
00150
00151     DX::ThrowIfFailed(
00152         m_d2dDevice->CreateDeviceContext(
00153             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00154             &m_d2dContext
00155             )
00156         );
00157 }
00158
00159 // Helps track the DPI in the helper class.
00160 // This is called in the dpiChanged event handler in the view class.
00161 void DirectXBase::SetDpi(float dpi)
00162 {
00163     if (dpi != m_dpi)
00164     {
00165         // Save the DPI of this display in our class.
00166         m_dpi = dpi;
00167
00168         // Update Direct2D's stored DPI.
00169         m_d2dContext->SetDpi(m_dpi, m_dpi);
00170
00171         // Often a DPI change implies a window size change. In some cases Windows will issue
00172         // both a size changed event and a DPI changed event. In this case, the resulting bounds
00173         // will not change, and the window resize code will only be executed once.
00174         UpdateForWindowSizeChange();
00175     }
00176 }
00177
00178 // This routine is called in the event handler for the view SizeChanged event.
00179 void DirectXBase::UpdateForWindowSizeChange()
00180 {
00181     // Only handle window size changed if there is no pending DPI change.
00182     if (m_dpi != DisplayProperties::LogicalDpi)
00183     {
00184         return;
00185     }
00186
00187     if (m_window->Bounds.Width  != m_windowBounds.Width ||
00188         m_window->Bounds.Height != m_windowBounds.Height)
00189     {
00190         m_d2dContext->SetTarget(nullptr);
00191         m_d2dTargetBitmap = nullptr;
00192         m_d3dRenderTargetView = nullptr;
00193         m_d3dDepthStencilView = nullptr;
00194         m_windowSizeChangeInProgress = true;
00195         CreateWindowSizeDependentResources();
00196     }
00197 }
00198
00199 // Allocate all memory resources that change on a window SizeChanged event.
00200 void DirectXBase::CreateWindowSizeDependentResources()
00201 {
00202     // Store the window bounds so the next time we get a SizeChanged event we can
00203     // avoid rebuilding everything if the size is identical.
00204     m_windowBounds = m_window->Bounds;
00205
00206     if (m_swapChain != nullptr)
00207     {
00208         // If the swap chain already exists, resize it.
00209         HRESULT hr = m_swapChain->ResizeBuffers(2, 0, 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0);
00210
00211         if (hr == DXGI_ERROR_DEVICE_REMOVED)
00212         {
00213             // If the device was removed for any reason, a new device and swapchain will need to be created.
00214             HandleDeviceLost();
00215
00216             // Everything is set up now. Do not continue execution of this method.
00217             return;
00218         }
00219         else
00220         {
00221             DX::ThrowIfFailed(hr);
00222         }
00223     }
00224     else
00225     {
00226         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00227         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00228         swapChainDesc.Width = 0;                                     // Use automatic sizing.
00229         swapChainDesc.Height = 0;
00230         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;           // This is the most common swap chain format.
00231         swapChainDesc.Stereo = false;
00232         swapChainDesc.SampleDesc.Count = 1;                          // Don't use multi-sampling.
00233         swapChainDesc.SampleDesc.Quality = 0;
00234         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00235         swapChainDesc.BufferCount = 2;                               // Use double-buffering to minimize latency.
00236         swapChainDesc.Scaling = DXGI_SCALING_NONE;
00237         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Windows Store apps must use this SwapEffect.
00238         swapChainDesc.Flags = 0;
00239
00240         ComPtr<IDXGIDevice1> dxgiDevice;
00241         DX::ThrowIfFailed(
00242             m_d3dDevice.As(&dxgiDevice)
00243             );
00244
00245         ComPtr<IDXGIAdapter> dxgiAdapter;
00246         DX::ThrowIfFailed(
00247             dxgiDevice->GetAdapter(&dxgiAdapter)
00248             );
00249
00250         ComPtr<IDXGIFactory2> dxgiFactory;
00251         DX::ThrowIfFailed(
00252             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00253             );
00254
00255         CoreWindow^ window = m_window.Get();
00256         DX::ThrowIfFailed(
00257             dxgiFactory->CreateSwapChainForCoreWindow(
00258                 m_d3dDevice.Get(),
00259                 reinterpret_cast<IUnknown*>(window),
00260                 &swapChainDesc,
00261                 nullptr,
00262                 &m_swapChain
00263                 )
00264             );
00265
00266         // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
00267         // ensures that the application will only render after each VSync, minimizing power consumption.
00268         DX::ThrowIfFailed(
00269             dxgiDevice->SetMaximumFrameLatency(1)
00270             );
00271     }
00272
00273     // Create a Direct3D render target view of the swap chain back buffer.
00274     ComPtr<ID3D11Texture2D> backBuffer;
00275     DX::ThrowIfFailed(
00276         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00277         );
00278
00279     DX::ThrowIfFailed(
00280         m_d3dDevice->CreateRenderTargetView(
00281             backBuffer.Get(),
00282             nullptr,
00283             &m_d3dRenderTargetView
00284             )
00285         );
00286
00287     // Cache the rendertarget dimensions in our helper class for convenient use.
00288     D3D11_TEXTURE2D_DESC backBufferDesc = {0};
00289     backBuffer->GetDesc(&backBufferDesc);
00290     m_renderTargetSize.Width  = static_cast<float>(backBufferDesc.Width);
00291     m_renderTargetSize.Height = static_cast<float>(backBufferDesc.Height);
00292
00293     // Create a depth stencil view for use with 3D rendering if needed.
00294     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00295         DXGI_FORMAT_D24_UNORM_S8_UINT,
00296         backBufferDesc.Width,
00297         backBufferDesc.Height,
00298         1,
00299         1,
00300         D3D11_BIND_DEPTH_STENCIL
00301         );
00302
00303     ComPtr<ID3D11Texture2D> depthStencil;
00304     DX::ThrowIfFailed(
00305         m_d3dDevice->CreateTexture2D(
00306             &depthStencilDesc,
00307             nullptr,
00308             &depthStencil
00309             )
00310         );
00311
00312     auto viewDesc = CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D);
00313     DX::ThrowIfFailed(
00314         m_d3dDevice->CreateDepthStencilView(
00315             depthStencil.Get(),
00316             &viewDesc,
00317             &m_d3dDepthStencilView
00318             )
00319         );
00320
00321     // Set the 3D rendering viewport to target the entire window.
00322     CD3D11_VIEWPORT viewport(
00323         0.0f,
00324         0.0f,
00325         static_cast<float>(backBufferDesc.Width),
00326         static_cast<float>(backBufferDesc.Height)
00327         );
00328
00329     m_d3dContext->RSSetViewports(1, &viewport);
00330
00331     // Create a Direct2D target bitmap associated with the
00332     // swap chain back buffer and set it as the current target.
00333     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00334         BitmapProperties1(
00335             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00336             PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00337             m_dpi,
00338             m_dpi
00339             );
00340
00341     ComPtr<IDXGISurface> dxgiBackBuffer;
00342     DX::ThrowIfFailed(
00343         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00344         );
00345
00346     DX::ThrowIfFailed(
00347         m_d2dContext->CreateBitmapFromDxgiSurface(
00348             dxgiBackBuffer.Get(),
00349             &bitmapProperties,
00350             &m_d2dTargetBitmap
00351             )
00352         );
00353
00354     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00355
00356     // Grayscale text anti-aliasing is recommended for all Windows Store apps.
00357     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00358 }
00359
00360 // Method to deliver the final image to the display.
00361 void DirectXBase::Present()
00362 {
00363     // The application may optionally specify "dirty" or "scroll" rects to improve efficiency
00364     // in certain scenarios.  In this sample, however, we do not utilize those features.
00365     DXGI_PRESENT_PARAMETERS parameters = {0};
00366     parameters.DirtyRectsCount = 0;
00367     parameters.pDirtyRects = nullptr;
00368     parameters.pScrollRect = nullptr;
00369     parameters.pScrollOffset = nullptr;
00370
00371     // The first argument instructs DXGI to block until VSync, putting the application
00372     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00373     // frames that will never be displayed to the screen.
00374     HRESULT hr = m_swapChain->Present1(1, 0, &parameters);
00375
00376     // Discard the contents of the render target.
00377     // This is a valid operation only when the existing contents will be entirely
00378     // overwritten. If dirty or scroll rects are used, this call should be removed.
00379     m_d3dContext->DiscardView(m_d3dRenderTargetView.Get());
00380
00381     // Discard the contents of the depth stencil.
00382     m_d3dContext->DiscardView(m_d3dDepthStencilView.Get());
00383
00384     // If the device was removed either by a disconnect or a driver upgrade, we
00385     // must recreate all device resources.
00386     if (hr == DXGI_ERROR_DEVICE_REMOVED)
00387     {
00388         HandleDeviceLost();
00389     }
00390     else
00391     {
00392         DX::ThrowIfFailed(hr);
00393     }
00394
00395     if (m_windowSizeChangeInProgress)
00396     {
00397         // A window size change has been initiated and the app has just completed presenting
00398         // the first frame with the new size. Notify the resize manager so we can short
00399         // circuit any resize animation and prevent unnecessary delays.
00400         CoreWindowResizeManager::GetForCurrentView()->NotifyLayoutCompleted();
00401         m_windowSizeChangeInProgress = false;
00402     }
00403 }
00404
00405 void DirectXBase::ValidateDevice()
00406 {
00407     // The D3D Device is no longer valid if the default adapter changes or if
00408     // the device has been removed.
00409
00410     // First, get the information for the adapter related to the current device.
00411
00412     ComPtr<IDXGIDevice1> dxgiDevice;
00413     ComPtr<IDXGIAdapter> deviceAdapter;
00414     DXGI_ADAPTER_DESC deviceDesc;
00415     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00416     DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter));
00417     DX::ThrowIfFailed(deviceAdapter->GetDesc(&deviceDesc));
00418
00419     // Next, get the information for the default adapter.
00420
00421     ComPtr<IDXGIFactory2> dxgiFactory;
00422     ComPtr<IDXGIAdapter1> currentAdapter;
00423     DXGI_ADAPTER_DESC currentDesc;
00424     DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)));
00425     DX::ThrowIfFailed(dxgiFactory->EnumAdapters1(0, &currentAdapter));
00426     DX::ThrowIfFailed(currentAdapter->GetDesc(&currentDesc));
00427
00428     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00429     // a new D3D device must be created.
00430
00431     if ((deviceDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart) ||
00432         (deviceDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart) ||
00433         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00434     {
00435         // Release references to resources related to the old device.
00436         dxgiDevice = nullptr;
00437         deviceAdapter = nullptr;
00438
00439         // Create a new device and swap chain.
00440         HandleDeviceLost();
00441     }
00442 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: App settings/C++/AddSettingsScenario.xaml.h Source File

  • App settings

AddSettingsScenario.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 // AddSettingsScenario.xaml.h
00013 // Declaration of the AddSettingsScenario class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "AddSettingsScenario.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace ApplicationSettings
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 AddSettingsScenario sealed
00031         {
00032         public:
00033             AddSettingsScenario();
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             MainPage^ rootPage;
00041             void addSettingsScenarioAdd_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00042
00043             bool isEventRegistered;
00044             Windows::Foundation::EventRegistrationToken commandsRequestedEventRegistrationToken;
00045
00046             void onSettingsCommand(Windows::UI::Popups::IUICommand^ command);
00047             void onCommandsRequested(Windows::UI::ApplicationSettings::SettingsPane^ settingsPane, Windows::UI::ApplicationSettings::SettingsPaneCommandsRequestedEventArgs^ eventArgs);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File access/C++/MainPage.xaml.cpp Source File

  • File access

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:42 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File picker contracts/C++/CachedFileUpdater_Local.xaml.cpp Source File

  • File picker contracts

CachedFileUpdater_Local.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 // CachedFileUpdater_Local.xaml.cpp
00013 // Implementation of the CachedFileUpdater_Local class
00014 //
00015
00016 #include "pch.h"
00017 #include "CachedFileUpdaterPage.xaml.h"
00018 #include "CachedFileUpdater_Local.xaml.h"
00019 #include "Constants.h"
00020
00021 using namespace SDKSample::FilePickerContracts;
00022
00023 using namespace concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::Foundation;
00027 using namespace Windows::Globalization::DateTimeFormatting;
00028 using namespace Windows::Storage;
00029 using namespace Windows::Storage::Pickers::Provider;
00030 using namespace Windows::Storage::Provider;
00031 using namespace Windows::UI::Core;
00032 using namespace Windows::UI::Popups;
00033 using namespace Windows::UI::Xaml;
00034 using namespace Windows::UI::Xaml::Controls;
00035 using namespace Windows::UI::Xaml::Navigation;
00036
00037 CachedFileUpdater_Local::CachedFileUpdater_Local()
00038 {
00039     InitializeComponent();
00040     FileIsCurrentButton->Click += ref new RoutedEventHandler(this, &CachedFileUpdater_Local::FileIsCurrentButton_Click);
00041     ProvideUpdatedVersionButton->Click += ref new RoutedEventHandler(this, &CachedFileUpdater_Local::ProvideUpdatedVersionButton_Click);
00042 }
00043
00044 void CachedFileUpdater_Local::FileIsCurrentButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00045 {
00046     FileUpdateRequest^ fileUpdateRequest = CachedFileUpdaterPage::Current->fileUpdateRequest;
00047     FileUpdateRequestDeferral^ fileUpdateRequestDeferral = CachedFileUpdaterPage::Current->fileUpdateRequestDeferral;
00048
00049     OutputFileAsync(fileUpdateRequest->File);
00050
00051     fileUpdateRequest->Status = FileUpdateStatus::Complete;
00052     fileUpdateRequestDeferral->Complete();
00053
00054     UpdateUI(CachedFileUpdaterPage::Current->cachedFileUpdaterUI->UIStatus);
00055 }
00056
00057 void CachedFileUpdater_Local::ProvideUpdatedVersionButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00058 {
00059     FileUpdateRequest^ fileUpdateRequest = CachedFileUpdaterPage::Current->fileUpdateRequest;
00060     FileUpdateRequestDeferral^ fileUpdateRequestDeferral = CachedFileUpdaterPage::Current->fileUpdateRequestDeferral;
00061
00062     Windows::Globalization::Calendar^ Calendar = ref new Windows::Globalization::Calendar;
00063     create_task(FileIO::AppendTextAsync(fileUpdateRequest->File, L"\nNew content added @ " + DateTimeFormatter::LongTime->Format(Calendar->GetDateTime()))).then([=]()
00064     {
00065         OutputFileAsync(fileUpdateRequest->File);
00066
00067         fileUpdateRequest->Status = FileUpdateStatus::Complete;
00068         fileUpdateRequestDeferral->Complete();
00069
00070         UpdateUI(CachedFileUpdaterPage::Current->cachedFileUpdaterUI->UIStatus);
00071     });
00072 }
00073
00074 void CachedFileUpdater_Local::OutputFileAsync(StorageFile^ file)
00075 {
00076     create_task(FileIO::ReadTextAsync(file)).then([this, file](String^ fileContent)
00077     {
00078         OutputFileName->Text = L"Received file: " + file->Name;
00079         OutputFileContent->Text = L"File content:\n" + fileContent;
00080     });
00081 }
00082
00083 void CachedFileUpdater_Local::UpdateUI(UIStatus uiStatus)
00084 {
00085     if (uiStatus == UIStatus::Complete)
00086     {
00087         FileIsCurrentButton->IsEnabled = false;
00088         ProvideUpdatedVersionButton->IsEnabled = false;
00089     }
00090 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Geolocation/C++/Scenario1_TrackPosition.xaml.h Source File

  • Geolocation

Scenario1_TrackPosition.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_TrackPosition.xaml.h
00013 // Declaration of the Scenario1 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario1_TrackPosition.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace GeolocationCPP
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 Scenario1 sealed
00031         {
00032         public:
00033             Scenario1();
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             MainPage^ rootPage;
00041             Windows::Devices::Geolocation::Geolocator^ geolocator;
00042             Windows::Foundation::EventRegistrationToken positionToken;
00043             Windows::Foundation::EventRegistrationToken statusToken;
00044
00045             void OnPositionChanged(Windows::Devices::Geolocation::Geolocator^ sender, Windows::Devices::Geolocation::PositionChangedEventArgs^ e);
00046             void OnStatusChanged(Windows::Devices::Geolocation::Geolocator^ sender, Windows::Devices::Geolocation::StatusChangedEventArgs^ e);
00047             void StartTracking(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void StopTracking(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00049         };
00050     }
00051 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: StreamSocket/C++/Scenario2.xaml.h Source File

  • StreamSocket

Scenario2.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.xaml.h
00013 // Declaration of the Scenario2 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario2.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace StreamSocketSample
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 sealed
00029     {
00030     public:
00031         Scenario2();
00032
00033     protected:
00034         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00035     private:
00036         MainPage^ rootPage;
00037         void ConnectSocket_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038     };
00039 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML AppBar control/C++/Scenario2.xaml.h Source File

  • XAML AppBar control

Scenario2.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.xaml.h
00013 // Declaration of the Scenario2 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario2.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace AppBarControl
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 sealed
00029     {
00030     public:
00031         Scenario2();
00032
00033     protected:
00034         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00035     private:
00036         MainPage^ rootPage;
00037         void IsSticky_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038     };
00039 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Sharing content source app/C++/ShareLink.xaml.h Source File

  • Sharing content source app

ShareLink.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 // ShareLink.xaml.h
00013 // Declaration of the ShareLink class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "SharePage.h"
00020 #include "ShareLink.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKSample
00024 {
00025     namespace ShareSource
00026     {
00027         public ref class ShareLink sealed
00028         {
00029         public:
00030             ShareLink();
00031
00032         protected:
00033             virtual bool GetShareContent(Windows::ApplicationModel::DataTransfer::DataRequest^ request) override;
00034
00035         private:
00036             MainPage^ rootPage;
00037             Windows::Foundation::Uri^ ValidateAndGetUri(Platform::String^ uriString);
00038         };
00039     }
00040 }
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAudio2 audio file playback/C++/BasicSound.h Source File

  • XAudio2 audio file playback

BasicSound.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 "SampleOverlay.h"
00011 #include "XAudio2SoundPlayer.h"
00012 #include "DirectXBase.h"
00013
00014 ref class BasicSound : public DirectXBase
00015 {
00016 internal:
00017     BasicSound();
00018
00019     // Overrides from DirectXBase
00020     virtual void CreateDeviceIndependentResources() override;
00021     virtual void CreateDeviceResources() override;
00022     virtual void CreateWindowSizeDependentResources() override;
00023     virtual void Render() override;
00024
00025     void OnSuspending();
00026     void OnResuming();
00027
00028     // Additional event handler not defined in DirectXBase
00029     void OnPointerPressed(_In_ Windows::UI::Input::PointerPoint^ p);
00030
00031 private:
00032     ~BasicSound();
00033
00034     // Overlay for generic sample graphics
00035     SampleOverlay^              m_sampleOverlay;
00036
00037     // Object to maintain and play a list of sounds via XAudio2
00038     XAudio2SoundPlayer*         m_soundPlayer;
00039
00040     // Display related items
00041     float                       m_rectangleWidth;
00042     float                       m_rectangleHeight;
00043
00044     // Rectangle painting brushes
00045     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_whiteBrush;
00046     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_greenBrush;
00047
00048     // Members for drawing text messages
00049     Microsoft::WRL::ComPtr<IDWriteTextFormat>       m_dataTextFormat;
00050     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_textBrush;
00051 };
Generated on Sat Nov 23 2024 16:08:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: OrientationSensor/C++/common/LayoutAwarePage.h Source File

  • OrientationSensor
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML Popup/C++/App.xaml.cpp Source File

  • XAML Popup

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-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]
operator()(T &t) | NoOp< T > | [inline]
operator()(T &t) | NoOp< T > | [inline]
Generated on Sat Nov 23 2024 16:09:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX postcard app/C++/BasicCamera.cpp Source File

  • DirectX postcard app

BasicCamera.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 "BasicCamera.h"
00010
00011 void BasicCamera::GetViewMatrix(_Out_ float4x4 *viewMatrix)
00012 {
00013     *viewMatrix = m_view;
00014 }
00015
00016 void BasicCamera::GetProjectionMatrix(_Out_ float4x4 *projectionMatrix)
00017 {
00018     *projectionMatrix = m_projection;
00019 }
00020
00021 // this method updates the view matrix based on new position and focus coordinates
00022 void BasicCamera::SetViewParameters(
00023     _In_ float3 eyePosition,    // the position of the camera
00024     _In_ float3 lookPosition,   // the point the camera should look at
00025     _In_ float3 up              // the durection vector for up
00026     )
00027 {
00028     m_position = eyePosition;
00029     m_direction = normalize(lookPosition - eyePosition);
00030     float3 zAxis = -m_direction;
00031     float3 xAxis = normalize(cross(up, zAxis));
00032     float3 yAxis = cross(zAxis, xAxis);
00033     float xOffset = -dot(xAxis, m_position);
00034     float yOffset = -dot(yAxis, m_position);
00035     float zOffset = -dot(zAxis, m_position);
00036     m_view = float4x4(
00037         xAxis.x, xAxis.y, xAxis.z, xOffset,
00038         yAxis.x, yAxis.y, yAxis.z, yOffset,
00039         zAxis.x, zAxis.y, zAxis.z, zOffset,
00040         0.0f,    0.0f,    0.0f,    1.0f
00041         );
00042 }
00043     // this method updates the projection matrix based on new parameters
00044 void BasicCamera::SetProjectionParameters(
00045     _In_ float minimumFieldOfView,  // the minimum horizontal or vertical field of view, in degrees
00046     _In_ float aspectRatio,         // the aspect ratio of the projection (width / height)
00047     _In_ float nearPlane,           // depth to map to 0
00048     _In_ float farPlane             // depth to map to 1
00049     )
00050 {
00051     float minScale = 1.0f / tan(minimumFieldOfView * PI_F / 360.0f);
00052     float xScale = 1.0f;
00053     float yScale = 1.0f;
00054     if (aspectRatio < 1.0f)
00055     {
00056         xScale = minScale;
00057         yScale = minScale * aspectRatio;
00058     }
00059     else
00060     {
00061         xScale = minScale / aspectRatio;
00062         yScale = minScale;
00063     }
00064     float zScale = farPlane / (farPlane - nearPlane);
00065     m_projection = float4x4(
00066         xScale, 0.0f,   0.0f,    0.0f,
00067         0.0f,   yScale, 0.0f,    0.0f,
00068         0.0f,   0.0f,   -zScale, -nearPlane*zScale,
00069         0.0f,   0.0f,   -1.0f,   0.0f
00070         );
00071 }
Generated on Sat Nov 23 2024 16:08:07 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media engine native C++ video playback/C++/pch.h Source File

  • Media engine native C++ video playback

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 <windows.h>
00009 #include <roapi.h>
00010 #include <wrl.h>
00011 #include <new>
00012 #include <mfapi.h>
00013 #include <mferror.h>
00014 #include <dxgitype.h>
00015 #include <strsafe.h>
00016 #include <vector>
00017 #include <memory>
00018 #include <limits>
00019 #include <common.h>
00020
00021 #using <Windows.winmd>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: App tiles and badges/C#,C++/SendWebImageTile.xaml.h Source File

  • App tiles and badges
  • C#,C++

SendWebImageTile.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 // SendWebImageTile.xaml.h
00013 // Declaration of the SendWebImageTile class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "SendWebImageTile.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace Tiles
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 SendWebImageTile sealed
00031       {
00032       public:
00033         SendWebImageTile();
00034
00035       protected:
00036         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037       private:
00038         MainPage^ rootPage;
00039         void UpdateTileWithWebImage_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040     void UpdateTileWithWebImageWithStringManipulation_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         void ClearTile_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00042       };
00043     }
00044 }
Generated on Sat Nov 23 2024 16:07:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D composite effect modes/C++/SampleOverlay.h Source File

  • Direct2D composite effect modes

SampleOverlay.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 "DirectXSample.h"
00011
00012 // This class is responsible for initializing and rendering the title overlay visible
00013 // at the top of the DirectX SDK samples.
00014 ref class SampleOverlay
00015 {
00016 internal:
00017     SampleOverlay();
00018
00019     void Initialize(
00020         _In_ ID2D1Device*         d2dDevice,
00021         _In_ ID2D1DeviceContext*  d2dContext,
00022         _In_ IWICImagingFactory*  wicFactory,
00023         _In_ IDWriteFactory*      dwriteFactory,
00024         _In_ Platform::String^    caption
00025         );
00026
00027     void ResetDirectXResources();
00028
00029     void UpdateForWindowSizeChange();
00030
00031     void Render();
00032
00033     float GetTitleHeightInDips();
00034
00035 private:
00036
00037     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00038     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00039     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00040     Microsoft::WRL::ComPtr<IDWriteFactory>          m_dwriteFactory;
00041     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_whiteBrush;
00042     Microsoft::WRL::ComPtr<ID2D1DrawingStateBlock>  m_stateBlock;
00043
00044     Microsoft::WRL::ComPtr<IWICImagingFactory>      m_wicFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Bitmap>             m_logoBitmap;
00046     Microsoft::WRL::ComPtr<IDWriteTextLayout>       m_textLayout;
00047
00048     UINT                                            m_idIncrement;
00049     bool                                            m_drawOverlay;
00050     Platform::String^                               m_sampleName;
00051     float                                           m_padding;
00052     float                                           m_textVerticalOffset;
00053     D2D1_SIZE_F                                     m_logoSize;
00054     float                                           m_overlayWidth;
00055 };
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D HLSL fractal generator/C++/SampleOverlay.h Source File

  • Direct3D HLSL fractal generator

SampleOverlay.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 "DirectXSample.h"
00011
00012 // This class is responsible for initializing and rendering the title overlay visible
00013 // at the top of the DirectX SDK samples.
00014 ref class SampleOverlay
00015 {
00016 internal:
00017     SampleOverlay();
00018
00019     void Initialize(
00020         _In_ ID2D1Device*         d2dDevice,
00021         _In_ ID2D1DeviceContext*  d2dContext,
00022         _In_ IWICImagingFactory*  wicFactory,
00023         _In_ IDWriteFactory*      dwriteFactory,
00024         _In_ Platform::String^    caption
00025         );
00026
00027     void ResetDirectXResources();
00028
00029     void UpdateForWindowSizeChange();
00030
00031     void Render();
00032
00033     float GetTitleHeightInDips();
00034
00035 private:
00036
00037     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00038     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00039     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00040     Microsoft::WRL::ComPtr<IDWriteFactory>          m_dwriteFactory;
00041     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_whiteBrush;
00042     Microsoft::WRL::ComPtr<ID2D1DrawingStateBlock>  m_stateBlock;
00043
00044     Microsoft::WRL::ComPtr<IWICImagingFactory>      m_wicFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Bitmap>             m_logoBitmap;
00046     Microsoft::WRL::ComPtr<IDWriteTextLayout>       m_textLayout;
00047
00048     UINT                                            m_idIncrement;
00049     bool                                            m_drawOverlay;
00050     Platform::String^                               m_sampleName;
00051     float                                           m_padding;
00052     float                                           m_textVerticalOffset;
00053     D2D1_SIZE_F                                     m_logoSize;
00054     float                                           m_overlayWidth;
00055 };
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

MediaExtensionsCPP::App Member List

This is the complete list of members for MediaExtensionsCPP::App, including all inherited members.
__pad0__ | MediaExtensionsCPP::App |
OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^pArgs) override | MediaExtensionsCPP::App | [virtual]
OnSuspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^pArgs) | MediaExtensionsCPP::App | [virtual]
Generated on Sat Nov 23 2024 16:09:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML AppBar control/C++/Scenario3.xaml.h Source File

  • XAML AppBar control

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 AppBarControl
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     void ShowMe_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038   };
00039 }
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File picker contracts/C++/MainPage.xaml.h Source File

  • File picker contracts

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     [Windows::Foundation::Metadata::WebHostHidden]
00026     public ref class MainPage sealed
00027     {
00028     public:
00029         MainPage();
00030         static property Platform::String^ FEATURE_NAME
00031         {
00032             Platform::String^ get()
00033             {
00034                 return ref new Platform::String(L"File picker contracts C++ sample");
00035             }
00036         }
00037
00038         static property Platform::Array<Scenario>^ scenarios
00039         {
00040             Platform::Array<Scenario>^ get()
00041             {
00042                 return scenariosInner;
00043             }
00044         }
00045
00046     internal:
00047         property bool AutoSizeInputSectionWhenSnapped
00048         {
00049             bool get()
00050             {
00051                 return autoSizeInputSectionWhenSnapped;
00052             }
00053
00054             void set(bool value)
00055             {
00056                 autoSizeInputSectionWhenSnapped = value;
00057             }
00058         }
00059
00060         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00061        {
00062             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00063             {
00064                 return safe_cast<App^>(App::Current)->LaunchArgs;
00065             }
00066         }
00067
00068         bool EnsureUnsnapped();
00069         void ResetScenarioOutput(Windows::UI::Xaml::Controls::TextBlock^ textblock);
00070         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00071         void LoadScenario(Platform::String^ scenarioName);
00072         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00073         event Windows::Foundation::EventHandler<PageSizeChangedEventArgs^>^ PageResized;
00074
00075     private:
00076         void PopulateScenarios();
00077         void InvalidateSize();
00078         void InvalidateViewState();
00079         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081         Platform::Collections::Vector<Object^>^ ScenarioList;
00082         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00083         bool autoSizeInputSectionWhenSnapped;
00084         static Platform::Array<Scenario>^ scenariosInner;
00085
00086     protected:
00087         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00088         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00089         virtual void LoadState(Platform::Object^ navigationParameter,
00090         Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00091         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00092
00093     internal:
00094         static MainPage^ Current;
00095     };
00096 }
Generated on Sat Nov 23 2024 16:07:46 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML data binding/C++/Scenario4.xaml.h Source File

  • XAML data binding

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
00022 namespace SDKSample
00023 {
00024     namespace DataBinding
00025     {
00026         /// <summary>
00027         /// An empty page that can be used on its own or navigated to within a Frame.
00028         /// </summary>
00029         public ref class Scenario4 sealed
00030         {
00031         public:
00032             Scenario4();
00033
00034         private:
00035             MainPage^ rootPage;
00036             void Scenario4Reset(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00037
00038         };
00039     }
00040 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Compression/C++/MainPage.xaml.cpp Source File

  • Compression

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:41 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/BasicShapes.h Source File

  • Direct3D resource loading

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 Sat Nov 23 2024 16:08:10 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Toast notifications/C#,C++/ScenarioInput6.xaml.h Source File

  • Toast notifications
  • C#,C++

ScenarioInput6.xaml.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 // ScenarioInput6.xaml.h
00009 // Declaration of the ScenarioInput6 class.
00010 //
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "ScenarioInput6.g.h"
00016 #include "MainPage.xaml.h"
00017
00018 using namespace Windows::UI::Xaml;
00019
00020 namespace ToastsSampleCPP
00021 {
00022   [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class ScenarioInput6 sealed
00024     {
00025     public:
00026         ScenarioInput6();
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         ~ScenarioInput6();
00034
00035     MainPage^ rootPage;
00036         void OutputText(Platform::String^ text);
00037         void Scenario6DisplayLongToast(bool loopAudio);
00038         void Scenario6DisplayLongToastWithStringManipulation(bool loopAudio);
00039
00040         Windows::UI::Xaml::Controls::TextBlock^ outputText;
00041     };
00042 }
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D post-processing effects/C++/pch.cpp Source File

  • Direct3D post-processing effects

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D animated text/C++/DirectXSample.h Source File

  • Direct2D animated text

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
00010 // This header defines helper utilities to make DirectX APIs work with exceptions.
00011 namespace DX
00012 {
00013     inline void ThrowIfFailed(HRESULT hr)
00014     {
00015         if (FAILED(hr))
00016         {
00017             // Set a breakpoint on this line to catch DX API errors.
00018             throw Platform::Exception::CreateException(hr);
00019         }
00020     }
00021 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D stereoscopic 3D/C++/SampleOverlay.h Source File

  • Direct3D stereoscopic 3D

SampleOverlay.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 "DirectXSample.h"
00011
00012 // This class is responsible for initializing and rendering the title overlay visible
00013 // at the top of the DirectX SDK samples.
00014 ref class SampleOverlay
00015 {
00016 internal:
00017     SampleOverlay();
00018
00019     void Initialize(
00020         _In_ ID2D1Device*         d2dDevice,
00021         _In_ ID2D1DeviceContext*  d2dContext,
00022         _In_ IWICImagingFactory*  wicFactory,
00023         _In_ IDWriteFactory*      dwriteFactory,
00024         _In_ Platform::String^    caption
00025         );
00026
00027     void ResetDirectXResources();
00028
00029     void UpdateForWindowSizeChange();
00030
00031     void Render();
00032
00033     float GetTitleHeightInDips();
00034
00035 private:
00036
00037     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00038     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00039     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00040     Microsoft::WRL::ComPtr<IDWriteFactory>          m_dwriteFactory;
00041     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_whiteBrush;
00042     Microsoft::WRL::ComPtr<ID2D1DrawingStateBlock>  m_stateBlock;
00043
00044     Microsoft::WRL::ComPtr<IWICImagingFactory>      m_wicFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Bitmap>             m_logoBitmap;
00046     Microsoft::WRL::ComPtr<IDWriteTextLayout>       m_textLayout;
00047
00048     UINT                                            m_idIncrement;
00049     bool                                            m_drawOverlay;
00050     Platform::String^                               m_sampleName;
00051     float                                           m_padding;
00052     float                                           m_textVerticalOffset;
00053     D2D1_SIZE_F                                     m_logoSize;
00054     float                                           m_overlayWidth;
00055 };
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Date and time formatting/C++/MainPage.xaml.cpp Source File

  • Date and time formatting

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:41 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D tutorial/C++/Lesson5.Components/BasicMath.h Source File

  • Direct3D tutorial
  • Lesson5.Components

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 Sat Nov 23 2024 16:08:08 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Clipboard app/C++/CopyFiles.xaml.cpp Source File

  • Clipboard app

CopyFiles.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 // CopyFiles.xaml.cpp
00013 // Implementation of the CopyFiles class
00014 //
00015
00016 #include "pch.h"
00017 #include "CopyFiles.xaml.h"
00018
00019 using namespace Clipboard;
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::ViewManagement;
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::Xaml::Media::Imaging;
00034
00035 using namespace concurrency;
00036 using namespace Windows::ApplicationModel;
00037 using namespace Windows::ApplicationModel::DataTransfer;
00038 using namespace Windows::Storage::Streams;
00039 using namespace Windows::Storage;
00040 using namespace Windows::Storage::Pickers;
00041
00042 CopyFiles::CopyFiles()
00043 {
00044     InitializeComponent();
00045 }
00046
00047 void CopyFiles::OnNavigatedTo(NavigationEventArgs^ e)
00048 {
00049     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00050     // as NotifyUser()
00051     rootPage = MainPage::Current;
00052 }
00053
00054 #pragma region CopyFiles handlers
00055
00056 void CopyFiles::CopyButton_Click(Object^ sender, RoutedEventArgs^ e)
00057 {
00058     OutputText->Text = "";
00059
00060     if (rootPage->EnsureUnsnapped())
00061     {
00062         // Select a file using the filepicker.
00063         auto filePicker = ref new FileOpenPicker();
00064         filePicker->ViewMode = PickerViewMode::List;
00065         filePicker->FileTypeFilter->Append("*");
00066
00067         create_task(filePicker->PickMultipleFilesAsync()).then(
00068             [this](IVectorView<StorageFile^>^ storageFiles)
00069             {
00070                 if (storageFiles->Size > 0)
00071                 {
00072                     auto dataPackage = ref new DataPackage();
00073                     auto items = safe_cast<IVectorView<IStorageItem^>^>(storageFiles);
00074
00075                     // Add picked files to DataPackage. Creates Read Only storage items by default.
00076                     dataPackage->SetStorageItems(items);
00077
00078                     // Request a copy operation from targets that support different file operations, like File Explorer.
00079                     dataPackage->RequestedOperation = DataPackageOperation::Copy;
00080
00081                     try
00082                     {
00083                         // Set the contents in clipboard
00084                         DataTransfer::Clipboard::SetContent(dataPackage);
00085                         rootPage->NotifyUserBackgroundThread("Storage Items: Total " + storageFiles->Size + " file(s) copied to the clipboard \n", NotifyType::StatusMessage);
00086                     }
00087                     catch (Exception^ ex)
00088                     {
00089                         // Copying data to Clipboard can potentially fail - for example, if another application is holding Clipboard open
00090                         rootPage->NotifyUserBackgroundThread("Error copying storage items to clipboard: " + ex->Message + ".", NotifyType::ErrorMessage);
00091                     }
00092                 }
00093                 else
00094                 {
00095                     rootPage->NotifyUserBackgroundThread("No file was selected \n", NotifyType::ErrorMessage);
00096                 }
00097             });
00098     }
00099 }
00100
00101 void CopyFiles::PasteButton_Click(Object^ sender, RoutedEventArgs^ e)
00102 {
00103     OutputText->Text = "";
00104
00105     // Get data package from clipboard
00106     DataPackageView^ dataPackageView = DataTransfer::Clipboard::GetContent();
00107
00108     if (dataPackageView->Contains(StandardDataFormats::StorageItems))
00109     {
00110         create_task(dataPackageView->GetStorageItemsAsync()).then(
00111             [this, dataPackageView](task<IVectorView<IStorageItem^>^> itemsTask)
00112             {
00113                 IVectorView<IStorageItem^>^ storageItems;
00114                 try
00115                 {
00116                     storageItems = itemsTask.get();
00117                 }
00118                 catch (Exception^ ex)
00119                 {
00120                     rootPage->NotifyUserBackgroundThread("Failed GetStorageItemsAsync - " + ex->Message, NotifyType::ErrorMessage);
00121                 }
00122
00123                 if (storageItems != nullptr)
00124                 {
00125                     rootPage->NotifyUserBackgroundThread("Pasting " + storageItems->Size + " file(s):\n", NotifyType::StatusMessage);
00126
00127                     OutputText->Text += "Requested Operation: ";
00128
00129                     switch (dataPackageView->RequestedOperation)
00130                     {
00131                     case DataPackageOperation::Copy:
00132                         {
00133                             OutputText->Text += "Copy \n\n";
00134                         }
00135                         break;
00136
00137                     case DataPackageOperation::Link:
00138                         {
00139                             OutputText->Text += "Link \n\n";
00140                         }
00141                         break;
00142
00143                     case DataPackageOperation::Move:
00144                         {
00145                             OutputText->Text += "Move \n\n";
00146                         }
00147                         break;
00148
00149                     case DataPackageOperation::None:
00150                         {
00151                             OutputText->Text += "None \n\n";
00152                         }
00153                         break;
00154
00155                     default:
00156                         break;
00157                     }
00158
00159                     // Iterate through each element in the storageitem vector.
00160                     std::for_each(begin(storageItems), end(storageItems),
00161                         [this](IStorageItem^ item)
00162                         {
00163                             if (item->IsOfType(StorageItemTypes::File))
00164                             {
00165                                 StorageFile^ file = safe_cast<StorageFile^>(item);
00166
00167                                 // Copy the file
00168                                 create_task(file->CopyAsync(ApplicationData::Current->LocalFolder, file->Name, NameCollisionOption::ReplaceExisting)).then(
00169                                     [=](task<StorageFile^> copiedTask)
00170                                     {
00171                                         StorageFile^ copiedFile;
00172                                         try
00173                                         {
00174                                             copiedFile = copiedTask.get();
00175                                         }
00176                                         catch (Exception^ ex)
00177                                         {
00178                                             rootPage->NotifyUserBackgroundThread("Failed CopyAsync - " + ex->Message, NotifyType::ErrorMessage);
00179                                         }
00180
00181                                         if (copiedFile)
00182                                         {
00183                                             OutputText->Text += "File: " + copiedFile->Name + " was copied from " + file->Name + "\n";
00184                                         }
00185                                     });
00186                             }
00187                             else
00188                             {
00189                                 // Skipping folders for brevity sake.
00190                                 OutputText->Text += item->Path + " is a folder, skipping \n";
00191                             }
00192                         });
00193                 }
00194             });
00195     }
00196     else
00197     {
00198         rootPage->NotifyUser("StorageItems format is not available in clipboard", NotifyType::StatusMessage);
00199     }
00200 }
00201
00202 #pragma endregion
Generated on Sat Nov 23 2024 16:07:58 for Win8-Examples by doxygen 1.7.1


Win8-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.
__pad0__ | MediaReader |
GetOutputWaveFormatEx() | MediaReader |
GetOutputWaveFormatEx() | MediaReader |
LoadMedia(_In_ Platform::String^filename) | MediaReader |
LoadMedia(_In_ Platform::String^filename) | MediaReader |
m_installedLocation | MediaReader | [private]
m_installedLocationPath | MediaReader | [private]
m_waveFormat | MediaReader | [private]
Generated on Sat Nov 23 2024 16:09:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Lock screen apps/C#,C++/ScenarioInput1.xaml.h Source File

  • Lock screen apps
  • C#,C++

ScenarioInput1.xaml.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 // ScenarioInput1.xaml.h
00009 // Declaration of the ScenarioInput1 class.
00010 //
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "ScenarioInput1.g.h"
00016 #include "MainPage.xaml.h"
00017
00018 using namespace Windows::UI::Xaml;
00019
00020 namespace LockScreenAppsCPP
00021 {
00022   [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class ScenarioInput1 sealed
00024     {
00025     public:
00026         ScenarioInput1();
00027
00028     protected:
00029         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030
00031     private:
00032         void RequestLockScreenAccess_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00033         void RemoveLockScreenAccess_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00034         void QueryLockScreenAccess_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00035         ~ScenarioInput1();
00036
00037         MainPage^ rootPage;
00038     };
00039 }
Generated on Sat Nov 23 2024 16:07:59 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D magazine app/C++/Document.h Source File

  • Direct2D magazine app

Document.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 ref class Element;
00011 ref class Story;
00012 ref class Design;
00013 ref class Renderer;
00014 ref class Document;
00015
00016 class FontLoader;
00017
00018 //  This method is called from Document::LoadAsync when the document is fully loaded.
00019 delegate void DocumentLoadedCallback(_In_ Document^ document);
00020
00021 //  Compound document at the storage location. A document consists of a document XML file
00022 //  describing the document structure and content as well as all its associated resource files.
00023 //
00024 //  Each document may contain a specific set of font files whose collective presence represents
00025 //  a collection of fonts available to the document text elements.
00026 //
00027 ref class Document
00028 {
00029 internal:
00030     Document(
00031         _In_ Windows::Storage::StorageFolder^ location,
00032         _In_ Platform::String^ fileName,
00033         _In_ Renderer^ renderer
00034         );
00035
00036     concurrency::task<void> LoadAsync();
00037
00038     void Parse();
00039
00040     void GetFontCollection(_Outptr_result_maybenull_ IDWriteFontCollection** fontCollection);
00041
00042     void GetDWriteFactory(_Outptr_ IDWriteFactory** dwriteFactory);
00043
00044     inline Windows::Storage::StorageFolder^ GetLocation()
00045     {
00046         return m_location;
00047     }
00048
00049     inline Renderer^ GetRenderer()
00050     {
00051         return m_renderer;
00052     }
00053
00054     Element^ GetContentRoot();
00055
00056     D2D1_SIZE_F GetPageSize();
00057
00058     float DesignToDisplayWidth(float designWidth);
00059
00060     float DesignToDisplayHeight(float designHeight);
00061
00062     float DisplayToDesignWidth(float displayWidth);
00063
00064     float DisplayToDesignHeight(float displayHeight);
00065
00066 private:
00067     ~Document();
00068
00069     Element^ UpdateDesign();
00070
00071     // Storage location of the document
00072     Windows::Storage::StorageFolder^ m_location;
00073
00074     // Document file name
00075     Platform::String^ m_fileName;
00076
00077     // Root XML node of the document structure
00078     Windows::Data::Xml::Dom::IXmlNode^ m_rootXml;
00079
00080     // Root of the element tree
00081     Story^ m_rootElement;
00082
00083     // The design element of the element tree
00084     Design^ m_design;
00085
00086     // DirectX renderer
00087     Renderer^ m_renderer;
00088
00089     // DirectWrite factory specific to this document
00090     Microsoft::WRL::ComPtr<IDWriteFactory> m_dwriteFactory;
00091
00092     // Loader of font files accessible within this document
00093     Microsoft::WRL::ComPtr<FontLoader> m_fontLoader;
00094
00095     // Collection of all document fonts
00096     Microsoft::WRL::ComPtr<IDWriteFontCollection> m_fontCollection;
00097 };
Generated on Sat Nov 23 2024 16:08:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Calendar details and math/C++/App.xaml.cpp Source File

  • Calendar details and math

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SetRateOp Member List

This is the complete list of members for SetRateOp, including all inherited members.
CreateOp(Operation op, SourceOp **ppOp) | SourceOp | [static]
CreateOp(Operation op, SourceOp **ppOp) | SourceOp | [static]
CreateSetRateOp(BOOL fThin, float flRate, SourceOp **ppOp) | SourceOp | [static]
CreateSetRateOp(BOOL fThin, float flRate, SourceOp **ppOp) | SourceOp | [static]
CreateStartOp(IMFPresentationDescriptor *pPD, SourceOp **ppOp) | SourceOp | [static]
CreateStartOp(IMFPresentationDescriptor *pPD, SourceOp **ppOp) | SourceOp | [static]
Data() | SourceOp | [inline]
Data() | SourceOp | [inline]
GetRate() const | SetRateOp | [inline]
GetRate() const | SetRateOp | [inline]
IsThin() const | SetRateOp | [inline]
IsThin() const | SetRateOp | [inline]
m_cRef | SourceOp | [protected]
m_data | SourceOp | [protected]
m_flRate | SetRateOp | [private]
m_fThin | SetRateOp | [private]
m_op | SourceOp | [protected]
Op() const | SourceOp | [inline]
Op() const | SourceOp | [inline]
OP_END_OF_STREAM enum value | SourceOp |
OP_PAUSE enum value | SourceOp |
OP_REQUEST_DATA enum value | SourceOp |
OP_SETRATE enum value | SourceOp |
OP_START enum value | SourceOp |
OP_STOP enum value | SourceOp |
Operation enum name | SourceOp |
Operation enum name | SourceOp |
QueryInterface(REFIID iid, void **ppv) | SourceOp |
QueryInterface(REFIID iid, void **ppv) | SourceOp |
SetData(const PROPVARIANT &var) | SourceOp |
SetData(const PROPVARIANT &var) | SourceOp |
SetRateOp(BOOL fThin, float flRate) | SetRateOp |
SetRateOp(BOOL fThin, float flRate) | SetRateOp |
SourceOp(Operation op) | SourceOp |
SourceOp(Operation op) | SourceOp |
STDMETHODIMP_(ULONG) AddRef() | SourceOp |
STDMETHODIMP_(ULONG) Release() | SourceOp |
STDMETHODIMP_(ULONG) AddRef() | SourceOp |
STDMETHODIMP_(ULONG) Release() | SourceOp |
~SetRateOp() | SetRateOp |
~SetRateOp() | SetRateOp |
~SourceOp() | SourceOp | [virtual]
~SourceOp() | SourceOp | [virtual]
Generated on Sat Nov 23 2024 16:09:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Touch keyboard/C++/MainPage.xaml.cpp Source File

  • Input Touch keyboard

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:42 for Win8-Examples by doxygen 1.7.1


Win8-Examples: SimpleOrientationSensor/C++/App.xaml.h Source File

  • SimpleOrientationSensor

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

AntSystem::Node Member List

This is the complete list of members for AntSystem::Node, including all inherited members.
InputName | AntSystem::Node |
Locations | AntSystem::Node |
Names | AntSystem::Node |
Node(const std::wstring &inputName) | AntSystem::Node | [inline, explicit]
ResolvedLocation | AntSystem::Node |
ResolvedName | AntSystem::Node |
Generated on Sat Nov 23 2024 16:09:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Transcoding media/C++/App.xaml.h Source File

  • Transcoding media

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media Server client/C++/common/suspensionmanager.h Source File

  • Media Server client
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Sharing content source app/C++/Constants.h Source File

  • Sharing content source app

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get() {  return ref new Platform::String(L"Share Source C++"); }
00029         }
00030
00031         static property Platform::String^ MissingTitleError
00032         {
00033             Platform::String^ get()
00034             {
00035                 return ref new Platform::String(L"Enter a title for what you are sharing and try again.");
00036             }
00037         }
00038
00039         static property Platform::Array<Scenario>^ scenarios
00040         {
00041             Platform::Array<Scenario>^ get()
00042             {
00043                 return scenariosInner;
00044             }
00045         }
00046
00047     internal:
00048         bool EnsureUnsnapped();
00049
00050     private:
00051         static Platform::Array<Scenario>^ scenariosInner;
00052     };
00053 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML WebView control/C++/MainPage.xaml.cpp Source File

  • XAML WebView control

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File and folder thumbnail/C++/common/suspensionmanager.h Source File

  • File and folder thumbnail
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

MPEG1StreamHeader Member List

This is the complete list of members for MPEG1StreamHeader, including all inherited members.
number | MPEG1StreamHeader
sizeBound | MPEG1StreamHeader
stream_id | MPEG1StreamHeader
type | MPEG1StreamHeader
Generated on Sat Nov 23 2024 16:09:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Lock screen personalization/C++/MainPage.xaml.cpp Source File

  • Lock screen personalization

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:42 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D sprite/C++/SampleOverlay.cpp Source File

  • Direct3D sprite

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 Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::UI::ViewManagement;
00015 using namespace Windows::Graphics::Display;
00016 using namespace D2D1;
00017
00018 SampleOverlay::SampleOverlay() :
00019     m_drawOverlay(true)
00020 {
00021 }
00022
00023 void SampleOverlay::Initialize(
00024     _In_ ID2D1Device*         d2dDevice,
00025     _In_ ID2D1DeviceContext*  d2dContext,
00026     _In_ IWICImagingFactory*  wicFactory,
00027     _In_ IDWriteFactory*      dwriteFactory,
00028     _In_ Platform::String^    caption
00029     )
00030 {
00031     m_wicFactory = wicFactory;
00032     m_dwriteFactory = dwriteFactory;
00033     m_sampleName = caption;
00034     m_d2dDevice = d2dDevice;
00035     m_d2dContext = d2dContext;
00036     m_padding = 3.0f;
00037     m_textVerticalOffset = 5.0f;
00038     m_logoSize = D2D1::SizeF(0.0f, 0.0f);
00039     m_overlayWidth = 0.0f;
00040
00041     ComPtr<ID2D1Factory> factory;
00042     d2dDevice->GetFactory(&factory);
00043
00044     DX::ThrowIfFailed(
00045         factory.As(&m_d2dFactory)
00046         );
00047
00048     ResetDirectXResources();
00049 }
00050
00051 void SampleOverlay::ResetDirectXResources()
00052 {
00053     DX::ThrowIfFailed(
00054         m_d2dContext->CreateSolidColorBrush(ColorF(ColorF::White), &m_whiteBrush)
00055         );
00056
00057     ComPtr<IWICBitmapDecoder> wicBitmapDecoder;
00058     DX::ThrowIfFailed(
00059         m_wicFactory->CreateDecoderFromFilename(
00060             L"windowsbig-sdk.png",
00061             nullptr,
00062             GENERIC_READ,
00063             WICDecodeMetadataCacheOnDemand,
00064             &wicBitmapDecoder
00065             )
00066         );
00067
00068     ComPtr<IWICBitmapFrameDecode> wicBitmapFrame;
00069     DX::ThrowIfFailed(
00070         wicBitmapDecoder->GetFrame(0, &wicBitmapFrame)
00071         );
00072
00073     ComPtr<IWICFormatConverter> wicFormatConverter;
00074     DX::ThrowIfFailed(
00075         m_wicFactory->CreateFormatConverter(&wicFormatConverter)
00076         );
00077
00078     DX::ThrowIfFailed(
00079         wicFormatConverter->Initialize(
00080             wicBitmapFrame.Get(),
00081             GUID_WICPixelFormat32bppPBGRA,
00082             WICBitmapDitherTypeNone,
00083             nullptr,
00084             0.0,
00085             WICBitmapPaletteTypeCustom  // the BGRA format has no palette so this value is ignored
00086             )
00087         );
00088
00089     double dpiX = 96.0f;
00090     double dpiY = 96.0f;
00091     DX::ThrowIfFailed(
00092         wicFormatConverter->GetResolution(&dpiX, &dpiY)
00093         );
00094
00095     DX::ThrowIfFailed(
00096         m_d2dContext->CreateBitmapFromWicBitmap(
00097             wicFormatConverter.Get(),
00098             BitmapProperties(
00099                 PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00100                 static_cast<float>(dpiX),
00101                 static_cast<float>(dpiY)
00102                 ),
00103             &m_logoBitmap
00104             )
00105         );
00106
00107     m_logoSize = m_logoBitmap->GetSize();
00108
00109     ComPtr<IDWriteTextFormat> nameTextFormat;
00110     DX::ThrowIfFailed(
00111         m_dwriteFactory->CreateTextFormat(
00112             L"Segoe UI",
00113             nullptr,
00114             DWRITE_FONT_WEIGHT_LIGHT,
00115             DWRITE_FONT_STYLE_NORMAL,
00116             DWRITE_FONT_STRETCH_NORMAL,
00117             36.0f,
00118             L"en-US",
00119             &nameTextFormat
00120             )
00121         );
00122
00123     DX::ThrowIfFailed(
00124         nameTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)
00125         );
00126
00127     DX::ThrowIfFailed(
00128         nameTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)
00129         );
00130
00131     DX::ThrowIfFailed(
00132         m_dwriteFactory->CreateTextLayout(
00133             m_sampleName->Data(),
00134             m_sampleName->Length(),
00135             nameTextFormat.Get(),
00136             4096.0f,
00137             4096.0f,
00138             &m_textLayout
00139             )
00140         );
00141
00142     DWRITE_TEXT_METRICS metrics = {0};
00143     DX::ThrowIfFailed(
00144         m_textLayout->GetMetrics(&metrics)
00145         );
00146
00147     m_overlayWidth = m_padding * 3.0f + m_logoSize.width + metrics.width;
00148
00149     DX::ThrowIfFailed(
00150         m_d2dFactory->CreateDrawingStateBlock(&m_stateBlock)
00151         );
00152
00153     UpdateForWindowSizeChange();
00154 }
00155
00156 void SampleOverlay::UpdateForWindowSizeChange()
00157 {
00158     if (CoreWindow::GetForCurrentThread()->Bounds.Width < m_overlayWidth)
00159     {
00160         m_drawOverlay = false;
00161     }
00162     else
00163     {
00164         m_drawOverlay = true;
00165     }
00166 }
00167
00168 void SampleOverlay::Render()
00169 {
00170     if (m_drawOverlay)
00171     {
00172         m_d2dContext->SaveDrawingState(m_stateBlock.Get());
00173
00174         m_d2dContext->BeginDraw();
00175         m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00176         m_d2dContext->DrawBitmap(
00177             m_logoBitmap.Get(),
00178             D2D1::RectF(m_padding, 0.0f, m_logoSize.width + m_padding, m_logoSize.height)
00179             );
00180
00181         m_d2dContext->DrawTextLayout(
00182             Point2F(m_logoSize.width + 2.0f * m_padding, m_textVerticalOffset),
00183             m_textLayout.Get(),
00184             m_whiteBrush.Get()
00185             );
00186
00187         // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00188         // is lost. It will be handled during the next call to Present.
00189         HRESULT hr = m_d2dContext->EndDraw();
00190         if (hr != D2DERR_RECREATE_TARGET)
00191         {
00192             DX::ThrowIfFailed(hr);
00193         }
00194
00195         m_d2dContext->RestoreDrawingState(m_stateBlock.Get());
00196     }
00197 }
00198
00199 float SampleOverlay::GetTitleHeightInDips()
00200 {
00201     return m_logoSize.height;
00202 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::Scenario Member List

This is the complete list of members for SDKSample::Scenario, including all inherited members.
ClassName | SDKSample::Scenario
ClassName | SDKSample::Scenario
Title | SDKSample::Scenario
Title | SDKSample::Scenario
Generated on Sat Nov 23 2024 16:09:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: HomeGroup app/C++/App.xaml.h Source File

  • HomeGroup app

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Audio Session (WASAPI)/C++/Constants.cpp Source File

  • Windows Audio Session (WASAPI)
  • C++

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
00021     { "Device Enumeration", "SDKSample.WASAPIAudio.Scenario1" },
00022     { "Audio Rendering with Hardware Offload", "SDKSample.WASAPIAudio.Scenario2" },
00023     { "PCM Audio Capture", "SDKSample.WASAPIAudio.Scenario3" }
00024 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

LockScreenAppsCPP::sealed Member List

This is the complete list of members for LockScreenAppsCPP::sealed, including all inherited members.
_displayHandlerToken | LockScreenAppsCPP::sealed | [private]
_inputFrame | LockScreenAppsCPP::sealed | [private]
_inputFrameLoadedToken | LockScreenAppsCPP::sealed | [private]
_logicalDpiChangedToken | LockScreenAppsCPP::sealed | [private]
_outputFrame | LockScreenAppsCPP::sealed | [private]
_outputFrameLoadedToken | LockScreenAppsCPP::sealed | [private]
_pageLoadedHandlerToken | LockScreenAppsCPP::sealed | [private]
_resizeHandlerToken | LockScreenAppsCPP::sealed | [private]
_scenariosFrame | LockScreenAppsCPP::sealed | [private]
App() | LockScreenAppsCPP::sealed |
CheckResolutionAndViewState() | LockScreenAppsCPP::sealed | [private]
ClearBadge_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | LockScreenAppsCPP::sealed | [private]
ClearTile_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | LockScreenAppsCPP::sealed | [private]
ConvertResolution(Windows::Graphics::Display::ResolutionScale scale) | LockScreenAppsCPP::sealed |
ConvertViewState(Windows::UI::ViewManagement::ApplicationViewState state) | LockScreenAppsCPP::sealed |
CreateBadgeAndTextTile_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | LockScreenAppsCPP::sealed | [private]
CreateBadgeTile_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | LockScreenAppsCPP::sealed | [private]
DisplayProperties_LogicalDpiChanged(Object^sender) | LockScreenAppsCPP::sealed | [private]
DoNavigation(Windows::UI::Xaml::Interop::TypeName inPageType, Windows::UI::Xaml::Controls::Frame^inFrame, Windows::UI::Xaml::Interop::TypeName outPageType, Windows::UI::Xaml::Controls::Frame^outFrame) | LockScreenAppsCPP::sealed |
Footer_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | LockScreenAppsCPP::sealed | [private]
GetElementRect(Windows::UI::Xaml::FrameworkElement^element) | LockScreenAppsCPP::sealed | [private]
inputFrameNavigated(Object^sender, Windows::UI::Xaml::Navigation::NavigationEventArgs^e) | LockScreenAppsCPP::sealed | [private]
MainPage() | LockScreenAppsCPP::sealed |
NotifyUser(Platform::String^strMessage, NotifyType type) | LockScreenAppsCPP::sealed |
OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^pArgs) override | LockScreenAppsCPP::sealed | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | LockScreenAppsCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | LockScreenAppsCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | LockScreenAppsCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | LockScreenAppsCPP::sealed | [protected, virtual]
OnSuspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^pArgs) | LockScreenAppsCPP::sealed | [virtual]
OutputFrameLoaded | LockScreenAppsCPP::sealed |
outputFrameNavigated(Object^sender, Windows::UI::Xaml::Navigation::NavigationEventArgs^e) | LockScreenAppsCPP::sealed | [private]
Page_Loaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | LockScreenAppsCPP::sealed | [private]
Page_SizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | LockScreenAppsCPP::sealed | [private]
QueryLockScreenAccess_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | LockScreenAppsCPP::sealed | [private]
RemoveLockScreenAccess_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | LockScreenAppsCPP::sealed | [private]
RequestLockScreenAccess_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | LockScreenAppsCPP::sealed | [private]
rootPage | LockScreenAppsCPP::sealed | [private]
ScenarioInput1() | LockScreenAppsCPP::sealed |
ScenarioInput2() | LockScreenAppsCPP::sealed |
ScenarioInput3() | LockScreenAppsCPP::sealed |
ScenarioList() | LockScreenAppsCPP::sealed |
ScenarioOutput1() | LockScreenAppsCPP::sealed |
ScenarioOutput2() | LockScreenAppsCPP::sealed |
ScenarioOutput3() | LockScreenAppsCPP::sealed |
Scenarios_SelectionChanged(Object^sender, SelectionChangedEventArgs^e) | LockScreenAppsCPP::sealed | [protected]
SendBadge_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | LockScreenAppsCPP::sealed | [private]
SendBadgeWithStringManipulation_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | LockScreenAppsCPP::sealed | [private]
SendTile_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | LockScreenAppsCPP::sealed | [private]
SendTileWithStringManipulation_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | LockScreenAppsCPP::sealed | [private]
SetFeatureName(Platform::String^strFeature) | LockScreenAppsCPP::sealed | [private]
~MainPage() | LockScreenAppsCPP::sealed | [private]
~ScenarioInput1() | LockScreenAppsCPP::sealed | [private]
~ScenarioInput2() | LockScreenAppsCPP::sealed | [private]
~ScenarioInput3() | LockScreenAppsCPP::sealed | [private]
~ScenarioList() | LockScreenAppsCPP::sealed | [private]
~ScenarioOutput1() | LockScreenAppsCPP::sealed | [private]
~ScenarioOutput2() | LockScreenAppsCPP::sealed | [private]
~ScenarioOutput3() | LockScreenAppsCPP::sealed | [private]
Generated on Sat Nov 23 2024 16:09:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XInput audio controller playback/C++/BasicTimer.h Source File

  • XInput audio controller playback

BasicTimer.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 timer class used to drive the render loop of the actively-animated
00011 // DirectX SDK samples. Uses the QueryPerformanceCounter function to retrieve
00012 // high-resolution timing information.
00013 ref class BasicTimer
00014 {
00015 private:
00016     LARGE_INTEGER m_frequency;
00017     LARGE_INTEGER m_currentTime;
00018     LARGE_INTEGER m_startTime;
00019     LARGE_INTEGER m_lastTime;
00020     float m_total;
00021     float m_delta;
00022
00023 internal:
00024     BasicTimer();
00025     void Reset();
00026     void Update();
00027     property float Total
00028     {
00029         float get();
00030     }
00031     property float Delta
00032     {
00033         float get();
00034     }
00035 };
Generated on Sat Nov 23 2024 16:08:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/App.xaml.h Source File

  • Hilo C++
  • Hilo

App.xaml.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 // App.xaml.h
00009 // Declaration of the App class
00010 //
00011
00012 #pragma once
00013
00014 #include "App.g.h"
00015 #include "HiloPage.h"
00016 #include "ViewModelLocator.h"  // Required by generated header
00017 #include "DesignTimeData.h" // Required by generated header
00018
00019 namespace Hilo
00020 {
00021     // See http://go.microsoft.com/fwlink/?LinkId=267274 for info about this app.
00022
00023     class ExceptionPolicy;
00024     class TileUpdateScheduler;
00025     class Repository;
00026
00027     /// <summary>
00028     /// Provides application-specific behavior to supplement the default Application class.
00029     /// </summary>
00030     ref class App sealed
00031     {
00032     public:
00033         App();
00034         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ args) override;
00035
00036     internal:
00037         std::shared_ptr<Repository> GetRepository() { return m_repository; }
00038
00039     private:
00040         void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ e);
00041         void App::OnResume(Object^ sender, Platform::Object^ e);
00042         std::shared_ptr<ExceptionPolicy> m_exceptionPolicy;
00043         std::shared_ptr<TileUpdateScheduler> m_tileUpdateScheduler;
00044         std::shared_ptr<Repository> m_repository;
00045     };
00046 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SourceOp Member List

This is the complete list of members for SourceOp, including all inherited members.
CreateOp(Operation op, SourceOp **ppOp) | SourceOp | [static]
CreateOp(Operation op, SourceOp **ppOp) | SourceOp | [static]
CreateSetRateOp(BOOL fThin, float flRate, SourceOp **ppOp) | SourceOp | [static]
CreateSetRateOp(BOOL fThin, float flRate, SourceOp **ppOp) | SourceOp | [static]
CreateStartOp(IMFPresentationDescriptor *pPD, SourceOp **ppOp) | SourceOp | [static]
CreateStartOp(IMFPresentationDescriptor *pPD, SourceOp **ppOp) | SourceOp | [static]
Data() | SourceOp | [inline]
Data() | SourceOp | [inline]
m_cRef | SourceOp | [protected]
m_data | SourceOp | [protected]
m_op | SourceOp | [protected]
Op() const | SourceOp | [inline]
Op() const | SourceOp | [inline]
OP_END_OF_STREAM enum value | SourceOp |
OP_PAUSE enum value | SourceOp |
OP_REQUEST_DATA enum value | SourceOp |
OP_SETRATE enum value | SourceOp |
OP_START enum value | SourceOp |
OP_STOP enum value | SourceOp |
Operation enum name | SourceOp |
Operation enum name | SourceOp |
QueryInterface(REFIID iid, void **ppv) | SourceOp |
QueryInterface(REFIID iid, void **ppv) | SourceOp |
SetData(const PROPVARIANT &var) | SourceOp |
SetData(const PROPVARIANT &var) | SourceOp |
SourceOp(Operation op) | SourceOp |
SourceOp(Operation op) | SourceOp |
STDMETHODIMP_(ULONG) AddRef() | SourceOp |
STDMETHODIMP_(ULONG) Release() | SourceOp |
STDMETHODIMP_(ULONG) AddRef() | SourceOp |
STDMETHODIMP_(ULONG) Release() | SourceOp |
~SourceOp() | SourceOp | [virtual]
~SourceOp() | SourceOp | [virtual]
Generated on Sat Nov 23 2024 16:09:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Toast notifications/C#,C++/ScenarioList.xaml.h Source File

  • Toast notifications
  • C#,C++

ScenarioList.xaml.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 //
00009 // ScenarioList.xaml.h
00010 // Declaration of the ScenarioList class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioList.g.h"
00017 #include "MainPage.g.h"
00018
00019 using namespace Windows::UI::Xaml::Controls;
00020 using namespace CppSamplesUtils;
00021
00022 namespace ToastsSampleCPP
00023 {
00024   [Windows::Foundation::Metadata::WebHostHidden]
00025     public ref class ScenarioList sealed
00026     {
00027     public:
00028         ScenarioList();
00029
00030     protected:
00031         void Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e);
00032         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00033
00034     private:
00035         ~ScenarioList();
00036
00037     MainPage^ rootPage;
00038     };
00039 }
Generated on Sat Nov 23 2024 16:07:58 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Custom driver access/C++,JavaScript/DLL/repeater.h Source File

  • Custom driver access
  • C++,JavaScript
  • DLL

repeater.h

Go to the documentation of this file.
00001 #include <strsafe.h>
00002 #include <assert.h>
00003
00004 #include <functional>
00005 #include <mutex>
00006
00007 #include <ppltasks.h>
00008
00009 #pragma once
00010
00011 namespace Samples {
00012     namespace Devices {
00013
00014         // Implementation details
00015         namespace Details {
00016             // The type of task the StartTaskFunction() returns.  The bool indicates whether the next
00017             // iteration should start.
00018             typedef concurrency::task<bool> RepeaterTaskType;
00019
00020             // The type of function the creator provides to run each iteration.  It returns a task
00021             // which the repeater chains onto.
00022             typedef std::function<RepeaterTaskType (concurrency::cancellation_token, concurrency::task_continuation_context)> StartRepeaterTaskFunction;
00023
00024             // The type of the function the creator calls once the repeater is stopped.
00025             typedef std::function<void(void)> RepeaterStoppedFunction;
00026         }
00027
00028         // The repeater class performs a task over and over again.  It can be used
00029         // to issue a device I/O repeatedly - for example reading events from the
00030         // device.
00031         class Repeater {
00032         public:
00033
00034             // The state of the repeater.  It is initialized in the stopped state.
00035             enum class RepeaterState {
00036                 Stopped,
00037                 Running,
00038                 Stopping
00039             };
00040
00041         private:
00042             // The function to call when starting each iteration of the repeater
00043             Details::StartRepeaterTaskFunction m_StartTaskFunction;
00044
00045             // The source of cancellation tokens passed to the start task function
00046             concurrency::cancellation_token_source m_Canceller;
00047
00048             // Whether the repeater is active, stopping or stopped.
00049             RepeaterState m_State;
00050
00051             // Lock to protect the state.  The task chains are created under this
00052             // lock, but they execute without the lock.
00053             std::mutex m_Lock;
00054
00055             // shorthand for our mutex's lock type (mlt)
00056             typedef std::unique_lock<std::mutex> mlt;
00057
00058             // An optional function to call once the repeater is stopped
00059             // TODO: should Stop return a task that the caller can .then?
00060             Details::RepeaterStoppedFunction m_RepeaterStoppedFunction;
00061
00062         public:
00063             Repeater() : m_StartTaskFunction(nullptr),
00064                          m_State(RepeaterState::Stopped),
00065                          m_RepeaterStoppedFunction(nullptr)
00066             {
00067                 return;
00068             }
00069
00070             ~Repeater()
00071             {
00072                 // TODO: Move the core of the repeater to an allocated
00073                 //       object that i can let run down on its own on destruction.  For now
00074                 //       !! don't delete a repeater that's still running !!
00075                 assert(m_State == RepeaterState::Stopped);
00076             }
00077
00078             // Starts the repeater.  Each iteration calls StartTaskFunction to kick off a chain of tasks.
00079             // The repeater then adds a task to the end of the chain that fires off the next iteration
00080             // Caller can provide a context that plumbs through to the start functions, or use current
00081             void Start(
00082                 Details::StartRepeaterTaskFunction StartTaskFunction,
00083                 concurrency::task_continuation_context Context = concurrency::task_continuation_context::use_current()
00084                 )
00085             {
00086                 // lock the mutex
00087                 mlt lock(m_Lock);
00088
00089                 assert(m_State == RepeaterState::Stopped);
00090
00091                 if (m_State == RepeaterState::Stopped) {
00092                     m_StartTaskFunction = StartTaskFunction;
00093                     m_RepeaterStoppedFunction = nullptr;
00094
00095                     // Get a new canceller before we start the tasks
00096                     auto c = concurrency::cancellation_token_source();
00097                     m_Canceller = std::move(c);
00098
00099                     // Update task state before starting the task so that it can
00100                     // restart itself properly.
00101                     m_State = RepeaterState::Running;
00102                     StartTask(Context);
00103                 }
00104             }
00105
00106             // Stop the repeater.  This will cancel the current task (caller's task
00107             // needs to have registered for cancellation).  Caller can optionally provide a
00108             // callback that the last task will invoke.
00109             bool Stop(Details::RepeaterStoppedFunction* callback = nullptr)
00110             {
00111                 mlt lock(m_Lock);
00112                 bool active;
00113
00114                 if (m_State == RepeaterState::Running) {
00115                     m_State = RepeaterState::Stopping;
00116                     m_Canceller.cancel();
00117
00118                     active = true;
00119                 } else if (m_State == RepeaterState::Stopping) {
00120                     active = true;
00121                 } else {
00122                     active = false;
00123                 }
00124
00125                 if (callback) {
00126                     if (active == true) {
00127                         m_RepeaterStoppedFunction = *callback;
00128                         lock.release();
00129                     }
00130                 }
00131
00132                 return active;
00133             }
00134
00135             // The current state of the repeater.
00136             RepeaterState GetState(void)
00137             {
00138                 return m_State;
00139             }
00140
00141         private:
00142
00143             // Creates the task chain, and appends the restart task to it
00144             void StartTask(concurrency::task_continuation_context context) {
00145                 // start the caller's task and add a restart task onto
00146                 // the end.
00147                 m_StartTaskFunction(m_Canceller.get_token(), context).
00148                     then([this, context](bool b) {
00149                         RestartTask(context, b);
00150                     }
00151                 );
00152             }
00153
00154             // The restart task mentioned above.  If the repeater is still running &
00155             // the previous iteration didn't return false, it calls StartTask() to
00156             // fire off the next iteration.  Otherwise it handles rundown.
00157             void RestartTask(concurrency::task_continuation_context context, bool Continue) {
00158                 // Check and see if the task is still running
00159                 mlt lock(m_Lock);
00160
00161                 if (Continue == false) {
00162                     m_State = RepeaterState::Stopping;
00163                 }
00164                 if (m_State == RepeaterState::Running) {
00165                     StartTask(context);
00166                 } else if (m_State == RepeaterState::Stopping) {
00167                     m_State = RepeaterState::Stopped;
00168                     if (m_RepeaterStoppedFunction != nullptr) {
00169                         Details::RepeaterStoppedFunction callback = m_RepeaterStoppedFunction;
00170                         m_RepeaterStoppedFunction = nullptr;
00171                         lock.release();
00172                         callback();
00173                     }
00174                 }
00175             }
00176         };
00177
00178
00179     }
00180 }
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/ProductItem.cpp Source File

  • XAML DirectX 3D shooting game

ProductItem.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 "ProductItem.h"
00010
00011 using namespace Simple3DGameXaml;
00012 using namespace Platform;
00013 using namespace Windows::Foundation;
00014 using namespace Windows::UI::Xaml;
00015 using namespace Windows::UI::Xaml::Interop;
00016 using namespace Windows::UI::Xaml::Data;
00017 using namespace Windows::ApplicationModel::Store;
00018
00019 ProductItem::ProductItem(
00020     ListingInformation^ listing,
00021     LicenseInformation^ license,
00022     Platform::String^ productId,
00023     bool isApp
00024     )
00025 {
00026     m_isApp = isApp;
00027     m_isAppActive = license->IsActive;
00028     m_isAppTrial = license->IsTrial;
00029     m_productId = productId;
00030
00031     if (m_isApp)
00032     {
00033         SetStatus(license);
00034         if (listing != nullptr)
00035         {
00036             m_title = listing->Name;
00037             m_formattedPrice = listing->FormattedPrice;
00038         }
00039         else
00040         {
00041             m_title = productId;
00042             m_formattedPrice = "";
00043         }
00044     }
00045     else
00046     {
00047         if (listing != nullptr)
00048         {
00049             ProductListing^ productListing = listing->ProductListings->Lookup(m_productId);
00050             m_title = productListing->Name;
00051             m_formattedPrice = productListing->FormattedPrice;
00052         }
00053         else
00054         {
00055             m_title = m_productId;
00056             m_formattedPrice = "";
00057         }
00058         SetStatus(license);
00059     }
00060 }
00061
00062 void ProductItem::SetStatus(LicenseInformation^ license)
00063 {
00064     if (m_isApp)
00065     {
00066         if (m_isAppActive)
00067         {
00068             if (m_isAppTrial)
00069             {
00070                 m_isAvailableForPurchase = true;
00071                 m_foreground = "#a0a0a0";
00072                 m_status = "Trial";
00073             }
00074             else
00075             {
00076                 m_isAvailableForPurchase = false;
00077                 m_foreground = "#707070";
00078                 m_status = "Purchased";
00079             }
00080         }
00081         else
00082         {
00083             m_isAvailableForPurchase = true;
00084             m_foreground = "#a0a0a0";
00085             m_status = "No License";
00086         }
00087     }
00088     else
00089     {
00090         if (m_isAppActive)
00091         {
00092             if (m_isAppTrial)
00093             {
00094                 m_isProductActive = false;
00095                 m_isAvailableForPurchase = false;
00096                 m_foreground = "#707070";
00097                 m_status = "unavailable";
00098             }
00099             else
00100             {
00101                 ProductLicense^ productLicense = license->ProductLicenses->Lookup(m_productId);
00102
00103                 m_isProductActive = productLicense->IsActive;
00104                 m_isAvailableForPurchase = !m_isProductActive;
00105                 if (m_isProductActive)
00106                 {
00107                     m_status = "Purchased";
00108                     m_foreground = "#707070";
00109                 }
00110                 else
00111                 {
00112                     m_status = "No License";
00113                     m_foreground = "#a0a0a0";
00114                 }
00115             }
00116         }
00117         else
00118         {
00119             m_isProductActive = false;
00120             m_isAvailableForPurchase = false;
00121             m_foreground = "#707070";
00122         }
00123     }
00124 }
00125
00126 void ProductItem::UpdateContent(LicenseInformation^ license)
00127 {
00128     if (m_isAppActive != license->IsActive ||
00129         m_isAppTrial != license->IsTrial)
00130     {
00131         m_isAppActive = license->IsActive;
00132         m_isAppTrial = license->IsTrial;
00133         SetStatus(license);
00134         PropertyChanged(this, ref new PropertyChangedEventArgs("Status"));
00135         PropertyChanged(this, ref new PropertyChangedEventArgs("BuyVisibility"));
00136         PropertyChanged(this, ref new PropertyChangedEventArgs("Foreground"));
00137     }
00138     else if (!m_isApp && m_isAppActive && !m_isAppTrial)
00139     {
00140         if (license->ProductLicenses->Lookup(m_productId)->IsActive != m_isProductActive)
00141         {
00142             SetStatus(license);
00143             PropertyChanged(this, ref new PropertyChangedEventArgs("Status"));
00144             PropertyChanged(this, ref new PropertyChangedEventArgs("BuyVisibility"));
00145             PropertyChanged(this, ref new PropertyChangedEventArgs("Foreground"));
00146         }
00147     }
00148 }
00149
00150 void ProductItem::UpdateContent(ListingInformation^ listing)
00151 {
00152     if (m_isApp)
00153     {
00154         if (m_title != listing->Name)
00155         {
00156             m_title = listing->Name;
00157             PropertyChanged(this, ref new PropertyChangedEventArgs("Title"));
00158         }
00159         if (m_formattedPrice != listing->FormattedPrice)
00160         {
00161             m_formattedPrice = listing->FormattedPrice;
00162             PropertyChanged(this, ref new PropertyChangedEventArgs("Price"));
00163         }
00164     }
00165     else
00166     {
00167         ProductListing^ productListing = listing->ProductListings->Lookup(m_productId);
00168         if (m_title != productListing->Name)
00169         {
00170             m_title = productListing->Name;
00171             PropertyChanged(this, ref new PropertyChangedEventArgs("Title"));
00172         }
00173         if (m_formattedPrice != productListing->FormattedPrice)
00174         {
00175             m_formattedPrice = productListing->FormattedPrice;
00176             PropertyChanged(this, ref new PropertyChangedEventArgs("Price"));
00177         }
00178     }
00179 }
Generated on Sat Nov 23 2024 16:08:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Lock screen apps/C#,C++/ScenarioOutput1.xaml.h Source File

  • Lock screen apps
  • C#,C++

ScenarioOutput1.xaml.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 //
00009 // Scenario1Output.xaml.h
00010 // Declaration of the Scenario1Output class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioOutput1.g.h"
00017 #include "MainPage.xaml.h"
00018
00019 namespace LockScreenAppsCPP
00020 {
00021     public ref class ScenarioOutput1 sealed
00022     {
00023     public:
00024         ScenarioOutput1();
00025
00026   private:
00027         ~ScenarioOutput1();
00028     };
00029 }
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Secondary tiles/C#,C++/EnumerateTiles.xaml.cpp Source File

  • Secondary tiles
  • C#,C++

EnumerateTiles.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 // EnumerateTiles.xaml.cpp
00013 // Implementation of the EnumerateTiles class
00014 //
00015
00016 #include "pch.h"
00017 #include "EnumerateTiles.xaml.h"
00018
00019 using namespace SecondaryTiles;
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::UI::StartScreen;
00025 using namespace Platform;
00026 using namespace concurrency;
00027 using namespace Windows::Foundation::Collections;
00028
00029 EnumerateTiles::EnumerateTiles()
00030 {
00031     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 void EnumerateTiles::OnNavigatedTo(NavigationEventArgs^ e)
00040 {
00041     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00042     // as NotifyUser()
00043     rootPage = MainPage::current;
00044     // Preserve the app bar
00045     appBar = rootPage->BottomAppBar;
00046     // Now null it so we don't show the appbar in this scenario
00047     rootPage->BottomAppBar = nullptr;
00048 }
00049
00050 /// <summary>
00051 /// Invoked when this page is about to be navigated out 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 void EnumerateTiles::OnNavigatingFrom(NavigatingCancelEventArgs^ e)
00056 {
00057     // Restore the app bar
00058     rootPage->BottomAppBar = appBar;
00059 }
00060
00061 void SecondaryTiles::EnumerateTiles::EnumerateSecondaryTiles_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00062 {
00063     Button^ button = safe_cast<Button^>(sender);
00064     if (button != nullptr)
00065     {
00066         create_task(SecondaryTile::FindAllAsync("SecondaryTiles.App")).then([this](IVectorView<SecondaryTile^>^ tileList)
00067         {
00068             if (tileList->Size > 0)
00069             {
00070                 Platform::String^ outputText;
00071                 std::for_each(begin(tileList), end(tileList), [this, &outputText](SecondaryTile^ tile)
00072                 {
00073                     outputText += "Tile Id: " + tile->TileId + ", Tile short display name: " + tile->ShortName + "\n";
00074                 });
00075                 rootPage->NotifyUser(outputText, NotifyType::StatusMessage);
00076             }
00077             else
00078             {
00079                 rootPage->NotifyUser("No secondary tiles are available for this appId.", NotifyType::ErrorMessage);
00080             }
00081         });
00082     }
00083 }
Generated on Sat Nov 23 2024 16:08:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

PageRoll Member List

This is the complete list of members for PageRoll, including all inherited members.
__pad0__ | PageRoll |
AcceptChildNode(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^childXmlNode) | Element | [virtual]
AddChild(_In_ Element^element) | Element |
AddSibling(_In_ Element^element) | Element |
BindResource(_In_ Element^rootElement) | Element | [virtual]
Create(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^xmlNode) | Element | [static]
Draw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
GetFirstChild() | Element | [inline]
GetName() | Element | [inline]
GetNextSibling() | Element | [inline]
GetOpacity() | Element | [inline, virtual]
GetParent() | Element | [inline]
GetSize() | Element | [inline]
Initialize(_In_ Document^document, _In_ Windows::Data::Xml::Dom::XmlElement^xmlElement) | Element | [virtual]
Measure(_In_ Document^document, D2D1_SIZE_F const &parentSize, _Out_ D2D1_RECT_F *bounds) override | PageRoll | [virtual]
override | PageRoll |
PrepareToDraw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
ReleaseParent() | Element | [virtual]
Generated on Sat Nov 23 2024 16:09:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Network information/C++/common/LayoutAwarePage.cpp Source File

  • Network information
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:32 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAudio2 audio file playback/C++/DirectXApp.h Source File

  • XAudio2 audio file playback

DirectXApp.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 "BasicSound.h"
00011
00012 ref class DirectXApp : public Windows::ApplicationModel::Core::IFrameworkView
00013 {
00014 internal:
00015     DirectXApp();
00016
00017 public:
00018     // IFrameworkView Methods
00019     virtual void Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00020     virtual void SetWindow(_In_ Windows::UI::Core::CoreWindow^ window);
00021     virtual void Load(_In_ Platform::String^ entryPoint);
00022     virtual void Run();
00023     virtual void Uninitialize();
00024
00025 private:
00026     // Event Handlers
00027     void OnWindowSizeChanged(
00028         _In_ Windows::UI::Core::CoreWindow^ sender,
00029         _In_ Windows::UI::Core::WindowSizeChangedEventArgs^ args
00030         );
00031
00032     void OnVisibilityChanged(
00033         _In_ Windows::UI::Core::CoreWindow^ sender,
00034         _In_ Windows::UI::Core::VisibilityChangedEventArgs^ args
00035         );
00036
00037     void OnLogicalDpiChanged(
00038         _In_ Platform::Object^ sender
00039         );
00040
00041     void OnActivated(
00042         _In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView,
00043         _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^ args
00044         );
00045
00046     void OnSuspending(
00047         _In_ Platform::Object^ sender,
00048         _In_ Windows::ApplicationModel::SuspendingEventArgs^ args
00049         );
00050
00051     void OnResuming(
00052         _In_ Platform::Object^ sender,
00053         _In_ Platform::Object^ args
00054         );
00055
00056     void OnWindowClosed(
00057         _In_ Windows::UI::Core::CoreWindow^ sender,
00058         _In_ Windows::UI::Core::CoreWindowEventArgs^ args
00059         );
00060
00061     void OnPointerPressed(
00062         _In_ Windows::UI::Core::CoreWindow^ sender,
00063         _In_ Windows::UI::Core::PointerEventArgs^ args
00064         );
00065
00066     BasicSound^ m_renderer;
00067     bool m_windowClosed;
00068     bool m_windowVisible;
00069 };
00070
00071 ref class DirectXAppSource : Windows::ApplicationModel::Core::IFrameworkViewSource
00072 {
00073 public:
00074     virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00075 };
Generated on Sat Nov 23 2024 16:08:07 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Audio Session (WASAPI)/C++/DeviceState.h Source File

  • Windows Audio Session (WASAPI)
  • C++

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             DeviceStateDiscontinutity,
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 Sat Nov 23 2024 16:08:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DrawRectCB Member List

This is the complete list of members for DrawRectCB, including all inherited members.
boundsTransform | DrawRectCB
texScale | DrawRectCB
Generated on Sat Nov 23 2024 16:09:12 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Compass sensor/C++/MainPage.xaml.cpp Source File

  • Compass sensor

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:41 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DirectX::D3DX_BC7::ModeInfo Member List

This is the complete list of members for DirectX::D3DX_BC7::ModeInfo, including all inherited members.
RGBAPrec | DirectX::D3DX_BC7::ModeInfo
RGBAPrecWithP | DirectX::D3DX_BC7::ModeInfo
uIndexModeBits | DirectX::D3DX_BC7::ModeInfo
uIndexPrec | DirectX::D3DX_BC7::ModeInfo
uIndexPrec2 | DirectX::D3DX_BC7::ModeInfo
uPartitionBits | DirectX::D3DX_BC7::ModeInfo
uPartitions | DirectX::D3DX_BC7::ModeInfo
uPBits | DirectX::D3DX_BC7::ModeInfo
uRotationBits | DirectX::D3DX_BC7::ModeInfo
Generated on Sat Nov 23 2024 16:09:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D tutorial/C++/Lesson5.Components/DirectXBase.h Source File

  • Direct3D tutorial
  • Lesson5.Components

DirectXBase.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 "DirectXSample.h"
00011
00012 // Helper class that initializes DirectX APIs for both 2D and 3D rendering.
00013 // Some of the code in this class may be omitted if only 2D or only 3D rendering is being used.
00014 ref class DirectXBase abstract
00015 {
00016 internal:
00017     DirectXBase();
00018
00019     virtual void Initialize(Windows::UI::Core::CoreWindow^ window, float dpi);
00020     virtual void HandleDeviceLost();
00021     virtual void CreateDeviceIndependentResources();
00022     virtual void CreateDeviceResources();
00023     virtual void SetDpi(float dpi);
00024     virtual void UpdateForWindowSizeChange();
00025     virtual void CreateWindowSizeDependentResources();
00026     virtual void Render() = 0;
00027     virtual void Present();
00028     void ValidateDevice();
00029
00030 protected private:
00031     Platform::Agile<Windows::UI::Core::CoreWindow>  m_window;
00032
00033     // DirectWrite & Windows Imaging Component Objects.
00034     Microsoft::WRL::ComPtr<IDWriteFactory1>         m_dwriteFactory;
00035     Microsoft::WRL::ComPtr<IWICImagingFactory2>     m_wicFactory;
00036
00037     // DirectX Core Objects. Required for 2D and 3D.
00038     Microsoft::WRL::ComPtr<ID3D11Device1>           m_d3dDevice;
00039     Microsoft::WRL::ComPtr<ID3D11DeviceContext1>    m_d3dContext;
00040     Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00041     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00042
00043     // Direct2D Rendering Objects. Required for 2D.
00044     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00046     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00047     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmap;
00048
00049     // Direct3D Rendering Objects. Required for 3D.
00050     Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00051
00052     // Cached renderer properties.
00053     D3D_FEATURE_LEVEL                               m_featureLevel;
00054     Windows::Foundation::Size                       m_renderTargetSize;
00055     Windows::Foundation::Rect                       m_windowBounds;
00056     float                                           m_dpi;
00057     bool                                            m_windowSizeChangeInProgress;
00058 };
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: PlayToReceiver/C++/App.xaml.cpp Source File

  • PlayToReceiver

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Toast notifications/C#,C++/MainPage.xaml.cpp Source File

  • Toast notifications
  • C#,C++

MainPage.xaml.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 //
00009 // MainPage.xaml.cpp
00010 // Implementation of the MainPage.xaml class.
00011 //
00012
00013 #include "pch.h"
00014 #include "MainPage.xaml.h"
00015 #include "App.xaml.h"
00016
00017 using namespace Windows::UI::Xaml;
00018 using namespace Windows::UI::Xaml::Controls;
00019 using namespace Windows::UI::Xaml::Data;
00020 using namespace Windows::System;
00021 using namespace Windows::Foundation;
00022 using namespace Platform;
00023 using namespace ToastsSampleCPP;
00024 using namespace CppSamplesUtils;
00025 using namespace Windows::UI::Xaml::Navigation;
00026 using namespace Windows::UI::Xaml::Interop;
00027
00028 MainPage::MainPage()
00029 {
00030     InitializeComponent();
00031
00032     SetFeatureName("Toasts");
00033
00034     _scenariosFrame = ScenarioList;
00035     _inputFrame = ScenarioInput;
00036     _outputFrame = ScenarioOutput;
00037
00038     _layoutHandlerToken = Window::Current->SizeChanged += ref new Windows::UI::Xaml::WindowSizeChangedEventHandler(this, &MainPage::Page_SizeChanged);
00039
00040     _pageLoadedHandlerToken = Loaded += ref new RoutedEventHandler(this, &MainPage::Page_Loaded);
00041     _logicalDpiChangedToken = DisplayProperties::LogicalDpiChanged += ref new DisplayPropertiesEventHandler(this, &MainPage::DisplayProperties_LogicalDpiChanged);
00042 }
00043
00044 void MainPage::OnNavigatedTo(NavigationEventArgs^ args)
00045 {
00046     // Store the toast context so it can be passed along to Scenario 5
00047     _toastContext = dynamic_cast<String^>(args->Parameter);
00048     if (_toastContext != "")
00049     {
00050         // Make sure we navigate to Scenario 5 first if a toast was clicked on from that scenario.
00051         // That way, we can see how the app responds to activation events.
00052         auto ps = SuspensionManager::SessionState();
00053         ps->Insert("SelectedScenario", "Scenario5");
00054     }
00055 }
00056
00057 MainPage::~MainPage()
00058 {
00059 }
00060
00061 void MainPage::Page_Loaded(Object^ sender, RoutedEventArgs^ e)
00062 {
00063     // Load the ScenarioList page into the proper frame
00064     TypeName pageType = { "ToastsSampleCPP.ScenarioList", TypeKind::Custom };
00065     ScenarioList->Navigate(pageType, this);
00066
00067     // Figure out what resolution and orientation we are in and respond appropriately.
00068     CheckResolutionAndViewState();
00069 }
00070
00071 void MainPage::SetFeatureName(String^ strFeature)
00072 {
00073     FeatureName->Text = strFeature;
00074 }
00075
00076 void MainPage::Page_SizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00077 {
00078     CheckResolutionAndViewState();
00079 }
00080
00081 void MainPage::DisplayProperties_LogicalDpiChanged(Object^ sender)
00082 {
00083     CheckResolutionAndViewState();
00084 }
00085
00086 void MainPage::CheckResolutionAndViewState()
00087 {
00088     ApplicationViewState state = ApplicationView::Value;
00089     String^ stateString = ConvertViewState(state);
00090
00091     ResolutionScale scale = DisplayProperties::ResolutionScale;
00092     String^ scaleString = ConvertResolution(scale);
00093
00094     VisualStateManager::GoToState(this, stateString + scaleString, false);
00095 }
00096
00097 String^ MainPage::ConvertViewState(ApplicationViewState state)
00098 {
00099     switch(state)
00100     {
00101     case ApplicationViewState::Filled:
00102         return "Filled";
00103     case ApplicationViewState::FullScreenLandscape:
00104         return "FullScreenLandscape";
00105     case ApplicationViewState::FullScreenPortrait:
00106         return "FullScreenPortrait";
00107     case ApplicationViewState::Snapped:
00108         return "Snapped";
00109     }
00110     return "";
00111 }
00112
00113 String^ MainPage::ConvertResolution(ResolutionScale scale)
00114 {
00115     switch(scale)
00116     {
00117     case ResolutionScale::Scale100Percent:
00118         return "Scale100Percent";
00119     case ResolutionScale::Scale140Percent:
00120         return "Scale140Percent";
00121     case ResolutionScale::Scale180Percent:
00122         return "Scale180Percent";
00123     }
00124     return "";
00125 }
00126
00127 void MainPage::DoNavigation(TypeName pageType, Windows::UI::Xaml::Controls::Frame^ frame)
00128 {
00129     // Make sure that if we're navigating to Scenario 5 because a toast was clicked on,
00130     // we pass along the toast context
00131     if (pageType.Name == "ToastsSampleCPP.ScenarioInput5")
00132     {
00133         frame->Navigate(pageType, ref new MainPageAndContext(this, _toastContext));
00134     }
00135     else
00136     {
00137         frame->Navigate(pageType, this);
00138     }
00139
00140     // Otherwise, clear the toast context data
00141     if (_toastContext != "")
00142     {
00143         _toastContext = "";
00144     }
00145
00146     std::wstring PageName(pageType.Name->Data());
00147     std::basic_string <wchar_t>::size_type indexSubstring;
00148     indexSubstring = PageName.find(L"Output");
00149     if(indexSubstring != std::wstring::npos)
00150     {
00151         // Raise OutputFrameLoaded so downstream pages know that the output frame content has been loaded
00152         OutputFrameLoaded(this, nullptr);
00153     }
00154     else
00155     {
00156         // Raise InputFrameLoaded so downstream pages know that the input frame content has been loaded
00157         InputFrameLoaded(this, nullptr);
00158     }
00159 }
00160
00161 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00162 {
00163     switch (type)
00164     {
00165     case NotifyType::StatusMessage:
00166         StatusBlock->Style = dynamic_cast<Windows::UI::Xaml::Style^>(App::Current->Resources->Lookup("StatusStyle"));
00167         break;
00168     case NotifyType::ErrorMessage:
00169         StatusBlock->Style = dynamic_cast<Windows::UI::Xaml::Style^>(App::Current->Resources->Lookup("ErrorStyle"));
00170         break;
00171     default:
00172         break;
00173     }
00174     StatusBlock->Text = strMessage;
00175 }
00176
00177 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00178 {
00179     auto _hyperlinkButton = (HyperlinkButton^)sender;
00180     auto uri = ref new Windows::Foundation::Uri((String^)_hyperlinkButton->Tag);
00181
00182     Windows::System::Launcher::LaunchUriAsync(uri);
00183 }
Generated on Sat Nov 23 2024 16:07:44 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D sprite/C++/pch.h Source File

  • Direct3D sprite

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 <d3d11_1.h>
00012 #include <d2d1_1.h>
00013 #include <d2d1effects.h>
00014 #include <dwrite_1.h>
00015 #include <wincodec.h>
00016 #include <agile.h>
00017 #include "BasicMath.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Transcoding media/C++/Presets.xaml.cpp Source File

  • Transcoding media

Presets.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 // Presets.xaml.cpp
00013 // Implementation of the Presets class
00014 //
00015
00016 #include "pch.h"
00017 #include "Presets.xaml.h"
00018
00019 using namespace SDKSample::Transcode;
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::Storage::Streams;
00025 using namespace Platform;
00026 using namespace Windows::Foundation;
00027 using namespace Windows::Media;
00028 using namespace Windows::Media::MediaProperties;
00029 using namespace Windows::Media::Transcoding;
00030 using namespace Windows::Storage;
00031 using namespace Windows::Storage::Pickers;
00032 using namespace Windows::Storage::Streams;
00033 using namespace concurrency;
00034
00035 Presets::Presets()
00036 {
00037     InitializeComponent();
00038
00039     // Hook up UI
00040     PickFileButton->Click += ref new RoutedEventHandler(this, &Presets::PickFile);
00041     TargetFormat->SelectionChanged += ref new SelectionChangedEventHandler(this, &Presets::OnTargetFormatChanged);
00042     Transcode->Click += ref new RoutedEventHandler(this, &Presets::TranscodePreset);
00043     Cancel->Click += ref new RoutedEventHandler(this, &Presets::TranscodeCancel);
00044
00045     // Media Controls
00046     InputPlayButton->Click += ref new RoutedEventHandler(this, &Presets::InputPlayButton_Click);
00047     InputPauseButton->Click += ref new RoutedEventHandler(this, &Presets::InputPauseButton_Click);
00048     InputStopButton->Click += ref new RoutedEventHandler(this, &Presets::InputStopButton_Click);
00049     OutputPlayButton->Click += ref new RoutedEventHandler(this, &Presets::OutputPlayButton_Click);
00050     OutputPauseButton->Click += ref new RoutedEventHandler(this, &Presets::OutputPauseButton_Click);
00051     OutputStopButton->Click += ref new RoutedEventHandler(this, &Presets::OutputStopButton_Click);
00052
00053     // File is not selected, disable all buttons but PickFileButton
00054     DisableButtons();
00055     SetPickFileButton(true);
00056     SetCancelButton(false);
00057
00058     // Initialize Objects
00059     _Transcoder = ref new MediaTranscoder();
00060     _Profile = nullptr;
00061     _InputFile = nullptr;
00062     _OutputFile = nullptr;
00063     _OutputFileName = "TranscodeSampleOutput.mp4";
00064     _CTS = cancellation_token_source();
00065
00066     _UseMp4 = true;
00067
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 Presets::OnNavigatedTo(NavigationEventArgs^ e)
00076 {
00077     // A pointer back to the main page.  This is needed if you want to call methods in Presets such
00078     // as NotifyUser()
00079     rootPage = MainPage::Current;
00080 }
00081
00082 void Presets::GetPresetProfile(ComboBox^ comboBox)
00083 {
00084     _Profile = nullptr;
00085     VideoEncodingQuality videoEncodingProfile = VideoEncodingQuality::Wvga;
00086     switch (comboBox->SelectedIndex)
00087     {
00088     case 0:
00089         videoEncodingProfile = VideoEncodingQuality::HD1080p;
00090         break;
00091     case 1:
00092         videoEncodingProfile = VideoEncodingQuality::HD720p;
00093         break;
00094     case 2:
00095         videoEncodingProfile = VideoEncodingQuality::Wvga;
00096         break;
00097     case 3:
00098         videoEncodingProfile = VideoEncodingQuality::Ntsc;
00099         break;
00100     case 4:
00101         videoEncodingProfile = VideoEncodingQuality::Pal;
00102         break;
00103     case 5:
00104         videoEncodingProfile = VideoEncodingQuality::Vga;
00105         break;
00106     case 6:
00107         videoEncodingProfile = VideoEncodingQuality::Qvga;
00108         break;
00109     }
00110
00111     if(_UseMp4)
00112     {
00113         _Profile = MediaEncodingProfile::CreateMp4(videoEncodingProfile);
00114     }
00115     else
00116     {
00117         _Profile = MediaEncodingProfile::CreateWmv(videoEncodingProfile);
00118     }
00119 }
00120
00121 void Presets::TranscodePreset(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00122 {
00123     StopPlayers();
00124     DisableButtons();
00125     GetPresetProfile(ProfileSelect);
00126
00127     // Clear messages
00128     StatusMessage->Text = "";
00129
00130     try
00131     {
00132         if (_InputFile != nullptr)
00133         {
00134             auto videoLibrary = KnownFolders::VideosLibrary;
00135             create_task(videoLibrary->CreateFileAsync(_OutputFileName, CreationCollisionOption::GenerateUniqueName), _CTS.get_token()).then(
00136                 [this](StorageFile^ destinationFile)
00137             {
00138                 try
00139                 {
00140                     _OutputFile = destinationFile;
00141                     return _Transcoder->PrepareFileTranscodeAsync(_InputFile, _OutputFile, _Profile);
00142                 }
00143                 catch (Platform::Exception^ exception)
00144                 {
00145                     TranscodeError(exception->Message);
00146                 }
00147
00148                 cancel_current_task();
00149             }).then(
00150                 [this](PrepareTranscodeResult^ transcode)
00151             {
00152                 try
00153                 {
00154                     if(transcode->CanTranscode)
00155                     {
00156                         OutputMsg->Text = "";
00157                         SetCancelButton(true);
00158                         Windows::Foundation::IAsyncActionWithProgress<double>^ transcodeOp = transcode->TranscodeAsync();
00159
00160                         // Set Progress Callback
00161                         transcodeOp->Progress = ref new AsyncActionProgressHandler<double>(
00162                         [this](IAsyncActionWithProgress<double>^ asyncInfo, double percent){
00163                             TranscodeProgress(asyncInfo, percent);
00164                         }, Platform::CallbackContext::Same);
00165
00166                         return transcodeOp;
00167                     }
00168                     else
00169                     {
00170                         TranscodeFailure(transcode->FailureReason);
00171                     }
00172                 }
00173                 catch (Platform::Exception^ exception)
00174                 {
00175                     TranscodeError(exception->Message);
00176                 }
00177
00178                 cancel_current_task();
00179             }).then(
00180                 [this](task<void> transcodeTask)
00181             {
00182                 try
00183                 {
00184                     transcodeTask.get();
00185                     OutputMsg->Text = "Transcode Completed.";
00186                     OutputPath->Text = "Output (" + _OutputFile->Path + ")";
00187                     PlayFile(_OutputFile);
00188                 }
00189                 catch (task_canceled&)
00190                 {
00191                     OutputMsg->Foreground = ref new Windows::UI::Xaml::Media::SolidColorBrush(Windows::UI::Colors::Red);
00192                     OutputMsg->Text = "Transcode Cancelled.";
00193                 }
00194                 catch(Exception^ exception)
00195                 {
00196                     TranscodeError(exception->Message);
00197                 }
00198
00199                 EnableButtons();
00200                 SetCancelButton(false);
00201             });
00202         }
00203     }
00204     catch (Platform::Exception^ exception)
00205     {
00206         TranscodeError(exception->Message);
00207     }
00208 }
00209
00210 void Presets::TranscodeCancel(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00211 {
00212     try
00213     {
00214         _CTS.cancel();
00215         _CTS = cancellation_token_source();
00216
00217         if(_OutputFile != nullptr)
00218         {
00219             create_task(_OutputFile->DeleteAsync()).then(
00220                 [this](task<void> deleteTask)
00221             {
00222                 try
00223                 {
00224                     deleteTask.get();
00225                 }
00226                 catch (Platform::Exception^ exception)
00227                 {
00228                     TranscodeError(exception->Message);
00229                 }
00230             });
00231         }
00232     }
00233     catch (Platform::Exception^ exception)
00234     {
00235         TranscodeError(exception->Message);
00236     }
00237 }
00238
00239 void Presets::TranscodeProgress(IAsyncActionWithProgress<double>^ asyncInfo, double percent)
00240 {
00241     OutputMsg->Foreground = ref new Windows::UI::Xaml::Media::SolidColorBrush(Windows::UI::Colors::Green);
00242     OutputMsg->Text = "Progress:  " + ((int)percent).ToString() + "%";
00243 }
00244
00245 void Presets::TranscodeError(Platform::String^ error)
00246 {
00247     StatusMessage->Foreground = ref new Windows::UI::Xaml::Media::SolidColorBrush(Windows::UI::Colors::Red);
00248     StatusMessage->Text = error;
00249     EnableButtons();
00250     SetCancelButton(false);
00251 }
00252
00253 void Presets::TranscodeFailure(TranscodeFailureReason reason)
00254 {
00255     try
00256     {
00257         if(_OutputFile != nullptr)
00258         {
00259             create_task(_OutputFile->DeleteAsync()).then(
00260                 [this](task<void> deleteTask)
00261             {
00262                 try
00263                 {
00264                     deleteTask.get();
00265                 }
00266                 catch (Platform::Exception^ exception)
00267                 {
00268                     TranscodeError(exception->Message);
00269                 }
00270             });
00271         }
00272     }
00273     catch(Platform::Exception^ exception)
00274     {
00275         TranscodeError(exception->Message);
00276     }
00277
00278     switch (reason)
00279     {
00280     case TranscodeFailureReason::CodecNotFound:
00281         TranscodeError("Codec not found.");
00282         break;
00283     case TranscodeFailureReason::InvalidProfile:
00284         TranscodeError("Invalid profile.");
00285         break;
00286     default:
00287         TranscodeError("Unknown failure.");
00288     }
00289 }
00290
00291 void Presets::SetCancelButton(bool isEnabled)
00292 {
00293     Cancel->IsEnabled = isEnabled;
00294 }
00295
00296 void Presets::EnableButtons()
00297 {
00298     PickFileButton->IsEnabled = true;
00299     TargetFormat->IsEnabled = true;
00300     ProfileSelect->IsEnabled = true;
00301     Transcode->IsEnabled = true;
00302 }
00303
00304 void Presets::DisableButtons()
00305 {
00306     ProfileSelect->IsEnabled = false;
00307     Transcode->IsEnabled = false;
00308     PickFileButton->IsEnabled = false;
00309     TargetFormat->IsEnabled = false;
00310 }
00311
00312 void Presets::PickFile(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00313 {
00314     try
00315     {
00316     Windows::UI::ViewManagement::ApplicationViewState currentState = Windows::UI::ViewManagement::ApplicationView::Value;
00317     if(currentState == Windows::UI::ViewManagement::ApplicationViewState::Snapped && !Windows::UI::ViewManagement::ApplicationView::TryUnsnap())
00318     {
00319       TranscodeError("Cannot pick files while application is in snapped view");
00320     }
00321     else
00322     {
00323       FileOpenPicker^ picker = ref new FileOpenPicker();
00324       picker->SuggestedStartLocation = PickerLocationId::VideosLibrary;
00325       picker->FileTypeFilter->Append(".wmv");
00326       picker->FileTypeFilter->Append(".mp4");
00327
00328       create_task(picker->PickSingleFileAsync()).then(
00329         [this](StorageFile^ inputFile)
00330       {
00331         try
00332         {
00333           _InputFile = inputFile;
00334
00335           if(_InputFile != nullptr)
00336           {
00337             return inputFile->OpenAsync(FileAccessMode::Read);
00338           }
00339         }
00340         catch (Platform::Exception^ exception)
00341         {
00342           TranscodeError(exception->Message);
00343         }
00344
00345         cancel_current_task();
00346       }).then(
00347         [this](IRandomAccessStream^ inputStream)
00348       {
00349         try
00350         {
00351           InputVideo->SetSource(inputStream, _InputFile->ContentType);;
00352           InputVideo->Play();
00353
00354           //Enable buttons
00355           EnableButtons();
00356         }
00357         catch (Platform::Exception^ exception)
00358         {
00359           TranscodeError(exception->Message);
00360         }
00361       });
00362     }
00363     }
00364     catch(Exception^ exception)
00365     {
00366         TranscodeError(exception->Message);
00367     }
00368 }
00369
00370 void Presets::OnTargetFormatChanged(Object^ sender, SelectionChangedEventArgs^ e)
00371 {
00372     if (TargetFormat->SelectedIndex > 0)
00373     {
00374         _OutputFileName = "TranscodeSampleOutput.wmv";
00375         _UseMp4 = false;
00376     }
00377     else
00378     {
00379         _OutputFileName = "TranscodeSampleOutput.mp4";
00380         _UseMp4 = true;
00381     }
00382 }
00383
00384 void Presets::InputPlayButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00385 {
00386     if (InputVideo->DefaultPlaybackRate == 0)
00387     {
00388         InputVideo->DefaultPlaybackRate = 1.0;
00389         InputVideo->PlaybackRate = 1.0;
00390     }
00391
00392     InputVideo->Play();
00393 }
00394
00395 void Presets::InputStopButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00396 {
00397     InputVideo->Stop();
00398 }
00399
00400 void Presets::InputPauseButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00401 {
00402     InputVideo->Pause();
00403 }
00404
00405 void Presets::OutputPlayButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00406 {
00407     if (OutputVideo->DefaultPlaybackRate == 0)
00408     {
00409         OutputVideo->DefaultPlaybackRate = 1.0;
00410         OutputVideo->PlaybackRate = 1.0;
00411     }
00412
00413     OutputVideo->Play();
00414 }
00415
00416 void Presets::OutputStopButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00417 {
00418     OutputVideo->Stop();
00419 }
00420
00421 void Presets::OutputPauseButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00422 {
00423     OutputVideo->Pause();
00424 }
00425
00426 void Presets::SetPickFileButton(bool isEnabled)
00427 {
00428     PickFileButton->IsEnabled = isEnabled;
00429 }
00430
00431
00432 void Presets::StopPlayers()
00433 {
00434     if(InputVideo->CurrentState != Media::MediaElementState::Paused)
00435     {
00436         InputVideo->Pause();
00437     }
00438     if(OutputVideo->CurrentState != Media::MediaElementState::Paused)
00439     {
00440         OutputVideo->Pause();
00441     }
00442 }
00443
00444 void Presets::PlayFile(Windows::Storage::StorageFile^ MediaFile)
00445 {
00446     try
00447     {
00448         create_task(MediaFile->OpenAsync(FileAccessMode::Read)).then(
00449             [&, this, MediaFile](IRandomAccessStream^ outputStream)
00450         {
00451             try
00452             {
00453                 OutputVideo->SetSource(outputStream, MediaFile->ContentType);
00454                 OutputVideo->Play();
00455             }
00456             catch (Platform::Exception^ exception)
00457             {
00458                 TranscodeError(exception->Message);
00459             }
00460         });
00461     }
00462     catch (Exception^ exception)
00463     {
00464         TranscodeError(exception->Message);
00465     }
00466 }
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Touch keyboard text input/C++/MainPage.xaml.cpp Source File

  • Input Touch keyboard text input

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:42 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File picker/C++/pch.h Source File

  • File picker

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::NotificationContentImage Member List

This is the complete list of members for NotificationsExtensions::NotificationContentImage, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationContentImage |
AddImageQueryNullable | NotificationsExtensions::NotificationContentImage |
Alt | NotificationsExtensions::NotificationContentImage |
m_AddImageQueryNullable | NotificationsExtensions::NotificationContentImage | [private]
m_Alt | NotificationsExtensions::NotificationContentImage | [private]
m_Src | NotificationsExtensions::NotificationContentImage | [private]
NotificationContentImage() | NotificationsExtensions::NotificationContentImage | [inline, private]
NotificationContentImage() | NotificationsExtensions::NotificationContentImage | [inline, private]
NotificationContentImage() | NotificationsExtensions::NotificationContentImage | [inline, private]
NotificationContentImage() | NotificationsExtensions::NotificationContentImage | [inline, private]
Src | NotificationsExtensions::NotificationContentImage |
Generated on Sat Nov 23 2024 16:09:41 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D magazine app/C++/PageRoll.h Source File

  • Direct2D magazine app

PageRoll.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 "Element.h"
00011
00012 //  <page-roll> contains all the pages in the book. It draws each page next to one another
00013 //  but shows only the pages visible in the display view. There may be multiple pages visible
00014 //  in the view while visual transition is happening. PageRoll responds to user's horizontal
00015 //  flick gesture by initiating an animation transition sequence. Note that <page-roll> element
00016 //  can only parent a <page> element. This rule is explicitly enforced in the class definition
00017 //  by overriding Element::AcceptChildNode virtual method.
00018 //
00019 ref class PageRoll : public Element
00020 {
00021 internal:
00022     virtual bool AcceptChildNode(
00023         _In_ Document^ document,
00024         _In_ Windows::Data::Xml::Dom::IXmlNode^ childXmlNode
00025         ) override;
00026
00027     virtual void Measure(
00028         _In_ Document^ document,
00029         D2D1_SIZE_F const& parentSize,
00030         _Out_ D2D1_RECT_F* bounds
00031         ) override;
00032 };
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File picker/C++/Constants.h Source File

  • File picker

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"File picker C++ sample");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041
00042     internal:
00043         bool EnsureUnsnapped();
00044         void ResetScenarioOutput(Windows::UI::Xaml::Controls::TextBlock^ textblock);
00045
00046     private:
00047         static Platform::Array<Scenario>^ scenariosInner;
00048     };
00049 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/App.xaml.cpp Source File

  • Media extensions

App.xaml.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 //
00009 // App.xaml.cpp
00010 // Implementation of the App.xaml class.
00011 //
00012
00013 #include "pch.h"
00014 #include "App.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace Windows::UI::Xaml;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::ApplicationModel;
00020 using namespace Windows::ApplicationModel::Activation;
00021 using namespace CppSamplesUtils;
00022 using namespace MediaExtensionsCPP;
00023 using namespace Windows::UI::Xaml::Interop;
00024
00025 App::App()
00026 {
00027     InitializeComponent();
00028     this->Suspending += ref new SuspendingEventHandler(this, &MediaExtensionsCPP::App::OnSuspending);
00029 }
00030
00031 void App::OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs)
00032 {
00033     auto deferral = pArgs->SuspendingOperation->GetDeferral();
00034     SuspensionManager::StartSaveTask().then([=]()
00035     {
00036         deferral->Complete();
00037     });
00038
00039 }
00040
00041 void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs)
00042 {
00043
00044     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Terminated)
00045     {
00046         SuspensionManager::StartRestoreTask().then([=]()
00047         {
00048             auto rootFrame = ref new Frame();
00049             TypeName pageType = { "MediaExtensionsCPP.MainPage", TypeKind::Custom };
00050             rootFrame->Navigate(pageType);
00051             Window::Current->Content = rootFrame;
00052             Window::Current->Activate();
00053         });
00054     }
00055     else
00056     {
00057         auto rootFrame = ref new Frame();
00058         TypeName pageType = { "MediaExtensionsCPP.MainPage", TypeKind::Custom };
00059         rootFrame->Navigate(pageType);
00060         Window::Current->Content = rootFrame;
00061         Window::Current->Activate();
00062     }
00063 }
Generated on Sat Nov 23 2024 16:07:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Geolocation/C++/Constants.h Source File

  • Geolocation

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"Geolocation");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044
00045
00046 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/GameRenderer.cpp Source File

  • DirectX 3D shooting game

GameRenderer.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 "DirectXSample.h"
00010 #include "GameRenderer.h"
00011 #include "ConstantBuffers.h"
00012 #include "TargetTexture.h"
00013 #include "BasicLoader.h"
00014 #include "CylinderMesh.h"
00015 #include "FaceMesh.h"
00016 #include "SphereMesh.h"
00017 #include "WorldMesh.h"
00018 #include "Face.h"
00019 #include "Sphere.h"
00020 #include "Cylinder.h"
00021
00022 using namespace concurrency;
00023 using namespace DirectX;
00024 using namespace Microsoft::WRL;
00025 using namespace Windows::UI::Core;
00026
00027 //----------------------------------------------------------------------
00028
00029 GameRenderer::GameRenderer() :
00030     m_initialized(false),
00031     m_gameResourcesLoaded(false),
00032     m_levelResourcesLoaded(false)
00033 {
00034 }
00035
00036 //----------------------------------------------------------------------
00037
00038 void GameRenderer::Initialize(
00039     _In_ CoreWindow^ window,
00040     float dpi
00041     )
00042 {
00043     m_gameHud = ref new GameHud(
00044         "Windows 8 Samples",
00045         "DirectX first-person game sample"
00046         );
00047     m_gameInfoOverlay = ref new GameInfoOverlay();
00048
00049     DirectXBase::Initialize(window, dpi);
00050 }
00051
00052 //----------------------------------------------------------------------
00053
00054 void GameRenderer::HandleDeviceLost()
00055 {
00056     // On device lost all the device resources are invalid.
00057     // Set the state of the renderer to not have a pointer to the
00058     // Simple3DGame object.  It will be reset as a part of the
00059     // game devices resources being recreated.
00060     m_game = nullptr;
00061
00062     DirectXBase::HandleDeviceLost();
00063 }
00064
00065 //----------------------------------------------------------------------
00066
00067 void GameRenderer::CreateDeviceIndependentResources()
00068 {
00069     DirectXBase::CreateDeviceIndependentResources();
00070     m_gameHud->CreateDeviceIndependentResources(m_dwriteFactory.Get(), m_wicFactory.Get());
00071     m_gameInfoOverlay->CreateDeviceIndependentResources(m_dwriteFactory.Get());
00072 }
00073
00074 //----------------------------------------------------------------------
00075
00076 void GameRenderer::CreateDeviceResources()
00077 {
00078     m_gameResourcesLoaded = false;
00079     m_levelResourcesLoaded = false;
00080
00081     DirectXBase::CreateDeviceResources();
00082
00083     m_gameHud->CreateDeviceResources(m_d2dContext.Get());
00084     m_gameInfoOverlay->CreateDeviceResources(m_d2dContext.Get());
00085 }
00086
00087 //----------------------------------------------------------------------
00088
00089 void GameRenderer::UpdateForWindowSizeChange()
00090 {
00091     DirectXBase::UpdateForWindowSizeChange();
00092
00093     m_gameHud->UpdateForWindowSizeChange(m_windowBounds);
00094
00095     if (m_game != nullptr)
00096     {
00097         // Update the Projection Matrix and the associated Constant Buffer.
00098         m_game->GameCamera()->SetProjParams(
00099             XM_PI / 2, m_renderTargetSize.Width / m_renderTargetSize.Height,
00100             0.01f,
00101             100.0f
00102             );
00103         ConstantBufferChangeOnResize changesOnResize;
00104         XMStoreFloat4x4(
00105             &changesOnResize.projection,
00106             XMMatrixMultiply(
00107                 XMMatrixTranspose(m_game->GameCamera()->Projection()),
00108                 XMMatrixTranspose(XMLoadFloat4x4(&m_rotationTransform3D))
00109                 )
00110             );
00111
00112         m_d3dContext->UpdateSubresource(
00113             m_constantBufferChangeOnResize.Get(),
00114             0,
00115             nullptr,
00116             &changesOnResize,
00117             0,
00118             0
00119             );
00120     }
00121 }
00122
00123 //----------------------------------------------------------------------
00124
00125 void GameRenderer::SetDpi(float dpi)
00126 {
00127     DirectXBase::SetDpi(dpi);
00128
00129     m_gameInfoOverlay->CreateDpiDependentResources(dpi);
00130 }
00131
00132 //----------------------------------------------------------------------
00133
00134 task<void> GameRenderer::CreateGameDeviceResourcesAsync(_In_ Simple3DGame^ game)
00135 {
00136     // Create the device dependent game resources.
00137     // Only the m_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 m_d3dDevice are free-threaded and are safe while any methods
00140     // in the m_d3dContext should only be used on a single thread and handled
00141     // in the FinalizeCreateGameDeviceResources method.
00142     m_game = game;
00143
00144     D3D11_BUFFER_DESC bd;
00145     ZeroMemory(&bd, sizeof(bd));
00146
00147     // Create the constant buffers.
00148     bd.Usage = D3D11_USAGE_DEFAULT;
00149     bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
00150     bd.CPUAccessFlags = 0;
00151     bd.ByteWidth = (sizeof(ConstantBufferNeverChanges) + 15) / 16 * 16;
00152     DX::ThrowIfFailed(
00153         m_d3dDevice->CreateBuffer(&bd, nullptr, &m_constantBufferNeverChanges)
00154         );
00155
00156     bd.ByteWidth = (sizeof(ConstantBufferChangeOnResize) + 15) / 16 * 16;
00157     DX::ThrowIfFailed(
00158         m_d3dDevice->CreateBuffer(&bd, nullptr, &m_constantBufferChangeOnResize)
00159         );
00160
00161     bd.ByteWidth = (sizeof(ConstantBufferChangesEveryFrame) + 15) / 16 * 16;
00162     DX::ThrowIfFailed(
00163         m_d3dDevice->CreateBuffer(&bd, nullptr, &m_constantBufferChangesEveryFrame)
00164         );
00165
00166     bd.ByteWidth = (sizeof(ConstantBufferChangesEveryPrim) + 15) / 16 * 16;
00167     DX::ThrowIfFailed(
00168         m_d3dDevice->CreateBuffer(&bd, nullptr, &m_constantBufferChangesEveryPrim)
00169         );
00170
00171     D3D11_SAMPLER_DESC sampDesc;
00172     ZeroMemory(&sampDesc, sizeof(sampDesc));
00173
00174     sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
00175     sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
00176     sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
00177     sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
00178     sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
00179     sampDesc.MinLOD = 0;
00180     sampDesc.MaxLOD = FLT_MAX;
00181     DX::ThrowIfFailed(
00182         m_d3dDevice->CreateSamplerState(&sampDesc, &m_samplerLinear)
00183         );
00184
00185     // Start the async tasks to load the shaders and textures.
00186     BasicLoader^ loader = ref new BasicLoader(m_d3dDevice.Get());
00187
00188     std::vector<task<void>> tasks;
00189
00190     uint32 numElements = ARRAYSIZE(PNTVertexLayout);
00191     tasks.push_back(loader->LoadShaderAsync("VertexShader.cso", PNTVertexLayout, numElements, &m_vertexShader, &m_vertexLayout));
00192     tasks.push_back(loader->LoadShaderAsync("VertexShaderFlat.cso", nullptr, numElements, &m_vertexShaderFlat, nullptr));
00193     tasks.push_back(loader->LoadShaderAsync("PixelShader.cso", &m_pixelShader));
00194     tasks.push_back(loader->LoadShaderAsync("PixelShaderFlat.cso", &m_pixelShaderFlat));
00195
00196     // Make sure the previous versions if any of the textures are released.
00197     m_sphereTexture = nullptr;
00198     m_cylinderTexture = nullptr;
00199     m_ceilingTexture = nullptr;
00200     m_floorTexture = nullptr;
00201     m_wallsTexture = nullptr;
00202
00203     // Load Game specific textures.
00204     tasks.push_back(loader->LoadTextureAsync("seafloor.dds", nullptr, &m_sphereTexture));
00205     tasks.push_back(loader->LoadTextureAsync("metal_texture.dds", nullptr, &m_cylinderTexture));
00206     tasks.push_back(loader->LoadTextureAsync("cellceiling.dds", nullptr, &m_ceilingTexture));
00207     tasks.push_back(loader->LoadTextureAsync("cellfloor.dds", nullptr, &m_floorTexture));
00208     tasks.push_back(loader->LoadTextureAsync("cellwall.dds", nullptr, &m_wallsTexture));
00209     tasks.push_back(create_task([]()
00210     {
00211         // Simulate loading additional resources by introducing a delay.
00212         wait(GameConstants::InitialLoadingDelay);
00213     }));
00214
00215     // Return the task group of all the async tasks for loading the shader and texture assets.
00216     return when_all(tasks.begin(), tasks.end());
00217 }
00218
00219 //----------------------------------------------------------------------
00220
00221 void GameRenderer::FinalizeCreateGameDeviceResources()
00222 {
00223     // All asynchronously loaded resources have completed loading.
00224     // Now associate all the resources with the appropriate game objects.
00225     // This method is expected to run in the same thread as the GameRenderer
00226     // was created. All work will happen behind the "Loading ..." screen after the
00227     // main loop has been entered.
00228
00229     // Initialize the Constant buffer with the light positions
00230     // These are handled here to ensure that the d3dContext is only
00231     // used in one thread.
00232
00233     ConstantBufferNeverChanges constantBufferNeverChanges;
00234     constantBufferNeverChanges.lightPosition[0] = XMFLOAT4( 3.5f, 2.5f,  5.5f, 1.0f);
00235     constantBufferNeverChanges.lightPosition[1] = XMFLOAT4( 3.5f, 2.5f, -5.5f, 1.0f);
00236     constantBufferNeverChanges.lightPosition[2] = XMFLOAT4(-3.5f, 2.5f, -5.5f, 1.0f);
00237     constantBufferNeverChanges.lightPosition[3] = XMFLOAT4( 3.5f, 2.5f,  5.5f, 1.0f);
00238     constantBufferNeverChanges.lightColor = XMFLOAT4(0.25f, 0.25f, 0.25f, 1.0f);
00239     m_d3dContext->UpdateSubresource(m_constantBufferNeverChanges.Get(), 0, nullptr, &constantBufferNeverChanges, 0, 0);
00240
00241     // For the targets, there are two unique generated textures.
00242     // Each texture image includes the number of the texture.
00243     // Make sure the 2D rendering is occurring on the same thread
00244     // as the main rendering.
00245
00246     TargetTexture^ textureGenerator = ref new TargetTexture(
00247         m_d3dDevice.Get(),
00248         m_d2dFactory.Get(),
00249         m_dwriteFactory.Get(),
00250         m_d2dContext.Get()
00251         );
00252
00253     MeshObject^ cylinderMesh = ref new CylinderMesh(m_d3dDevice.Get(), 26);
00254     MeshObject^ targetMesh = ref new FaceMesh(m_d3dDevice.Get());
00255     MeshObject^ sphereMesh = ref new SphereMesh(m_d3dDevice.Get(), 26);
00256
00257     Material^ cylinderMaterial = ref new Material(
00258         XMFLOAT4(0.8f, 0.8f, 0.8f, .5f),
00259         XMFLOAT4(0.8f, 0.8f, 0.8f, .5f),
00260         XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f),
00261         15.0f,
00262         m_cylinderTexture.Get(),
00263         m_vertexShader.Get(),
00264         m_pixelShader.Get()
00265         );
00266
00267     Material^ sphereMaterial = ref new Material(
00268         XMFLOAT4(0.8f, 0.4f, 0.0f, 1.0f),
00269         XMFLOAT4(0.8f, 0.4f, 0.0f, 1.0f),
00270         XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f),
00271         50.0f,
00272         m_sphereTexture.Get(),
00273         m_vertexShader.Get(),
00274         m_pixelShader.Get()
00275         );
00276
00277     auto objects = m_game->RenderObjects();
00278
00279     // Attach the textures to the appropriate game objects.
00280     for (auto object = objects.begin(); object != objects.end(); object++)
00281     {
00282         if ((*object)->TargetId() == GameConstants::WorldFloorId)
00283         {
00284             (*object)->NormalMaterial(
00285                 ref new Material(
00286                     XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f),
00287                     XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f),
00288                     XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f),
00289                     150.0f,
00290                     m_floorTexture.Get(),
00291                     m_vertexShaderFlat.Get(),
00292                     m_pixelShaderFlat.Get()
00293                     )
00294                 );
00295             (*object)->Mesh(ref new WorldFloorMesh(m_d3dDevice.Get()));
00296         }
00297         else if ((*object)->TargetId() == GameConstants::WorldCeilingId)
00298         {
00299             (*object)->NormalMaterial(
00300                 ref new Material(
00301                     XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f),
00302                     XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f),
00303                     XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f),
00304                     150.0f,
00305                     m_ceilingTexture.Get(),
00306                     m_vertexShaderFlat.Get(),
00307                     m_pixelShaderFlat.Get()
00308                     )
00309                 );
00310             (*object)->Mesh(ref new WorldCeilingMesh(m_d3dDevice.Get()));
00311         }
00312         else if ((*object)->TargetId() == GameConstants::WorldWallsId)
00313         {
00314             (*object)->NormalMaterial(
00315                 ref new Material(
00316                     XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f),
00317                     XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f),
00318                     XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f),
00319                     150.0f,
00320                     m_wallsTexture.Get(),
00321                     m_vertexShaderFlat.Get(),
00322                     m_pixelShaderFlat.Get()
00323                     )
00324                 );
00325             (*object)->Mesh(ref new WorldWallsMesh(m_d3dDevice.Get()));
00326         }
00327         else if (Cylinder^ cylinder = dynamic_cast<Cylinder^>(*object))
00328         {
00329             cylinder->Mesh(cylinderMesh);
00330             cylinder->NormalMaterial(cylinderMaterial);
00331         }
00332         else if (Face^ target = dynamic_cast<Face^>(*object))
00333         {
00334             const int bufferLength = 16;
00335             char16 str[bufferLength];
00336             int len = swprintf_s(str, bufferLength, L"%d", target->TargetId());
00337             Platform::String^ string = ref new Platform::String(str, len);
00338
00339             ComPtr<ID3D11ShaderResourceView> texture;
00340             textureGenerator->CreateTextureResourceView(string, &texture);
00341             target->NormalMaterial(
00342                 ref new Material(
00343                     XMFLOAT4(0.8f, 0.8f, 0.8f, 0.5f),
00344                     XMFLOAT4(0.8f, 0.8f, 0.8f, 0.5f),
00345                     XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f),
00346                     5.0f,
00347                     texture.Get(),
00348                     m_vertexShader.Get(),
00349                     m_pixelShader.Get()
00350                     )
00351                 );
00352
00353             textureGenerator->CreateHitTextureResourceView(string, &texture);
00354             target->HitMaterial(
00355                 ref new 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             target->Mesh(targetMesh);
00367         }
00368         else if (Sphere^ sphere = dynamic_cast<Sphere^>(*object))
00369         {
00370             sphere->Mesh(sphereMesh);
00371             sphere->NormalMaterial(sphereMaterial);
00372         }
00373     }
00374
00375     // Ensure that the camera has been initialized with the right Projection
00376     // matrix.  The camera is not created at the time the first window resize event
00377     // occurs.
00378     m_game->GameCamera()->SetProjParams(
00379         XM_PI / 2,
00380         m_renderTargetSize.Width / m_renderTargetSize.Height,
00381         0.01f,
00382         100.0f
00383         );
00384
00385     // Make sure that Projection matrix has been set in the constant buffer
00386     // now that all the resources are loaded.
00387     // DirectXBase is handling screen rotations directly to eliminate an unaligned
00388     // fullscreen copy.  As a result, it is necessary to post multiply the rotationTransform3D
00389     // matrix to the camera projection matrix.
00390     // The matrices are transposed due to the shader code expecting the matrices in the opposite
00391     // row/column order from the DirectX math library.
00392     ConstantBufferChangeOnResize changesOnResize;
00393     XMStoreFloat4x4(
00394         &changesOnResize.projection,
00395         XMMatrixMultiply(
00396             XMMatrixTranspose(m_game->GameCamera()->Projection()),
00397             XMMatrixTranspose(XMLoadFloat4x4(&m_rotationTransform3D))
00398             )
00399         );
00400
00401     m_d3dContext->UpdateSubresource(
00402         m_constantBufferChangeOnResize.Get(),
00403         0,
00404         nullptr,
00405         &changesOnResize,
00406         0,
00407         0
00408         );
00409
00410     m_gameResourcesLoaded = true;
00411 }
00412
00413 //----------------------------------------------------------------------
00414
00415 task<void> GameRenderer::LoadLevelResourcesAsync()
00416 {
00417     m_levelResourcesLoaded = false;
00418
00419     return create_task([this]()
00420     {
00421         // This is where additional async loading of level specific resources
00422         // would be done.  Since there aren't any to load, just simulate
00423         // by delaying for some time.
00424         wait(GameConstants::LevelLoadingDelay);
00425     });
00426 }
00427
00428 //----------------------------------------------------------------------
00429
00430 void GameRenderer::FinalizeLoadLevelResources()
00431 {
00432     // Once the level specific resources had been loaded, this method is
00433     // where D3D context specific actions would be handled.  This method
00434     // runs in the same thread context as the GameRenderer was created.
00435
00436     m_levelResourcesLoaded = true;
00437 }
00438
00439 //----------------------------------------------------------------------
00440
00441 void GameRenderer::Render()
00442 {
00443     int renderingPasses = 1;
00444     if (m_stereoEnabled)
00445     {
00446         renderingPasses = 2;
00447     }
00448
00449     for (int i = 0; i < renderingPasses; i++)
00450     {
00451         // Iterate through the number of rendering passes to be completed.
00452         if (m_stereoEnabled && i > 0)
00453         {
00454             // Doing the Right Eye View.
00455             m_d3dContext->OMSetRenderTargets(1, m_d3dRenderTargetViewRight.GetAddressOf(), m_d3dDepthStencilView.Get());
00456             m_d3dContext->ClearDepthStencilView(m_d3dDepthStencilView.Get(), D3D11_CLEAR_DEPTH, 1.0f, 0);
00457             m_d2dContext->SetTarget(m_d2dTargetBitmapRight.Get());
00458         }
00459         else
00460         {
00461             // Doing the Mono or Left Eye View.
00462             m_d3dContext->OMSetRenderTargets(1, m_d3dRenderTargetView.GetAddressOf(), m_d3dDepthStencilView.Get());
00463             m_d3dContext->ClearDepthStencilView(m_d3dDepthStencilView.Get(), D3D11_CLEAR_DEPTH, 1.0f, 0);
00464             m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00465         }
00466
00467         if (m_game != nullptr && m_gameResourcesLoaded && m_levelResourcesLoaded)
00468         {
00469             // This section is only used after the game state has been initialized and all device
00470             // resources needed for the game have been created and associated with the game objects.
00471             if (m_stereoEnabled)
00472             {
00473                 // When doing stereo, it is necessary to update the projection matrix once per rendering pass.
00474                 ConstantBufferChangeOnResize changesOnResize;
00475                 XMStoreFloat4x4(
00476                     &changesOnResize.projection,
00477                     XMMatrixMultiply(
00478                         XMMatrixTranspose(
00479                             i == 0 ?
00480                             m_game->GameCamera()->LeftEyeProjection() :
00481                             m_game->GameCamera()->RightEyeProjection()
00482                             ),
00483                         XMMatrixTranspose(XMLoadFloat4x4(&m_rotationTransform3D))
00484                         )
00485                     );
00486
00487                 m_d3dContext->UpdateSubresource(
00488                     m_constantBufferChangeOnResize.Get(),
00489                     0,
00490                     nullptr,
00491                     &changesOnResize,
00492                     0,
00493                     0
00494                     );
00495             }
00496             // Update variables that change once per frame.
00497
00498             ConstantBufferChangesEveryFrame constantBufferChangesEveryFrame;
00499             XMStoreFloat4x4(
00500                 &constantBufferChangesEveryFrame.view,
00501                 XMMatrixTranspose(m_game->GameCamera()->View())
00502                 );
00503             m_d3dContext->UpdateSubresource(
00504                 m_constantBufferChangesEveryFrame.Get(),
00505                 0,
00506                 nullptr,
00507                 &constantBufferChangesEveryFrame,
00508                 0,
00509                 0
00510                 );
00511
00512             // Setup the graphics pipeline. This sample uses the same InputLayout and set of
00513             // constant buffers for all shaders, so they only need to be set once per frame.
00514
00515             m_d3dContext->IASetInputLayout(m_vertexLayout.Get());
00516             m_d3dContext->VSSetConstantBuffers(0, 1, m_constantBufferNeverChanges.GetAddressOf());
00517             m_d3dContext->VSSetConstantBuffers(1, 1, m_constantBufferChangeOnResize.GetAddressOf());
00518             m_d3dContext->VSSetConstantBuffers(2, 1, m_constantBufferChangesEveryFrame.GetAddressOf());
00519             m_d3dContext->VSSetConstantBuffers(3, 1, m_constantBufferChangesEveryPrim.GetAddressOf());
00520
00521             m_d3dContext->PSSetConstantBuffers(2, 1, m_constantBufferChangesEveryFrame.GetAddressOf());
00522             m_d3dContext->PSSetConstantBuffers(3, 1, m_constantBufferChangesEveryPrim.GetAddressOf());
00523             m_d3dContext->PSSetSamplers(0, 1, m_samplerLinear.GetAddressOf());
00524
00525             auto objects = m_game->RenderObjects();
00526             for (auto object = objects.begin(); object != objects.end(); object++)
00527             {
00528                 (*object)->Render(m_d3dContext.Get(), m_constantBufferChangesEveryPrim.Get());
00529             }
00530         }
00531         else
00532         {
00533             const float ClearColor[4] = {0.1f, 0.1f, 0.1f, 1.0f};
00534
00535             // Only need to clear the background when not rendering the full 3D scene since
00536             // the 3D world is a fully enclosed box and the dynamics prevents the camera from
00537             // moving outside this space.
00538             if (m_stereoEnabled && i > 0)
00539             {
00540                 // Doing the Right Eye View.
00541                 m_d3dContext->ClearRenderTargetView(m_d3dRenderTargetViewRight.Get(), ClearColor);
00542             }
00543             else
00544             {
00545                 // Doing the Mono or Left Eye View.
00546                 m_d3dContext->ClearRenderTargetView(m_d3dRenderTargetView.Get(), ClearColor);
00547             }
00548         }
00549
00550         m_d2dContext->BeginDraw();
00551
00552         // To handle the swapchain being pre-rotated, set the D2D transformation to include it.
00553         m_d2dContext->SetTransform(m_rotationTransform2D);
00554
00555         if (m_game != nullptr && m_gameResourcesLoaded)
00556         {
00557             // This is only used after the game state has been initialized.
00558             m_gameHud->Render(m_game, m_d2dContext.Get(), m_windowBounds);
00559         }
00560
00561         if (m_gameInfoOverlay->Visible())
00562         {
00563             m_d2dContext->DrawBitmap(
00564                 m_gameInfoOverlay->Bitmap(),
00565                 D2D1::RectF(
00566                     (m_windowBounds.Width - GameInfoOverlayConstant::Width)/2.0f,
00567                     (m_windowBounds.Height - GameInfoOverlayConstant::Height)/2.0f,
00568                     (m_windowBounds.Width - GameInfoOverlayConstant::Width)/2.0f + GameInfoOverlayConstant::Width,
00569                     (m_windowBounds.Height - GameInfoOverlayConstant::Height)/2.0f + GameInfoOverlayConstant::Height
00570                     )
00571                 );
00572         }
00573
00574         // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00575         // is lost. It will be handled during the next call to Present.
00576         HRESULT hr = m_d2dContext->EndDraw();
00577         if (hr != D2DERR_RECREATE_TARGET)
00578         {
00579             DX::ThrowIfFailed(hr);
00580         }
00581     }
00582     Present();
00583 }
00584
00585 //----------------------------------------------------------------------
00586
00587 #if defined(_DEBUG)
00588 void GameRenderer::ReportLiveDeviceObjects()
00589 {
00590     // If the debug layer isn't present on the system then this QI will fail.  In that case
00591     // the routine just exits.   This is a debugging aid to see the active D3D objects and
00592     // is not critical to functional operation of the sample.
00593
00594     ComPtr<ID3D11Debug> debugLayer;
00595     HRESULT hr = m_d3dDevice.As(&debugLayer);
00596     if (FAILED(hr))
00597     {
00598         return;
00599     }
00600     DX::ThrowIfFailed(
00601         debugLayer->ReportLiveDeviceObjects(D3D11_RLDO_DETAIL)
00602         );
00603 }
00604
00605 //----------------------------------------------------------------------
00606
00607 #endif
00608
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Touch keyboard text input/C++/common/suspensionmanager.cpp Source File

  • Input Touch keyboard text input
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:36 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D geometry realization/C++/GeometryRealizationPackage.h Source File

  • Direct2D geometry realization

GeometryRealizationPackage.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 <d2d1_1.h>
00011
00012 #ifndef REALIZATIONS_DECLARE_INTERFACE
00013 #define REALIZATIONS_DECLARE_INTERFACE(X) DECLSPEC_UUID(X) DECLSPEC_NOVTABLE
00014 #endif
00015
00016 typedef enum REALIZATION_CREATION_OPTIONS
00017 {
00018     //
00019     // Generate mesh
00020     //
00021     REALIZATION_CREATION_OPTIONS_ALIASED = 1,
00022
00023     //
00024     // Generate opacity mask
00025     //
00026     REALIZATION_CREATION_OPTIONS_ANTI_ALIASED = 2,
00027
00028     //
00029     // Retain pointer to original geometry for unrealized rendering
00030     //
00031     REALIZATION_CREATION_OPTIONS_UNREALIZED = 4,
00032
00033     //
00034     // Generate fill realization
00035     //
00036     REALIZATION_CREATION_OPTIONS_FILLED = 8,
00037
00038     //
00039     // Generate stroke realization
00040     //
00041     REALIZATION_CREATION_OPTIONS_STROKED = 16
00042 } REALIZATION_CREATION_OPTIONS;
00043
00044 typedef enum REALIZATION_RENDER_MODE
00045 {
00046     //
00047     // Force the use of the realization
00048     //
00049     REALIZATION_RENDER_MODE_FORCE_REALIZED = 0,
00050
00051     //
00052     // Force the use of the original geometry
00053     //
00054     REALIZATION_RENDER_MODE_FORCE_UNREALIZED = 1,
00055
00056     //
00057     // Key off of the render-target to decide:
00058     //  SW: Unrealized
00059     //  HW: Realized
00060     //
00061     REALIZATION_RENDER_MODE_DEFAULT = 2
00062
00063 } REALIZATION_RENDER_MODE;
00064
00065
00066 //+-----------------------------------------------------------------------------
00067 //
00068 //  Interface:
00069 //      IGeometryRealization
00070 //
00071 //  Description:
00072 //      Encapsulates various mesh and/or opacity mask instances to provide
00073 //      efficient rendering of complex primitives.
00074 //
00075 //------------------------------------------------------------------------------
00076 interface REALIZATIONS_DECLARE_INTERFACE("a0b504a9-be04-44a7-ae05-71ac89c1b6a7") IGeometryRealization : public IUnknown
00077 {
00078     //
00079     // Render the fill realization to the render target
00080     //
00081     STDMETHOD(Fill)(
00082         ID2D1DeviceContext *deviceContext,
00083         ID2D1Brush *brush,
00084         REALIZATION_RENDER_MODE mode
00085         ) PURE;
00086
00087     //
00088     // Render the stroke realization to the render target
00089     //
00090     STDMETHOD(Draw)(
00091         ID2D1DeviceContext *deviceContext,
00092         ID2D1Brush *brush,
00093         REALIZATION_RENDER_MODE mode
00094         ) PURE;
00095
00096     //
00097     // Discard the current realization's contents and replace with new contents.
00098     //
00099     // Note: This method will attempt to reuse the existing bitmaps (but will
00100     // replace the bitmaps if they aren't large enough). Since the cost of
00101     // destroying a texture can be surprisingly astronomical, using this method
00102     // can be substantially more performant than recreating a new realization
00103     // every time.
00104     //
00105     // Note: pWorldTransform is the transform that the realization will
00106     // be optimized for. If, at the time of rendering, the render target's
00107     // transform is the same as pWorldTransform,
00108     // the realization will appear identical to the unrealized version. Otherwise,
00109     // quality will be degraded.
00110     //
00111     STDMETHOD(Update)(
00112         ID2D1Geometry *geometry,
00113         REALIZATION_CREATION_OPTIONS options,
00114         CONST D2D1_MATRIX_3X2_F *worldTransform,
00115         float strokeWidth,
00116         ID2D1StrokeStyle *strokeStyle
00117         ) PURE;
00118 };
00119
00120
00121 //+-----------------------------------------------------------------------------
00122 //
00123 //  Interface:
00124 //      IGeometryRealizationFactory
00125 //
00126 //------------------------------------------------------------------------------
00127 interface REALIZATIONS_DECLARE_INTERFACE("27866d9f-8865-461d-8a10-2531156398b2") IGeometryRealizationFactory : public IUnknown
00128 {
00129     //
00130     // Create a realization object with no content (should be populated with
00131     // Update() before use).
00132     //
00133     STDMETHOD(CreateGeometryRealization)(
00134         IGeometryRealization **realization
00135         ) PURE;
00136
00137     //
00138     // Create a geometry realization.
00139     //
00140     // Note: Here, pWorldTransform is the transform that the realization will
00141     // be optimized for. If, at the time of rendering, the render target's
00142     // transform is the same as the pWorldTransform passed in here then
00143     // the realization will look identical to the unrealized version. Otherwise,
00144     // quality will be degraded.
00145     //
00146     STDMETHOD(CreateGeometryRealization)(
00147         ID2D1Geometry *geometry,
00148         REALIZATION_CREATION_OPTIONS options,
00149         CONST D2D1_MATRIX_3X2_F *worldTransform,
00150         float strokeWidth,
00151         ID2D1StrokeStyle *strokeStyle,
00152         IGeometryRealization **realization
00153         ) PURE;
00154 };
00155
00156 //+-----------------------------------------------------------------------------
00157 //
00158 //  Function:
00159 //      CreateGeometryRealizationFactory
00160 //
00161 //------------------------------------------------------------------------------
00162 HRESULT CreateGeometryRealizationFactory(
00163     ID2D1DeviceContext *deviceContext,
00164     UINT maxRealizationDimension,
00165     IGeometryRealizationFactory **factory
00166     );
00167
00168 HRESULT CreateGeometryRealizationFactory(
00169     ID2D1DeviceContext *deviceContext,
00170     IGeometryRealizationFactory **factory
00171     );
Generated on Sat Nov 23 2024 16:08:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML personality animations/C++/Page2.xaml.h Source File

  • XAML personality animations

Page2.xaml.h

Go to the documentation of this file.
00001 ﻿//
00002 // Page2.xaml.h
00003 // Declaration of the Page2 class
00004 //
00005
00006 #pragma once
00007
00008 #include "Page2.g.h"
00009 #include "SampleData/SampleDataSource.h"
00010
00011 using namespace SDKSample::ExpressionBlendSampleDataSampleDataSource;
00012
00013 namespace SDKSample
00014 {
00015 namespace PersonalityAnimations
00016 {
00017   /// <summary>
00018   /// An empty page that can be used on its own or navigated to within a Frame.
00019   /// </summary>
00020   public ref class Page2 sealed
00021   {
00022   public:
00023     Page2();
00024
00025   protected:
00026     virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00027
00028   private:
00029     MessageData^ messageData;
00030   };
00031 }
00032 }
Generated on Sat Nov 23 2024 16:08:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::FileThumbnails::sealed Member List

This is the complete list of members for SDKSample::FileThumbnails::sealed, including all inherited members.
GetThumbnailButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::FileThumbnails::sealed | [private]
GetThumbnailButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::FileThumbnails::sealed | [private]
GetThumbnailButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::FileThumbnails::sealed | [private]
GetThumbnailButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::FileThumbnails::sealed | [private]
GetThumbnailButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::FileThumbnails::sealed | [private]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::FileThumbnails::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::FileThumbnails::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::FileThumbnails::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::FileThumbnails::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::FileThumbnails::sealed | [protected, virtual]
rootPage | SDKSample::FileThumbnails::sealed | [private]
Scenario1() | SDKSample::FileThumbnails::sealed |
Scenario2() | SDKSample::FileThumbnails::sealed |
Scenario3() | SDKSample::FileThumbnails::sealed |
Scenario4() | SDKSample::FileThumbnails::sealed |
Scenario5() | SDKSample::FileThumbnails::sealed |
Generated on Sat Nov 23 2024 16:09:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/ImageNavigationData.cpp Source File

  • Hilo C++
  • Hilo

ImageNavigationData.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 #include "ImageNavigationData.h"
00009 #include "IPhoto.h"
00010 #include "CalendarExtensions.h"
00011
00012
00013 using namespace Hilo;
00014 using namespace Platform;
00015 using namespace std;
00016 using namespace Windows::Foundation;
00017
00018
00019 ImageNavigationData::ImageNavigationData(IPhoto^ photo)
00020 {
00021     m_fileDate = photo->DateTaken;
00022     m_filePath = photo->Path;
00023 }
00024
00025 ImageNavigationData::ImageNavigationData(String^ serializedData)
00026 {
00027     wstring data(serializedData->Data());
00028     auto index = data.find('|');
00029     assert(index > 0);
00030
00031     auto path = data.substr(0, index);
00032     auto date = data.substr(index+1, data.length());
00033     DateTime fileDate;
00034     fileDate.UniversalTime = _wtoi64(date.c_str());
00035
00036     m_filePath = ref new String(path.c_str());
00037     m_fileDate = fileDate;
00038 }
00039
00040 DateTime ImageNavigationData::GetFileDate() const
00041 {
00042     return m_fileDate;
00043 }
00044
00045 String^ ImageNavigationData::GetFilePath() const
00046 {
00047     return m_filePath;
00048 }
00049
00050 String^ ImageNavigationData::GetDateQuery()
00051 {
00052     if (nullptr == m_dateQuery)
00053     {
00054         m_dateQuery = CalendarExtensions::CreateMonthRangeFromDate(m_fileDate);
00055     }
00056     return m_dateQuery;
00057 }
00058
00059 String^ ImageNavigationData::SerializeToString()
00060 {
00061     wstringstream stringStream;
00062     stringStream << m_filePath->Data() << L"|" << m_fileDate.UniversalTime ;
00063     return ref new String(stringStream.str().c_str());
00064 }
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CryptoWinRT/C++/Scenario9.xaml.cpp Source File

  • CryptoWinRT

Scenario9.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 // Scenario9.xaml.cpp
00013 // Implementation of the Scenario9 class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario9.xaml.h"
00018
00019 using namespace SDKSample::CryptoWinRT;
00020
00021 using namespace concurrency;
00022 using namespace Platform;
00023 using namespace Windows::Foundation;
00024 using namespace Windows::Security::Cryptography;
00025 using namespace Windows::Security::Cryptography::Core;
00026 using namespace Windows::Security::Cryptography::DataProtection;
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 Scenario9::Scenario9()
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 Scenario9::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 SDKSample::CryptoWinRT::Scenario9::RunSample_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00050 {
00051     Scenario9Text->Text = "";
00052     String^ descriptor = tbDescriptor->Text;
00053
00054     Scenario9Text->Text += "*** Sample Data Protection for " + descriptor + " ***\n";
00055
00056     DataProtectionProvider^ Provider = ref new DataProtectionProvider(descriptor);
00057     Scenario9Text->Text += "    DataProtectionProvider is Ready\n";
00058
00059     // Create random data for protection
00060     IBuffer^ data = CryptographicBuffer::GenerateRandom(73);
00061     Scenario9Text->Text += "    Original Data: " + CryptographicBuffer::EncodeToHexString(data) + "\n";
00062
00063     // Protect the random data
00064     create_task(Provider->ProtectAsync(data)).then([=](task<IBuffer ^> protectedDataTask)
00065     {
00066         IBuffer ^ protectedData;
00067         Scenario9Text->Text += "    ProtectAsync completed\n";
00068         protectedData = protectedDataTask.get();
00069         Scenario9Text->Text += "    Protected Data: " + CryptographicBuffer::EncodeToHexString(protectedData) + "\n";
00070
00071         if(protectedData==nullptr)
00072         {
00073             Scenario9Text->Text += "    ProtectedData is a nullptr\n";
00074             return;
00075         }
00076         else
00077         {
00078             DataProtectionProvider ^ testProvider2 = ref new DataProtectionProvider();
00079             Scenario9Text->Text += "    Starting UnprotectAsync()\n";
00080
00081             create_task(testProvider2->UnprotectAsync(protectedData)).then([=](task<IBuffer^> unprotectTask)
00082             {
00083                 IBuffer ^ data2 = unprotectTask.get();
00084
00085                 Scenario9Text->Text += "    Data protected and unprotected\n";
00086
00087                 if(data2==nullptr)
00088                 {
00089                     Scenario9Text->Text += "    UnprotectAsync failed!\n";
00090                     return;
00091                 }
00092                 else if(!CryptographicBuffer::Compare(data, data2))
00093                 {
00094                     Scenario9Text->Text += "    UnprotectAsync returned invalid data\n";
00095                     return;
00096                 }
00097                 Scenario9Text->Text += "    UnprotectAsync completed successfully\n";
00098                 Scenario9Text->Text += "    Unprotected Data: " + CryptographicBuffer::EncodeToHexString(data2) + "\n";
00099             });
00100         }
00101     });
00102 }
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX touch input/C++/BasicShapes.cpp Source File

  • DirectX touch input

BasicShapes.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 #pragma once
00009
00010 #include "pch.h"
00011 #include "BasicShapes.h"
00012 #include "DirectXSample.h"
00013 #include <memory>
00014
00015 BasicShapes::BasicShapes(ID3D11Device *d3dDevice) : m_d3dDevice(d3dDevice)
00016 {
00017 }
00018
00019 void BasicShapes::CreateVertexBuffer(
00020     _In_ unsigned int numVertices,
00021     _In_ BasicVertex *vertexData,
00022     _Out_ ID3D11Buffer **vertexBuffer
00023     )
00024 {
00025     *vertexBuffer = nullptr;
00026     Microsoft::WRL::ComPtr<ID3D11Buffer> vertexBufferInternal;
00027
00028     D3D11_BUFFER_DESC VertexBufferDesc;
00029     VertexBufferDesc.ByteWidth = sizeof(BasicVertex) * numVertices;
00030     VertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
00031     VertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
00032     VertexBufferDesc.CPUAccessFlags = 0;
00033     VertexBufferDesc.MiscFlags = 0;
00034     VertexBufferDesc.StructureByteStride = 0;
00035
00036     D3D11_SUBRESOURCE_DATA VertexBufferData;
00037     VertexBufferData.pSysMem = vertexData;
00038     VertexBufferData.SysMemPitch = 0;
00039     VertexBufferData.SysMemSlicePitch = 0;
00040
00041     DX::ThrowIfFailed(
00042         m_d3dDevice->CreateBuffer(
00043             &VertexBufferDesc,
00044             &VertexBufferData,
00045             &vertexBufferInternal
00046             )
00047         );
00048
00049
00050     *vertexBuffer = vertexBufferInternal.Detach();
00051 }
00052
00053 void BasicShapes::CreateIndexBuffer(
00054     _In_ unsigned int numIndices,
00055     _In_ unsigned short *indexData,
00056     _Out_ ID3D11Buffer **indexBuffer
00057     )
00058 {
00059     *indexBuffer = nullptr;
00060     Microsoft::WRL::ComPtr<ID3D11Buffer> indexBufferInternal;
00061
00062     D3D11_BUFFER_DESC IndexBufferDesc;
00063     IndexBufferDesc.ByteWidth = sizeof(unsigned short) * numIndices;
00064     IndexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
00065     IndexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
00066     IndexBufferDesc.CPUAccessFlags = 0;
00067     IndexBufferDesc.MiscFlags = 0;
00068     IndexBufferDesc.StructureByteStride = 0;
00069
00070     D3D11_SUBRESOURCE_DATA IndexBufferData;
00071     IndexBufferData.pSysMem = indexData;
00072     IndexBufferData.SysMemPitch = 0;
00073     IndexBufferData.SysMemSlicePitch = 0;
00074
00075     DX::ThrowIfFailed(
00076         m_d3dDevice->CreateBuffer(
00077             &IndexBufferDesc,
00078             &IndexBufferData,
00079             &indexBufferInternal
00080             )
00081         );
00082
00083     *indexBuffer = indexBufferInternal.Detach();
00084 }
00085
00086 void BasicShapes::CreateTangentVertexBuffer(
00087     _In_ unsigned int numVertices,
00088     _In_ TangentVertex *vertexData,
00089     _Out_ ID3D11Buffer **vertexBuffer
00090     )
00091 {
00092     *vertexBuffer = nullptr;
00093     Microsoft::WRL::ComPtr<ID3D11Buffer> vertexBufferInternal;
00094
00095     D3D11_BUFFER_DESC VertexBufferDesc;
00096     VertexBufferDesc.ByteWidth = sizeof(TangentVertex) * numVertices;
00097     VertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
00098     VertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
00099     VertexBufferDesc.CPUAccessFlags = 0;
00100     VertexBufferDesc.MiscFlags = 0;
00101     VertexBufferDesc.StructureByteStride = 0;
00102
00103     D3D11_SUBRESOURCE_DATA VertexBufferData;
00104     VertexBufferData.pSysMem = vertexData;
00105     VertexBufferData.SysMemPitch = 0;
00106     VertexBufferData.SysMemSlicePitch = 0;
00107
00108     DX::ThrowIfFailed(
00109         m_d3dDevice->CreateBuffer(
00110             &VertexBufferDesc,
00111             &VertexBufferData,
00112             &vertexBufferInternal
00113             )
00114         );
00115
00116
00117     *vertexBuffer = vertexBufferInternal.Detach();
00118 }
00119
00120 void BasicShapes::CreateCube(
00121     _Out_ ID3D11Buffer **vertexBuffer,
00122     _Out_ ID3D11Buffer **indexBuffer,
00123     _Out_opt_ unsigned int *vertexCount,
00124     _Out_opt_ unsigned int *indexCount
00125     )
00126 {
00127     BasicVertex cubeVertices[] =
00128     {
00129         { float3(-0.5f, 0.5f, -0.5f), float3(0.0f, 1.0f, 0.0f), float2(0.0f, 0.0f) }, // +Y (top face)
00130         { float3( 0.5f, 0.5f, -0.5f), float3(0.0f, 1.0f, 0.0f), float2(1.0f, 0.0f) },
00131         { float3( 0.5f, 0.5f,  0.5f), float3(0.0f, 1.0f, 0.0f), float2(1.0f, 1.0f) },
00132         { float3(-0.5f, 0.5f,  0.5f), float3(0.0f, 1.0f, 0.0f), float2(0.0f, 1.0f) },
00133
00134         { float3(-0.5f, -0.5f,  0.5f), float3(0.0f, -1.0f, 0.0f), float2(0.0f, 0.0f) }, // -Y (bottom face)
00135         { float3( 0.5f, -0.5f,  0.5f), float3(0.0f, -1.0f, 0.0f), float2(1.0f, 0.0f) },
00136         { float3 (0.5f, -0.5f, -0.5f), float3(0.0f, -1.0f, 0.0f), float2(1.0f, 1.0f) },
00137         { float3(-0.5f, -0.5f, -0.5f), float3(0.0f, -1.0f, 0.0f), float2(0.0f, 1.0f) },
00138
00139         { float3(0.5f,  0.5f,  0.5f), float3(1.0f, 0.0f, 0.0f), float2(0.0f, 0.0f) }, // +X (right face)
00140         { float3(0.5f,  0.5f, -0.5f), float3(1.0f, 0.0f, 0.0f), float2(1.0f, 0.0f) },
00141         { float3(0.5f, -0.5f, -0.5f), float3(1.0f, 0.0f, 0.0f), float2(1.0f, 1.0f) },
00142         { float3(0.5f, -0.5f,  0.5f), float3(1.0f, 0.0f, 0.0f), float2(0.0f, 1.0f) },
00143
00144         { float3(-0.5f,  0.5f, -0.5f), float3(-1.0f, 0.0f, 0.0f), float2(0.0f, 0.0f) }, // -X (left face)
00145         { float3(-0.5f,  0.5f,  0.5f), float3(-1.0f, 0.0f, 0.0f), float2(1.0f, 0.0f) },
00146         { float3(-0.5f, -0.5f,  0.5f), float3(-1.0f, 0.0f, 0.0f), float2(1.0f, 1.0f) },
00147         { float3(-0.5f, -0.5f, -0.5f), float3(-1.0f, 0.0f, 0.0f), float2(0.0f, 1.0f) },
00148
00149         { float3(-0.5f,  0.5f, 0.5f), float3(0.0f, 0.0f, 1.0f), float2(0.0f, 0.0f) }, // +Z (front face)
00150         { float3( 0.5f,  0.5f, 0.5f), float3(0.0f, 0.0f, 1.0f), float2(1.0f, 0.0f) },
00151         { float3( 0.5f, -0.5f, 0.5f), float3(0.0f, 0.0f, 1.0f), float2(1.0f, 1.0f) },
00152         { float3(-0.5f, -0.5f, 0.5f), float3(0.0f, 0.0f, 1.0f), float2(0.0f, 1.0f) },
00153
00154         { float3( 0.5f,  0.5f, -0.5f), float3(0.0f, 0.0f, -1.0f), float2(0.0f, 0.0f) }, // -Z (back face)
00155         { float3(-0.5f,  0.5f, -0.5f), float3(0.0f, 0.0f, -1.0f), float2(1.0f, 0.0f) },
00156         { float3(-0.5f, -0.5f, -0.5f), float3(0.0f, 0.0f, -1.0f), float2(1.0f, 1.0f) },
00157         { float3( 0.5f, -0.5f, -0.5f), float3(0.0f, 0.0f, -1.0f), float2(0.0f, 1.0f) },
00158     };
00159
00160     unsigned short cubeIndices[] =
00161     {
00162         0, 1, 2,
00163         0, 2, 3,
00164
00165         4, 5, 6,
00166         4, 6, 7,
00167
00168         8, 9, 10,
00169         8, 10, 11,
00170
00171         12, 13, 14,
00172         12, 14, 15,
00173
00174         16, 17, 18,
00175         16, 18, 19,
00176
00177         20, 21, 22,
00178         20, 22, 23
00179     };
00180
00181     CreateVertexBuffer(
00182         ARRAYSIZE(cubeVertices),
00183         cubeVertices,
00184         vertexBuffer
00185         );
00186     if (vertexCount != nullptr)
00187     {
00188         *vertexCount = ARRAYSIZE(cubeVertices);
00189     }
00190
00191     CreateIndexBuffer(
00192         ARRAYSIZE(cubeIndices),
00193         cubeIndices,
00194         indexBuffer
00195         );
00196     if (indexCount != nullptr)
00197     {
00198         *indexCount = ARRAYSIZE(cubeIndices);
00199     }
00200 }
00201
00202 void BasicShapes::CreateBox(
00203     float3 r,
00204     _Out_ ID3D11Buffer **vertexBuffer,
00205     _Out_ ID3D11Buffer **indexBuffer,
00206     _Out_opt_ unsigned int *vertexCount,
00207     _Out_opt_ unsigned int *indexCount
00208     )
00209 {
00210     BasicVertex boxVertices[] =
00211     {
00212         // FLOOR
00213         {float3(-r.x, -r.y,  r.z), float3(0.0f, 1.0f, 0.0f), float2(0.0f, 0.0f)},
00214         {float3( r.x, -r.y,  r.z), float3(0.0f, 1.0f, 0.0f), float2(1.0f, 0.0f)},
00215         {float3(-r.x, -r.y, -r.z), float3(0.0f, 1.0f, 0.0f), float2(0.0f, 1.5f)},
00216         {float3( r.x, -r.y, -r.z), float3(0.0f, 1.0f, 0.0f), float2(1.0f, 1.5f)},
00217         // WALL
00218         {float3(-r.x,  r.y, r.z), float3(0.0f, 0.0f, -1.0f), float2(0.0f, 0.0f)},
00219         {float3( r.x,  r.y, r.z), float3(0.0f, 0.0f, -1.0f), float2(2.0f, 0.0f)},
00220         {float3(-r.x, -r.y, r.z), float3(0.0f, 0.0f, -1.0f), float2(0.0f, 1.5f)},
00221         {float3( r.x, -r.y, r.z), float3(0.0f, 0.0f, -1.0f), float2(2.0f, 1.5f)},
00222         // WALL
00223         {float3(r.x,  r.y,  r.z), float3(-1.0f, 0.0f, 0.0f), float2(0.0f, 0.0f)},
00224         {float3(r.x,  r.y, -r.z), float3(-1.0f, 0.0f, 0.0f), float2(r.y,  0.0f)},
00225         {float3(r.x, -r.y,  r.z), float3(-1.0f, 0.0f, 0.0f), float2(0.0f, 1.5f)},
00226         {float3(r.x, -r.y, -r.z), float3(-1.0f, 0.0f, 0.0f), float2(r.y,  1.5f)},
00227         // WALL
00228         {float3( r.x,  r.y, -r.z), float3(0.0f, 0.0f, 1.0f), float2(0.0f, 0.0f)},
00229         {float3(-r.x,  r.y, -r.z), float3(0.0f, 0.0f, 1.0f), float2(2.0f, 0.0f)},
00230         {float3( r.x, -r.y, -r.z), float3(0.0f, 0.0f, 1.0f), float2(0.0f, 1.5f)},
00231         {float3(-r.x, -r.y, -r.z), float3(0.0f, 0.0f, 1.0f), float2(2.0f, 1.5f)},
00232         // WALL
00233         {float3(-r.x,  r.y, -r.z), float3(1.0f, 0.0f, 0.0f), float2(0.0f, 0.0f)},
00234         {float3(-r.x,  r.y,  r.z), float3(1.0f, 0.0f, 0.0f), float2(r.y,  0.0f)},
00235         {float3(-r.x, -r.y, -r.z), float3(1.0f, 0.0f, 0.0f), float2(0.0f, 1.5f)},
00236         {float3(-r.x, -r.y,  r.z), float3(1.0f, 0.0f, 0.0f), float2(r.y,  1.5f)},
00237         // CEILING
00238         {float3(-r.x, r.y, -r.z), float3(0.0f, -1.0f, 0.0f), float2(-0.15f, 0.0f)},
00239         {float3( r.x, r.y, -r.z), float3(0.0f, -1.0f, 0.0f), float2( 1.25f, 0.0f)},
00240         {float3(-r.x, r.y,  r.z), float3(0.0f, -1.0f, 0.0f), float2(-0.15f, 2.1f)},
00241         {float3( r.x, r.y,  r.z), float3(0.0f, -1.0f, 0.0f), float2( 1.25f, 2.1f)},
00242     };
00243
00244     unsigned short boxIndices[] =
00245     {
00246         0, 2, 1,
00247         1, 2, 3,
00248
00249         4, 6, 5,
00250         5, 6, 7,
00251
00252         8, 10, 9,
00253         9, 10, 11,
00254
00255         12, 14, 13,
00256         13, 14, 15,
00257
00258         16, 18, 17,
00259         17, 18, 19,
00260
00261         20, 22, 21,
00262         21, 22, 23,
00263     };
00264
00265     CreateVertexBuffer(
00266         ARRAYSIZE(boxVertices),
00267         boxVertices,
00268         vertexBuffer
00269         );
00270     if (vertexCount != nullptr)
00271     {
00272         *vertexCount = ARRAYSIZE(boxVertices);
00273     }
00274
00275     CreateIndexBuffer(
00276         ARRAYSIZE(boxIndices),
00277         boxIndices,
00278         indexBuffer
00279         );
00280     if (indexCount != nullptr)
00281     {
00282         *indexCount = ARRAYSIZE(boxIndices);
00283     }
00284 }
00285
00286 void BasicShapes::CreateSphere(
00287     _Out_ ID3D11Buffer **vertexBuffer,
00288     _Out_ ID3D11Buffer **indexBuffer,
00289     _Out_opt_ unsigned int *vertexCount,
00290     _Out_opt_ unsigned int *indexCount
00291     )
00292 {
00293     const int numSegments = 64;
00294     const int numSlices = numSegments / 2;
00295
00296     const int numVertices = (numSlices + 1) * (numSegments + 1);
00297     std::unique_ptr<BasicVertex[]> sphereVertices(new BasicVertex[numVertices]);
00298
00299     for (int slice = 0; slice <= numSlices; slice++)
00300     {
00301         float v = (float)slice/(float)numSlices;
00302         float inclination = v * PI_F;
00303         float y = cos(inclination);
00304         float r = sin(inclination);
00305         for (int segment = 0; segment <= numSegments; segment++)
00306         {
00307             float u = (float)segment/(float)numSegments;
00308             float azimuth = u * PI_F * 2.0f;
00309             int index = slice * (numSegments+1) + segment;
00310             sphereVertices[index].pos = float3(r * sin(azimuth), y, r * cos(azimuth));
00311             sphereVertices[index].norm = sphereVertices[index].pos;
00312             sphereVertices[index].tex = float2(u, v);
00313         }
00314     }
00315
00316     const int numIndices = numSlices * (numSegments-2) * 6;
00317     std::unique_ptr<unsigned short[]> sphereIndices(new unsigned short[numIndices]);
00318
00319     unsigned int index = 0;
00320     for (int slice = 0; slice < numSlices; slice++)
00321     {
00322         unsigned short sliceBase0 = (unsigned short)((slice)*(numSegments+1));
00323         unsigned short sliceBase1 = (unsigned short)((slice+1)*(numSegments+1));
00324         for (int segment = 0; segment < numSegments; segment++)
00325         {
00326             if (slice > 0)
00327             {
00328                 sphereIndices[index++] = sliceBase0 + segment;
00329                 sphereIndices[index++] = sliceBase0 + segment + 1;
00330                 sphereIndices[index++] = sliceBase1 + segment + 1;
00331             }
00332             if (slice < numSlices-1)
00333             {
00334                 sphereIndices[index++] = sliceBase0 + segment;
00335                 sphereIndices[index++] = sliceBase1 + segment + 1;
00336                 sphereIndices[index++] = sliceBase1 + segment;
00337             }
00338         }
00339     }
00340
00341     CreateVertexBuffer(
00342         numVertices,
00343         sphereVertices.get(),
00344         vertexBuffer
00345         );
00346     if (vertexCount != nullptr)
00347     {
00348         *vertexCount = numVertices;
00349     }
00350
00351     CreateIndexBuffer(
00352         numIndices,
00353         sphereIndices.get(),
00354         indexBuffer
00355         );
00356     if (indexCount != nullptr)
00357     {
00358         *indexCount = numIndices;
00359     }
00360 }
00361 void BasicShapes::CreateTangentSphere(
00362     _Out_ ID3D11Buffer **vertexBuffer,
00363     _Out_ ID3D11Buffer **indexBuffer,
00364     _Out_opt_ unsigned int *vertexCount,
00365     _Out_opt_ unsigned int *indexCount
00366     )
00367 {
00368     const int numSegments = 64;
00369     const int numSlices = numSegments / 2;
00370
00371     const int numVertices = (numSlices + 1) * (numSegments + 1);
00372     std::unique_ptr<TangentVertex[]> sphereVertices(new TangentVertex[numVertices]);
00373
00374     for (int slice = 0; slice <= numSlices; slice++)
00375     {
00376         float v = (float)slice/(float)numSlices;
00377         float inclination = v * PI_F;
00378         float y = cos(inclination);
00379         float r = sin(inclination);
00380         for (int segment = 0; segment <= numSegments; segment++)
00381         {
00382             float u = (float)segment/(float)numSegments;
00383             float azimuth = u * PI_F * 2.0f;
00384             int index = slice * (numSegments+1) + segment;
00385             sphereVertices[index].pos = float3(r*sin(azimuth), y, r*cos(azimuth));
00386             sphereVertices[index].tex = float2(u, v);
00387             sphereVertices[index].uTan = float3(cos(azimuth), 0, -sin(azimuth));
00388             sphereVertices[index].vTan = float3(cos(inclination)*sin(azimuth), -sin(inclination), cos(inclination)*cos(azimuth));
00389
00390         }
00391     }
00392
00393     const int numIndices = numSlices * (numSegments-2) * 6;
00394     std::unique_ptr<unsigned short[]> sphereIndices(new unsigned short[numIndices]);
00395
00396     unsigned int index = 0;
00397     for (int slice = 0; slice < numSlices; slice++)
00398     {
00399         unsigned short sliceBase0 = (unsigned short)((slice)*(numSegments+1));
00400         unsigned short sliceBase1 = (unsigned short)((slice+1)*(numSegments+1));
00401         for (int segment = 0; segment < numSegments; segment++)
00402         {
00403             if (slice > 0)
00404             {
00405                 sphereIndices[index++] = sliceBase0 + segment;
00406                 sphereIndices[index++] = sliceBase0 + segment + 1;
00407                 sphereIndices[index++] = sliceBase1 + segment + 1;
00408             }
00409             if (slice < numSlices-1)
00410             {
00411                 sphereIndices[index++] = sliceBase0 + segment;
00412                 sphereIndices[index++] = sliceBase1 + segment + 1;
00413                 sphereIndices[index++] = sliceBase1 + segment;
00414             }
00415         }
00416     }
00417
00418     CreateTangentVertexBuffer(
00419         numVertices,
00420         sphereVertices.get(),
00421         vertexBuffer
00422         );
00423     if (vertexCount != nullptr)
00424     {
00425         *vertexCount = numVertices;
00426     }
00427
00428     CreateIndexBuffer(
00429         numIndices,
00430         sphereIndices.get(),
00431         indexBuffer
00432         );
00433     if (indexCount != nullptr)
00434     {
00435         *indexCount = numIndices;
00436     }
00437 }
00438
00439 void BasicShapes::CreateReferenceAxis(
00440     _Out_ ID3D11Buffer **vertexBuffer,
00441     _Out_ ID3D11Buffer **indexBuffer,
00442     _Out_opt_ unsigned int *vertexCount,
00443     _Out_opt_ unsigned int *indexCount
00444     )
00445 {
00446     BasicVertex axisVertices[] =
00447     {
00448         { float3( 0.500f, 0.000f, 0.000f), float3( 0.125f, 0.500f, 0.500f), float2(0.250f, 0.250f) },
00449         { float3( 0.000f, 0.125f, 0.000f), float3( 0.125f, 0.500f, 0.500f), float2(0.250f, 0.250f) },
00450         { float3( 0.000f, 0.000f, 0.125f), float3( 0.125f, 0.500f, 0.500f), float2(0.250f, 0.250f) },
00451         { float3( 0.500f, 0.000f, 0.000f), float3( 0.125f,-0.500f, 0.500f), float2(0.250f, 0.250f) },
00452         { float3( 0.000f, 0.000f, 0.125f), float3( 0.125f,-0.500f, 0.500f), float2(0.250f, 0.250f) },
00453         { float3( 0.000f,-0.125f, 0.000f), float3( 0.125f,-0.500f, 0.500f), float2(0.250f, 0.250f) },
00454         { float3( 0.500f, 0.000f, 0.000f), float3( 0.125f,-0.500f,-0.500f), float2(0.250f, 0.250f) },
00455         { float3( 0.000f,-0.125f, 0.000f), float3( 0.125f,-0.500f,-0.500f), float2(0.250f, 0.250f) },
00456         { float3( 0.000f, 0.000f,-0.125f), float3( 0.125f,-0.500f,-0.500f), float2(0.250f, 0.250f) },
00457         { float3( 0.500f, 0.000f, 0.000f), float3( 0.125f, 0.500f,-0.500f), float2(0.250f, 0.250f) },
00458         { float3( 0.000f, 0.000f,-0.125f), float3( 0.125f, 0.500f,-0.500f), float2(0.250f, 0.250f) },
00459         { float3( 0.000f, 0.125f, 0.000f), float3( 0.125f, 0.500f,-0.500f), float2(0.250f, 0.250f) },
00460         { float3( 0.000f, 0.125f, 0.000f), float3(-0.125f, 0.000f, 0.000f), float2(0.250f, 0.250f) },
00461         { float3( 0.000f, 0.000f,-0.125f), float3(-0.125f, 0.000f, 0.000f), float2(0.250f, 0.250f) },
00462         { float3( 0.000f,-0.125f, 0.000f), float3(-0.125f, 0.000f, 0.000f), float2(0.250f, 0.250f) },
00463         { float3( 0.000f, 0.000f, 0.125f), float3(-0.125f, 0.000f, 0.000f), float2(0.250f, 0.250f) },
00464         { float3(-0.500f, 0.000f, 0.000f), float3(-0.125f, 0.500f, 0.500f), float2(0.250f, 0.500f) },
00465         { float3( 0.000f, 0.000f, 0.125f), float3(-0.125f, 0.500f, 0.500f), float2(0.250f, 0.500f) },
00466         { float3( 0.000f, 0.125f, 0.000f), float3(-0.125f, 0.500f, 0.500f), float2(0.250f, 0.500f) },
00467         { float3(-0.500f, 0.000f, 0.000f), float3(-0.125f, 0.500f,-0.500f), float2(0.250f, 0.500f) },
00468         { float3( 0.000f, 0.125f, 0.000f), float3(-0.125f, 0.500f,-0.500f), float2(0.250f, 0.500f) },
00469         { float3( 0.000f, 0.000f,-0.125f), float3(-0.125f, 0.500f,-0.500f), float2(0.250f, 0.500f) },
00470         { float3(-0.500f, 0.000f, 0.000f), float3(-0.125f,-0.500f,-0.500f), float2(0.250f, 0.500f) },
00471         { float3( 0.000f, 0.000f,-0.125f), float3(-0.125f,-0.500f,-0.500f), float2(0.250f, 0.500f) },
00472         { float3( 0.000f,-0.125f, 0.000f), float3(-0.125f,-0.500f,-0.500f), float2(0.250f, 0.500f) },
00473         { float3(-0.500f, 0.000f, 0.000f), float3(-0.125f,-0.500f, 0.500f), float2(0.250f, 0.500f) },
00474         { float3( 0.000f,-0.125f, 0.000f), float3(-0.125f,-0.500f, 0.500f), float2(0.250f, 0.500f) },
00475         { float3( 0.000f, 0.000f, 0.125f), float3(-0.125f,-0.500f, 0.500f), float2(0.250f, 0.500f) },
00476         { float3( 0.000f, 0.000f, 0.125f), float3( 0.125f, 0.000f, 0.000f), float2(0.250f, 0.500f) },
00477         { float3( 0.000f,-0.125f, 0.000f), float3( 0.125f, 0.000f, 0.000f), float2(0.250f, 0.500f) },
00478         { float3( 0.000f, 0.000f,-0.125f), float3( 0.125f, 0.000f, 0.000f), float2(0.250f, 0.500f) },
00479         { float3( 0.000f, 0.125f, 0.000f), float3( 0.125f, 0.000f, 0.000f), float2(0.250f, 0.500f) },
00480         { float3( 0.000f, 0.500f, 0.000f), float3( 0.500f, 0.125f, 0.500f), float2(0.500f, 0.250f) },
00481         { float3( 0.000f, 0.000f, 0.125f), float3( 0.500f, 0.125f, 0.500f), float2(0.500f, 0.250f) },
00482         { float3( 0.125f, 0.000f, 0.000f), float3( 0.500f, 0.125f, 0.500f), float2(0.500f, 0.250f) },
00483         { float3( 0.000f, 0.500f, 0.000f), float3( 0.500f, 0.125f,-0.500f), float2(0.500f, 0.250f) },
00484         { float3( 0.125f, 0.000f, 0.000f), float3( 0.500f, 0.125f,-0.500f), float2(0.500f, 0.250f) },
00485         { float3( 0.000f, 0.000f,-0.125f), float3( 0.500f, 0.125f,-0.500f), float2(0.500f, 0.250f) },
00486         { float3( 0.000f, 0.500f, 0.000f), float3(-0.500f, 0.125f,-0.500f), float2(0.500f, 0.250f) },
00487         { float3( 0.000f, 0.000f,-0.125f), float3(-0.500f, 0.125f,-0.500f), float2(0.500f, 0.250f) },
00488         { float3(-0.125f, 0.000f, 0.000f), float3(-0.500f, 0.125f,-0.500f), float2(0.500f, 0.250f) },
00489         { float3( 0.000f, 0.500f, 0.000f), float3(-0.500f, 0.125f, 0.500f), float2(0.500f, 0.250f) },
00490         { float3(-0.125f, 0.000f, 0.000f), float3(-0.500f, 0.125f, 0.500f), float2(0.500f, 0.250f) },
00491         { float3( 0.000f, 0.000f, 0.125f), float3(-0.500f, 0.125f, 0.500f), float2(0.500f, 0.250f) },
00492         { float3( 0.125f, 0.000f, 0.000f), float3( 0.000f,-0.125f, 0.000f), float2(0.500f, 0.250f) },
00493         { float3( 0.000f, 0.000f, 0.125f), float3( 0.000f,-0.125f, 0.000f), float2(0.500f, 0.250f) },
00494         { float3(-0.125f, 0.000f, 0.000f), float3( 0.000f,-0.125f, 0.000f), float2(0.500f, 0.250f) },
00495         { float3( 0.000f, 0.000f,-0.125f), float3( 0.000f,-0.125f, 0.000f), float2(0.500f, 0.250f) },
00496         { float3( 0.000f,-0.500f, 0.000f), float3( 0.500f,-0.125f, 0.500f), float2(0.500f, 0.500f) },
00497         { float3( 0.125f, 0.000f, 0.000f), float3( 0.500f,-0.125f, 0.500f), float2(0.500f, 0.500f) },
00498         { float3( 0.000f, 0.000f, 0.125f), float3( 0.500f,-0.125f, 0.500f), float2(0.500f, 0.500f) },
00499         { float3( 0.000f,-0.500f, 0.000f), float3(-0.500f,-0.125f, 0.500f), float2(0.500f, 0.500f) },
00500         { float3( 0.000f, 0.000f, 0.125f), float3(-0.500f,-0.125f, 0.500f), float2(0.500f, 0.500f) },
00501         { float3(-0.125f, 0.000f, 0.000f), float3(-0.500f,-0.125f, 0.500f), float2(0.500f, 0.500f) },
00502         { float3( 0.000f,-0.500f, 0.000f), float3(-0.500f,-0.125f,-0.500f), float2(0.500f, 0.500f) },
00503         { float3(-0.125f, 0.000f, 0.000f), float3(-0.500f,-0.125f,-0.500f), float2(0.500f, 0.500f) },
00504         { float3( 0.000f, 0.000f,-0.125f), float3(-0.500f,-0.125f,-0.500f), float2(0.500f, 0.500f) },
00505         { float3( 0.000f,-0.500f, 0.000f), float3( 0.500f,-0.125f,-0.500f), float2(0.500f, 0.500f) },
00506         { float3( 0.000f, 0.000f,-0.125f), float3( 0.500f,-0.125f,-0.500f), float2(0.500f, 0.500f) },
00507         { float3( 0.125f, 0.000f, 0.000f), float3( 0.500f,-0.125f,-0.500f), float2(0.500f, 0.500f) },
00508         { float3( 0.000f, 0.000f,-0.125f), float3( 0.000f, 0.125f, 0.000f), float2(0.500f, 0.500f) },
00509         { float3(-0.125f, 0.000f, 0.000f), float3( 0.000f, 0.125f, 0.000f), float2(0.500f, 0.500f) },
00510         { float3( 0.000f, 0.000f, 0.125f), float3( 0.000f, 0.125f, 0.000f), float2(0.500f, 0.500f) },
00511         { float3( 0.125f, 0.000f, 0.000f), float3( 0.000f, 0.125f, 0.000f), float2(0.500f, 0.500f) },
00512         { float3( 0.000f, 0.000f, 0.500f), float3( 0.500f, 0.500f, 0.125f), float2(0.750f, 0.250f) },
00513         { float3( 0.125f, 0.000f, 0.000f), float3( 0.500f, 0.500f, 0.125f), float2(0.750f, 0.250f) },
00514         { float3( 0.000f, 0.125f, 0.000f), float3( 0.500f, 0.500f, 0.125f), float2(0.750f, 0.250f) },
00515         { float3( 0.000f, 0.000f, 0.500f), float3(-0.500f, 0.500f, 0.125f), float2(0.750f, 0.250f) },
00516         { float3( 0.000f, 0.125f, 0.000f), float3(-0.500f, 0.500f, 0.125f), float2(0.750f, 0.250f) },
00517         { float3(-0.125f, 0.000f, 0.000f), float3(-0.500f, 0.500f, 0.125f), float2(0.750f, 0.250f) },
00518         { float3( 0.000f, 0.000f, 0.500f), float3(-0.500f,-0.500f, 0.125f), float2(0.750f, 0.250f) },
00519         { float3(-0.125f, 0.000f, 0.000f), float3(-0.500f,-0.500f, 0.125f), float2(0.750f, 0.250f) },
00520         { float3( 0.000f,-0.125f, 0.000f), float3(-0.500f,-0.500f, 0.125f), float2(0.750f, 0.250f) },
00521         { float3( 0.000f, 0.000f, 0.500f), float3( 0.500f,-0.500f, 0.125f), float2(0.750f, 0.250f) },
00522         { float3( 0.000f,-0.125f, 0.000f), float3( 0.500f,-0.500f, 0.125f), float2(0.750f, 0.250f) },
00523         { float3( 0.125f, 0.000f, 0.000f), float3( 0.500f,-0.500f, 0.125f), float2(0.750f, 0.250f) },
00524         { float3( 0.125f, 0.000f, 0.000f), float3( 0.000f, 0.000f,-0.125f), float2(0.750f, 0.250f) },
00525         { float3( 0.000f,-0.125f, 0.000f), float3( 0.000f, 0.000f,-0.125f), float2(0.750f, 0.250f) },
00526         { float3(-0.125f, 0.000f, 0.000f), float3( 0.000f, 0.000f,-0.125f), float2(0.750f, 0.250f) },
00527         { float3( 0.000f, 0.125f, 0.000f), float3( 0.000f, 0.000f,-0.125f), float2(0.750f, 0.250f) },
00528         { float3( 0.000f, 0.000f,-0.500f), float3( 0.500f, 0.500f,-0.125f), float2(0.750f, 0.500f) },
00529         { float3( 0.000f, 0.125f, 0.000f), float3( 0.500f, 0.500f,-0.125f), float2(0.750f, 0.500f) },
00530         { float3( 0.125f, 0.000f, 0.000f), float3( 0.500f, 0.500f,-0.125f), float2(0.750f, 0.500f) },
00531         { float3( 0.000f, 0.000f,-0.500f), float3( 0.500f,-0.500f,-0.125f), float2(0.750f, 0.500f) },
00532         { float3( 0.125f, 0.000f, 0.000f), float3( 0.500f,-0.500f,-0.125f), float2(0.750f, 0.500f) },
00533         { float3( 0.000f,-0.125f, 0.000f), float3( 0.500f,-0.500f,-0.125f), float2(0.750f, 0.500f) },
00534         { float3( 0.000f, 0.000f,-0.500f), float3(-0.500f,-0.500f,-0.125f), float2(0.750f, 0.500f) },
00535         { float3( 0.000f,-0.125f, 0.000f), float3(-0.500f,-0.500f,-0.125f), float2(0.750f, 0.500f) },
00536         { float3(-0.125f, 0.000f, 0.000f), float3(-0.500f,-0.500f,-0.125f), float2(0.750f, 0.500f) },
00537         { float3( 0.000f, 0.000f,-0.500f), float3(-0.500f, 0.500f,-0.125f), float2(0.750f, 0.500f) },
00538         { float3(-0.125f, 0.000f, 0.000f), float3(-0.500f, 0.500f,-0.125f), float2(0.750f, 0.500f) },
00539         { float3( 0.000f, 0.125f, 0.000f), float3(-0.500f, 0.500f,-0.125f), float2(0.750f, 0.500f) },
00540         { float3( 0.000f, 0.125f, 0.000f), float3( 0.000f, 0.000f, 0.125f), float2(0.750f, 0.500f) },
00541         { float3(-0.125f, 0.000f, 0.000f), float3( 0.000f, 0.000f, 0.125f), float2(0.750f, 0.500f) },
00542         { float3( 0.000f,-0.125f, 0.000f), float3( 0.000f, 0.000f, 0.125f), float2(0.750f, 0.500f) },
00543         { float3( 0.125f, 0.000f, 0.000f), float3( 0.000f, 0.000f, 0.125f), float2(0.750f, 0.500f) },
00544     };
00545
00546     unsigned short axisIndices[] =
00547     {
00548          0,  2,  1,
00549          3,  5,  4,
00550          6,  8,  7,
00551          9, 11, 10,
00552         12, 14, 13,
00553         12, 15, 14,
00554         16, 18, 17,
00555         19, 21, 20,
00556         22, 24, 23,
00557         25, 27, 26,
00558         28, 30, 29,
00559         28, 31, 30,
00560         32, 34, 33,
00561         35, 37, 36,
00562         38, 40, 39,
00563         41, 43, 42,
00564         44, 46, 45,
00565         44, 47, 46,
00566         48, 50, 49,
00567         51, 53, 52,
00568         54, 56, 55,
00569         57, 59, 58,
00570         60, 62, 61,
00571         60, 63, 62,
00572         64, 66, 65,
00573         67, 69, 68,
00574         70, 72, 71,
00575         73, 75, 74,
00576         76, 78, 77,
00577         76, 79, 78,
00578         80, 82, 81,
00579         83, 85, 84,
00580         86, 88, 87,
00581         89, 91, 90,
00582         92, 94, 93,
00583         92, 95, 94,
00584     };
00585
00586     CreateVertexBuffer(
00587         ARRAYSIZE(axisVertices),
00588         axisVertices,
00589         vertexBuffer
00590         );
00591     if (vertexCount != nullptr)
00592     {
00593         *vertexCount = ARRAYSIZE(axisVertices);
00594     }
00595
00596     CreateIndexBuffer(
00597         ARRAYSIZE(axisIndices),
00598         axisIndices,
00599         indexBuffer
00600         );
00601     if (indexCount != nullptr)
00602     {
00603         *indexCount = ARRAYSIZE(axisIndices);
00604     }
00605 }
Generated on Sat Nov 23 2024 16:08:10 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Lock screen apps/C#,C++/ScenarioInput2.xaml.cpp Source File

  • Lock screen apps
  • C#,C++

ScenarioInput2.xaml.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 //
00009 // Scenario2Input.xaml.cpp
00010 // Implementation of the Scenario2Input class.
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioInput2.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace LockScreenAppsCPP;
00018
00019 using namespace NotificationsExtensions::BadgeContent;
00020 using namespace NotificationsExtensions::TileContent;
00021 using namespace Platform;
00022 using namespace Windows::ApplicationModel::Background;
00023 using namespace Windows::UI::Notifications;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Controls;
00026 using namespace Windows::UI::Xaml::Navigation;
00027
00028
00029 ScenarioInput2::ScenarioInput2()
00030 {
00031   InitializeComponent();
00032 }
00033
00034 ScenarioInput2::~ScenarioInput2()
00035 {
00036 }
00037
00038 void ScenarioInput2::SendBadge_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00039 {
00040   BadgeNumericNotificationContent^ badgeContent = ref new BadgeNumericNotificationContent(6);
00041   BadgeUpdateManager::CreateBadgeUpdaterForApplication()->Update(badgeContent->CreateNotification());
00042
00043   rootPage->NotifyUser("Badge notification sent", NotifyType::StatusMessage);
00044 }
00045
00046 void ScenarioInput2::SendBadgeWithStringManipulation_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00047 {
00048   Platform::String^ badgeXmlString = "<badge value='6'/>";
00049   auto badgeDOM = ref new Windows::Data::Xml::Dom::XmlDocument();
00050   badgeDOM->LoadXml(badgeXmlString);
00051   auto badge = ref new BadgeNotification(badgeDOM);
00052   BadgeUpdateManager::CreateBadgeUpdaterForApplication()->Update(badge);
00053   rootPage->NotifyUser("Badge notification sent", NotifyType::StatusMessage);
00054 }
00055
00056 void ScenarioInput2::ClearBadge_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00057 {
00058   BadgeUpdateManager::CreateBadgeUpdaterForApplication()->Clear();
00059   rootPage->NotifyUser("Badge notification cleared", NotifyType::StatusMessage);
00060 }
00061
00062 void ScenarioInput2::SendTile_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00063 {
00064   ITileWideSmallImageAndText03^ tileContent = TileContentFactory::CreateTileWideSmallImageAndText03();
00065   tileContent->TextBodyWrap->Text = "This tile notification has an image, but it won't be displayed on the lock screen";
00066   tileContent->Image->Src = "ms-appx:///images/tile-sdk.png";
00067   tileContent->RequireSquareContent = false;
00068
00069   TileUpdateManager::CreateTileUpdaterForApplication()->Update(tileContent->CreateNotification());
00070
00071   rootPage->NotifyUser("Tile notification sent", NotifyType::StatusMessage);
00072 }
00073
00074 void ScenarioInput2::SendTileWithStringManipulation_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00075 {
00076   auto tileXmlString = "<tile>"
00077     +  "<visual>"
00078     +   "<binding template='TileWideSmallImageAndText03'>"
00079     +    "<image id='1' src='ms-appx:///images/tile-sdk.png'/>"
00080     +    "<text id='1'>This tile notification has an image, but it won't be displayed on the lock screen</text>"
00081     +   "</binding>"
00082     +  "</visual>"
00083     + "</tile>";
00084
00085   auto tileDOM = ref new Windows::Data::Xml::Dom::XmlDocument();
00086   tileDOM->LoadXml(tileXmlString);
00087   auto tile = ref new TileNotification(tileDOM);
00088   TileUpdateManager::CreateTileUpdaterForApplication()->Update(tile);
00089   rootPage->NotifyUser("Tile notification sent", NotifyType::StatusMessage);
00090 }
00091
00092 void ScenarioInput2::ClearTile_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00093 {
00094   TileUpdateManager::CreateTileUpdaterForApplication()->Clear();
00095   rootPage->NotifyUser("Tile notification cleared", NotifyType::StatusMessage);
00096 }
00097
00098 void ScenarioInput2::OnNavigatedTo(NavigationEventArgs^ e)
00099 {
00100   // Get a pointer to our main page.
00101   rootPage = dynamic_cast<MainPage^>(e->Parameter);
00102 }
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

StreamEffect Member List

This is the complete list of members for StreamEffect, including all inherited members.
__pad0__ | StreamEffect |
CreateAudioResources() | StreamEffect |
CreateDeviceIndependentResources() override | StreamEffect | [virtual]
CreateDeviceResources() override | StreamEffect | [virtual]
CreateWindowSizeDependentResources() override | StreamEffect | [virtual]
IsAudioSetup() | StreamEffect |
m_audioBuffers | StreamEffect | [private]
m_currentBuffer | StreamEffect | [private]
m_dataTextFormat | StreamEffect | [private]
m_isAudioStarted | StreamEffect | [private]
m_musicEngine | StreamEffect | [private]
m_musicMasteringVoice | StreamEffect | [private]
m_musicSourceVoice | StreamEffect | [private]
m_musicStreamer | StreamEffect | [private]
m_sampleOverlay | StreamEffect | [private]
m_textBrush | StreamEffect | [private]
OnResuming() | StreamEffect |
OnSuspending() | StreamEffect |
ReleaseAudioResources() | StreamEffect |
Render() override | StreamEffect | [virtual]
RenderAudio() | StreamEffect |
Update(float TimeTotal, float TimeDelta) | StreamEffect |
~StreamEffect() | StreamEffect | [private]
Generated on Sat Nov 23 2024 16:09:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Audio Session (WASAPI)/C++/Constants.h Source File

  • Windows Audio Session (WASAPI)
  • C++

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"Windows Audio Session API (WASAPI) Sample");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044
00045
00046 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/TaskExceptionsExtensions.h Source File

  • Hilo C++
  • Hilo

TaskExceptionsExtensions.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 "ExceptionPolicy.h"
00009
00010 namespace Hilo
00011 {
00012     template<typename T>
00013     struct ObserveException
00014     {
00015         ObserveException(std::shared_ptr<ExceptionPolicy> handler) : m_handler(handler)
00016         {
00017         }
00018
00019         concurrency::task<T> operator()(concurrency::task<T> antecedent) const
00020         {
00021             T result;
00022             try
00023             {
00024                 result = antecedent.get();
00025             }
00026             catch(const concurrency::task_canceled&)
00027             {
00028                 // don't need to run canceled tasks through the policy
00029             }
00030             catch(const std::exception&)
00031             {
00032                 auto translatedException = ref new Platform::FailureException();
00033                 m_handler->HandleException(translatedException);
00034                 throw;
00035             }
00036             catch(Platform::Exception^ ex)
00037             {
00038                 m_handler->HandleException(ex);
00039                 throw;
00040             }
00041             return antecedent;
00042         }
00043
00044     private:
00045         std::shared_ptr<ExceptionPolicy> m_handler;
00046     };
00047
00048     template<>
00049     concurrency::task<void> ObserveException<void>::operator()(concurrency::task<void> antecedent) const
00050     {
00051         try
00052         {
00053             antecedent.get();
00054         }
00055         catch(const concurrency::task_canceled&)
00056         {
00057             // don't need to run canceled tasks through the policy
00058         }
00059         catch(const std::exception&)
00060         {
00061             auto translatedException = ref new Platform::FailureException();
00062             m_handler->HandleException(translatedException);
00063             throw;
00064         }
00065         catch(Platform::Exception^ ex)
00066         {
00067             m_handler->HandleException(ex);
00068             throw;
00069         }
00070
00071         return antecedent;
00072     }
00073 }
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Custom driver access/C++/app_cpp/common/suspensionmanager.cpp Source File

  • Custom driver access
  • app_cpp
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:36 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/BooleanToBrushConverter.h Source File

  • Hilo C++
  • Hilo

BooleanToBrushConverter.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
00009 namespace Hilo
00010 {
00011     // See http://go.microsoft.com/fwlink/?LinkId=267279 for info about data converters in the Hilo app.
00012
00013     // The BooleanToBrushConverter class converts true/false values to two distinct colors. It is used by XAML
00014     // controls to indicate state based on fill color.
00015     [Windows::Foundation::Metadata::WebHostHidden]
00016     public ref class BooleanToBrushConverter sealed : public Windows::UI::Xaml::Data::IValueConverter
00017     {
00018     public:
00019         virtual Object^ Convert(Object^ value, Windows::UI::Xaml::Interop::TypeName targetType, Object^ parameter, Platform::String^ language);
00020         virtual Object^ ConvertBack(Object^ value, Windows::UI::Xaml::Interop::TypeName targetType, Object^ parameter, Platform::String^ language);
00021     };
00022 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML two-dimensional transforms/C++/common/LayoutAwarePage.cpp Source File

  • XAML two-dimensional transforms
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CameraOptionsUI/C++/MainPage.xaml.cpp Source File

  • CameraOptionsUI

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Date and time formatting/C++/ParametrizedTemplate.xaml.h Source File

  • Date and time formatting

ParametrizedTemplate.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 // ParametrizedTemplate.xaml.h
00013 // Declaration of the ParametrizedTemplate class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "ParametrizedTemplate.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace DateTimeFormatting
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 ParametrizedTemplate sealed
00031         {
00032         public:
00033             ParametrizedTemplate();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void Display_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:08:02 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D stereoscopic 3D/C++/pch.cpp Source File

  • Direct3D stereoscopic 3D

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application data/C++/SettingContainer.xaml.cpp Source File

  • Application data

SettingContainer.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 // SettingContainer.xaml.cpp
00013 // Implementation of the SettingContainer class
00014 //
00015
00016 #include "pch.h"
00017 #include "SettingContainer.xaml.h"
00018
00019 using namespace SDKSample::ApplicationDataSample;
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::Storage;
00027
00028 #define containerName "exampleContainer"
00029 #define settingName "exampleSetting"
00030 #define settingValue "Hello World"
00031
00032 SettingContainer::SettingContainer()
00033 {
00034     InitializeComponent();
00035
00036     localSettings = ApplicationData::Current->LocalSettings;
00037
00038     DisplayOutput();
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 SettingContainer::OnNavigatedTo(NavigationEventArgs^ e)
00047 {
00048     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00049     // as NotifyUser()
00050     rootPage = MainPage::Current;
00051 }
00052
00053 void SettingContainer::CreateContainer_Click(Object^ sender, RoutedEventArgs^ e)
00054 {
00055     ApplicationDataContainer^ container = localSettings->CreateContainer(containerName, ApplicationDataCreateDisposition::Always);
00056
00057     DisplayOutput();
00058 }
00059
00060 void SettingContainer::DeleteContainer_Click(Object^ sender, RoutedEventArgs^ e)
00061 {
00062     localSettings->DeleteContainer(containerName);
00063
00064     DisplayOutput();
00065 }
00066
00067 void SettingContainer::WriteSetting_Click(Object^ sender, RoutedEventArgs^ e)
00068 {
00069     if (localSettings->Containers->HasKey(containerName))
00070     {
00071         auto values = localSettings->Containers->Lookup(containerName)->Values;
00072         values->Insert(settingName, settingValue);
00073     }
00074
00075     DisplayOutput();
00076 }
00077
00078 void SettingContainer::DeleteSetting_Click(Object^ sender, RoutedEventArgs^ e)
00079 {
00080     if (localSettings->Containers->HasKey(containerName))
00081     {
00082         auto values = localSettings->Containers->Lookup(containerName)->Values;
00083         values->Remove(settingName);
00084     }
00085
00086     DisplayOutput();
00087 }
00088
00089 void SettingContainer::DisplayOutput()
00090 {
00091     bool hasContainer = localSettings->Containers->HasKey(containerName);
00092     bool hasSetting = false;
00093
00094     if (hasContainer)
00095     {
00096         auto values = localSettings->Containers->Lookup(containerName)->Values;
00097         hasSetting = values->HasKey(settingName);
00098     }
00099
00100     OutputTextBlock->Text = "Container Exists: " + (hasContainer ? "true" : "false") + "\n" +
00101                             "Setting Exists: " + (hasSetting ? "true" : "false");
00102 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D basic image effects/C++/D2DEffectsHelloWorld.h Source File

  • Direct2D basic image effects

D2DEffectsHelloWorld.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 "DirectXBase.h"
00011 #include "SampleOverlay.h"
00012
00013 ref class D2DEffectsHelloWorld : public DirectXBase, public Windows::ApplicationModel::Core::IFrameworkView
00014 {
00015 internal:
00016     // DirectXBase methods
00017     virtual void HandleDeviceLost() override;
00018     virtual void CreateDeviceIndependentResources() override;
00019     virtual void CreateDeviceResources() override;
00020     virtual void CreateWindowSizeDependentResources() override;
00021     virtual void Render() override;
00022
00023 public:
00024     // IFrameworkView methods
00025     virtual void Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00026     virtual void SetWindow(_In_ Windows::UI::Core::CoreWindow^ window);
00027     virtual void Load(_In_ Platform::String^ entryPoint);
00028     virtual void Run();
00029     virtual void Uninitialize();
00030
00031 private:
00032     // Event handlers
00033     void OnWindowSizeChanged(
00034         _In_ Windows::UI::Core::CoreWindow^ sender,
00035         _In_ Windows::UI::Core::WindowSizeChangedEventArgs^ args
00036         );
00037
00038     void OnLogicalDpiChanged(
00039         _In_ Platform::Object^ sender
00040         );
00041
00042     void OnDisplayContentsInvalidated(
00043         _In_ Platform::Object^ sender
00044         );
00045
00046     void OnActivated(
00047         _In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView,
00048         _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^ args
00049         );
00050
00051     void DecodeImage();
00052     void CreateEffectGraph();
00053
00054     SampleOverlay^                                      m_sampleOverlay;
00055
00056     Microsoft::WRL::ComPtr<ID2D1Effect>                 m_bitmapSourceEffect;
00057     Microsoft::WRL::ComPtr<ID2D1Effect>                 m_gaussianBlurEffect;
00058
00059     Microsoft::WRL::ComPtr<IWICBitmapDecoder>           m_wicDecoder;
00060     Microsoft::WRL::ComPtr<IWICBitmapFrameDecode>       m_wicFrameDecode;
00061     Microsoft::WRL::ComPtr<IWICFormatConverter>         m_wicFormatConverter;
00062 };
00063
00064 ref class DirectXAppSource : Windows::ApplicationModel::Core::IFrameworkViewSource
00065 {
00066 public:
00067     virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00068 };
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite custom text renderer/C++/CustomTextRenderer.h Source File

  • DirectWrite custom text renderer

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 "DirectXBase.h"
00010
00011
00012 ////  CustomTextRenderer
00013 ////
00014 ////  The IDWriteTextRenderer interface is an input parameter to
00015 ////  IDWriteTextLayout::Draw.  This interfaces defines a number of
00016 ////  callback functions that the client application implements for
00017 ////  custom text rendering.  This sample renderer implementation
00018 ////  renders text using text outlines and Direct2D.
00019 ////  A more sophisticated client would also support bitmap
00020 ////  renderings.
00021
00022 class CustomTextRenderer : public IDWriteTextRenderer
00023 {
00024 public:
00025     CustomTextRenderer(
00026         Microsoft::WRL::ComPtr<ID2D1Factory> D2DFactory,
00027         Microsoft::WRL::ComPtr<ID2D1DeviceContext> D2DDeviceContext,
00028         Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> outlineBrush,
00029         Microsoft::WRL::ComPtr<ID2D1BitmapBrush> fillBrush
00030         );
00031
00032     IFACEMETHOD(IsPixelSnappingDisabled)(
00033         _In_opt_ void* clientDrawingContext,
00034         _Out_ BOOL* isDisabled
00035         );
00036
00037     IFACEMETHOD(GetCurrentTransform)(
00038         _In_opt_ void* clientDrawingContext,
00039         _Out_ DWRITE_MATRIX* transform
00040         );
00041
00042     IFACEMETHOD(GetPixelsPerDip)(
00043         _In_opt_ void* clientDrawingContext,
00044         _Out_ FLOAT* pixelsPerDip
00045         );
00046
00047     IFACEMETHOD(DrawGlyphRun)(
00048         _In_opt_ void* clientDrawingContext,
00049         FLOAT baselineOriginX,
00050         FLOAT baselineOriginY,
00051         DWRITE_MEASURING_MODE measuringMode,
00052         _In_ DWRITE_GLYPH_RUN const* glyphRun,
00053         _In_ DWRITE_GLYPH_RUN_DESCRIPTION const* glyphRunDescription,
00054         IUnknown* clientDrawingEffect
00055         );
00056
00057     IFACEMETHOD(DrawUnderline)(
00058         _In_opt_ void* clientDrawingContext,
00059         FLOAT baselineOriginX,
00060         FLOAT baselineOriginY,
00061         _In_ DWRITE_UNDERLINE const* underline,
00062         IUnknown* clientDrawingEffect
00063         );
00064
00065     IFACEMETHOD(DrawStrikethrough)(
00066         _In_opt_ void* clientDrawingContext,
00067         FLOAT baselineOriginX,
00068         FLOAT baselineOriginY,
00069         _In_ DWRITE_STRIKETHROUGH const* strikethrough,
00070         IUnknown* clientDrawingEffect
00071         );
00072
00073     IFACEMETHOD(DrawInlineObject)(
00074         _In_opt_ void* clientDrawingContext,
00075         FLOAT originX,
00076         FLOAT originY,
00077         IDWriteInlineObject* inlineObject,
00078         BOOL isSideways,
00079         BOOL isRightToLeft,
00080         IUnknown* clientDrawingEffect
00081         );
00082
00083 public:
00084     IFACEMETHOD_(unsigned long, AddRef) ();
00085     IFACEMETHOD_(unsigned long, Release) ();
00086     IFACEMETHOD(QueryInterface) (
00087         IID const& riid,
00088         void** ppvObject
00089         );
00090
00091 private:
00092     unsigned long                                                     refCount;
00093     Microsoft::WRL::ComPtr<ID2D1Factory>                              D2DFactory;
00094     Microsoft::WRL::ComPtr<ID2D1DeviceContext>                        D2DDeviceContext;
00095     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>                      outlineBrush;
00096     Microsoft::WRL::ComPtr<ID2D1BitmapBrush>                          fillBrush;
00097 };
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application resources and localization/C++/Scenario5.xaml.h Source File

  • Application resources and localization

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 SDKSample
00023 {
00024     namespace ApplicationResources
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 Scenario5 sealed
00031         {
00032         public:
00033             Scenario5();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void Scenario5Button_Show_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/ScenarioList.xaml.h Source File

  • Media extensions

ScenarioList.xaml.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 //
00009 // ScenarioList.xaml.h
00010 // Declaration of the ScenarioList class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioList.g.h"
00017 #include "MainPage.g.h"
00018
00019 using namespace Windows::UI::Xaml::Controls;
00020 using namespace CppSamplesUtils;
00021
00022 namespace MediaExtensionsCPP
00023 {
00024     [Windows::Foundation::Metadata::WebHostHidden]
00025     public ref class ScenarioList sealed
00026     {
00027     public:
00028         ScenarioList();
00029
00030     protected:
00031         void Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e);
00032         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00033
00034     private:
00035         ~ScenarioList();
00036         MainPage^ rootPage;
00037     };
00038 }
Generated on Sat Nov 23 2024 16:07:57 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::FileExtensions Member List

This is the complete list of members for SDKSample::FileExtensions, including all inherited members.
Document | SDKSample::FileExtensions | [static]
Image | SDKSample::FileExtensions | [static]
Music | SDKSample::FileExtensions | [static]
Generated on Sat Nov 23 2024 16:09:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Thread pool/C++/pch.h Source File

  • Thread pool

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite vertical text/C++/FlowSink.cpp Source File

  • DirectWrite vertical text

FlowSink.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 // Contents:    Sink interface for where text is placed.
00009 //
00010 //----------------------------------------------------------------------------
00011 #include "pch.h"
00012 #include "DirectXBase.h"
00013 #include "FlowSink.h"
00014 #include "TextAnalysis.h"
00015
00016 void FlowLayoutSink::Reset()
00017 {
00018     m_glyphRuns.clear();
00019     m_glyphIndices.clear();
00020     m_glyphAdvances.clear();
00021     m_glyphOffsets.clear();
00022 }
00023
00024 void FlowLayoutSink::Prepare(UINT32 glyphCount)
00025 {
00026     // Reserve a known glyph count up front.
00027     m_glyphIndices.reserve (glyphCount);
00028     m_glyphAdvances.reserve(glyphCount);
00029     m_glyphOffsets.reserve (glyphCount);
00030 }
00031
00032 void FlowLayoutSink::SetGlyphRun(
00033     float x,
00034     float y,
00035     UINT32 glyphCount,
00036     const UINT16* glyphIndices,                 // [glyphCount]
00037     const float* glyphAdvances,                 // [glyphCount]
00038     const DWRITE_GLYPH_OFFSET* glyphOffsets,    // [glyphCount]
00039     Microsoft::WRL::ComPtr<IDWriteFontFace> fontFace,
00040     float fontEmSize,
00041     UINT8 glyphOrientation,
00042     bool isReversed,
00043     bool isSideways
00044     )
00045 {
00046     // Append this glyph run to the list.
00047     m_glyphRuns.resize(m_glyphRuns.size() + 1);
00048     CustomGlyphRun& glyphRun = m_glyphRuns.back();
00049     UINT32 glyphStart = static_cast<UINT32>(m_glyphAdvances.size());
00050
00051     m_glyphIndices.insert (m_glyphIndices.end(),  glyphIndices,  glyphIndices  + glyphCount);
00052     m_glyphAdvances.insert(m_glyphAdvances.end(), glyphAdvances, glyphAdvances + glyphCount);
00053     m_glyphOffsets.insert (m_glyphOffsets.end(),  glyphOffsets,  glyphOffsets  + glyphCount);
00054
00055     glyphRun.x                  = x;
00056     glyphRun.y                  = y;
00057     glyphRun.glyphOrientation   = glyphOrientation;
00058     glyphRun.glyphStart         = glyphStart;
00059     glyphRun.isSideways         = isSideways;
00060     glyphRun.isReversed         = isReversed;
00061     glyphRun.glyphCount         = glyphCount;
00062     glyphRun.fontEmSize         = fontEmSize;
00063     glyphRun.fontFace           = fontFace.Get();
00064 }
00065
00066 void FlowLayoutSink::DrawGlyphRuns(
00067     Microsoft::WRL::ComPtr<ID2D1DeviceContext> deviceContext,
00068     Microsoft::WRL::ComPtr<IDWriteRenderingParams> renderingParams,
00069     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> textColor
00070     ) const
00071 {
00072     // Just iterate through all the saved glyph runs
00073     // and have DWrite to draw each one.
00074     if (m_dwriteFactory == nullptr)
00075     {
00076         return;
00077     }
00078
00079     if (m_textAnalyzer == nullptr)
00080     {
00081         Microsoft::WRL::ComPtr<IDWriteTextAnalyzer> textAnalyzer0;
00082
00083         DX::ThrowIfFailed(
00084             m_dwriteFactory->CreateTextAnalyzer(&textAnalyzer0)
00085             );
00086
00087         DX::ThrowIfFailed(
00088             textAnalyzer0.As(&m_textAnalyzer)
00089             );
00090     }
00091
00092     // Mapping from small orientation back to DWrite compatible angle.
00093     const static DWRITE_GLYPH_ORIENTATION_ANGLE glyphOrientationAngle[] = {
00094         DWRITE_GLYPH_ORIENTATION_ANGLE_0_DEGREES,   // LTR TTB
00095         DWRITE_GLYPH_ORIENTATION_ANGLE_0_DEGREES,   // RTL TTB * no mapping, so just zero
00096         DWRITE_GLYPH_ORIENTATION_ANGLE_0_DEGREES,   // LTR BTT * no mapping, so just zero
00097         DWRITE_GLYPH_ORIENTATION_ANGLE_180_DEGREES, // RTL BTT
00098         DWRITE_GLYPH_ORIENTATION_ANGLE_0_DEGREES,   // TTB LTR * no mapping, so just zero
00099         DWRITE_GLYPH_ORIENTATION_ANGLE_270_DEGREES, // BTT LTR
00100         DWRITE_GLYPH_ORIENTATION_ANGLE_90_DEGREES,  // TTB RTL
00101         DWRITE_GLYPH_ORIENTATION_ANGLE_0_DEGREES,   // BTT RTL * no mapping, so just zero
00102     };
00103
00104     DWRITE_MATRIX transform = { };
00105
00106     for (size_t i = 0; i < m_glyphRuns.size(); ++i)
00107     {
00108         DWRITE_GLYPH_RUN glyphRun;
00109         const CustomGlyphRun& customGlyphRun = m_glyphRuns[i];
00110
00111         if (customGlyphRun.glyphCount == 0)
00112         {
00113             continue;
00114         }
00115
00116         // Massage the custom glyph run to something directly
00117         // digestable by DrawGlyphRun.
00118         customGlyphRun.Convert(
00119             &m_glyphIndices [0],
00120             &m_glyphAdvances[0],
00121             &m_glyphOffsets [0],
00122             &glyphRun
00123             );
00124
00125         // This call is valid for both horizontal and vertical
00126         // (though it's a nop for horizontal, returning identity).
00127         m_textAnalyzer->GetGlyphOrientationTransform(
00128             glyphOrientationAngle[customGlyphRun.glyphOrientation],
00129             customGlyphRun.isSideways,
00130             OUT &transform
00131             );
00132
00133         transform.dx = customGlyphRun.x;
00134         transform.dy = customGlyphRun.y;
00135         deviceContext->SetTransform((D2D_MATRIX_3X2_F*) &transform);
00136
00137         deviceContext->DrawGlyphRun(
00138             D2D1::Point2F(0, 0),
00139             &glyphRun,
00140             nullptr,
00141             textColor.Get()
00142             );
00143     }
00144 }
00145
00146 void FlowLayoutSink::CustomGlyphRun::Convert(
00147     const UINT16* glyphIndices,
00148     const float* glyphAdvances,
00149     const DWRITE_GLYPH_OFFSET* glyphOffsets,
00150     OUT DWRITE_GLYPH_RUN* glyphRun
00151     ) const
00152 {
00153     // Populate the DWrite glyph run.
00154     glyphRun->glyphIndices  = &glyphIndices [glyphStart];
00155     glyphRun->glyphAdvances = &glyphAdvances[glyphStart];
00156     glyphRun->glyphOffsets  = &glyphOffsets [glyphStart];
00157     glyphRun->glyphCount    = glyphCount;
00158     glyphRun->fontEmSize    = fontEmSize;
00159     glyphRun->fontFace      = fontFace;
00160     glyphRun->bidiLevel     = isReversed;
00161     glyphRun->isSideways    = isSideways;
00162 }
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Touch hit testing/C++/Program.cpp Source File

  • Input Touch hit testing

Program.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 <stdio.h>
00010 #include "Program.h"
00011
00012 using namespace Windows::ApplicationModel::Core;
00013 using namespace Windows::ApplicationModel::Activation;
00014 using namespace Windows::UI::Core;
00015 using namespace Windows::UI::Input;
00016 using namespace Windows::Devices::Input;
00017 using namespace Windows::System;
00018 using namespace Windows::Foundation;
00019
00020 //
00021 // Definitions
00022 //
00023 int const CONTROLS_AREA_SIZE = 300; // Relative size of area where regular shapes are initially drawn
00024
00025 Program::Program():
00026     m_shapes(nullptr),
00027     m_width(-1),
00028     m_height(-1)
00029 {
00030 }
00031
00032 Program::~Program()
00033 {
00034 }
00035
00036 // Add new shape to the top of the list
00037 void Program::AddShape(_In_reads_(numPoints) Windows::Foundation::Point const* points, _In_ int numPoints,
00038                        _In_ D2D1::ColorF color)
00039 {
00040     // Create new record for this shape
00041     std::shared_ptr<ShapeRecord> shapeRecord = std::shared_ptr<ShapeRecord>(new ShapeRecord());
00042     shapeRecord->shape = std::shared_ptr<Shape>(new Shape());
00043     shapeRecord->shape->InitializeObject(points, numPoints, color);
00044     shapeRecord->next = nullptr;
00045     shapeRecord->cursorId = CURSOR_ID_NONE;
00046
00047     if (m_shapes == nullptr)
00048     {
00049         // The first entry
00050         m_shapes = shapeRecord;
00051     }
00052     else
00053     {
00054         // Add to top
00055         shapeRecord->next = m_shapes;
00056         m_shapes = shapeRecord;
00057     }
00058 }
00059
00060 // Move selected shape to the top
00061 void Program::MoveToFront(_Inout_ std::shared_ptr<ShapeRecord>& shapeRec)
00062 {
00063     // Find previos shape
00064     std::shared_ptr<ShapeRecord> shapeRecPrev = m_shapes;
00065     while (shapeRecPrev != nullptr && (shapeRecPrev->next != shapeRec))
00066     {
00067         shapeRecPrev = shapeRecPrev->next;
00068     }
00069
00070     if (shapeRecPrev != nullptr)
00071     {
00072         // It's not on top yet, move it to front
00073         shapeRecPrev->next = shapeRec->next;
00074         shapeRec->next = m_shapes;
00075         m_shapes = shapeRec;
00076     }
00077 }
00078
00079 // Initialize and place all controls on the page
00080 void Program::SetupControls()
00081 {
00082     Windows::Foundation::Point poly[MAX_POLY_VERTICES];
00083
00084     // Drawing parameters
00085     // Triangle side
00086     float triangleSide = CONTROLS_AREA_SIZE;
00087     // Triangle height
00088     float triangleHeight = triangleSide * 87 / 100;
00089
00090     // 1st control
00091     // rectangle
00092     poly[0].X = triangleSide   / 3;
00093     poly[0].Y = triangleHeight * 2 / 3;
00094     poly[1].X = triangleSide   * 2 / 3;
00095     poly[1].Y = triangleHeight;
00096     AddShape(poly, 2, D2D1::ColorF::Blue);
00097
00098     // 2nd control
00099     // Triangle
00100     poly[0].X = triangleSide   / 3;
00101     poly[0].Y = triangleHeight * 2 / 3;
00102     poly[1].X = triangleSide   * 2 / 3;
00103     poly[1].Y = triangleHeight * 2 / 3;
00104     poly[2].X = triangleSide   / 2;
00105     poly[2].Y = triangleHeight / 3;
00106     AddShape(poly, 3, D2D1::ColorF::Orange);
00107 }
00108
00109 // Initialize page
00110 void Program::Initialize(_In_ Windows::UI::Core::CoreWindow^ window)
00111 {
00112     m_window = window;
00113
00114     // Enable Touch Hit Test
00115     window->TouchHitTesting +=
00116         ref new TypedEventHandler<CoreWindow^, TouchHitTestingEventArgs^>(this, &Program::OnTouchHitTesting);
00117
00118     // Create and initialize core objects
00119     SetupControls();
00120 }
00121
00122 // Draw shapes in backward order.
00123 // First draw shape with the lowest z-order and so on.
00124 // The last drawn shape has the highest z-order.
00125 void Program::DrawBackward(_In_ std::shared_ptr<ShapeRecord> const& shapeRec)
00126 {
00127     if (shapeRec != nullptr)
00128     {
00129         DrawBackward(shapeRec->next);
00130         shapeRec->shape->Paint(m_d2dContext.Get());
00131     }
00132 }
00133
00134 // Render whole page.
00135 void Program::RenderObjects()
00136 {
00137     DrawBackward(m_shapes);
00138 }
00139
00140 void Program::CreateWindowSizeDependentResources()
00141 {
00142     m_width = m_window->Bounds.Width;
00143     m_height = m_window->Bounds.Height;
00144
00145     // Scaling factor
00146     float minWH = m_width > m_height ? m_height : m_width;
00147     float scale = minWH / (2 * CONTROLS_AREA_SIZE);
00148
00149     // Origin of the objects
00150     Windows::Foundation::Point orig;
00151
00152     orig.X = (m_width  - CONTROLS_AREA_SIZE * scale) / 2.0F;
00153     orig.Y = (m_height - CONTROLS_AREA_SIZE * scale) / 2.0F;
00154
00155     // Assign the setup defined above to each of the core objects
00156     std::shared_ptr<ShapeRecord> shapeRec = m_shapes;
00157     while (shapeRec != nullptr)
00158     {
00159         shapeRec->shape->ResetState(orig.X, orig.Y, m_width, m_height, scale);
00160         shapeRec = shapeRec->next;
00161     }
00162 }
00163
00164 void Program::SetD2DContext(_In_ ID2D1DeviceContext*  d2dContext)
00165 {
00166     m_d2dContext = d2dContext;
00167 }
00168
00169 // Return shape that is hit with given point.
00170 std::shared_ptr<ShapeRecord> Program::PointHitTest(_In_ Windows::Foundation::Point pt)
00171 {
00172     std::shared_ptr<ShapeRecord> shapeRec = m_shapes;
00173     while (shapeRec != nullptr)
00174     {
00175         if (shapeRec->shape->InRegion(pt))
00176         {
00177             return shapeRec;
00178         }
00179         shapeRec = shapeRec->next;
00180     }
00181
00182     return nullptr;
00183 }
00184
00185 // On pointer down event select target shape (associate shape with cursor)
00186 // and move shape to the front.
00187 void Program::OnPointerPressed(_In_ Windows::UI::Core::PointerEventArgs^ args)
00188 {
00189     std::shared_ptr<ShapeRecord> shapeRec = PointHitTest(args->CurrentPoint->Position);
00190     if (shapeRec != nullptr)
00191     {
00192         shapeRec->cursorId = args->CurrentPoint->PointerId;
00193         shapeRec->shape->OnPointerEvent(args->CurrentPoint->Position, false);
00194
00195         MoveToFront(shapeRec);
00196     }
00197 }
00198
00199 // On pointer move event, translate the shape that is associated with
00200 // current cursor (if any).
00201 void Program::OnPointerMoved(_In_ Windows::UI::Core::PointerEventArgs^ args)
00202 {
00203     // find object held with this cursor
00204     std::shared_ptr<ShapeRecord> shapeRec = m_shapes;
00205     while (shapeRec != nullptr && (shapeRec->cursorId != args->CurrentPoint->PointerId))
00206     {
00207         shapeRec = shapeRec->next;
00208     }
00209
00210     // move object
00211     if (shapeRec != nullptr)
00212     {
00213         // move the object
00214         shapeRec->shape->OnPointerEvent(args->CurrentPoint->Position, true);
00215     }
00216 }
00217
00218 // On pointer up event, release the associated shape (if any).
00219 void Program::OnPointerReleased(_In_ Windows::UI::Core::PointerEventArgs^ args)
00220 {
00221     // find object held with this cursor
00222     std::shared_ptr<ShapeRecord> shapeRec = m_shapes;
00223     while (shapeRec != nullptr && (shapeRec->cursorId != args->CurrentPoint->PointerId))
00224     {
00225         shapeRec = shapeRec->next;
00226     }
00227
00228     if (shapeRec != nullptr)
00229     {
00230         shapeRec->shape->OnPointerEvent(args->CurrentPoint->Position, true);
00231
00232         // Release cursor from shape
00233         shapeRec->cursorId = CURSOR_ID_NONE;
00234     }
00235 }
00236
00237 // Intelligent Touch Hit Test handler - sample implementation of the Touch Hit Test
00238 // Algorithm.
00239 void Program::OnTouchHitTesting(_In_ Windows::UI::Core::CoreWindow^ /*sender*/,
00240                                 _In_ Windows::UI::Core::TouchHitTestingEventArgs^ touchHitTestingArgs)
00241 {
00242     // Current and best Touch Hit Test results
00243     Windows::UI::Core::CoreProximityEvaluation bestResult;
00244     Windows::UI::Core::CoreProximityEvaluation currentResult;
00245
00246     // Initialize best result from input arguments.
00247     // In theory there may be more than one listener to this event.
00248     bestResult = touchHitTestingArgs->ProximityEvaluation;
00249
00250     // Best Touch Hit Test target
00251     std::shared_ptr<Shape> bestTarget = nullptr;
00252
00253     bestResult.AdjustedPoint = touchHitTestingArgs->Point;
00254
00255     // Iterate through all shapes by their z-order (starting from shape with highest z-order)
00256     // Stop early if there's no chance to find better target.
00257     std::shared_ptr<ShapeRecord> shapeRec = m_shapes;
00258     while (shapeRec != nullptr && bestResult.Score > static_cast<int>(Windows::UI::Core::CoreProximityEvaluationScore::Closest))
00259     {
00260         Polygon* poly = shapeRec->shape->GetPolygon();
00261
00262         // Hit test current shape
00263         if (poly->isRect)
00264         {
00265             currentResult = touchHitTestingArgs->EvaluateProximity(poly->rcBound);
00266         }
00267         else
00268         {
00269             // Create correctly sized array of Points
00270             auto controlVertices = ref new Platform::Array<Windows::Foundation::Point>(poly->points, poly->numPoints);
00271             currentResult = touchHitTestingArgs->EvaluateProximity(controlVertices);
00272         }
00273
00274         // Does the shape intersect touch contact and is it the best target so far?
00275         if (currentResult.Score < bestResult.Score)
00276         {
00277             // Even if this shape has better score than the score of the shape with higher z-order,
00278             // don't select this shape if previous adjusted point belongs to this shape.
00279             // In other words, if this shape overlaps shape with higher z-order, favor the shape with
00280             // higher z-order.
00281             if (bestTarget == nullptr || !shapeRec->shape->InRegion(currentResult.AdjustedPoint))
00282             {
00283                 // Finally, don't select target if adjusted touch point is not on the control.
00284                 // That may happen if another shape with higher z-order overlaps this shape at adjusted touch
00285                 // point.
00286                 if (PointHitTest(currentResult.AdjustedPoint) == shapeRec)
00287                 {
00288                     // This is the best touch target so far.
00289                     bestTarget = shapeRec->shape;
00290                     bestResult = currentResult;
00291                 }
00292             }
00293         }
00294
00295         // Evaluate next shape.
00296         shapeRec = shapeRec->next;
00297     }
00298
00299     // Set best target
00300     touchHitTestingArgs->ProximityEvaluation = bestResult;
00301
00302     // Event is handled
00303     touchHitTestingArgs->Handled = true;
00304 }
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Print/C++/ScenarioOutput4.xaml.cpp Source File

  • Print

ScenarioOutput4.xaml.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 //
00009 // ScenarioOutput4.xaml.cpp
00010 // Implementation of the ScenarioOutput4 class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioOutput4.xaml.h"
00015
00016 using namespace PrintSample;
00017
00018 ScenarioOutput4::ScenarioOutput4()
00019 {
00020     InitializeComponent();
00021 }
00022
00023 ScenarioOutput4::~ScenarioOutput4()
00024 {
00025 }
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Background task/C++/BackgroundTask/common/LayoutAwarePage.h Source File

  • Background task
  • BackgroundTask
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Gyrometer sensor/C++/Scenario1.xaml.h Source File

  • Gyrometer sensor

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 SDKSample
00023 {
00024     namespace GyrometerCPP
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 Scenario1 sealed
00031         {
00032         public:
00033             Scenario1();
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             MainPage^ rootPage;
00041             Windows::Devices::Sensors::Gyrometer^ gyrometer;
00042             Windows::Foundation::EventRegistrationToken visibilityToken;
00043             Windows::Foundation::EventRegistrationToken readingToken;
00044             uint32 desiredReportInterval;
00045
00046             void VisibilityChanged(Platform::Object^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ e);
00047             void ReadingChanged(Windows::Devices::Sensors::Gyrometer^ sender, Windows::Devices::Sensors::GyrometerReadingChangedEventArgs^ 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     }
00052 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Print/C++/ScenarioInput5.xaml.cpp Source File

  • Print

ScenarioInput5.xaml.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 //
00009 // ScenarioInput5.xaml.cpp
00010 // Implementation of the ScenarioInput5 class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioInput5.xaml.h"
00015 #include "ScenarioOutput5.xaml.h"
00016 #include <algorithm>
00017 #include <regex>
00018
00019 using namespace PrintSample;
00020
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Foundation;
00023 using namespace Windows::Graphics::Display;
00024 using namespace Windows::Graphics::Printing;
00025 using namespace Windows::Graphics::Printing::OptionDetails;
00026 using namespace Windows::UI;
00027 using namespace Windows::UI::Text;
00028 using namespace Windows::UI::Xaml::Controls;
00029 using namespace Windows::UI::Xaml::Documents;
00030 using namespace Windows::UI::Xaml::Media;
00031 using namespace Windows::UI::Xaml::Media::Imaging;
00032 using namespace Windows::UI::Xaml::Navigation;
00033
00034
00035 ScenarioInput5::ScenarioInput5()
00036     :m_totalPages(0)
00037 {
00038     InitializeComponent();
00039 }
00040
00041 /// <summary>
00042 /// Provide print content for scenario 5 first page
00043 /// </summary>
00044 void ScenarioInput5::PreparetPrintContent()
00045 {
00046     if (FirstPage == nullptr)
00047     {
00048         FirstPage = ref new ScenarioOutput5();
00049         StackPanel^ header = safe_cast<StackPanel^>(FirstPage->FindName("header"));
00050         header->Visibility = Windows::UI::Xaml::Visibility::Visible;
00051     }
00052
00053     // Add the (newley created) page to the printing root which is part of the visual tree and force it to go
00054     // through layout so that the linked containers correctly distribute the content inside them.
00055     PrintingRoot->Children->Append(FirstPage);
00056     PrintingRoot->InvalidateMeasure();
00057     PrintingRoot->UpdateLayout();
00058 }
00059
00060 /// <summary>
00061 /// Removes pages that are not in the given range
00062 /// </summary>
00063 /// <param name="sender">The list of preview pages</param>
00064 /// <param name="e"></param>
00065 /// <note> Handling preview for page range
00066 /// Developers have the control over how the preview should look when the user specifies a valid page range.
00067 /// There are three common ways to handle this:
00068 /// 1) Preview remains unaffected by the page range and all the pages are shown independent of the specified page range.
00069 /// 2) Preview is changed and only the pages specified in the range are shown to the user.
00070 /// 3) Preview is changed, showing all the pages and graying out the pages not in page range.
00071 /// We chose option (2) for this sample, developers can choose their preview option.
00072 /// </note>
00073 void ScenarioInput5::OnContentCreated()
00074 {
00075     m_totalPages = PrintPreviewPages;
00076
00077     if (m_pageRangeEditVisible)
00078     {
00079         // ignore page range if there are any invalid pages regarding current context
00080         if(m_pageList.size() > 0 &&
00081            std::find_if(m_pageList.begin(), m_pageList.end(),
00082                         [this](int page)
00083                         {
00084                             return page > static_cast<int>(m_totalPages);
00085                         }
00086                        ) == m_pageList.end())
00087         {
00088             for(int it = static_cast<int>(PrintPreviewPages) - 1; it >= 0; --it)
00089             {
00090                 if(m_pageList.end() == std::find(m_pageList.begin(), m_pageList.end(), it + 1))
00091                 {
00092                     RemovePageFromPrintPreviewCollection(it);
00093                 }
00094             }
00095         }
00096     }
00097 }
00098
00099 /// <summary>
00100 /// This is the event handler for PrintManager.PrintTaskRequested.
00101 /// 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.
00102 /// Therefore, we use this handler to only create the print task.
00103 /// The print settings customization can be done when the print document source is requested.
00104 /// </summary>
00105 /// <param name="sender">PrintManager</param>
00106 /// <param name="e">PrintTaskRequestedEventArgs</param>
00107 void ScenarioInput5::PrintTaskRequested(PrintManager^ sender, PrintTaskRequestedEventArgs^ e)
00108 {
00109     auto printTaskRef = std::make_shared<PrintTask^>(nullptr);
00110     *printTaskRef = e->Request->CreatePrintTask(L"C++ Printing SDK Sample",
00111                                                 ref new PrintTaskSourceRequestedHandler([this, printTaskRef](PrintTaskSourceRequestedArgs^ args)
00112                                                 {
00113                                                     PrintTask^ printTask = *printTaskRef;
00114                                                     PrintTaskOptionDetails^ printDetailedOptions = PrintTaskOptionDetails::GetFromPrintTaskOptions(printTask->Options);
00115                                                     IVector<String^>^ displayedOptions = printDetailedOptions->DisplayedOptions;
00116
00117                                                     // Choose the printer options to be shown.
00118                                                     // The order in which the options are appended determines the order in which they appear in the UI
00119                                                     displayedOptions->Clear();
00120
00121                                                     displayedOptions->Append(StandardPrintTaskOptions::Copies);
00122                                                     displayedOptions->Append(StandardPrintTaskOptions::Orientation);
00123                                                     displayedOptions->Append(StandardPrintTaskOptions::ColorMode);
00124
00125                                                     // Create a new list option
00126
00127                                                     PrintCustomItemListOptionDetails^ pageFormat = printDetailedOptions->CreateItemListOption(L"PageRange", L"Page Range");
00128                                                     pageFormat->AddItem(L"PrintAll", L"Print all");
00129                                                     pageFormat->AddItem(L"PrintSelection", L"Print Selection");
00130                                                     pageFormat->AddItem(L"PrintRange", L"Print Range");
00131
00132                                                     // Add the custom option to the option list
00133                                                     displayedOptions->Append(L"PageRange");
00134
00135                                                     // Create new edit option
00136                                                     PrintCustomTextOptionDetails^ pageRangeEdit = printDetailedOptions->CreateTextOption(L"PageRangeEdit", L"Range");
00137
00138                                                     // Register the handler for the option change event
00139                                                     printDetailedOptions->OptionChanged += ref new TypedEventHandler<PrintTaskOptionDetails^, PrintTaskOptionChangedEventArgs^>(this, &ScenarioInput5::printDetailedOptions_OptionChanged);
00140
00141                                                     // Print Task event handler is invoked when the print job is completed.
00142                                                     printTask->Completed += ref new TypedEventHandler<PrintTask^, PrintTaskCompletedEventArgs^>(
00143                                                     [=](PrintTask^ sender, PrintTaskCompletedEventArgs^ e)
00144                                                     {
00145                                                         m_pageRangeEditVisible = false;
00146                                                         m_selectionMode = false;
00147                                                         m_pageList.clear();
00148
00149                                                         // Notify the user when the print operation fails.
00150                                                         if (e->Completion == Windows::Graphics::Printing::PrintTaskCompletion::Failed)
00151                                                         {
00152                                                             auto callback = ref new Windows::UI::Core::DispatchedHandler(
00153                                                             [=]()
00154                                                             {
00155                                                                 RootPage->NotifyUser(ref new String(L"Failed to print."), NotifyType::ErrorMessage);
00156                                                             });
00157
00158                                                             Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, callback);
00159                                                         }
00160
00161                                                         auto callback = ref new Windows::UI::Core::DispatchedHandler(
00162                                                         [=]()
00163                                                         {
00164                                                             // Restore first page to its default layout
00165                                                             // Undo any changes made by a text selection
00166                                                             ShowContent(nullptr);
00167                                                         });
00168
00169                                                         Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, callback);
00170                                                     });
00171
00172                                                     args->SetSource(PrintDocumentSource);
00173                                                 }));
00174 }
00175
00176 /// <summary>
00177 /// Option change event handler
00178 /// </summary>
00179 /// <param name="sender">PrintTaskOptionsDetails object</param>
00180 /// <param name="args">the event arguments containing the changed option id</param>
00181 void ScenarioInput5::printDetailedOptions_OptionChanged(PrintTaskOptionDetails^ sender, PrintTaskOptionChangedEventArgs^ args)
00182 {
00183     if (args->OptionId == nullptr)
00184         return;
00185
00186     String^ optionId = args->OptionId->ToString();
00187
00188     // Handle change in Page Range Option
00189
00190     if (optionId == L"PageRange")
00191     {
00192         IPrintOptionDetails^ pageRange = sender->Options->Lookup(optionId);
00193         String^ pageRangeValue = pageRange->Value->ToString();
00194
00195         m_selectionMode = false;
00196
00197         if(pageRangeValue == L"PrintRange")
00198         {
00199             // Add PageRangeEdit custom option to the option list
00200             sender->DisplayedOptions->Append(L"PageRangeEdit");
00201             m_pageRangeEditVisible = true;
00202
00203             auto callback = ref new Windows::UI::Core::DispatchedHandler(
00204             [=]()
00205             {
00206                 // Restore first page to its default layout
00207                 // Undo any changes made by a text selection
00208                 ShowContent(nullptr);
00209             });
00210
00211             Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, callback);
00212         }
00213         else if(pageRangeValue == L"PrintSelection")
00214         {
00215             Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal,
00216                                  ref new Windows::UI::Core::DispatchedHandler([this]()
00217                                                             {
00218                                                                 ScenarioOutput5^ outputScenario = safe_cast<ScenarioOutput5^>(RootPage->OutputFrame->Content);
00219
00220                                                                 ShowContent(outputScenario->SelectedText);
00221                                                             }));
00222             RemovePageRangeEdit(sender);
00223         }
00224         else
00225         {
00226             auto callback = ref new Windows::UI::Core::DispatchedHandler(
00227             [=]()
00228             {
00229                 // Restore first page to its default layout
00230                 // Undo any changes made by a text selection
00231                 ShowContent(nullptr);
00232             });
00233
00234             Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, callback);
00235             RemovePageRangeEdit(sender);
00236         }
00237
00238         RefreshPreview();
00239
00240     }
00241     else if (optionId == L"PageRangeEdit")
00242     {
00243         IPrintOptionDetails^ pageRange = sender->Options->Lookup(optionId);
00244
00245         // Expected range format (p1,p2...)*, (p3-p9)* ...
00246         std::wregex rangePattern(L"^\\s*\\d+\\s*(\\-\\s*\\d+\\s*)?(\\,\\s*\\d+\\s*(\\-\\s*\\d+\\s*)?)*$");
00247         std::wstring pageRangeValue(pageRange->Value->ToString()->Data());
00248
00249         if(!std::regex_match(pageRangeValue.begin(), pageRangeValue.end(), rangePattern))
00250         {
00251             pageRange->ErrorText = L"Invalid Page Range (eg: 1-3, 5)";
00252         }
00253         else
00254         {
00255             pageRange->ErrorText = L"";
00256             try
00257             {
00258                 GetPagesInRange(pageRange->Value->ToString());
00259             }
00260             catch(InvalidPageException* rangeException)
00261             {
00262                 pageRange->ErrorText = ref new String(rangeException->get_DisplayMessage().data());
00263
00264                 delete rangeException;
00265             }
00266
00267             RefreshPreview();
00268         }
00269     }
00270 }
00271
00272 /// <summary>
00273 /// Helper function used to split a string based on some delimiters
00274 /// </summary>
00275 /// <param name="string">String to be splited</param>
00276 /// <param name="delimiter">Delimiter character used to split the string</param>
00277 /// <param name="words">Splited words</param>
00278 void ScenarioInput5::SplitString(String^ string, wchar_t delimiter, std::vector<std::wstring>& words)
00279 {
00280     std::wistringstream iss(string->Data());
00281
00282     std::wstring part;
00283     while(std::getline(iss, part, delimiter))
00284     {
00285         words.push_back(part);
00286     };
00287 }
00288
00289 /// <summary>
00290 /// This is where we parse the range field
00291 /// </summary>
00292 /// <param name="pageRange">the page range value</param>
00293 void ScenarioInput5::GetPagesInRange(String^ pageRange)
00294 {
00295     std::vector<std::wstring> vector_range;
00296     SplitString(pageRange, ',', vector_range);
00297
00298     // Clear the previous values
00299     m_pageList.clear();
00300
00301     for(std::vector<std::wstring>::iterator it = vector_range.begin(); it != vector_range.end(); ++ it)
00302     {
00303         int intervalPos = static_cast<int>((*it).find('-'));
00304         if( intervalPos != -1)
00305         {
00306             int start = _wtoi((*it).substr(0, intervalPos).data());
00307             int end = _wtoi((*it).substr(intervalPos + 1, (*it).length() - intervalPos - 1).data());
00308
00309             if ((start < 1) || (end > static_cast<int>(m_totalPages)) || (start >= end))
00310             {
00311                 std::wstring message(L"Invalid page(s) in range ");
00312
00313                 message.append(std::to_wstring(start));
00314                 message.append(L" - ");
00315                 message.append(std::to_wstring(end));
00316
00317                 throw new InvalidPageException(message);
00318             }
00319
00320             for(int intervalPage=start; intervalPage <= end; ++intervalPage)
00321             {
00322                 m_pageList.push_back(intervalPage);
00323             }
00324         }
00325         else
00326         {
00327             int pageNr = _wtoi((*it).data());
00328             std::wstring message(L"Invalid page ");
00329
00330             if (pageNr < 1)
00331             {
00332                 message.append(std::to_wstring(pageNr));
00333                 throw new InvalidPageException(message);
00334             }
00335
00336             if (pageNr > static_cast<int>(m_totalPages))
00337             {
00338                 message.append(std::to_wstring(pageNr));
00339                 throw new InvalidPageException(message);
00340             }
00341
00342             m_pageList.push_back(pageNr);
00343         }
00344     }
00345
00346     // sort in decreasing order
00347     std::sort(m_pageList.begin(), m_pageList.end(), std::greater<int>());
00348     // remove duplicates
00349     std::unique(m_pageList.begin(), m_pageList.end());
00350 }
00351
00352 /// <summary>
00353 /// Helper function used to triger a preview refresh
00354 /// </summary>
00355 void ScenarioInput5::RefreshPreview()
00356 {
00357     auto callback = ref new Windows::UI::Core::DispatchedHandler([this]()
00358                                                                   {
00359                                                                     CurrentPrintDocument->InvalidatePreview();
00360                                                                   });
00361
00362     Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, callback);
00363 }
00364
00365 /// <summary>
00366 /// Removes the PageRange edit from the charm window
00367 /// </summary>
00368 /// <param name="printTaskOptionDetails">Details regarding PrintTaskOptions</param>
00369 void ScenarioInput5::RemovePageRangeEdit(PrintTaskOptionDetails^ printTaskOptionDetails)
00370 {
00371     if (m_pageRangeEditVisible)
00372     {
00373         unsigned int index;
00374         if(printTaskOptionDetails->DisplayedOptions->IndexOf(ref new String(L"PageRangeEdit"), &index))
00375         {
00376             printTaskOptionDetails->DisplayedOptions->RemoveAt(index);
00377         }
00378         m_pageRangeEditVisible = false;
00379     }
00380 }
00381
00382 void ScenarioInput5::ShowContent(String^ selectionText)
00383 {
00384     bool hasSelection = selectionText != nullptr && !selectionText->IsEmpty();
00385     m_selectionMode = hasSelection;
00386
00387     // Hide/show images depending by the selected text
00388     StackPanel^ header = safe_cast<StackPanel^>(FirstPage->FindName("header"));
00389     header->Visibility = hasSelection ? Windows::UI::Xaml::Visibility::Collapsed : Windows::UI::Xaml::Visibility::Visible;
00390     Grid^ pageContent = safe_cast<Grid^>(FirstPage->FindName("printableArea"));
00391     pageContent->RowDefinitions->GetAt(0)->Height = GridLengthHelper::Auto;
00392
00393     Image^ scenarioImage = safe_cast<Image^>(FirstPage->FindName("scenarioImage"));
00394     scenarioImage->Visibility = hasSelection ? Windows::UI::Xaml::Visibility::Collapsed : Windows::UI::Xaml::Visibility::Visible;
00395
00396     // Expand the middle paragraph on the full page if printing only selected text
00397     RichTextBlockOverflow^ firstLink = safe_cast<RichTextBlockOverflow^>(FirstPage->FindName("firstLinkedContainer"));
00398     firstLink->SetValue(Grid::ColumnSpanProperty, hasSelection ? 2 : 1);
00399
00400     // Clear(hide) current text and add only the selection if a selection exists
00401     RichTextBlock^ mainText = safe_cast<RichTextBlock^>(FirstPage->FindName("textContent"));
00402     RichTextBlock^ textSelection = safe_cast<RichTextBlock^>(FirstPage->FindName("textSelection"));
00403
00404     // Main (default) scenario text
00405     mainText->Visibility = hasSelection ? Windows::UI::Xaml::Visibility::Collapsed : Windows::UI::Xaml::Visibility::Visible;
00406     mainText->OverflowContentTarget = hasSelection ? nullptr : firstLink;
00407
00408     // Scenario text-blocks used for displaying selection
00409     textSelection->OverflowContentTarget = hasSelection ? firstLink : nullptr;
00410     textSelection->Visibility = hasSelection ? Windows::UI::Xaml::Visibility::Visible : Windows::UI::Xaml::Visibility::Collapsed;
00411     textSelection->Blocks->Clear();
00412
00413     // Force the visual root to go through layout so that the linked containers correctly distribute the content inside them.
00414     PrintingRoot->InvalidateArrange();
00415     PrintingRoot->InvalidateMeasure();
00416     PrintingRoot->UpdateLayout();
00417
00418     // Add the selection if any
00419     if (hasSelection)
00420     {
00421         Run^ inlineText = ref new Run();
00422         inlineText->Text = selectionText;
00423
00424         Paragraph^ paragraph = ref new Paragraph();
00425         paragraph->Inlines->Append(inlineText);
00426
00427         textSelection->Blocks->Append(paragraph);
00428     }
00429 }
00430
00431 /// <summary>
00432 /// This function creates and adds one print preview page to the internal cache of print preview
00433 /// pages stored in m_printPreviewPages.
00434 /// </summary>
00435 /// <param name="lastRTBOAdded">Last RichTextBlockOverflow element added in the current content</param>
00436 /// <param name="printPageDescription">Printer's page description</param>
00437 RichTextBlockOverflow^ ScenarioInput5::AddOnePrintPreviewPage(RichTextBlockOverflow^ lastRTBOAdded, Windows::Graphics::Printing::PrintPageDescription printPageDescription)
00438 {
00439     RichTextBlockOverflow^ textLink = BasePrintPage::AddOnePrintPreviewPage(lastRTBOAdded, printPageDescription);
00440
00441     ScenarioOutput5^ outputScenario = safe_cast<ScenarioOutput5^>(RootPage->OutputFrame->Content);
00442
00443     // Don't show footer in selection mode
00444     if(m_selectionMode)
00445     {
00446         FrameworkElement^ page = safe_cast<FrameworkElement^>(PrintingRoot->Children->GetAt(PrintingRoot->Children->Size -1));
00447         StackPanel^ footer = safe_cast<StackPanel^>(page->FindName("footer"));
00448         footer->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00449     }
00450
00451     return textLink;
00452 }
00453
00454 void ScenarioInput5::OnNavigatedTo(NavigationEventArgs^ e)
00455 {
00456     BasePrintPage::OnNavigatedTo(e);
00457
00458     RegisterForPrinting();
00459 }
00460
00461 void ScenarioInput5::OnNavigatedFrom(NavigationEventArgs^ e)
00462 {
00463     UnregisterForPrinting() ;
00464 }
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

QiList< InterfaceName, InterfaceChain > Member List

This is the complete list of members for QiList< InterfaceName, InterfaceChain >, including all inherited members.
QueryInterfaceInternal(IID const &iid, OUT void **ppObject) QiList< InterfaceName, InterfaceChain > [inline]
Generated on Sat Nov 23 2024 16:09:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Samples::Devices::Repeater Member List

This is the complete list of members for Samples::Devices::Repeater, including all inherited members.
GetState(void) | Samples::Devices::Repeater | [inline]
GetState(void) | Samples::Devices::Repeater | [inline]
GetState(void) | Samples::Devices::Repeater | [inline]
m_Canceller | Samples::Devices::Repeater | [private]
m_Lock | Samples::Devices::Repeater | [private]
m_RepeaterStoppedFunction | Samples::Devices::Repeater | [private]
m_StartTaskFunction | Samples::Devices::Repeater | [private]
m_State | Samples::Devices::Repeater | [private]
mlt typedef | Samples::Devices::Repeater | [private]
mlt typedef | Samples::Devices::Repeater | [private]
mlt typedef | Samples::Devices::Repeater | [private]
Repeater() | Samples::Devices::Repeater | [inline]
Repeater() | Samples::Devices::Repeater | [inline]
Repeater() | Samples::Devices::Repeater | [inline]
RepeaterState enum name | Samples::Devices::Repeater |
RepeaterState enum name | Samples::Devices::Repeater |
RepeaterState enum name | Samples::Devices::Repeater |
RestartTask(concurrency::task_continuation_context context, bool Continue) | Samples::Devices::Repeater | [inline, private]
RestartTask(concurrency::task_continuation_context context, bool Continue) | Samples::Devices::Repeater | [inline, private]
RestartTask(concurrency::task_continuation_context context, bool Continue) | Samples::Devices::Repeater | [inline, private]
Running enum value | Samples::Devices::Repeater |
Start(Details::StartRepeaterTaskFunction StartTaskFunction, concurrency::task_continuation_context Context=concurrency::task_continuation_context::use_current()) | Samples::Devices::Repeater | [inline]
Start(Details::StartRepeaterTaskFunction StartTaskFunction, concurrency::task_continuation_context Context=concurrency::task_continuation_context::use_current()) | Samples::Devices::Repeater | [inline]
Start(Details::StartRepeaterTaskFunction StartTaskFunction, concurrency::task_continuation_context Context=concurrency::task_continuation_context::use_current()) | Samples::Devices::Repeater | [inline]
StartTask(concurrency::task_continuation_context context) | Samples::Devices::Repeater | [inline, private]
StartTask(concurrency::task_continuation_context context) | Samples::Devices::Repeater | [inline, private]
StartTask(concurrency::task_continuation_context context) | Samples::Devices::Repeater | [inline, private]
Stop(Details::RepeaterStoppedFunction *callback=nullptr) | Samples::Devices::Repeater | [inline]
Stop(Details::RepeaterStoppedFunction *callback=nullptr) | Samples::Devices::Repeater | [inline]
Stop(Details::RepeaterStoppedFunction *callback=nullptr) | Samples::Devices::Repeater | [inline]
Stopped enum value | Samples::Devices::Repeater |
Stopping enum value | Samples::Devices::Repeater |
~Repeater() | Samples::Devices::Repeater | [inline]
~Repeater() | Samples::Devices::Repeater | [inline]
~Repeater() | Samples::Devices::Repeater | [inline]
Generated on Sat Nov 23 2024 16:09:46 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Compass sensor/C++/common/suspensionmanager.cpp Source File

  • Compass sensor
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Push and periodic notifications client-side/C++/App.xaml.h Source File

  • Push and periodic notifications client-side

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Hilo::WideFiveImageTile Member List

This is the complete list of members for Hilo::WideFiveImageTile, including all inherited members.
GetTileNotification() | Hilo::WideFiveImageTile |
m_fileNames | Hilo::WideFiveImageTile | [private]
m_loader | Hilo::WideFiveImageTile | [private]
SetImageFilePaths(const std::vector< std::wstring > &fileNames) | Hilo::WideFiveImageTile |
UpdateContentWithValues(Windows::Data::Xml::Dom::XmlDocument^content) | Hilo::WideFiveImageTile | [private]
WideFiveImageTile() | Hilo::WideFiveImageTile |
WideFiveImageTile(IResourceLoader^loader) | Hilo::WideFiveImageTile |
Generated on Sat Nov 23 2024 16:09:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/NullPhotoGroup.h Source File

  • Hilo C++
  • Hilo

NullPhotoGroup.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
00009 #include "IPhotoGroup.h"
00010
00011 namespace Hilo
00012 {
00013     interface class IPhoto;
00014
00015     // Instances of the NullPhotoGroup class are placeholders used by photos that are not part of any group.
00016     ref class NullPhotoGroup : public IPhotoGroup
00017     {
00018
00019     internal:
00020         virtual operator Windows::Storage::IStorageFolder^ ()
00021         {
00022             return nullptr;
00023         }
00024
00025     public:
00026         property Platform::String^ Title
00027         {
00028             virtual Platform::String^ get()
00029             {
00030                 return "";
00031             }
00032         }
00033
00034         property Windows::Foundation::Collections::IObservableVector<IPhoto^>^ Items
00035         {
00036             virtual Windows::Foundation::Collections::IObservableVector<IPhoto^>^ get()
00037             {
00038                 return nullptr;
00039             }
00040         }
00041     };
00042 }
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D stereoscopic 3D/C++/DirectXBase.h Source File

  • Direct3D stereoscopic 3D

DirectXBase.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 "DirectXSample.h"
00011
00012 // Helper class that initializes DirectX APIs for both 2D and 3D rendering.
00013 // Some of the code in this class may be omitted if only 2D or only 3D rendering is being used.
00014 ref class DirectXBase abstract
00015 {
00016 internal:
00017     DirectXBase();
00018
00019     virtual void Initialize(Windows::UI::Core::CoreWindow^ window, float dpi);
00020     virtual void HandleDeviceLost();
00021     virtual void CreateDeviceIndependentResources();
00022     virtual void CreateDeviceResources();
00023     virtual void SetDpi(float dpi);
00024     virtual void UpdateForWindowSizeChange();
00025     virtual void CreateWindowSizeDependentResources();
00026     virtual void Render() = 0;
00027     virtual void Present();
00028
00029     bool GetStereoEnabledStatus();
00030
00031 protected private:
00032     void OnStereoEnabledChanged(_In_ Platform::Object^ sender);
00033     void UpdateStereoEnabledStatus();
00034
00035     Platform::Agile<Windows::UI::Core::CoreWindow>  m_window;
00036
00037     // DirectWrite & Windows Imaging Component Objects.
00038     Microsoft::WRL::ComPtr<IDWriteFactory1>         m_dwriteFactory;
00039     Microsoft::WRL::ComPtr<IWICImagingFactory2>     m_wicFactory;
00040
00041     // DirectX Core Objects. Required for 2D and 3D.
00042     Microsoft::WRL::ComPtr<ID3D11Device1>           m_d3dDevice;
00043     Microsoft::WRL::ComPtr<ID3D11DeviceContext1>    m_d3dContext;
00044     Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00045     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00046     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetViewRight;
00047
00048     // Direct2D Rendering Objects. Required for 2D.
00049     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00050     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00051     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00052     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmap;
00053     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmapRight;
00054
00055     // Direct3D Rendering Objects. Required for 3D.
00056     Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00057
00058     // Cached renderer properties.
00059     D3D_FEATURE_LEVEL                               m_featureLevel;
00060     Windows::Foundation::Size                       m_renderTargetSize;
00061     Windows::Foundation::Rect                       m_windowBounds;
00062     float                                           m_dpi;
00063     bool                                            m_windowSizeChangeInProgress;
00064     bool                                            m_stereoEnabled;
00065 };
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D HLSL fractal generator/C++/DoublePrecisionMath.h Source File

  • Direct3D HLSL fractal generator

DoublePrecisionMath.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 typedef Vector2<double> double2;
00011
00012 typedef Matrix4x4<double> double4x4;
00013
00014 inline double4x4 identityDouble()
00015 {
00016     double4x4 mOut;
00017
00018     mOut._11 = 1.0; mOut._12 = 0.0; mOut._13 = 0.0; mOut._14 = 0.0;
00019     mOut._21 = 0.0; mOut._22 = 1.0; mOut._23 = 0.0; mOut._24 = 0.0;
00020     mOut._31 = 0.0; mOut._32 = 0.0; mOut._33 = 1.0; mOut._34 = 0.0;
00021     mOut._41 = 0.0; mOut._42 = 0.0; mOut._43 = 0.0; mOut._44 = 1.0;
00022
00023     return mOut;
00024 }
00025
00026 inline double4x4 translationDouble(double x, double y, double z)
00027 {
00028     double4x4 mOut;
00029
00030     mOut._11 = 1.0; mOut._12 = 0.0; mOut._13 = 0.0; mOut._14 = x;
00031     mOut._21 = 0.0; mOut._22 = 1.0; mOut._23 = 0.0; mOut._24 = y;
00032     mOut._31 = 0.0; mOut._32 = 0.0; mOut._33 = 1.0; mOut._34 = z;
00033     mOut._41 = 0.0; mOut._42 = 0.0; mOut._43 = 0.0; mOut._44 = 1.0;
00034
00035     return mOut;
00036 }
00037
00038 inline double4x4 scaleDouble(double x, double y, double z)
00039 {
00040     double4x4 mOut;
00041
00042     mOut._11 = x;   mOut._12 = 0.0; mOut._13 = 0.0; mOut._14 = 0.0;
00043     mOut._21 = 0.0; mOut._22 = y;   mOut._23 = 0.0; mOut._24 = 0.0;
00044     mOut._31 = 0.0; mOut._32 = 0.0; mOut._33 = z;   mOut._34 = 0.0;
00045     mOut._41 = 0.0; mOut._42 = 0.0; mOut._43 = 0.0; mOut._44 = 1.0;
00046
00047     return mOut;
00048 }
00049
00050 inline double4x4 rotationZDouble(double degreeZ)
00051 {
00052     double angleInRadians = degreeZ * (M_PI / 180.0);
00053
00054     double sinAngle = sin(angleInRadians);
00055     double cosAngle = cos(angleInRadians);
00056
00057     double4x4 mOut;
00058
00059     mOut._11 = cosAngle; mOut._12 = -sinAngle; mOut._13 = 0.0; mOut._14 = 0.0;
00060     mOut._21 = sinAngle; mOut._22 = cosAngle;  mOut._23 = 0.0; mOut._24 = 0.0;
00061     mOut._31 = 0.0;      mOut._32 = 0.0;       mOut._33 = 1.0; mOut._34 = 0.0;
00062     mOut._41 = 0.0;      mOut._42 = 0.0;       mOut._43 = 0.0; mOut._44 = 1.0;
00063
00064     return mOut;
00065 }
00066
00067 inline double4x4 mulDouble(double4x4 m1, double4x4 m2)
00068 {
00069     double4x4 mr;
00070     mr._11 = m1._11 * m2._11 + m1._12 * m2._21 + m1._13 * m2._31 + m1._14 * m2._41;
00071     mr._12 = m1._11 * m2._12 + m1._12 * m2._22 + m1._13 * m2._32 + m1._14 * m2._42;
00072     mr._13 = m1._11 * m2._13 + m1._12 * m2._23 + m1._13 * m2._33 + m1._14 * m2._43;
00073     mr._14 = m1._11 * m2._14 + m1._12 * m2._24 + m1._13 * m2._34 + m1._14 * m2._44;
00074     mr._21 = m1._21 * m2._11 + m1._22 * m2._21 + m1._23 * m2._31 + m1._24 * m2._41;
00075     mr._22 = m1._21 * m2._12 + m1._22 * m2._22 + m1._23 * m2._32 + m1._24 * m2._42;
00076     mr._23 = m1._21 * m2._13 + m1._22 * m2._23 + m1._23 * m2._33 + m1._24 * m2._43;
00077     mr._24 = m1._21 * m2._14 + m1._22 * m2._24 + m1._23 * m2._34 + m1._24 * m2._44;
00078     mr._31 = m1._31 * m2._11 + m1._32 * m2._21 + m1._33 * m2._31 + m1._34 * m2._41;
00079     mr._32 = m1._31 * m2._12 + m1._32 * m2._22 + m1._33 * m2._32 + m1._34 * m2._42;
00080     mr._33 = m1._31 * m2._13 + m1._32 * m2._23 + m1._33 * m2._33 + m1._34 * m2._43;
00081     mr._34 = m1._31 * m2._14 + m1._32 * m2._24 + m1._33 * m2._34 + m1._34 * m2._44;
00082     mr._41 = m1._41 * m2._11 + m1._42 * m2._21 + m1._43 * m2._31 + m1._44 * m2._41;
00083     mr._42 = m1._41 * m2._12 + m1._42 * m2._22 + m1._43 * m2._32 + m1._44 * m2._42;
00084     mr._43 = m1._41 * m2._13 + m1._42 * m2._23 + m1._43 * m2._33 + m1._44 * m2._43;
00085     mr._44 = m1._41 * m2._14 + m1._42 * m2._24 + m1._43 * m2._34 + m1._44 * m2._44;
00086     return mr;
00087 }
00088
00089 inline double2 mulDouble(double2 v, double4x4 m)
00090 {
00091     return double2(
00092         v.x * m._11 + v.y * m._12 + m._14,
00093         v.x * m._21 + v.y * m._22 + m._24
00094     );
00095 }
00096
00097 inline float4x4 convert(double4x4 m)
00098 {
00099     float4x4 mr;
00100     mr._11 = static_cast<float>(m._11); mr._12 = static_cast<float>(m._12); mr._13 = static_cast<float>(m._13); mr._14 = static_cast<float>(m._14);
00101     mr._21 = static_cast<float>(m._21); mr._22 = static_cast<float>(m._22); mr._23 = static_cast<float>(m._23); mr._24 = static_cast<float>(m._24);
00102     mr._31 = static_cast<float>(m._31); mr._32 = static_cast<float>(m._32); mr._33 = static_cast<float>(m._33); mr._34 = static_cast<float>(m._34);
00103     mr._41 = static_cast<float>(m._41); mr._42 = static_cast<float>(m._42); mr._43 = static_cast<float>(m._43); mr._44 = static_cast<float>(m._44);
00104     return mr;
00105 }
Generated on Sat Nov 23 2024 16:08:11 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Bluetooth call control/C++/common/suspensionmanager.h Source File

  • Bluetooth call control
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Contact Picker app/C++/MainPagePicker.xaml.h Source File

  • Contact Picker app

MainPagePicker.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 // MainPagePicker.xaml.h
00013 // Declaration of the MainPagePicker.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPagePicker.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace ContactPicker
00024 {
00025     public ref class MainPagePickerSizeChangedEventArgs sealed
00026     {
00027     public:
00028         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00029         {
00030             Windows::UI::ViewManagement::ApplicationViewState get()
00031             {
00032                 return viewState;
00033             }
00034
00035             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00036             {
00037                 viewState = value;
00038             }
00039         }
00040
00041     private:
00042         Windows::UI::ViewManagement::ApplicationViewState viewState;
00043     };
00044
00045     [Windows::Foundation::Metadata::WebHostHidden]
00046     public ref class MainPagePicker sealed
00047     {
00048     public:
00049         MainPagePicker();
00050
00051         property bool AutoSizeInputSectionWhenSnapped
00052         {
00053             bool get()
00054             {
00055                 return autoSizeInputSectionWhenSnapped;
00056             }
00057
00058             void set(bool value)
00059             {
00060                 autoSizeInputSectionWhenSnapped = value;
00061             }
00062         }
00063
00064         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00065         void LoadScenario(Platform::String^ scenarioName);
00066         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00067         event Windows::Foundation::EventHandler<MainPagePickerSizeChangedEventArgs^>^ MainPagePickerResized;
00068
00069
00070     private:
00071         void SetContactPicker(Platform::String^ strFeature);
00072         void PopulateScenarios();
00073         void InvalidateSize();
00074         void InvalidateViewState();
00075         ~MainPagePicker();
00076
00077         Platform::Collections::Vector<Object^>^ ScenarioList;
00078         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00079         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080         bool autoSizeInputSectionWhenSnapped;
00081
00082     protected:
00083         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00084         void MainPagePicker_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00085         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00086
00087     internal:
00088         static MainPagePicker^ Current;
00089         Windows::ApplicationModel::Contacts::Provider::ContactPickerUI^ contactPickerUI;
00090     };
00091
00092 }
Generated on Sat Nov 23 2024 16:07:59 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML personality animations/C++/common/LayoutAwarePage.h Source File

  • XAML personality animations
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Splash screen/C++/Constants.h Source File

  • Splash screen

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"Splash screen C++ sample");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041
00042     private:
00043         static Platform::Array<Scenario>^ scenariosInner;
00044     };
00045 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: LightSensor/C++/common/LayoutAwarePage.cpp Source File

  • LightSensor
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:32 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

MediaExtensionsCS::ScenarioInput2 Member List

This is the complete list of members for MediaExtensionsCS::ScenarioInput2, including all inherited members.
__pad0__ | Element |
AcceptChildNode(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^childXmlNode) override | Page | [virtual]
AddChild(_In_ Element^element) | Element |
AddSibling(_In_ Element^element) | Element |
BindResource(_In_ Element^rootElement) | Element | [virtual]
Circle_Click(object sender, RoutedEventArgs e) | MediaExtensionsCS::ScenarioInput2 | [inline, private]
Create(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^xmlNode) | Element | [static]
Draw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
GetFirstChild() | Element | [inline]
GetName() | Element | [inline]
GetNextSibling() | Element | [inline]
GetOpacity() | Element | [inline, virtual]
GetParent() | Element | [inline]
GetSize() | Element | [inline]
Initialize(_In_ Document^document, _In_ Windows::Data::Xml::Dom::XmlElement^xmlElement) | Element | [virtual]
Measure(_In_ Document^document, D2D1_SIZE_F const &parentSize, _Out_ D2D1_RECT_F *bounds) | Element | [virtual]
OnNavigatedFrom(NavigationEventArgs e) | MediaExtensionsCS::ScenarioInput2 | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | MediaExtensionsCS::ScenarioInput2 | [inline, protected]
outputVideo | MediaExtensionsCS::ScenarioInput2 | [private]
PrepareToDraw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
ReleaseParent() | Element | [virtual]
rootPage | MediaExtensionsCS::ScenarioInput2 | [private]
rootPage_OutputFrameLoaded(object sender, object e) | MediaExtensionsCS::ScenarioInput2 | [inline, private]
ScenarioInput2() | MediaExtensionsCS::ScenarioInput2 | [inline]
Square_Click(object sender, RoutedEventArgs e) | MediaExtensionsCS::ScenarioInput2 | [inline, private]
Triangle_Click(object sender, RoutedEventArgs e) | MediaExtensionsCS::ScenarioInput2 | [inline, private]
Generated on Sat Nov 23 2024 16:09:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML Popup/C++/common/LayoutAwarePage.cpp Source File

  • XAML Popup
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:33 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

MEPlayer Member List

This is the complete list of members for MEPlayer, including all inherited members.
__pad0__ | MEPlayer |
AutoPlay(BOOL autoPlay) | MEPlayer | [inline]
CloseFilePicker() | MEPlayer | [inline]
CreateBackBuffers() | MEPlayer |
CreateDX11Device() | MEPlayer |
EnableVideoEffect(BOOL enable) | MEPlayer |
ExitApp() | MEPlayer |
FrameStep() | MEPlayer |
GetDuration(double *pDuration, BOOL *pbCanSeek) | MEPlayer |
GetPlaybackPosition() | MEPlayer |
Initialize(Windows::UI::Core::CoreWindow^window) | MEPlayer |
IsPlaying() | MEPlayer | [inline]
IsSeeking() | MEPlayer |
Loop() | MEPlayer | [inline]
m_bkgColor | MEPlayer |
m_bstrURL | MEPlayer |
m_critSec | MEPlayer |
m_d3dFormat | MEPlayer |
m_fEOS | MEPlayer |
m_fExitApp | MEPlayer |
m_fInitSuccess | MEPlayer |
m_fLoop | MEPlayer |
m_fPlaying | MEPlayer |
m_fStopTimer | MEPlayer |
m_fUseDX | MEPlayer |
m_pickFileTask | MEPlayer |
m_rcTarget | MEPlayer |
m_spDX11Device | MEPlayer |
m_spDX11DeviceContext | MEPlayer |
m_spDX11SwapChain | MEPlayer |
m_spDXGIManager | MEPlayer |
m_spDXGIOutput | MEPlayer |
m_spEngineEx | MEPlayer |
m_spMediaEngine | MEPlayer |
m_tcs | MEPlayer |
m_TimerThreadHandle | MEPlayer |
m_window | MEPlayer | [private]
Mute(BOOL mute) | MEPlayer |
OnMediaEngineEvent(DWORD meEvent) override | MEPlayer | [virtual]
OnTimer() | MEPlayer |
OpenFile() | MEPlayer |
Pause() | MEPlayer |
Play() | MEPlayer |
RealVSyncTimer() | MEPlayer |
ResizeVideo(HWND hwnd) | MEPlayer |
SetBalance(float fBal) | MEPlayer |
SetBytestream(Windows::Storage::Streams::IRandomAccessStream^streamHandle) | MEPlayer |
SetPlaybackPosition(float pos) | MEPlayer |
SetURL(Platform::String^szURL) | MEPlayer |
SetVolume(float fVol) | MEPlayer |
Shutdown() | MEPlayer |
StartTimer() | MEPlayer |
StopTimer() | MEPlayer |
UpdateForWindowSizeChange() | MEPlayer |
~MEPlayer() | MEPlayer | [private]
Generated on Sat Nov 23 2024 16:09:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::TileContent::TileWideText07 Member List

This is the complete list of members for NotificationsExtensions::TileContent::TileWideText07, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
Branding | NotificationsExtensions::TileContent::TileNotificationBase |
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
RequireSquareContent | NotificationsExtensions::TileContent::TileWideBase |
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SquareContent | NotificationsExtensions::TileContent::TileWideBase |
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextColumn2Row1 | NotificationsExtensions::TileContent::TileWideText07 |
TextColumn2Row2 | NotificationsExtensions::TileContent::TileWideText07 |
TextColumn2Row3 | NotificationsExtensions::TileContent::TileWideText07 |
TextColumn2Row4 | NotificationsExtensions::TileContent::TileWideText07 |
TextFields | NotificationsExtensions::NotificationBase |
TextHeading | NotificationsExtensions::TileContent::TileWideText07 |
TextShortColumn1Row1 | NotificationsExtensions::TileContent::TileWideText07 |
TextShortColumn1Row2 | NotificationsExtensions::TileContent::TileWideText07 |
TextShortColumn1Row3 | NotificationsExtensions::TileContent::TileWideText07 |
TextShortColumn1Row4 | NotificationsExtensions::TileContent::TileWideText07 |
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWideText07() | NotificationsExtensions::TileContent::TileWideText07 | [inline]
TileWideText07() | NotificationsExtensions::TileContent::TileWideText07 | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:44 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML AppBar control/C++/GlobalPage.xaml.cpp Source File

  • XAML AppBar control

GlobalPage.xaml.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // GlobalPage.xaml.cpp
00003 // Implementation of the GlobalPage class
00004 //
00005
00006 #include "pch.h"
00007 #include "Page1.xaml.h"
00008 #include "GlobalPage.xaml.h"
00009
00010 using namespace AppBarControl;
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::Interop;
00021 using namespace Windows::UI::Xaml::Media;
00022 using namespace Windows::UI::Xaml::Navigation;
00023
00024 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00025 MainPage^ GlobalPage::rootPage = nullptr;
00026
00027 GlobalPage::GlobalPage()
00028 {
00029
00030   InitializeComponent();
00031   //Add Click handler to "Back" button
00032   Back->Click += ref new RoutedEventHandler(this, &GlobalPage::Back_Click);
00033 }
00034
00035
00036 // Invoked when this page is about to be displayed in a Frame.
00037 void GlobalPage::OnNavigatedTo(NavigationEventArgs^ e)
00038 {
00039   rootPage = (MainPage^) e->Parameter;
00040   TypeName page1 = {Page1::typeid->FullName, TypeKind::Custom};
00041   Frame1->Navigate(page1, this);
00042 }
00043
00044 void GlobalPage::Back_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00045 {
00046   if (Frame1->CanGoBack)
00047             {
00048                 Frame1->GoBack();
00049             }
00050             else
00051             {
00052                rootPage->Frame->GoBack();
00053             }
00054 }
Generated on Sat Nov 23 2024 16:08:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: UI contrast and settings/C++/pch.h Source File

  • UI contrast and settings

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media capture using capture device/C#,C++/App.xaml.cs Source File

  • Media capture using capture device
  • C#,C++

App.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.ApplicationModel;
00012 using Windows.ApplicationModel.Activation;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Navigation;
00016 using SDKTemplate;
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// Provides application-specific behavior to supplement the default Application class.
00022     /// </summary>
00023     sealed partial class App : Application
00024     {
00025         public LaunchActivatedEventArgs LaunchArgs;
00026
00027         /// <summary>
00028         /// Initializes the singleton application object.  This is the first line of authored code
00029         /// executed, and as such is the logical equivalent of main() or WinMain().
00030         /// </summary>
00031         public App()
00032         {
00033             this.InitializeComponent();
00034             this.Suspending += new SuspendingEventHandler(OnSuspending);
00035         }
00036
00037         async void OnSuspending(object sender, SuspendingEventArgs args)
00038         {
00039             SuspendingDeferral deferral = args.SuspendingOperation.GetDeferral();
00040             await SuspensionManager.SaveAsync();
00041             deferral.Complete();
00042         }
00043
00044         /// <summary>
00045         /// Invoked when the application is launched normally by the end user.  Other entry points
00046         /// will be used when the application is launched to open a specific file, to display
00047         /// search results, and so forth.
00048         /// </summary>
00049         /// <param name="args">Details about the launch request and process.</param>
00050         async protected override void OnLaunched(LaunchActivatedEventArgs args)
00051         {
00052             this.LaunchArgs = args;
00053
00054             Frame rootFrame = null;
00055             if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
00056             {
00057                 // Do an asynchronous restore
00058                 await SuspensionManager.RestoreAsync();
00059             }
00060             if (Window.Current.Content == null)
00061             {
00062                 rootFrame = new Frame();
00063                 rootFrame.Navigate(typeof(MainPage));
00064                 Window.Current.Content = rootFrame;
00065             }
00066             Window.Current.Activate();
00067         }
00068     }
00069 }
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Touch hit testing/C++/Program.h Source File

  • Input Touch hit testing

Program.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 <new>
00011 #include <memory>
00012 #include "Shape.h"
00013
00014 // Shapes list
00015 struct ShapeRecord
00016 {
00017     std::shared_ptr<Shape> shape;      // Internal shape object
00018     int cursorId;                      // Cursor (mouse or pointer) identifier that 'holds' the object
00019     std::shared_ptr<ShapeRecord> next; // Next object
00020 };
00021
00022 ref class Program : public Platform::Object
00023 {
00024 internal:
00025     Program();
00026
00027     // Initializes Core Objects, Manipulation Processors and Inertia Processors
00028     void Initialize(_In_ Windows::UI::Core::CoreWindow^ window);
00029
00030     // Event handlers
00031     void OnPointerPressed(_In_ Windows::UI::Core::PointerEventArgs^ args);
00032     void OnPointerMoved(_In_ Windows::UI::Core::PointerEventArgs^ args);
00033     void OnPointerReleased(_In_ Windows::UI::Core::PointerEventArgs^ args);
00034
00035     void RenderObjects();
00036     void SetD2DContext(_In_ ID2D1DeviceContext* d2dContext);
00037     void CreateWindowSizeDependentResources();
00038
00039 private:
00040     ~Program();
00041     // Touch hit testing events
00042     void OnTouchHitTesting(
00043         _In_ Windows::UI::Core::CoreWindow^ sender,
00044         _In_ Windows::UI::Core::TouchHitTestingEventArgs^ args);
00045
00046     void SetupControls();
00047
00048     // List of shapes (includes regular shapes and controls)
00049     // List contains shapes in their z-order
00050     std::shared_ptr<ShapeRecord> m_shapes;
00051
00052     // Add new shape to the list
00053     void AddShape(_In_reads_(numPoints) Windows::Foundation::Point const* points, _In_ int numPoints,
00054                   _In_ D2D1::ColorF color);
00055     // Move shape to the top of the list
00056     void MoveToFront(_Inout_ std::shared_ptr<ShapeRecord>& shapeRec);
00057     // Drawing
00058     void DrawBackward(_In_ std::shared_ptr<ShapeRecord> const& shapeRec);
00059
00060     // Main window
00061     Platform::Agile<Windows::UI::Core::CoreWindow> m_window;
00062     Microsoft::WRL::ComPtr<ID2D1DeviceContext> m_d2dContext;
00063
00064     // The client width and height
00065     float m_width;
00066     float m_height;
00067
00068     // Hit test method
00069     std::shared_ptr<ShapeRecord> PointHitTest(_In_ Windows::Foundation::Point pt);
00070 };
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML WebView control/C++/common/LayoutAwarePage.h Source File

  • XAML WebView control
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Message dialog/C++/pch.cpp Source File

  • Message dialog

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DatagramSocket/C++/Scenario2.xaml.h Source File

  • DatagramSocket

Scenario2.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.xaml.h
00013 // Declaration of the Scenario2 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario2.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 using namespace Platform;
00023 using namespace Windows::Storage::Streams;
00024 using namespace Windows::Networking::Sockets;
00025
00026 namespace DatagramSocketSample
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 Scenario2 sealed
00033     {
00034     public:
00035         Scenario2();
00036
00037     protected:
00038         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00039     private:
00040         MainPage^ rootPage;
00041         void ConnectSocket_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00042     };
00043
00044     [Windows::Foundation::Metadata::WebHostHidden]
00045     public ref class SocketContext sealed
00046     {
00047     public:
00048         SocketContext(MainPage^ rootPage, DatagramSocket^ socket);
00049         void OnMessage(DatagramSocket^ socket, DatagramSocketMessageReceivedEventArgs^ eventArguments);
00050         DataWriter^ GetWriter();
00051         boolean IsConnected();
00052         void SetConnected();
00053
00054     private:
00055         ~SocketContext();
00056         MainPage^ rootPage;
00057         DatagramSocket^ socket;
00058         DataWriter^ writer;
00059         boolean connected;
00060
00061         void NotifyUserFromAsyncThread(String^ message, NotifyType type);
00062     };
00063 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/ObservableQuery.h Source File

  • Hilo C++
  • Hilo

ObservableQuery.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
00009 #include "PageType.h"
00010
00011 namespace Hilo
00012 {
00013     // The ObservableQuery class provides an interface for view models to receive notifications of file system changes.
00014     class ObservableQuery
00015     {
00016     public:
00017         virtual void AddObserver(const std::function<void()> callback, PageType pageType) = 0;
00018         virtual void RemoveObserver(PageType pageType) = 0;
00019     };
00020 }
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

ElementBase Member List

This is the complete list of members for ElementBase, including all inherited members.
CalculateSize() | ElementBase | [inline, protected, virtual]
ElementBase() | ElementBase | [protected]
GetBounds() | ElementBase |
Initialize() | ElementBase | [inline, virtual]
IsVisible() const | ElementBase | [inline]
m_alignment | ElementBase | [protected]
m_container | ElementBase | [protected]
m_size | ElementBase | [protected]
m_visible | ElementBase | [protected]
Render() | ElementBase | [inline, virtual]
SetAlignment(AlignType horizontal, AlignType vertical) | ElementBase |
SetContainer(const D2D1_RECT_F &container) | ElementBase | [virtual]
SetVisible(bool visible) | ElementBase |
Update(float timeTotal, float timeDelta) | ElementBase | [inline, virtual]
Generated on Sat Nov 23 2024 16:09:12 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::TileContent::TileWideText02 Member List

This is the complete list of members for NotificationsExtensions::TileContent::TileWideText02, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
Branding | NotificationsExtensions::TileContent::TileNotificationBase |
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
RequireSquareContent | NotificationsExtensions::TileContent::TileWideBase |
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SquareContent | NotificationsExtensions::TileContent::TileWideBase |
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextColumn1Row1 | NotificationsExtensions::TileContent::TileWideText02 |
TextColumn1Row2 | NotificationsExtensions::TileContent::TileWideText02 |
TextColumn1Row3 | NotificationsExtensions::TileContent::TileWideText02 |
TextColumn1Row4 | NotificationsExtensions::TileContent::TileWideText02 |
TextColumn2Row1 | NotificationsExtensions::TileContent::TileWideText02 |
TextColumn2Row2 | NotificationsExtensions::TileContent::TileWideText02 |
TextColumn2Row3 | NotificationsExtensions::TileContent::TileWideText02 |
TextColumn2Row4 | NotificationsExtensions::TileContent::TileWideText02 |
TextFields | NotificationsExtensions::NotificationBase |
TextHeading | NotificationsExtensions::TileContent::TileWideText02 |
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWideText02() | NotificationsExtensions::TileContent::TileWideText02 | [inline]
TileWideText02() | NotificationsExtensions::TileContent::TileWideText02 | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:44 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Thread pool/C++/Constants.h Source File

  • Thread pool

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME {
00027             Platform::String^ get() {  return ref new Platform::String(L"ThreadPool"); }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios {
00031             Platform::Array<Scenario>^ get()
00032             {
00033                 return scenariosInner;
00034             }
00035         }
00036     private:
00037         static Platform::Array<Scenario>^ scenariosInner;
00038     };
00039
00040     namespace ThreadPool
00041     {
00042         ref class DelayTimerScenario;
00043         ref class PeriodicTimerScenario;
00044         ref class WorkItemScenario;
00045
00046         public enum class Status
00047         {
00048             Unregistered = 0,
00049             Started = 1,
00050             Canceled = 2,
00051             Completed = 3
00052         };
00053
00054         struct ThreadPoolSample {
00055         public:
00056             static Windows::Foundation::TimeSpan MillisecondsToTimeSpan(long milliseconds);
00057             static Platform::String^ GetStatusString(ThreadPool::Status status);
00058         };
00059
00060         static DelayTimerScenario^ DelayScenario;
00061         static Windows::System::Threading::ThreadPoolTimer^ DelayTimer;
00062         static int DelayTimerMilliseconds;
00063         static Platform::String^ DelayTimerInfo;
00064         static Status DelayTimerStatus;
00065         static int DelayTimerSelectedIndex;
00066
00067         static PeriodicTimerScenario^ PeriodicScenario;
00068         static int PeriodicTimerCount;
00069         static Windows::System::Threading::ThreadPoolTimer^ PeriodicTimer;
00070         static int PeriodicTimerMilliseconds;
00071         static Platform::String^ PeriodicTimerInfo;
00072         static Status PeriodicTimerStatus;
00073         static int PeriodicTimerSelectedIndex;
00074
00075         static WorkItemScenario^ WorkScenario;
00076         static Windows::Foundation::IAsyncAction^ WorkItem;
00077         static Platform::String^ WorkItemInfo;
00078         static Windows::System::Threading::WorkItemPriority WorkPriority;
00079         static Status WorkItemStatus;
00080         static int WorkItemSelectedIndex;
00081     }
00082 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Inclinometer sensor/C++/Scenario2.xaml.cpp Source File

  • Inclinometer sensor

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 SDKSample::InclinometerCPP;
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::Devices::Sensors;
00025 using namespace Windows::Foundation;
00026 using namespace Windows::UI::Core;
00027 using namespace Platform;
00028
00029 Scenario2::Scenario2() : rootPage(MainPage::Current), desiredReportInterval(0)
00030 {
00031     InitializeComponent();
00032
00033     inclinometer = Inclinometer::GetDefault();
00034     if (inclinometer != nullptr)
00035     {
00036         // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
00037         // This value will be used later to activate the sensor.
00038         uint32 minReportInterval = inclinometer->MinimumReportInterval;
00039         desiredReportInterval = minReportInterval > 16 ? minReportInterval : 16;
00040
00041         // Set up a DispatchTimer
00042         TimeSpan span;
00043         span.Duration = static_cast<int32>(desiredReportInterval) * 10000;   // convert to 100ns ticks
00044         dispatcherTimer = ref new DispatcherTimer();
00045         dispatcherTimer->Interval = span;
00046         dispatcherTimer->Tick += ref new Windows::Foundation::EventHandler<Object^>(this, &Scenario2::DisplayCurrentReading);
00047     }
00048     else
00049     {
00050         rootPage->NotifyUser("No inclinometer found", NotifyType::ErrorMessage);
00051     }
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 void Scenario2::OnNavigatedTo(NavigationEventArgs^ e)
00060 {
00061     ScenarioEnableButton->IsEnabled = true;
00062     ScenarioDisableButton->IsEnabled = false;
00063 }
00064
00065 /// <summary>
00066 /// Invoked when this page is no longer displayed.
00067 /// </summary>
00068 /// <param name="e"></param>
00069 void Scenario2::OnNavigatedFrom(NavigationEventArgs^ e)
00070 {
00071     if (ScenarioDisableButton->IsEnabled)
00072     {
00073         Window::Current->VisibilityChanged::remove(visibilityToken);
00074         dispatcherTimer->Stop();
00075
00076         // Restore the default report interval to release resources while the sensor is not in use
00077         inclinometer->ReportInterval = 0;
00078     }
00079 }
00080
00081 /// <summary>
00082 /// This is the event handler for VisibilityChanged events. You would register for these notifications
00083 /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00084 /// </summary>
00085 /// <param name="sender"></param>
00086 /// <param name="e">
00087 /// Event data that can be examined for the current visibility state.
00088 /// </param>
00089 void Scenario2::VisibilityChanged(Object^ sender, VisibilityChangedEventArgs^ e)
00090 {
00091     // The app should watch for VisibilityChanged events to disable and re-enable sensor input as appropriate
00092     if (ScenarioDisableButton->IsEnabled)
00093     {
00094         if (e->Visible)
00095         {
00096             // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00097             dispatcherTimer->Start();
00098         }
00099         else
00100         {
00101             // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00102             dispatcherTimer->Stop();
00103         }
00104     }
00105 }
00106
00107 void Scenario2::DisplayCurrentReading(Object^ sender, Object^ e)
00108 {
00109     InclinometerReading^ reading = inclinometer->GetCurrentReading();
00110     if (reading != nullptr)
00111     {
00112         ScenarioOutput_X->Text = reading->PitchDegrees.ToString();
00113         ScenarioOutput_Y->Text = reading->RollDegrees.ToString();
00114         ScenarioOutput_Z->Text = reading->YawDegrees.ToString();
00115     }
00116 }
00117
00118 void Scenario2::ScenarioEnable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00119 {
00120     if (inclinometer != nullptr)
00121     {
00122         visibilityToken = Window::Current->VisibilityChanged::add(ref new WindowVisibilityChangedEventHandler(this, &Scenario2::VisibilityChanged));
00123
00124         // Set the report interval to enable the sensor for polling
00125         inclinometer->ReportInterval = desiredReportInterval;
00126
00127         dispatcherTimer->Start();
00128
00129         ScenarioEnableButton->IsEnabled = false;
00130         ScenarioDisableButton->IsEnabled = true;
00131     }
00132     else
00133     {
00134         rootPage->NotifyUser("No inclinometer found", NotifyType::ErrorMessage);
00135     }
00136 }
00137
00138 void Scenario2::ScenarioDisable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00139 {
00140     Window::Current->VisibilityChanged::remove(visibilityToken);
00141
00142     dispatcherTimer->Stop();
00143
00144     // Restore the default report interval to release resources while the sensor is not in use
00145     inclinometer->ReportInterval = 0;
00146
00147     ScenarioEnableButton->IsEnabled = true;
00148     ScenarioDisableButton->IsEnabled = false;
00149 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::CameraOptions::sealed Member List

This is the complete list of members for SDKSample::CameraOptions::sealed, including all inherited members.
dispatcher | SDKSample::CameraOptions::sealed | [private]
mediaCaptureMgr | SDKSample::CameraOptions::sealed | [private]
MediaControl_SoundLevelChanged(Platform::Object^sender, Platform::Object^e) | SDKSample::CameraOptions::sealed | [private]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::CameraOptions::sealed | [protected, virtual]
previewStarted | SDKSample::CameraOptions::sealed | [private]
rootPage | SDKSample::CameraOptions::sealed | [private]
ShowOptionsUI() | SDKSample::CameraOptions::sealed |
ShowSettings_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CameraOptions::sealed | [private]
StartPreview_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CameraOptions::sealed | [private]
Generated on Sat Nov 23 2024 16:09:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML data binding/C++/Common/LayoutAwarePage.h Source File

  • XAML data binding
  • Common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Sharing content source app/C++/ShareFiles.xaml.cpp Source File

  • Sharing content source app

ShareFiles.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 // ShareFiles.xaml.cpp
00013 // Implementation of the ShareFiles class
00014 //
00015
00016 #include "pch.h"
00017 #include "ShareFiles.xaml.h"
00018
00019 using namespace SDKSample::ShareSource;
00020 using namespace SDKSample::Common;
00021
00022 using namespace Platform;
00023 using namespace Windows::Foundation::Collections;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::Storage;
00026 using namespace Windows::Storage::Pickers;
00027 using namespace concurrency;
00028 using namespace Windows::ApplicationModel::DataTransfer;
00029
00030 ShareFiles::ShareFiles()
00031 {
00032     InitializeComponent();
00033
00034     // Get a pointer to our main page.
00035     rootPage = MainPage::Current;
00036 }
00037
00038 bool ShareFiles::GetShareContent(DataRequest^ request)
00039 {
00040     bool succeeded = false;
00041
00042     if (storageItems != nullptr)
00043     {
00044         auto requestData = request->Data;
00045         requestData->Properties->Title = TitleInputBox->Text;
00046
00047         // The description is optional.
00048         auto dataPackageDescription = DescriptionInputBox->Text;
00049         if (dataPackageDescription != nullptr)
00050         {
00051             requestData->Properties->Description = dataPackageDescription;
00052         }
00053         requestData->SetStorageItems(dynamic_cast<IIterable<IStorageItem^>^>(storageItems));
00054         succeeded = true;
00055     }
00056     else
00057     {
00058         request->FailWithDisplayText("Select the files you would like to share and try again.");
00059     }
00060     return succeeded;
00061 }
00062
00063 void ShareFiles::SelectFilesButton_Click(Object^ sender, RoutedEventArgs^ e)
00064 {
00065     if (rootPage->EnsureUnsnapped())
00066     {
00067         auto filePicker = ref new FileOpenPicker();
00068         filePicker->ViewMode = PickerViewMode::List;
00069         filePicker->SuggestedStartLocation = PickerLocationId::DocumentsLibrary;
00070         filePicker->FileTypeFilter->Append("*");
00071
00072         create_task(filePicker->PickMultipleFilesAsync()).then([this](IVectorView<StorageFile^>^ pickedFiles)
00073         {
00074             if (pickedFiles->Size > 0)
00075             {
00076                 storageItems = pickedFiles;
00077
00078                 // Display the file names in the UI.
00079                 std::wstringstream sstream;
00080                 sstream << L"Picked files: ";
00081                 for (unsigned int i = 0; i < pickedFiles->Size; i++)
00082                 {
00083                     sstream << pickedFiles->GetAt(i)->Name->Data();
00084                     if (i < pickedFiles->Size - 1)
00085                     {
00086                         sstream << L", ";
00087                     }
00088                 }
00089                 sstream << L".";
00090                 rootPage->NotifyUser(ref new String(sstream.str().c_str()), NotifyType::StatusMessage);
00091
00092                 ShareStep->Visibility = Windows::UI::Xaml::Visibility::Visible;
00093             }
00094         });
00095     }
00096 }
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: SMS message send, receive, and SIM management/C++/pch.h Source File

  • SMS message send, receive, and SIM management

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application resources and localization/C++/Scenario8.xaml.cpp Source File

  • Application resources and localization

Scenario8.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 // Scenario8.xaml.cpp
00013 // Implementation of the Scenario8 class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario8.xaml.h"
00018
00019 using namespace SDKSample::ApplicationResources;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel::Resources::Core;
00026
00027
00028 Scenario8::Scenario8()
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 Scenario8::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 SDKSample::ApplicationResources::Scenario8::Scenario8Button_Show_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00047 {
00048     Button^ b = safe_cast<Button^>(sender);
00049     if (b != nullptr)
00050     {
00051     String^ newAppLanguage = "";
00052
00053     auto selectedLanguage = Scenario8ComboBox->SelectedValue;
00054     if (selectedLanguage != nullptr)
00055     {
00056       newAppLanguage = selectedLanguage->ToString();
00057     }
00058     if (Windows::Globalization::ApplicationLanguages::PrimaryLanguageOverride != newAppLanguage)
00059     {
00060       Windows::Globalization::ApplicationLanguages::PrimaryLanguageOverride = newAppLanguage;
00061       // flush the internal cache
00062             ResourceManager::Current->DefaultContext->Reset();
00063     }
00064     auto resourceStringMap = ResourceManager::Current->MainResourceMap->GetSubtree("Resources");
00065     Scenario8TextBlock->Text = resourceStringMap->GetValue("string1")->ValueAsString;
00066     }
00067 }
00068
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D HLSL fractal generator/C++/DirectXApp.cpp Source File

  • Direct3D HLSL fractal generator

DirectXApp.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 "DirectXApp.h"
00010 #include "BasicTimer.h"
00011
00012 using namespace Windows::ApplicationModel;
00013 using namespace Windows::ApplicationModel::Core;
00014 using namespace Windows::ApplicationModel::Activation;
00015 using namespace Windows::UI::Core;
00016 using namespace Windows::UI::Input;
00017 using namespace Windows::System;
00018 using namespace Windows::Storage;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::Graphics::Display;
00022
00023 DirectXApp::DirectXApp() :
00024     m_windowClosed(false),
00025     m_windowVisible(true),
00026     m_rotationKeyDown(false)
00027 {
00028 }
00029
00030 void DirectXApp::Initialize(
00031     _In_ CoreApplicationView^ applicationView
00032     )
00033 {
00034     applicationView->Activated +=
00035         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &DirectXApp::OnActivated);
00036
00037     CoreApplication::Suspending +=
00038         ref new EventHandler<SuspendingEventArgs^>(this, &DirectXApp::OnSuspending);
00039
00040     m_renderer = ref new DirectXFractal();
00041 }
00042
00043 void DirectXApp::SetWindow(
00044     _In_ CoreWindow^ window
00045     )
00046 {
00047     window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
00048
00049     window->SizeChanged +=
00050         ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &DirectXApp::OnWindowSizeChanged);
00051
00052     window->VisibilityChanged +=
00053         ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &DirectXApp::OnVisibilityChanged);
00054
00055     window->Closed +=
00056         ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &DirectXApp::OnWindowClosed);
00057
00058     DisplayProperties::LogicalDpiChanged +=
00059         ref new DisplayPropertiesEventHandler(this, &DirectXApp::OnLogicalDpiChanged);
00060
00061     m_gestureRecognizer = ref new GestureRecognizer();
00062
00063     m_gestureRecognizer->AutoProcessInertia = false;
00064
00065     m_gestureRecognizer->GestureSettings =
00066         GestureSettings::ManipulationTranslateX       |
00067         GestureSettings::ManipulationTranslateY       |
00068         GestureSettings::ManipulationTranslateInertia |
00069         GestureSettings::ManipulationScale            |
00070         GestureSettings::ManipulationScaleInertia     |
00071         GestureSettings::ManipulationRotate           |
00072         GestureSettings::ManipulationRotateInertia;
00073
00074     window->PointerPressed +=
00075         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &DirectXApp::OnPointerPressed);
00076
00077     window->PointerReleased +=
00078         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &DirectXApp::OnPointerReleased);
00079
00080     window->PointerMoved +=
00081         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &DirectXApp::OnPointerMoved);
00082
00083     window->PointerWheelChanged +=
00084         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &DirectXApp::OnPointerWheelChanged);
00085
00086     window->KeyDown +=
00087         ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &DirectXApp::OnKeyDown);
00088
00089     window->KeyUp +=
00090         ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &DirectXApp::OnKeyUp);
00091
00092     m_gestureRecognizer->ManipulationUpdated +=
00093         ref new TypedEventHandler<GestureRecognizer^, ManipulationUpdatedEventArgs^>(this, &DirectXApp::OnManipulationUpdated);
00094
00095     m_renderer->Initialize(window, DisplayProperties::LogicalDpi);
00096 }
00097
00098 void DirectXApp::Load(
00099     _In_ Platform::String^ entryPoint
00100     )
00101 {
00102     IPropertySet^ appState = ApplicationData::Current->LocalSettings->Values;
00103     m_renderer->LoadInternalState(appState);
00104 }
00105
00106 void DirectXApp::Run()
00107 {
00108     BasicTimer^ timer = ref new BasicTimer();
00109
00110     while (!m_windowClosed)
00111     {
00112         if (m_windowVisible)
00113         {
00114             timer->Update();
00115             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
00116             m_gestureRecognizer->ProcessInertia();
00117             m_renderer->Update(timer->Total, timer->Delta);
00118             m_renderer->Render();
00119             m_renderer->Present(); // This call is synchronized to the display frame rate.
00120         }
00121         else
00122         {
00123             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
00124         }
00125     }
00126 }
00127
00128 void DirectXApp::Uninitialize()
00129 {
00130 }
00131
00132 void DirectXApp::OnWindowSizeChanged(
00133     _In_ CoreWindow^ sender,
00134     _In_ WindowSizeChangedEventArgs^ args
00135     )
00136 {
00137     m_renderer->UpdateForWindowSizeChange();
00138 }
00139
00140 void DirectXApp::OnWindowClosed(
00141     _In_ CoreWindow^ sender,
00142     _In_ CoreWindowEventArgs^ args
00143     )
00144 {
00145     m_windowClosed = true;
00146 }
00147
00148 void DirectXApp::OnVisibilityChanged(
00149     _In_ CoreWindow^ sender,
00150     _In_ VisibilityChangedEventArgs^ args
00151     )
00152 {
00153     m_windowVisible = args->Visible;
00154 }
00155
00156 void DirectXApp::OnLogicalDpiChanged(
00157     _In_ Platform::Object^ sender
00158     )
00159 {
00160     m_renderer->SetDpi(DisplayProperties::LogicalDpi);
00161 }
00162
00163 void DirectXApp::OnActivated(
00164     _In_ CoreApplicationView^ applicationView,
00165     _In_ IActivatedEventArgs^ args
00166     )
00167 {
00168     CoreWindow::GetForCurrentThread()->Activate();
00169 }
00170
00171 void DirectXApp::OnSuspending(
00172     _In_ Platform::Object^ sender,
00173     _In_ SuspendingEventArgs^ args
00174     )
00175 {
00176     IPropertySet^ appState = ApplicationData::Current->LocalSettings->Values;
00177     m_renderer->SaveInternalState(appState);
00178 }
00179
00180 void DirectXApp::OnPointerPressed(
00181     _In_ Windows::UI::Core::CoreWindow^ sender,
00182     _In_ Windows::UI::Core::PointerEventArgs^ args
00183     )
00184 {
00185     m_gestureRecognizer->ProcessDownEvent(args->CurrentPoint);
00186 }
00187
00188 void DirectXApp::OnPointerReleased(
00189     _In_ Windows::UI::Core::CoreWindow^ sender,
00190     _In_ Windows::UI::Core::PointerEventArgs^ args
00191     )
00192 {
00193     m_gestureRecognizer->ProcessUpEvent(args->CurrentPoint);
00194 }
00195
00196 void DirectXApp::OnPointerMoved(
00197     _In_ Windows::UI::Core::CoreWindow^ sender,
00198     _In_ Windows::UI::Core::PointerEventArgs^ args
00199     )
00200 {
00201     m_gestureRecognizer->ProcessMoveEvents(args->GetIntermediatePoints());
00202 }
00203
00204 void DirectXApp::OnPointerWheelChanged(
00205     _In_ Windows::UI::Core::CoreWindow^ sender,
00206     _In_ Windows::UI::Core::PointerEventArgs^ args
00207     )
00208 {
00209     // Force mouse wheel movement to be interpreted as zooming or rotating.
00210     m_gestureRecognizer->ProcessMouseWheelEvent(args->CurrentPoint, m_rotationKeyDown, true);
00211 }
00212
00213 void DirectXApp::OnKeyDown(
00214     _In_ Windows::UI::Core::CoreWindow^ sender,
00215     _In_ Windows::UI::Core::KeyEventArgs^ args
00216     )
00217 {
00218     if (args->VirtualKey == VirtualKey::Shift)
00219     {
00220         m_rotationKeyDown = true;
00221     }
00222 }
00223
00224 void DirectXApp::OnKeyUp(
00225     _In_ Windows::UI::Core::CoreWindow^ sender,
00226     _In_ Windows::UI::Core::KeyEventArgs^ args
00227     )
00228 {
00229     if (args->VirtualKey == VirtualKey::Shift)
00230     {
00231         m_rotationKeyDown = false;
00232     }
00233 }
00234
00235 void DirectXApp::OnManipulationUpdated(
00236     _In_ Windows::UI::Input::GestureRecognizer^ sender,
00237     _In_ Windows::UI::Input::ManipulationUpdatedEventArgs^ args
00238     )
00239 {
00240     m_renderer->HandleViewManipulation(
00241         args->Delta.Rotation,
00242         args->Delta.Scale,
00243         args->Delta.Translation.X,
00244         args->Delta.Translation.Y
00245         );
00246 }
00247
00248 IFrameworkView^ DirectXAppSource::CreateView()
00249 {
00250     return ref new DirectXApp();
00251 }
00252
00253 [Platform::MTAThread]
00254 int main(Platform::Array<Platform::String^>^)
00255 {
00256     auto directXAppSource = ref new DirectXAppSource();
00257     CoreApplication::Run(directXAppSource);
00258     return 0;
00259 }
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKTemplate::Scenario Member List

This is the complete list of members for SDKTemplate::Scenario, including all inherited members.
ClassType | SDKTemplate::Scenario |
Title | SDKTemplate::Scenario |
ToString() | SDKTemplate::Scenario | [inline]
ToString() | SDKTemplate::Scenario | [inline]
ToString() | SDKTemplate::Scenario | [inline]
ToString() | SDKTemplate::Scenario | [inline]
ToString() | SDKTemplate::Scenario | [inline]
Generated on Sat Nov 23 2024 16:09:53 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Edge gesture invocation/C++/ScenarioOutput2.xaml.cpp Source File

  • Edge gesture invocation

ScenarioOutput2.xaml.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 //
00009 // ScenarioOutput2.xaml.cpp
00010 // Implementation of the ScenarioOutput2 class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioOutput2.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace EdgeGestureSample;
00018
00019 using namespace Platform;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Graphics::Display;
00023 using namespace Windows::UI::ViewManagement;
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 ScenarioOutput2::ScenarioOutput2()
00033 {
00034     InitializeComponent();
00035 }
00036
00037 ScenarioOutput2::~ScenarioOutput2()
00038 {
00039 }
00040
00041 #pragma region Template-Related Code - Do not remove
00042 void ScenarioOutput2::OnNavigatedTo(NavigationEventArgs^ e)
00043 {
00044     // Get a pointer to our main page.
00045     rootPage = dynamic_cast<MainPage^>(e->Parameter);
00046
00047     // We want to be notified when the OutputFrame is loaded so we can get to the content.
00048     _frameLoadedToken = rootPage->InputFrameLoaded += ref new Windows::Foundation::EventHandler<Platform::Object^>(this, &ScenarioOutput2::rootPage_InputFrameLoaded);
00049 }
00050
00051 void ScenarioOutput2::OnNavigatedFrom(NavigationEventArgs^ e)
00052 {
00053     rootPage->InputFrameLoaded -= _frameLoadedToken;
00054 }
00055
00056 #pragma endregion
00057
00058 #pragma region Use this code if you need access to elements in the input frame - otherwise delete
00059 void ScenarioOutput2::rootPage_InputFrameLoaded(Object^ sender, Object^ e)
00060 {
00061     // Get a pointer to the content within the OutputFrame.
00062     Page^ inputFrame = dynamic_cast<Page^>(rootPage->InputFrame->Content);
00063 }
00064
00065 #pragma endregion
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playback Manager msAudioCategory/C++/StreamTypeMedia.xaml.h Source File

  • Playback Manager msAudioCategory

StreamTypeMedia.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 // StreamTypeMedia.xaml.h
00013 // Declaration of the StreamTypeMedia class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "StreamTypeMedia.g.h"
00020 #include "MainPage.xaml.h"
00021 #include "Playback.h"
00022
00023 namespace SDKSample
00024 {
00025     namespace  PlaybackManager
00026     {
00027         /// <summary>
00028         /// An empty page that can be used on its own or navigated to within a Frame.
00029         /// </summary>
00030       public ref class StreamTypeMedia sealed
00031         {
00032         public:
00033             StreamTypeMedia();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         Playback^ _playback;
00041       };
00042     }
00043 }
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML FlipView control/C++/Scenario5.xaml.h Source File

  • XAML FlipView control

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 SDKSample
00023 {
00024   namespace FlipViewCPP
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::WebHostHiddenAttribute]
00030     public ref class Scenario5 sealed
00031     {
00032     public:
00033       Scenario5();
00034
00035     protected:
00036       virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037     private:
00038       MainPage^ rootPage;
00039       bool bHorizontal;
00040
00041       void Orientation_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00042     };
00043   }
00044 }
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML ListView and GridView essentials/C++/Scenario3.xaml.cpp Source File

  • XAML ListView and GridView essentials

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 SDKSample::ListViewSimple;
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::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Windows::Graphics::Display;
00027 using namespace Windows::UI::ViewManagement;
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 SDKSample::ListViewSampleDataSource;
00033
00034 Scenario3::Scenario3()
00035 {
00036     InitializeComponent();
00037
00038   storeData = ref new StoreData();
00039   ItemListView->ItemsSource = storeData->Items;
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 void Scenario3::OnNavigatedTo(NavigationEventArgs^ e)
00048 {
00049     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00050     // as NotifyUser()
00051     rootPage = MainPage::Current;
00052 }
00053
00054
00055 void SDKSample::ListViewSimple::Scenario3::Go_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00056 {
00057     Button^ b = safe_cast<Button^>(sender);
00058     if (b != nullptr)
00059     {
00060         rootPage->NotifyUser("You clicked the " + b->Name + " button", NotifyType::StatusMessage);
00061     }
00062 }
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DatagramSocket/C++/Common/LayoutAwarePage.cpp Source File

  • DatagramSocket
  • Common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013
00014 using namespace DatagramSocketSample::Common;
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::UI::ViewManagement;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Interop;
00024
00025 /// <summary>
00026 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00027 /// </summary>
00028 LayoutAwarePage::LayoutAwarePage()
00029 {
00030     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled) return;
00031
00032     // Create an empty default view model
00033     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00034
00035     // Map application view state to visual state for this page when it is part of the visual tree
00036     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::StartLayoutUpdates);
00037     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::StopLayoutUpdates);
00038 }
00039
00040 static TypeName _thisType = { LayoutAwarePage::typeid->FullName, TypeKind::Custom };
00041 static TypeName _observableMapType = { IObservableMap<Platform::String^, Object^>::typeid->FullName, TypeKind::Metadata };
00042 static Windows::UI::Xaml::DependencyProperty^ _defaultViewModelProperty =
00043     DependencyProperty::Register("DefaultViewModel", _observableMapType, _thisType, nullptr);
00044
00045 /// <summary>
00046 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00047 /// </summary>
00048 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00049 {
00050     return _defaultViewModelProperty;
00051 }
00052
00053 /// <summary>
00054 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00055 /// used as a trivial view model.
00056 /// </summary>
00057 IObservableMap<Platform::String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00058 {
00059     return safe_cast<Windows::Foundation::Collections::IObservableMap<Platform::String^, Object^>^>(GetValue(DefaultViewModelProperty));
00060 }
00061
00062 /// <summary>
00063 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00064 /// used as a trivial view model.
00065 /// </summary>
00066 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<Platform::String^, Object^>^ value)
00067 {
00068     SetValue(DefaultViewModelProperty, value);
00069 }
00070
00071 /// <summary>
00072 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00073 /// until it reaches the top of the navigation stack.
00074 /// </summary>
00075 /// <param name="sender">Instance that triggered the event.</param>
00076 /// <param name="e">Event data describing the conditions that led to the event.</param>
00077 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00078 {
00079     // Use the navigation frame to return to the topmost page
00080     if (Frame != nullptr)
00081     {
00082         while (Frame->CanGoBack) Frame->GoBack();
00083     }
00084 }
00085
00086 /// <summary>
00087 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00088 /// to go back one step on the navigation stack.
00089 /// </summary>
00090 /// <param name="sender">Instance that triggered the event.</param>
00091 /// <param name="e">Event data describing the conditions that led to the event.</param>
00092 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00093 {
00094     // Use the navigation frame to return to the previous page
00095     if (Frame != nullptr && Frame->CanGoBack) Frame->GoBack();
00096 }
00097
00098 /// <summary>
00099 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00100 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00101 /// visual state management changes that correspond to application view state changes.
00102 /// </summary>
00103 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00104 /// corresponding to view states.</param>
00105 /// <param name="e">Event data that describes how the request was made.</param>
00106 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00107 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00108 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00109 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00110 /// events.</remarks>
00111 /// <seealso cref="DetermineVisualState"/>
00112 /// <seealso cref="InvalidateVisualState"/>
00113 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00114 {
00115     auto control = safe_cast<Control^>(sender);
00116     if (_layoutAwareControls == nullptr) {
00117         // Start listening to view state changes when there are controls interested in updates
00118         _layoutAwareControls = ref new Vector<Control^>();
00119         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00120     }
00121     _layoutAwareControls->Append(control);
00122
00123     // Set the initial visual state of the control
00124     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00125 }
00126
00127 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00128 {
00129     InvalidateVisualState();
00130 }
00131
00132 /// <summary>
00133 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00134 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00135 /// management changes that correspond to application view state changes.
00136 /// </summary>
00137 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00138 /// corresponding to view states.</param>
00139 /// <param name="e">Event data that describes how the request was made.</param>
00140 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00141 /// when layout updates are requested.</remarks>
00142 /// <seealso cref="StartLayoutUpdates"/>
00143 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00144 {
00145     auto control = safe_cast<Control^>(sender);
00146     unsigned int index;
00147     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00148     {
00149         _layoutAwareControls->RemoveAt(index);
00150         if (_layoutAwareControls->Size == 0)
00151         {
00152             // Stop listening to view state changes when no controls are interested in updates
00153             Window::Current->SizeChanged -= _windowSizeEventToken;
00154             _layoutAwareControls = nullptr;
00155         }
00156     }
00157 }
00158
00159 /// <summary>
00160 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00161 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00162 /// override this method to control the mapping scheme used.
00163 /// </summary>
00164 /// <param name="viewState">View state for which a visual state is desired.</param>
00165 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00166 /// <seealso cref="InvalidateVisualState"/>
00167 Platform::String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00168 {
00169     switch (viewState)
00170     {
00171     case ApplicationViewState::Filled: return "Filled";
00172     case ApplicationViewState::Snapped: return "Snapped";
00173     case ApplicationViewState::FullScreenPortrait: return "FullScreenPortrait";
00174     default: case ApplicationViewState::FullScreenLandscape: return "FullScreenLandscape";
00175     }
00176 }
00177
00178 /// <summary>
00179 /// Updates all controls that are listening for visual state changes with the correct visual
00180 /// state.
00181 /// </summary>
00182 /// <remarks>
00183 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00184 /// signal that a different value may be returned even though the view state has not changed.
00185 /// </remarks>
00186 void LayoutAwarePage::InvalidateVisualState()
00187 {
00188     if (_layoutAwareControls != nullptr)
00189     {
00190         String^ visualState = DetermineVisualState(ApplicationView::Value);
00191         auto controlIterator = _layoutAwareControls->First();
00192         while (controlIterator->HasCurrent)
00193         {
00194             auto control = controlIterator->Current;
00195             VisualStateManager::GoToState(control, visualState, false);
00196             controlIterator->MoveNext();
00197         }
00198     }
00199 }
Generated on Sat Nov 23 2024 16:07:31 for Win8-Examples by doxygen 1.7.1


Win8-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 Sat Nov 23 2024 16:09:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Hilo::NullPhotoGroup Member List

This is the complete list of members for Hilo::NullPhotoGroup, including all inherited members.
__pad0__ Hilo::NullPhotoGroup
Generated on Sat Nov 23 2024 16:09:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Accelerometer sensor/C++/common/suspensionmanager.h Source File

  • Accelerometer sensor
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text editing/C++/Scenario5.xaml.cpp Source File

  • XAML text editing

Scenario5.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 // Scenario5.xaml.cpp
00013 // Implementation of the Scenario5 class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario5.xaml.h"
00018
00019 using namespace SDKSample::TextEditing;
00020
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 /// <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 Scenario5::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 SDKSample::TextEditing::Scenario5::Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00043 {
00044     Button^ b = safe_cast<Button^>(sender);
00045     if (b != nullptr)
00046     {
00047         rootPage->NotifyUser("You clicked the " + b->Name + " button", NotifyType::StatusMessage);
00048     }
00049 }
00050
00051 void SDKSample::TextEditing::Scenario5::Other_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00052 {
00053     Button^ b = safe_cast<Button^>(sender);
00054     if (b != nullptr)
00055     {
00056         rootPage->NotifyUser("You clicked the " + b->Name + " button", NotifyType::StatusMessage);
00057     }
00058 }
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D custom image effects/C++/PixelShader/BasicTimer.h Source File

  • Direct2D custom image effects
  • PixelShader

BasicTimer.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 timer class used to drive the render loop of the actively-animated
00011 // DirectX SDK samples. Uses the QueryPerformanceCounter function to retrieve
00012 // high-resolution timing information.
00013 ref class BasicTimer
00014 {
00015 private:
00016     LARGE_INTEGER m_frequency;
00017     LARGE_INTEGER m_currentTime;
00018     LARGE_INTEGER m_startTime;
00019     LARGE_INTEGER m_lastTime;
00020     float m_total;
00021     float m_delta;
00022
00023 internal:
00024     BasicTimer();
00025     void Reset();
00026     void Update();
00027     property float Total
00028     {
00029         float get();
00030     }
00031     property float Delta
00032     {
00033         float get();
00034     }
00035 };
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D magazine app/C++/Element.cpp Source File

  • Direct2D magazine app

Element.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
00010 using namespace Windows::Data::Xml::Dom;
00011
00012 Element::Element() :
00013     m_offset(),
00014     m_size(),
00015     m_name(nullptr),
00016     m_parent(nullptr),
00017     m_nextSibling(nullptr),
00018     m_firstChild(nullptr)
00019 {
00020 }
00021
00022 //  This method is called to release the reference to the parent element.
00023 //  It is necessary to traverse the tree to release the references explicitly,
00024 //  otherwise the destructor will never be called due to cycle dependency
00025 //  between the child and its parent element.
00026 //
00027 //  This method could be removed once the reference to the parent element
00028 //  can be expressed as a weak reference.
00029 //
00030 void Element::ReleaseParent()
00031 {
00032     if (m_firstChild != nullptr)
00033     {
00034         m_firstChild->ReleaseParent();
00035     }
00036
00037     if (m_nextSibling != nullptr)
00038     {
00039         m_nextSibling->ReleaseParent();
00040     }
00041
00042     m_parent = nullptr;
00043 }
00044
00045 void Element::AddChild(_In_ Element^ element)
00046 {
00047     if (m_firstChild == nullptr)
00048     {
00049         element->m_parent = this;
00050         m_firstChild = element;
00051     }
00052     else
00053     {
00054         m_firstChild->AddSibling(element);
00055     }
00056 }
00057
00058 void Element::AddSibling(_In_ Element^ element)
00059 {
00060     if (m_nextSibling == nullptr)
00061     {
00062         element->m_parent = m_parent;
00063         m_nextSibling = element;
00064     }
00065     else
00066     {
00067         m_nextSibling->AddSibling(element);
00068     }
00069 }
00070
00071 bool Element::Initialize(
00072     _In_ Document^ document,
00073     _In_ XmlElement^ xmlElement
00074     )
00075 {
00076     Platform::String^ value;
00077
00078     value = xmlElement->GetAttribute("name");
00079
00080     if (value != nullptr)
00081     {
00082         m_name = ref new Platform::String(value->Data());
00083     }
00084
00085     value = xmlElement->GetAttribute("x");
00086
00087     if (value != nullptr)
00088     {
00089         m_offset.x = static_cast<float>(_wtof(value->Data()));
00090     }
00091
00092     value = xmlElement->GetAttribute("y");
00093
00094     if (value != nullptr)
00095     {
00096         m_offset.y = static_cast<float>(_wtof(value->Data()));
00097     }
00098
00099     value = xmlElement->GetAttribute("width");
00100
00101     if (value != nullptr)
00102     {
00103         m_size.width = static_cast<float>(_wtof(value->Data()));
00104     }
00105
00106     value = xmlElement->GetAttribute("height");
00107
00108     if (value != nullptr)
00109     {
00110         m_size.height = static_cast<float>(_wtof(value->Data()));
00111     }
00112
00113     return true;
00114 }
00115
00116 bool Element::AcceptChildNode(
00117     _In_ Document^ document,
00118     _In_ IXmlNode^ childXmlNode
00119     )
00120 {
00121     // Not accepting any child element by default
00122     return false;
00123 }
00124
00125 bool Element::BindResource(_In_ Element^ rootElement)
00126 {
00127     // Succeed by default without actually binding any resource
00128     return true;
00129 }
00130
00131 void Element::Measure(
00132     _In_ Document^ document,
00133     D2D1_SIZE_F const& parentSize,
00134     _Out_ D2D1_RECT_F* bounds
00135     )
00136 {
00137     D2D1_SIZE_F size = m_size;
00138
00139     if (size.width <= 0 && size.height <= 0)
00140     {
00141         // When no size is specified, assume its parent size.
00142         size = parentSize;
00143     }
00144
00145     D2D1_RECT_F maxBounds = {0};
00146
00147     Element^ child = GetFirstChild();
00148
00149     while (child)
00150     {
00151         D2D1_RECT_F childBounds = {0};
00152
00153         child->Measure(document, size, &childBounds);
00154
00155         if (childBounds.left < maxBounds.left)
00156         {
00157             maxBounds.left = childBounds.left;
00158         }
00159
00160         if (childBounds.right > maxBounds.right)
00161         {
00162             maxBounds.right = childBounds.right;
00163         }
00164
00165         if (childBounds.top < maxBounds.top)
00166         {
00167             maxBounds.top = childBounds.top;
00168         }
00169
00170         if (childBounds.bottom > maxBounds.bottom)
00171         {
00172             maxBounds.bottom = childBounds.bottom;
00173         }
00174
00175         child = child->GetNextSibling();
00176     }
00177
00178     // Element size may be adjusted to accommodate the bounds of all its children.
00179     m_size = D2D1::SizeF(maxBounds.right - maxBounds.left, maxBounds.bottom - maxBounds.top);
00180
00181     *bounds = D2D1::RectF(
00182         maxBounds.left + m_offset.x,
00183         maxBounds.top + m_offset.y,
00184         maxBounds.right + m_offset.x,
00185         maxBounds.bottom + m_offset.y
00186         );
00187 }
00188
00189 bool Element::PrepareToDraw(
00190     _In_ Document^ document,
00191     D2D1::Matrix3x2F const& transform
00192     )
00193 {
00194     return PrepareToDrawChildren(
00195         document,
00196         D2D1::Matrix3x2F::Translation(m_offset.x, m_offset.y) * transform
00197         );
00198 }
00199
00200 bool Element::PrepareToDrawChildren(
00201     _In_ Document^ document,
00202     D2D1::Matrix3x2F const& transform
00203     )
00204 {
00205     Element^ child = GetFirstChild();
00206
00207     while (child)
00208     {
00209         if (child->PrepareToDraw(document, transform))
00210             return true;
00211
00212         child = child->GetNextSibling();
00213     }
00214
00215     return false;
00216 }
00217
00218 bool Element::Draw(
00219     _In_ Document^ document,
00220     D2D1::Matrix3x2F const& transform
00221     )
00222 {
00223     return DrawChildren(
00224         document,
00225         D2D1::Matrix3x2F::Translation(m_offset.x, m_offset.y) * transform
00226         );
00227 }
00228
00229 bool Element::DrawChildren(
00230     _In_ Document^ document,
00231     D2D1::Matrix3x2F const& transform
00232     )
00233 {
00234     Element^ child = GetFirstChild();
00235
00236     while (child)
00237     {
00238         if (child->Draw(document, transform))
00239             return true;
00240
00241         child = child->GetNextSibling();
00242     }
00243
00244     return false;
00245 }
00246
00247 uint32 Element::ParseColor(_In_ Platform::String^ value)
00248 {
00249     uint32 color = 0;
00250
00251     wchar_t const* string = value->Data();
00252
00253     if (!value->IsEmpty() && string[0] == '#')
00254     {
00255         color = wcstoul(string + 1, nullptr, 16);
00256     }
00257
00258     return color;
00259 }
00260
00261 Platform::String^ Element::ParseNameIdentifier(_In_ Platform::String^ value)
00262 {
00263     wchar_t const* string = value->Data();
00264
00265     if (!value->IsEmpty() && string[0] == '#')
00266     {
00267         Platform::String^ name = ref new Platform::String(const_cast<wchar_t*>(string + 1));
00268         return name;
00269     }
00270
00271     return nullptr;
00272 }
Generated on Sat Nov 23 2024 16:08:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX touch input/C++/DDSTextureLoader.h Source File

  • DirectX touch input

DDSTextureLoader.h

Go to the documentation of this file.
00001 //--------------------------------------------------------------------------------------
00002 // File: DDSTextureLoader.h
00003 //
00004 // Function for loading a DDS texture and creating a Direct3D 11 runtime resource for it
00005 //
00006 // Note this function is 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
00018 #pragma once
00019
00020 void CreateDDSTextureFromMemory(
00021     _In_ ID3D11Device* d3dDevice,
00022     _In_reads_bytes_(ddsDataSize) const byte* ddsData,
00023     _In_ size_t ddsDataSize,
00024     _Out_opt_ ID3D11Resource** texture,
00025     _Out_opt_ ID3D11ShaderResourceView** textureView,
00026     _In_ size_t maxsize = 0
00027     );
Generated on Sat Nov 23 2024 16:08:11 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Account picture name/C++/pch.h Source File

  • Account picture name

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include "Sample-Utils\CppSamplesUtils.h"
00019 #include <ppltasks.h>
00020 #include <wrl\implements.h>
00021 #include <wrl\async.h>
00022 #include <wrl\wrappers\corewrappers.h>
00023 #include <windows.system.userprofile.h>
00024
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File picker contracts/C++/FileSavePickerPage.xaml.h Source File

  • File picker contracts

FileSavePickerPage.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 // FileSavePickerPage.xaml.h
00013 // Declaration of the FileSavePickerPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "FileSavePickerPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     namespace FilePickerContracts
00026     {
00027         [Windows::Foundation::Metadata::WebHostHidden]
00028         public ref class FileSavePickerPage sealed
00029         {
00030         public:
00031             FileSavePickerPage();
00032             void Activate(Windows::ApplicationModel::Activation::FileSavePickerActivatedEventArgs^ e);
00033
00034             static property Platform::String^ FEATURE_NAME
00035             {
00036                 Platform::String^ get()
00037                 {
00038                     return ref new Platform::String(L"File Save Picker Page");
00039                 }
00040             }
00041
00042             static property Platform::Array<Scenario>^ scenarios
00043             {
00044                 Platform::Array<Scenario>^ get()
00045                 {
00046                     return scenariosInner;
00047                 }
00048             }
00049
00050         internal:
00051             property bool AutoSizeInputSectionWhenSnapped
00052             {
00053                 bool get()
00054                 {
00055                     return autoSizeInputSectionWhenSnapped;
00056                 }
00057
00058                 void set(bool value)
00059                 {
00060                     autoSizeInputSectionWhenSnapped = value;
00061                 }
00062             }
00063
00064             property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00065             {
00066                 Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00067                 {
00068                     return safe_cast<App^>(App::Current)->LaunchArgs;
00069                 }
00070             }
00071
00072             bool EnsureUnsnapped();
00073             void ResetScenarioOutput(Windows::UI::Xaml::Controls::TextBlock^ textblock);
00074             void NotifyUser(Platform::String^ strMessage, NotifyType type);
00075             void LoadScenario(Platform::String^ scenarioName);
00076             event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00077             event Windows::Foundation::EventHandler<PageSizeChangedEventArgs^>^ PageResized;
00078
00079         private:
00080             void PopulateScenarios();
00081             void InvalidateSize();
00082             void InvalidateViewState();
00083             void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00084
00085             Platform::Collections::Vector<Object^>^ ScenarioList;
00086             Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00087             bool autoSizeInputSectionWhenSnapped;
00088             static Platform::Array<Scenario>^ scenariosInner;
00089
00090         protected:
00091             void FileSavePickerPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00092             void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00093             virtual void LoadState(Platform::Object^ navigationParameter,
00094                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00095             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00096
00097         internal:
00098             static FileSavePickerPage^ Current;
00099             Windows::Storage::Pickers::Provider::FileSavePickerUI^ fileSavePickerUI;
00100         };
00101     }
00102 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML personality animations/C++/SampleData/SampleDataSource.cpp Source File

  • XAML personality animations
  • SampleData

SampleDataSource.cpp

Go to the documentation of this file.
00001
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 #pragma once
00013
00014 #include "pch.h"
00015 #include "SampleDataSource.h"
00016
00017 using namespace Windows::UI::Xaml::Media;
00018
00019 using namespace SDKSample::ExpressionBlendSampleDataSampleDataSource;
00020
00021 //Methods of class Item
00022 Item::Item():_Title(""),_Subtitle(""),_Link(""),_Category(""),_Description(""),_Content(""),_Image(nullptr)
00023 {
00024 }
00025
00026
00027
Generated on Sat Nov 23 2024 16:08:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Account picture name/C++/Constants.cpp Source File

  • Account picture name

Constants.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 "Constants.h"
00014
00015 using namespace AccountPictureName;
00016 using namespace Windows::UI::ViewManagement;
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 quaified name for the class that implements the scenario" }
00022     { "Get User DisplayName", "AccountPictureName.GetUserDisplayName" },
00023     { "Get User First and Last Name", "AccountPictureName.GetUserFirstAndLastName" },
00024     { "Get Account Picture", "AccountPictureName.GetAccountPicture" },
00025     { "Set Account Picture", "AccountPictureName.SetAccountPicture" }
00026 };
00027
00028 void MainPage::LoadSetAccountPictureScenario()
00029 {
00030     LoadScenario("AccountPictureName.SetAccountPicture");
00031     Scenarios->SelectedIndex = 3;
00032     InvalidateSize();
00033 }
00034
00035 bool MainPage::EnsureUnsnapped()
00036 {
00037     // FilePicker APIs will not work if the application is in a snapped state. If an app wants to show a FilePicker while snapped,
00038     // it must attempt to unsnap first.
00039     bool unsnapped = ((ApplicationView::Value != ApplicationViewState::Snapped) || ApplicationView::TryUnsnap());
00040     if (!unsnapped)
00041     {
00042         NotifyUser("Cannot unsnap the sample application.", NotifyType::StatusMessage);
00043     }
00044
00045     return unsnapped;
00046 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Background Transfer/C++/pch.cpp Source File

  • Background Transfer

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 Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Touch keyboard text input/C++/pch.cpp Source File

  • Input Touch keyboard text input

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D magazine app/C++/ImageFile.cpp Source File

  • Direct2D magazine app

ImageFile.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
00010 using namespace concurrency;
00011 using namespace Windows::Data::Xml::Dom;
00012 using namespace Windows::Storage;
00013 using namespace Windows::Storage::Streams;
00014
00015 ImageFile::ImageFile() :
00016     m_refCount(0),
00017     m_offset(0),
00018     m_data(nullptr)
00019 {
00020 }
00021
00022 //  Asynchronously load image data from an image file
00023 //
00024 void ImageFile::LoadAsync(
00025     _In_ StorageFolder^ location,
00026     _In_ Platform::String^ fileName
00027     )
00028 {
00029     task<StorageFile^> getFile(location->GetFileAsync(fileName));
00030     getFile.then([=](StorageFile^ file)
00031     {
00032         return FileIO::ReadBufferAsync(file);
00033     }).then([=](IBuffer^ buffer)
00034     {
00035         m_data = ref new Platform::Array<byte>(buffer->Length);
00036         DataReader::FromBuffer(buffer)->ReadBytes(m_data);
00037     });
00038 }
00039
00040 HRESULT STDMETHODCALLTYPE ImageFile::QueryInterface(
00041     REFIID uuid,
00042     _Outptr_ void** object
00043     )
00044 {
00045     *object = nullptr;
00046
00047     if (    uuid == __uuidof(IUnknown)
00048         ||  uuid == __uuidof(IStream)
00049         ||  uuid == __uuidof(ISequentialStream)
00050         )
00051     {
00052         *object = static_cast<IStream*>(this);
00053         AddRef();
00054         return S_OK;
00055     }
00056     else
00057     {
00058         *object = nullptr;
00059         return E_NOINTERFACE;
00060     }
00061 }
00062
00063 ULONG STDMETHODCALLTYPE ImageFile::AddRef()
00064 {
00065     return static_cast<ULONG>(InterlockedIncrement(&m_refCount));
00066 }
00067
00068 ULONG STDMETHODCALLTYPE ImageFile::Release()
00069 {
00070     ULONG newCount = static_cast<ULONG>(InterlockedDecrement(&m_refCount));
00071
00072     if (newCount == 0)
00073         delete this;
00074
00075     return newCount;
00076 }
00077
00078 HRESULT STDMETHODCALLTYPE ImageFile::Read(
00079     _Out_writes_bytes_(bytesToRead) void* outputBuffer,
00080     ULONG bytesToRead,
00081     _Out_ ULONG* bytesRead
00082     )
00083 {
00084     HRESULT hr = S_OK;
00085
00086     if (m_offset + bytesToRead > m_data->Length)
00087     {
00088         bytesToRead = m_data->Length - m_offset;
00089         hr = S_FALSE;
00090     }
00091
00092     if (bytesToRead > 0)
00093     {
00094         memcpy(outputBuffer, m_data->Data + m_offset, bytesToRead);
00095     }
00096
00097     *bytesRead = bytesToRead;
00098     m_offset += bytesToRead;
00099
00100     return hr;
00101 }
00102
00103 HRESULT STDMETHODCALLTYPE ImageFile::Seek(
00104     LARGE_INTEGER distance,
00105     DWORD origin,
00106     _Out_ ULARGE_INTEGER* newLocation
00107     )
00108 {
00109     ULONG offset = 0;
00110
00111     switch (origin)
00112     {
00113         case STREAM_SEEK_CUR:
00114             offset = m_offset;
00115
00116         case STREAM_SEEK_SET:
00117             if (    distance.HighPart != 0
00118                 ||  distance.LowPart + offset > m_data->Length
00119                 )
00120             {
00121                 return STG_E_INVALIDFUNCTION;
00122             }
00123
00124             offset += distance.LowPart;
00125             break;
00126
00127         case STREAM_SEEK_END:
00128             if (    distance.HighPart != 0
00129                 ||  distance.LowPart > m_data->Length
00130                 )
00131             {
00132                 return STG_E_INVALIDFUNCTION;
00133             }
00134
00135             offset = m_data->Length - distance.LowPart;
00136             break;
00137
00138         default:
00139             return STG_E_INVALIDFUNCTION;
00140     }
00141
00142     m_offset = offset;
00143
00144     if (newLocation)
00145     {
00146         newLocation->HighPart = 0;
00147         newLocation->LowPart = m_offset;
00148     }
00149
00150     return S_OK;
00151 }
00152
00153 HRESULT STDMETHODCALLTYPE ImageFile::Write(
00154     _In_reads_bytes_(bytesToWrite) void const* inputBuffer,
00155     ULONG bytesToWrite,
00156     _Out_ ULONG* bytesWritten
00157     )
00158 {
00159     return E_NOTIMPL;
00160 }
00161
00162 HRESULT STDMETHODCALLTYPE ImageFile::SetSize(ULARGE_INTEGER)
00163 {
00164     return E_NOTIMPL;
00165 }
00166
00167 HRESULT STDMETHODCALLTYPE ImageFile::CopyTo(
00168     _In_ IStream*,
00169     ULARGE_INTEGER,
00170     _Out_ ULARGE_INTEGER*,
00171     _Out_ ULARGE_INTEGER*
00172     )
00173 {
00174     return E_NOTIMPL;
00175 }
00176
00177 HRESULT STDMETHODCALLTYPE ImageFile::Commit(DWORD)
00178 {
00179     return E_NOTIMPL;
00180 }
00181
00182 HRESULT STDMETHODCALLTYPE ImageFile::Revert()
00183 {
00184     return E_NOTIMPL;
00185 }
00186
00187 HRESULT STDMETHODCALLTYPE ImageFile::LockRegion(
00188     ULARGE_INTEGER,
00189     ULARGE_INTEGER,
00190     DWORD
00191     )
00192 {
00193     return E_NOTIMPL;
00194 }
00195
00196 HRESULT STDMETHODCALLTYPE ImageFile::UnlockRegion(
00197     ULARGE_INTEGER,
00198     ULARGE_INTEGER,
00199     DWORD
00200     )
00201 {
00202     return E_NOTIMPL;
00203 }
00204
00205 HRESULT STDMETHODCALLTYPE ImageFile::Clone(_Outptr_ IStream **)
00206 {
00207     return E_NOTIMPL;
00208 }
00209
00210 HRESULT STDMETHODCALLTYPE ImageFile::Stat(
00211     _Out_ STATSTG* statistics,
00212     DWORD
00213     )
00214 {
00215     memset(statistics, 0, sizeof(*statistics));
00216
00217     statistics->cbSize.LowPart = m_data->Length;
00218     statistics->cbSize.HighPart = 0;
00219
00220     return S_OK;
00221 }
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Print/C++/ScenarioList.xaml.h Source File

  • Print

ScenarioList.xaml.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 //
00009 // ScenarioList.xaml.h
00010 // Declaration of the ScenarioList class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioList.g.h"
00017 #include "MainPage.g.h"
00018
00019 using namespace Windows::UI::Xaml::Controls;
00020 using namespace CppSamplesUtils;
00021
00022 namespace PrintSample
00023 {
00024     [Windows::Foundation::Metadata::WebHostHidden]
00025     public ref class ScenarioList sealed
00026     {
00027     public:
00028         ScenarioList();
00029
00030     protected:
00031         void Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e);
00032         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00033
00034     private:
00035         ~ScenarioList();
00036         MainPage^ rootPage;
00037     };
00038 }
Generated on Sat Nov 23 2024 16:07:57 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Store device app for camera/C#,C++/Constants.cs Source File

  • Windows Store device app for camera
  • C#,C++

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 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.Collections.Generic;
00013 using System;
00014
00015 namespace SDKTemplate
00016 {
00017     public partial class MainPage : SDKTemplate.Common.LayoutAwarePage
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 = "Windows Store app for webcam sample";
00022     }
00023
00024     public class Scenario
00025     {
00026         public string Title { get; set; }
00027
00028         public Type ClassType { get; set; }
00029
00030         public override string ToString()
00031         {
00032             return Title;
00033         }
00034     }
00035 }
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Calendar details and math/C++/common/suspensionmanager.cpp Source File

  • Calendar details and math
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Proximity/C++/MainPage.xaml.cpp Source File

  • Proximity

MainPage.xaml.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 //
00009 // MainPage.xaml.cpp
00010 // Implementation of the MainPage.xaml class.
00011 //
00012
00013 #include "pch.h"
00014 #include "MainPage.xaml.h"
00015 #include "App.xaml.h"
00016
00017 #include <collection.h>
00018
00019 using namespace Windows::UI::Xaml;
00020 using namespace Windows::UI::Xaml::Controls;
00021 using namespace Windows::Foundation;
00022 using namespace Platform;
00023 using namespace ProximityCPP;
00024 using namespace CppSamplesUtils;
00025 using namespace Windows::UI::Xaml::Navigation;
00026 using namespace Windows::UI::Xaml::Interop;
00027 using namespace Windows::Graphics::Display;
00028 using namespace Windows::UI::ViewManagement;
00029 using namespace Windows::ApplicationModel::Activation;
00030
00031 MainPage^ MainPage::Current = nullptr;
00032
00033 MainPage::MainPage()
00034 {
00035     InitializeComponent();
00036
00037     // This frame is hidden, meaning it is never shown.  It is simply used to load
00038     // each scenario page and then pluck out the input and output sections and
00039     // place them into the UserControls on the main page.
00040     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00041     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00042     LayoutRoot->Children->Append(HiddenFrame);
00043
00044     // Populate the sample title from the constant in the GlobalVariables.cs file.
00045     SetFeatureName(FEATURE_NAME);
00046
00047     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00048     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00049
00050     MainPage::Current = this;
00051     m_IsLaunchedByTap = false;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 MainPage::~MainPage()
00056 {
00057 }
00058
00059 /// <summary>
00060 /// Invoked when this page is about to be displayed in a Frame.
00061 /// </summary>
00062 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00063 /// property is typically used to configure the page.</param>
00064 void MainPage::OnNavigatedTo(NavigationEventArgs^ e)
00065 {
00066     Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ launchArgs = safe_cast<LaunchActivatedEventArgs^>(e->Parameter);
00067     // Check if this app was launched by a tap action
00068     if (launchArgs->Arguments == "Windows.Networking.Proximity.PeerFinder:StreamSocket")
00069     {
00070         m_IsLaunchedByTap = true;
00071     }
00072     PopulateScenarios();
00073     InvalidateViewState();
00074 }
00075
00076 /// <summary>
00077 /// We need to handle SizeChanged so that we can make the sample layout property
00078 /// in the various layouts.
00079 /// </summary>
00080 /// <param name="sender"></param>
00081 /// <param name="args"></param>
00082 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ args)
00083 {
00084     InvalidateSize();
00085 }
00086
00087 void MainPage::InvalidateSize()
00088 {
00089     // Get the window width
00090     double windowWidth = this->ActualWidth;
00091
00092     if (windowWidth != 0.0)
00093     {
00094
00095         // Get the width of the ListBox.
00096         double listBoxWidth = Scenarios->ActualWidth;
00097
00098         // Is the ListBox using any margins that we need to consider?
00099         double listBoxMarginLeft = Scenarios->Margin.Left;
00100         double listBoxMarginRight = Scenarios->Margin.Right;
00101
00102         // Figure out how much room is left after considering the list box width
00103         double availableWidth = windowWidth - listBoxWidth;
00104
00105         // Is the top most child using margins?
00106         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00107         double layoutRootMarginRight = ContentRoot->Margin.Right;
00108
00109         // We have different widths to use depending on the view state
00110         if (ApplicationView::Value != ApplicationViewState::Snapped)
00111         {
00112             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00113             // and the LayoutRoot's margins
00114             InputSection->Width = ((availableWidth) -
00115                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00116         }
00117         else
00118         {
00119             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00120             if (autoSizeInputSectionWhenSnapped)
00121             {
00122                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00123             }
00124         }
00125     }
00126     InvalidateViewState();
00127 }
00128
00129 void MainPage::InvalidateViewState()
00130 {
00131     // Are we going to snapped mode?
00132     if (ApplicationView::Value == ApplicationViewState::Snapped)
00133     {
00134         Grid::SetRow(DescriptionText, 3);
00135         Grid::SetColumn(DescriptionText, 0);
00136
00137         Grid::SetRow(InputSection, 4);
00138         Grid::SetColumn(InputSection, 0);
00139
00140         Grid::SetRow(FooterPanel, 2);
00141         Grid::SetColumn(FooterPanel, 0);
00142     }
00143     else
00144     {
00145         Grid::SetRow(DescriptionText, 1);
00146         Grid::SetColumn(DescriptionText, 1);
00147
00148         Grid::SetRow(InputSection, 2);
00149         Grid::SetColumn(InputSection, 1);
00150
00151         Grid::SetRow(FooterPanel, 1);
00152         Grid::SetColumn(FooterPanel, 1);
00153     }
00154
00155 }
00156
00157 #pragma optimize("", off)
00158 void MainPage::PopulateScenarios()
00159 {
00160     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00161
00162     // Populate the ListBox with the list of scenarios as defined in Constants.cs.
00163     for(unsigned int i = 0; i < scenarios->Length; ++i)
00164     {
00165         Scenario s = scenarios[i];
00166         ListBoxItem^ item = ref new ListBoxItem();
00167         item->Name = s.ClassName;
00168         item->Content = (i + 1).ToString() + ") " + s.Title;
00169         ScenarioList->Append(item);
00170     }
00171
00172     // Bind the ListBox to the scenario list.
00173     Scenarios->ItemsSource = ScenarioList;
00174
00175     // Starting scenario is the first or based upon a previous selection.
00176     ListBoxItem^ startingScenario = nullptr;
00177
00178     // Starting scenario is the first or based upon a previous selection.
00179     int startingScenarioIndex = -1;
00180
00181     if (m_IsLaunchedByTap)
00182     {
00183         startingScenarioIndex = 0;
00184     }
00185     else
00186     {
00187         auto ps = SuspensionManager::SessionState();
00188         if (ps->HasKey("SelectedScenarioIndex"))
00189         {
00190             int selectedScenarioIndex = safe_cast<int>(ps->Lookup("SelectedScenarioIndex"));
00191             startingScenarioIndex = selectedScenarioIndex;
00192         }
00193     }
00194     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00195 }
00196 #pragma optimize("", on)
00197
00198 /// <summary>
00199 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00200 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00201 /// and output sections into the respective UserControl on the main page.
00202 /// </summary>
00203 /// <param name="scenarioName"></param>
00204 void MainPage::LoadScenario(String^ scenarioName)
00205 {
00206     autoSizeInputSectionWhenSnapped = true;
00207
00208     // Load the ScenarioX.xaml file into the Frame.
00209     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00210     HiddenFrame->Navigate(scenarioType, this);
00211
00212     // Get the top element, the Page, so we can look up the elements
00213     // that represent the input and output sections of the ScenarioX file.
00214     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00215
00216     // Get each element.
00217     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00218     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00219
00220     if (input == nullptr)
00221     {
00222         // Malformed input section.
00223         NotifyUser("Cannot load scenario input section for " + scenarioName +
00224             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00225         return;
00226     }
00227
00228     if (output == nullptr)
00229     {
00230         // Malformed output section.
00231         NotifyUser("Cannot load scenario output section for " + scenarioName +
00232             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00233         return;
00234     }
00235
00236     // Find the LayoutRoot which parents the input and output sections in the main page.
00237     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00238
00239     if (panel != nullptr)
00240     {
00241         unsigned int index = 0;
00242         UIElementCollection^ collection = panel->Children;
00243
00244         // Get rid of the content that is currently in the intput and output sections.
00245         collection->IndexOf(input, &index);
00246         collection->RemoveAt(index);
00247
00248         collection->IndexOf(output, &index);
00249         collection->RemoveAt(index);
00250
00251         // Populate the input and output sections with the newly loaded content.
00252         InputSection->Content = input;
00253         OutputSection->Content = output;
00254         ScenarioLoaded(this, nullptr);
00255     }
00256     else
00257     {
00258         // Malformed Scenario file.
00259         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00260             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00261     }
00262 }
00263
00264 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00265 {
00266     if (Scenarios->SelectedItem != nullptr)
00267     {
00268         NotifyUser("", NotifyType::StatusMessage);
00269
00270         int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00271         SuspensionManager::SessionState()->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00272
00273         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00274         InvalidateSize();
00275     }
00276 }
00277
00278 void MainPage::SetFeatureName(String^ strFeature)
00279 {
00280     FeatureName->Text = strFeature;
00281 }
00282
00283 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00284 {
00285     switch (type)
00286     {
00287     case NotifyType::StatusMessage:
00288         // Use the status message style.
00289         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00290         break;
00291     case NotifyType::ErrorMessage:
00292         // Use the error message style.
00293         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00294         break;
00295     default:
00296         break;
00297     }
00298     StatusBlock->Text = strMessage;
00299 }
00300
00301 void MainPage::ClearLog(TextBlock^ textBlock)
00302 {
00303     textBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00304     textBlock->Text = "";
00305 }
00306
00307 void MainPage::LogInfo(String^ strMessage, TextBlock^ textBlock)
00308 {
00309     textBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00310     textBlock->Text += strMessage + "\n";
00311 }
00312
00313 // This is used by the peerfinder scenario
00314 bool MainPage::IsLaunchedByTap()
00315 {
00316     bool isLaunchedByTap = m_IsLaunchedByTap;
00317     m_IsLaunchedByTap = false;
00318     return isLaunchedByTap;
00319 }
00320
00321 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00322 {
00323     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00324     Windows::System::Launcher::LaunchUriAsync(uri);
00325 }
00326
00327
Generated on Sat Nov 23 2024 16:07:43 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D sprite/C++/DirectXSample.h Source File

  • Direct3D sprite

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
00010 // This header defines helper utilities to make DirectX APIs work with exceptions.
00011 namespace DX
00012 {
00013     inline void ThrowIfFailed(HRESULT hr)
00014     {
00015         if (FAILED(hr))
00016         {
00017             // Set a breakpoint on this line to catch DX API errors.
00018             throw Platform::Exception::CreateException(hr);
00019         }
00020     }
00021 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/GameObject.cpp Source File

  • XAML DirectX 3D shooting game

GameObject.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 "GameObject.h"
00010 #include "ConstantBuffers.h"
00011 #include "GameConstants.h"
00012
00013 using namespace DirectX;
00014
00015 //--------------------------------------------------------------------------------
00016
00017 GameObject::GameObject() :
00018     m_normalMaterial(nullptr),
00019     m_hitMaterial(nullptr)
00020 {
00021     m_active          = false;
00022     m_target          = false;
00023     m_targetId        = 0;
00024     m_hit             = false;
00025     m_ground          = true;
00026
00027     m_position        = XMFLOAT3(0.0f, 0.0f, 0.0f);
00028     m_velocity        = XMFLOAT3(0.0f, 0.0f, 0.0f);
00029     m_defaultXAxis    = XMFLOAT3(1.0f, 0.0f, 0.0f);
00030     m_defaultYAxis    = XMFLOAT3(0.0f, 1.0f, 0.0f);
00031     m_defaultZAxis    = XMFLOAT3(0.0f, 0.0f, 1.0f);
00032     XMStoreFloat4x4(&m_modelMatrix, XMMatrixIdentity());
00033
00034     m_hitTime         = 0.0f;
00035
00036     m_animatePosition = nullptr;
00037 }
00038
00039 //----------------------------------------------------------------------
00040
00041 void GameObject::Render(
00042     _In_ ID3D11DeviceContext *context,
00043     _In_ ID3D11Buffer *primitiveConstantBuffer
00044     )
00045 {
00046     if (!m_active || (m_mesh == nullptr) || (m_normalMaterial == nullptr))
00047     {
00048         return;
00049     }
00050
00051     ConstantBufferChangesEveryPrim constantBuffer;
00052
00053     XMStoreFloat4x4(
00054         &constantBuffer.worldMatrix,
00055         XMMatrixTranspose(ModelMatrix())
00056         );
00057
00058     if (m_hit && m_hitMaterial != nullptr)
00059     {
00060         m_hitMaterial->RenderSetup(context, &constantBuffer);
00061     }
00062     else
00063     {
00064         m_normalMaterial->RenderSetup(context, &constantBuffer);
00065     }
00066     context->UpdateSubresource(primitiveConstantBuffer, 0, nullptr, &constantBuffer, 0, 0);
00067
00068     m_mesh->Render(context);
00069 }
00070
00071 //----------------------------------------------------------------------
00072
00073 void GameObject::PlaySound(float impactSpeed, XMFLOAT3 eyePoint)
00074 {
00075     if (m_hitSound != nullptr)
00076     {
00077         // Determine the sound volume adjustment based on velocity.
00078         float adjustment;
00079         if (impactSpeed < GameConstants::Sound::MinVelocity)
00080         {
00081             adjustment = 0.0f;  // Too soft.  Don't play sound.
00082         }
00083         else
00084         {
00085             adjustment = min(1.0f, impactSpeed / GameConstants::Sound::MaxVelocity);
00086             adjustment = GameConstants::Sound::MinAdjustment + adjustment * (1.0f - GameConstants::Sound::MinAdjustment);
00087         }
00088
00089         // Compute Distance to eyePoint to adjust the volume based on that distance.
00090         XMVECTOR cameraToPosition = XMLoadFloat3(&eyePoint) - VectorPosition();
00091         float distToPositionSquared = XMVectorGetX(XMVector3LengthSq(cameraToPosition));
00092
00093         float volume = min(distToPositionSquared, 1.0f);
00094         // Scale
00095         // Sound is proportional to how hard the ball is hitting.
00096         volume = adjustment * volume;
00097
00098         m_hitSound->PlaySound(volume);
00099     }
00100 }
00101
00102 //----------------------------------------------------------------------
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

TripOptimizerComponent::sealed Member List

This is the complete list of members for TripOptimizerComponent::sealed, including all inherited members.
m_impl | TripOptimizerComponent::sealed | [private]
OptimizeTripAsync(Windows::Foundation::Collections::IVector< Platform::String^>^waypoints, Platform::String^travelMode, Platform::String^optimize, Platform::String^bingMapsKey, double alpha, double beta, double rho, unsigned int iterations, bool parallel) | TripOptimizerComponent::sealed |
TripOptimizer() | TripOptimizerComponent::sealed |
~TripOptimizer() | TripOptimizerComponent::sealed | [private]
Generated on Sat Nov 23 2024 16:09:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

UiaCoreWindowProvider::IAppWindowProvider Member List

This is the complete list of members for UiaCoreWindowProvider::IAppWindowProvider, including all inherited members.
Initialize([in] ITriColorControlInternal *pControl,[in] IInspectable *pWindow) UiaCoreWindowProvider::IAppWindowProvider
Generated on Sat Nov 23 2024 16:09:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: USSD message management/C++/Constants.h Source File

  • USSD message management

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"USSD API");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044
00045
00046 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/ScenarioInput1.xaml.cpp Source File

  • Media extensions

ScenarioInput1.xaml.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 //
00009 // Scenario1Input.xaml.cpp
00010 // Implementation of the Scenario1Input class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioInput1.xaml.h"
00015
00016 #define INITGUID // for MFVideoFormat_MPG1
00017 #include <guiddef.h>
00018 #include <cguid.h>
00019 #include <mfapi.h>
00020
00021 using namespace MediaExtensionsCPP;
00022
00023 using namespace Platform;
00024 using namespace Platform::Collections;
00025 using namespace Windows::Foundation;
00026 using namespace Windows::Foundation::Collections;
00027 using namespace Windows::Graphics::Display;
00028 using namespace Windows::UI::ViewManagement;
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 ScenarioInput1::ScenarioInput1()
00038 {
00039     InitializeComponent();
00040 }
00041
00042 ScenarioInput1::~ScenarioInput1()
00043 {
00044 }
00045
00046 #pragma region Template-Related Code - Do not remove
00047 void ScenarioInput1::OnNavigatedTo(NavigationEventArgs^ e)
00048 {
00049     // Get a pointer to our main page.
00050     rootPage = dynamic_cast<MainPage^>(e->Parameter);
00051
00052     // We want to be notified with the OutputFrame is loaded so we can get to the content.
00053     _frameLoadedToken = rootPage->OutputFrameLoaded += ref new Windows::Foundation::EventHandler<Platform::Object^>(this, &ScenarioInput1::rootPage_OutputFrameLoaded);
00054
00055     rootPage->ExtensionManager->RegisterByteStreamHandler("MPEG1Source.MPEG1ByteStreamHandler", ".mpg", "video/mpeg");
00056     rootPage->ExtensionManager->RegisterVideoDecoder("MPEG1Decoder.MPEG1Decoder", Guid(MFVideoFormat_MPG1), Guid(GUID_NULL));
00057 }
00058
00059 void ScenarioInput1::OnNavigatedFrom(NavigationEventArgs^ e)
00060 {
00061     rootPage->OutputFrameLoaded -= _frameLoadedToken;
00062 }
00063
00064 #pragma endregion
00065
00066 #pragma region Event handlers
00067 void ScenarioInput1::rootPage_OutputFrameLoaded(Object^ sender, Object^ e)
00068 {
00069     // Get a pointer to the content within the OutputFrame.
00070     Page^ outputFrame = dynamic_cast<Page^>(rootPage->OutputFrame->Content);
00071
00072     // Go find the elements that we need for this scenario.
00073     outputVideo = dynamic_cast<MediaElement^>(outputFrame->FindName("Video"));
00074
00075 }
00076
00077 void ScenarioInput1::Open_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00078 {
00079     auto v = ref new Vector<String^>();
00080     v->Append(".mpg");
00081     auto me = ref new Vector<MediaElement^>();
00082     me->Append(outputVideo);
00083     rootPage->PickSingleFileAndSet(v, me);
00084 }
00085
00086 void ScenarioInput1::Stop_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088     outputVideo->Source = nullptr;
00089 }
00090 #pragma endregion
Generated on Sat Nov 23 2024 16:07:59 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D tutorial/C++/Lesson4.Textures/pch.cpp Source File

  • Direct3D tutorial
  • Lesson4.Textures

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

TextStyle Member List

This is the complete list of members for TextStyle, including all inherited members.
GetTextFormat() | TextStyle |
HasTextFormatChanged() | TextStyle | [inline]
m_fontName | TextStyle | [private]
m_fontSize | TextStyle | [private]
m_fontStyle | TextStyle | [private]
m_fontWeight | TextStyle | [private]
m_textAlignment | TextStyle | [private]
m_textFormat | TextStyle | [private]
SetFontName(Platform::String^fontName) | TextStyle |
SetFontSize(float fontSize) | TextStyle |
SetFontStyle(DWRITE_FONT_STYLE fontStyle) | TextStyle |
SetFontWeight(DWRITE_FONT_WEIGHT fontWeight) | TextStyle |
SetTextAlignment(DWRITE_TEXT_ALIGNMENT textAlignment) | TextStyle |
TextStyle() | TextStyle |
Generated on Sat Nov 23 2024 16:09:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Association launching/C++/CppSamplesUtils.h Source File

  • Association launching

CppSamplesUtils.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 <string>
00014 #include <sstream>
00015 #include <algorithm>
00016 #include <collection.h>
00017 #include <ppltasks.h>
00018
00019 namespace CppSamplesUtils
00020 {
00021     namespace Details
00022     {
00023         static Windows::Foundation::Collections::PropertySet^ sessionState = nullptr;
00024         static Platform::String^ sessionStateFileName = ref new Platform::String(L"_cppSessionState.xml");
00025
00026         concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file);
00027         concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file);
00028     }
00029
00030     class SuspensionManager
00031     {
00032     public:
00033         static Windows::Foundation::Collections::PropertySet^ SessionState()
00034         {
00035             using namespace Windows::Foundation::Collections;
00036             using namespace Details;
00037
00038             if (sessionState == nullptr)
00039             {
00040                 sessionState = ref new PropertySet();
00041             }
00042             return sessionState;
00043         }
00044
00045         static concurrency::task<void> StartRestoreTask()
00046         {
00047             using namespace Windows::Foundation;
00048             using namespace Windows::Storage;
00049             using namespace Windows::Storage::Streams;
00050             using namespace Details;
00051
00052             auto state = SessionState();
00053             state->Clear();
00054
00055             concurrency::task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFileName));
00056             return getFileTask.then([=](StorageFile^ file)
00057             {
00058                 return DeserializeSessionState(file);
00059             });
00060         }
00061
00062         static concurrency::task<void> StartSaveTask()
00063         {
00064             using namespace Windows::Foundation;
00065             using namespace Windows::Storage;
00066             using namespace Windows::Storage::Streams;
00067             using namespace Details;
00068
00069             concurrency::task<StorageFile^> createFileTask(ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFileName, CreationCollisionOption::ReplaceExisting));
00070             return createFileTask.then([=](StorageFile^ file)
00071             {
00072                 return SerializeSessionState(file);
00073             });
00074         }
00075     };
00076
00077     namespace Details
00078     {
00079         template <class T>
00080         inline Platform::String^ ToString(T value)
00081         {
00082             std::wstringstream wss;
00083             wss << value;
00084             return ref new Platform::String(wss.str().c_str());
00085         }
00086
00087         template <class T>
00088         inline T FromStringTo(Platform::String^ str)
00089         {
00090             std::wistringstream wiss(str->Data());
00091             T value = 0;
00092             wiss >> value;
00093             return value;
00094         }
00095
00096         template <class T>
00097         inline T FromHexStringTo(Platform::String^ str)
00098         {
00099             std::wistringstream wiss(str->Data());
00100             T value = 0;
00101             wiss >> std::hex >> value;
00102             return value;
00103         }
00104
00105         template <>
00106         inline Platform::Guid FromStringTo<Platform::Guid>(Platform::String^ str)
00107         {
00108             using namespace Platform;
00109
00110             if (str->Length() != 38)
00111             {
00112                 throw ref new InvalidArgumentException;
00113             }
00114             std::wstring ws(str->Data());
00115             if (ws[0] != L'{' || ws[37] != L'}' || ws[9] != L'-' || ws[14] != L'-' || ws[19] != L'-' || ws[24] != L'-')
00116             {
00117                 throw ref new InvalidArgumentException;
00118             }
00119             ws[0] = ws[37] = ws[9] = ws[14] = ws[19] =ws[24] = L' ';
00120             std::wistringstream wiss(ws);
00121             unsigned int a = 0;
00122             unsigned short b = 0;
00123             unsigned short c = 0;
00124             unsigned short d = 0;
00125             unsigned long long e = 0;
00126             static_assert(sizeof(d) == sizeof(char) * 2, "sizeof(d) == sizeof(char) * 2");
00127             static_assert(sizeof(e) == sizeof(char) * 8, "sizeof(e) == sizeof(char) * 8");
00128             wiss >> std::hex >> a >> b >> c >> d >> e;
00129             unsigned char *ad = (unsigned char*)(&d);
00130             unsigned char *ae = (unsigned char*)(&e);
00131             return Platform::Guid(a, b, c, ad[1], ad[0], ae[5], ae[4], ae[3], ae[2], ae[1], ae[0]);
00132         }
00133
00134         inline Platform::Object^ ConvertStringToObject(Windows::Foundation::PropertyType type, Platform::String^ str)
00135         {
00136             using namespace Platform;
00137             using namespace Windows::Foundation;
00138
00139             if (type == PropertyType::String)
00140             {
00141                 return PropertyValue::CreateString(str);
00142             }
00143
00144             switch (type)
00145             {
00146             case PropertyType::UInt8:
00147                 return PropertyValue::CreateUInt8((unsigned char)FromStringTo<unsigned short>(str));
00148             case PropertyType::UInt16:
00149                 return PropertyValue::CreateUInt16(FromStringTo<unsigned short>(str));
00150             case PropertyType::UInt32:
00151                 return PropertyValue::CreateUInt32(FromStringTo<unsigned int>(str));
00152             case PropertyType::UInt64:
00153                 return PropertyValue::CreateUInt64(FromStringTo<unsigned long long>(str));
00154             case PropertyType::Int16:
00155                 return PropertyValue::CreateInt16(FromStringTo<short>(str));
00156             case PropertyType::Int32:
00157                 return PropertyValue::CreateInt32(FromStringTo<int>(str));
00158             case PropertyType::Int64:
00159                 return PropertyValue::CreateInt64(FromStringTo<long long>(str));
00160             case PropertyType::Single:
00161                 return PropertyValue::CreateSingle(FromStringTo<float>(str));
00162             case PropertyType::Double:
00163                 return PropertyValue::CreateDouble(FromStringTo<double>(str));
00164             case PropertyType::Boolean:
00165                 return PropertyValue::CreateBoolean(FromStringTo<bool>(str));
00166             case PropertyType::Char16:
00167                 return PropertyValue::CreateChar16(str->Data()[0]);
00168             case PropertyType::Guid:
00169                 return PropertyValue::CreateGuid(FromStringTo<Guid>(str));
00170             default:
00171                 throw ref new Platform::InvalidCastException;
00172             }
00173         }
00174
00175         inline Platform::String^ ConvertPropertyValueToString(Windows::Foundation::IPropertyValue^ pv)
00176         {
00177             using namespace Platform;
00178             using namespace Windows::Foundation;
00179
00180             String^ valueString;
00181
00182             switch (pv->Type)
00183             {
00184             case PropertyType::String:
00185                 valueString = pv->GetString();
00186                 break;
00187
00188             case PropertyType::UInt8:
00189             case PropertyType::UInt16:
00190             case PropertyType::UInt32:
00191             case PropertyType::UInt64:
00192                 valueString = ToString(pv->GetUInt64());
00193                 break;
00194
00195             case PropertyType::Int16:
00196             case PropertyType::Int32:
00197             case PropertyType::Int64:
00198                 valueString = ToString(pv->GetInt64());
00199                 break;
00200
00201             case PropertyType::Single:
00202                 valueString = ToString(pv->GetSingle());
00203                 break;
00204
00205             case PropertyType::Double:
00206                 valueString = ToString(pv->GetDouble());
00207                 break;
00208
00209             case PropertyType::Boolean:
00210                 valueString = ToString(pv->GetBoolean());
00211                 break;
00212
00213             case PropertyType::Char16:
00214                 wchar_t buffer[2];
00215                 buffer[0] = pv->GetChar16();
00216                 buffer[1] = 0;
00217                 valueString = ref new String(buffer);
00218                 break;
00219
00220             case PropertyType::Guid:
00221                 valueString = pv->GetGuid().ToString();
00222                 break;
00223
00224             default:
00225                 throw ref new InvalidCastException;
00226             }
00227
00228             return valueString;
00229         }
00230
00231         inline Windows::Data::Xml::Dom::XmlElement^ CreateXmlElementFromObject(Windows::Data::Xml::Dom::XmlDocument^ doc, Platform::String^ name, Platform::Object^ value)
00232         {
00233             using namespace Platform;
00234             using namespace Windows::Foundation;
00235             using namespace Windows::Data::Xml::Dom;
00236
00237             XmlElement^ element = doc->CreateElement("item");
00238             element->SetAttribute("name", name);
00239
00240             IPropertyValue^ pv = (IPropertyValue^)value;
00241             element->SetAttribute("type", ToString((int)pv->Type));
00242             element->SetAttribute("value", ConvertPropertyValueToString(pv));
00243
00244             return element;
00245         }
00246
00247         inline concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file)
00248         {
00249             using namespace Windows::Data::Xml::Dom;
00250             using namespace Windows::Foundation;
00251             namespace WFC = Windows::Foundation::Collections;
00252             typedef Windows::Foundation::Collections::IKeyValuePair<Platform::String^, Platform::Object^> KVPair;
00253
00254             XmlDocument^ doc = ref new XmlDocument;
00255             doc->AppendChild(doc->CreateElement("items"));
00256             auto sessionState = SuspensionManager::SessionState();
00257
00258             std::for_each(WFC::begin(sessionState), WFC::end(sessionState), [doc](KVPair^ item)
00259             {
00260                 doc->DocumentElement->AppendChild(CreateXmlElementFromObject(doc, item->Key, item->Value));
00261             });
00262
00263             return concurrency::task<void>(doc->SaveToFileAsync(file));
00264         }
00265
00266         inline Windows::Foundation::PropertyType PropertyTypeFromString(Platform::String^ str)
00267         {
00268             int value = FromStringTo<int>(str);
00269             return (Windows::Foundation::PropertyType)value;
00270         }
00271
00272         inline concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file)
00273         {
00274             using namespace Platform;
00275             using namespace Windows::Foundation;
00276             using namespace Windows::Data::Xml::Dom;
00277             namespace WFC = Windows::Foundation::Collections;
00278
00279             concurrency::task<XmlDocument^> loadFileTask(XmlDocument::LoadFromFileAsync(file));
00280             return loadFileTask.then([=](concurrency::task<XmlDocument^> docTask)
00281             {
00282                 try
00283                 {
00284                     auto doc = docTask.get();
00285                     auto items = doc->SelectNodes("/items/item");
00286                     auto sessionState = SuspensionManager::SessionState();
00287
00288                     std::for_each(WFC::begin(items), WFC::end(items), [sessionState](IXmlNode^ node)
00289                     {
00290                         auto element = (IXmlElement^)node;
00291                         String^ name = element->GetAttribute("name");
00292                         String^ value = element->GetAttribute("value");
00293                         PropertyType type = PropertyTypeFromString(element->GetAttribute("type"));
00294
00295                         Object^ valueObject = ConvertStringToObject(type, value);
00296                         sessionState->Insert(name, valueObject);
00297                     });
00298
00299                 }
00300                 catch (Platform::Exception^)
00301                 {
00302                     // Restoring is best effort
00303                 }
00304             });
00305         }
00306     } // namespace Details
00307 } // namespace CppSamplesUtils
Generated on Sat Nov 23 2024 16:07:53 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2Dapp printing/C++/D2DPageRenderer.h Source File

  • Direct2Dapp printing

D2DPageRenderer.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 <DirectXBase.h>
00010 #include <printpreview.h>
00011 #include "SampleOverlay.h"
00012
00013 ref class PageRendererContext;
00014
00015 // This class is shared between the display, print, and print-preview threads.
00016 // To ensure thread-safety, it should contain only immutable resources,
00017 // factories, and devices.
00018 //
00019 // For performance, we also cache the display PageRendererContext on the
00020 // PageRenderer.
00021 ref class PageRenderer : public DirectXBase
00022 {
00023 internal:
00024     PageRenderer();
00025
00026     virtual void CreateDeviceIndependentResources() override;
00027     virtual void CreateDeviceResources() override;
00028     virtual void Render() override;
00029     virtual void UpdateForWindowSizeChange() override;
00030
00031     void SetSnappedMode(_In_ bool isSnapped);
00032
00033     // Print out one page.
00034     void PrintPage(
00035         _In_ uint32                 pageNumber,
00036         _In_ D2D1_RECT_F            imageableArea,
00037         _In_ D2D1_SIZE_F            pageSize,
00038         _In_opt_ IStream*           pagePrintTicketStream
00039         );
00040
00041     // Create DXGI surface for preview.
00042     void DrawPreviewSurface(
00043         _In_  float                             width,
00044         _In_  float                             height,
00045         _In_  float                             scale,
00046         _In_  D2D1_RECT_F                       contentBox,
00047         _In_  uint32                            desiredJobPage,
00048         _In_  IPrintPreviewDxgiPackageTarget*   previewTarget
00049         );
00050
00051     // Create Direct2D print control for caller, who only needs to
00052     // specify IPrintDocumentPackageTarget and print control property.
00053     void CreatePrintControl(
00054         _In_  IPrintDocumentPackageTarget*      docPackageTarget,
00055         _In_  D2D1_PRINT_CONTROL_PROPERTIES*    printControlProperties
00056         );
00057
00058     // Close print control with protection.
00059     HRESULT ClosePrintControl();
00060
00061     IDWriteTextFormat* GetTextFormatNoRef();
00062     IDWriteTextFormat* GetMessageFormatNoRef();
00063
00064 private:
00065     Microsoft::WRL::ComPtr<ID2D1PrintControl>       m_d2dPrintControl;
00066
00067     // Overlay for sample title.
00068     SampleOverlay^                                  m_sampleOverlay;
00069
00070     // Whether the app is in the snapped mode.
00071     bool                                            m_isSnapped;
00072
00073     // Page renderer context for use for display. Note that this object is mutable
00074     // and hence should *only* be used by the display thread.
00075     PageRendererContext^                            m_displayPageRendererContext;
00076
00077     // Immutable resources
00078     Microsoft::WRL::ComPtr<IDWriteTextFormat>       m_textFormat;
00079     Microsoft::WRL::ComPtr<IDWriteTextFormat>       m_messageFormat;
00080 };
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/RandomPhotoSelector.h Source File

  • Hilo C++
  • Hilo

RandomPhotoSelector.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
00009 namespace Hilo
00010 {
00011     // See http://go.microsoft.com/fwlink/?LinkId=267275 for info about Hilo's implementation of tiles.
00012
00013     // The RandomPhotoSelector static class creates a randomly shuffled vector of image files.
00014     class RandomPhotoSelector
00015     {
00016     public:
00017         static concurrency::task<Windows::Foundation::Collections::IVector<Windows::Storage::StorageFile^>^> SelectFilesAsync(Windows::Foundation::Collections::IVectorView<Windows::Storage::StorageFile^>^ photos, unsigned int count );
00018         static std::vector<unsigned int> CreateRandomizedVector(unsigned int vectorSize, unsigned int sampleSize);
00019     };
00020 }
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

ContentImageSource::ImageSourceDrawHelper Member List

This is the complete list of members for ContentImageSource::ImageSourceDrawHelper, including all inherited members.
ImageSourceDrawHelper(IVirtualSurfaceImageSourceNative *imageSourceNative, _In_ RECT updateRect, _Out_ IDXGISurface **pSurface, _Out_ POINT *offset, HRESULT *hr) | ContentImageSource::ImageSourceDrawHelper |
m_hr | ContentImageSource::ImageSourceDrawHelper | [private]
m_imageSourceNative | ContentImageSource::ImageSourceDrawHelper | [private]
~ImageSourceDrawHelper() | ContentImageSource::ImageSourceDrawHelper |
Generated on Sat Nov 23 2024 16:09:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DirectX::TexMetadata Member List

This is the complete list of members for DirectX::TexMetadata, including all inherited members.
arraySize | DirectX::TexMetadata
ComputeIndex(_In_ size_t mip, _In_ size_t item, _In_ size_t slice) const | DirectX::TexMetadata
depth | DirectX::TexMetadata
dimension | DirectX::TexMetadata
format | DirectX::TexMetadata
height | DirectX::TexMetadata
mipLevels | DirectX::TexMetadata
miscFlags | DirectX::TexMetadata
width | DirectX::TexMetadata
Generated on Sat Nov 23 2024 16:09:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

AccountPictureName::Scenario Member List

This is the complete list of members for AccountPictureName::Scenario, including all inherited members.
ClassName | AccountPictureName::Scenario
Title | AccountPictureName::Scenario
Generated on Sat Nov 23 2024 16:09:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playback Manager msAudioCategory/C++/StreamTypeAlert.xaml.h Source File

  • Playback Manager msAudioCategory

StreamTypeAlert.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 // StreamTypeAlert.xaml.h
00013 // Declaration of the StreamTypeAlert class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "StreamTypeAlert.g.h"
00020 #include "MainPage.xaml.h"
00021 #include "PlaybackControl.xaml.h"
00022
00023 namespace SDKSample
00024 {
00025     namespace  PlaybackManager
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 StreamTypeAlert sealed
00032         {
00033         public:
00034             StreamTypeAlert();
00035
00036         protected:
00037             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00038         private:
00039             MainPage^ rootPage;
00040             void Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         };
00042     }
00043 }
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Secondary tiles/C#,C++/UnpinTile.xaml.h Source File

  • Secondary tiles
  • C#,C++

UnpinTile.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 // UnpinTile.xaml.h
00013 // Declaration of the UnpinTile class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "UnpinTile.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SecondaryTiles
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 UnpinTile sealed
00029     {
00030     public:
00031         UnpinTile();
00032
00033     protected:
00034         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00035         virtual void OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^ e) override;
00036     private:
00037         MainPage^ rootPage;
00038         Windows::UI::Xaml::Controls::AppBar^ appBar;
00039         void UnpinSecondaryTile_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040     };
00041 }
Generated on Sat Nov 23 2024 16:08:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D custom image effects/C++/PixelShader/RippleEffect.cpp Source File

  • Direct2D custom image effects
  • PixelShader

RippleEffect.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 "RippleEffect.h"
00011 #include "BasicReaderWriter.h"
00012
00013 #define XML(X) TEXT(#X)
00014
00015 RippleEffect::RippleEffect() :
00016     m_refCount(1)
00017 {
00018     m_constants.amplitude = 0;
00019     m_constants.center = D2D1::Point2F(0, 0);
00020     m_constants.frequency = 0;
00021     m_constants.phase = 0;
00022     m_constants.spread = 0;
00023 }
00024
00025 HRESULT __stdcall RippleEffect::CreateRippleImpl(_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) RippleEffect());
00029
00030     if (*ppEffectImpl == nullptr)
00031     {
00032         return E_OUTOFMEMORY;
00033     }
00034     else
00035     {
00036         return S_OK;
00037     }
00038 }
00039
00040 HRESULT RippleEffect::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='Ripple'/>
00050                 <Property name='Author' type='string' value='Microsoft Corporation'/>
00051                 <Property name='Category' type='string' value='Stylize'/>
00052                 <Property name='Description' type='string' value='Adds a ripple effect that can be animated'/>
00053                 <Inputs>
00054                     <Input name='Source'/>
00055                 </Inputs>
00056                 <!-- Custom Properties go here -->
00057                 <Property name='Frequency' type='float'>
00058                     <Property name='DisplayName' type='string' value='Frequency'/>
00059                     <Property name='Min' type='float' value='0.0' />
00060                     <Property name='Max' type='float' value='1000.0' />
00061                     <Property name='Default' type='float' value='0.0' />
00062                 </Property>
00063                 <Property name='Phase' type='float'>
00064                     <Property name='DisplayName' type='string' value='Phase'/>
00065                     <Property name='Min' type='float' value='-100.0' />
00066                     <Property name='Max' type='float' value='100.0' />
00067                     <Property name='Default' type='float' value='0.0' />
00068                 </Property>
00069                 <Property name='Amplitude' type='float'>
00070                     <Property name='DisplayName' type='string' value='Amplitude'/>
00071                     <Property name='Min' type='float' value='0.0001' />
00072                     <Property name='Max' type='float' value='1000.0' />
00073                     <Property name='Default' type='float' value='0.0' />
00074                 </Property>
00075                 <Property name='Spread' type='float'>
00076                     <Property name='DisplayName' type='string' value='Spread'/>
00077                     <Property name='Min' type='float' value='0.0001' />
00078                     <Property name='Max' type='float' value='1000.0' />
00079                     <Property name='Default' type='float' value='0.0' />
00080                 </Property>
00081                 <Property name='Center' type='vector2'>
00082                     <Property name='DisplayName' type='string' value='Center'/>
00083                     <Property name='Default' type='vector2' value='(0.0, 0.0)' />
00084                 </Property>
00085             </Effect>
00086             );
00087
00088     // This defines the bindings from specific properties to the callback functions
00089     // on the class that ID2D1Effect::SetValue() & GetValue() will call.
00090     const D2D1_PROPERTY_BINDING bindings[] =
00091     {
00092         D2D1_VALUE_TYPE_BINDING(L"Frequency", &SetFrequency, &GetFrequency),
00093         D2D1_VALUE_TYPE_BINDING(L"Phase", &SetPhase, &GetPhase),
00094         D2D1_VALUE_TYPE_BINDING(L"Amplitude", &SetAmplitude, &GetAmplitude),
00095         D2D1_VALUE_TYPE_BINDING(L"Spread", &SetSpread, &GetSpread),
00096         D2D1_VALUE_TYPE_BINDING(L"Center", &SetCenter, &GetCenter),
00097     };
00098
00099     // This registers the effect with the factory, which will make the effect
00100     // instantiatable.
00101     return pFactory->RegisterEffectFromString(
00102         CLSID_CustomRippleEffect,
00103         pszXml,
00104         bindings,
00105         ARRAYSIZE(bindings),
00106         CreateRippleImpl
00107         );
00108 }
00109
00110 IFACEMETHODIMP RippleEffect::Initialize(
00111     _In_ ID2D1EffectContext* pEffectContext,
00112     _In_ ID2D1TransformGraph* pTransformGraph
00113     )
00114 {
00115     // To maintain consistency across different DPIs, this effect needs to cover more pixels at
00116     // higher than normal DPIs. The context is saved here so the effect can later retrieve the DPI.
00117     m_effectContext = pEffectContext;
00118
00119     BasicReaderWriter^ reader = ref new BasicReaderWriter();
00120     Platform::Array<unsigned char, 1U>^ data;
00121
00122     try
00123     {
00124         data = reader->ReadData("RippleEffect.cso");
00125     }
00126     catch (Platform::Exception^ e)
00127     {
00128         // Return error if file can not be read.
00129         return e->HResult;
00130     }
00131
00132     HRESULT hr = pEffectContext->LoadPixelShader(GUID_RipplePixelShader, data->Data, data->Length);
00133
00134     // This loads the shader into the Direct2D image effects system and associates it with the GUID passed in.
00135     // If this method is called more than once (say by other instances of the effect) with the same GUID,
00136     // the system will simply do nothing, ensuring that only one instance of a shader is stored regardless of how
00137     // many time it is used.
00138     if (SUCCEEDED(hr))
00139     {
00140         // The graph consists of a single transform. In fact, this class is the transform,
00141         // reducing the complexity of implementing an effect when all we need to
00142         // do is use a single pixel shader.
00143         hr = pTransformGraph->SetSingleTransformNode(this);
00144     }
00145
00146     return hr;
00147 }
00148
00149 HRESULT RippleEffect::SetFrequency(float frequency)
00150 {
00151     // Limit to the published possible values in the XML.
00152     m_constants.frequency = Clamp(frequency, 0.0f, 1000.0f);
00153     return S_OK;
00154 }
00155
00156 float RippleEffect::GetFrequency() const
00157 {
00158     return m_constants.frequency;
00159 }
00160
00161 HRESULT RippleEffect::SetPhase(float phase)
00162 {
00163     // Limit to the published possible values in the XML.
00164     m_constants.phase = Clamp(phase, -100.0f, 100.0f);
00165     return S_OK;
00166 }
00167
00168 float RippleEffect::GetPhase() const
00169 {
00170     return m_constants.phase;
00171 }
00172
00173 HRESULT RippleEffect::SetAmplitude(float amplitude)
00174 {
00175     // Limit to the published possible values in the XML.
00176     m_constants.amplitude = Clamp(amplitude, 0.0001f, 1000.0f);
00177     return S_OK;
00178 }
00179
00180 float RippleEffect::GetSpread() const
00181 {
00182     return m_constants.spread;
00183 }
00184
00185 HRESULT RippleEffect::SetSpread(float spread)
00186 {
00187     // Limit to the published possible values in the XML.
00188     m_constants.spread = Clamp(spread, 0.0001f, 1000.0f);
00189     return S_OK;
00190 }
00191
00192 float RippleEffect::GetAmplitude() const
00193 {
00194     return m_constants.amplitude;
00195 }
00196
00197 HRESULT RippleEffect::SetCenter(D2D1_POINT_2F center)
00198 {
00199     // The valid range is all possible point positions, so no clamping is needed.
00200     m_constants.center = center;
00201     return S_OK;
00202 }
00203
00204 D2D1_POINT_2F RippleEffect::GetCenter() const
00205 {
00206     return m_constants.center;
00207 }
00208
00209 HRESULT RippleEffect::UpdateConstants()
00210 {
00211     // Update the DPI if it has changed. This allows the effect to scale across different DPIs automatically.
00212     m_effectContext->GetDpi(&m_dpi, &m_dpi);
00213     m_constants.dpi = m_dpi;
00214
00215     return m_drawInfo->SetPixelShaderConstantBuffer(reinterpret_cast<BYTE*>(&m_constants), sizeof(m_constants));
00216 }
00217
00218 IFACEMETHODIMP RippleEffect::PrepareForRender(D2D1_CHANGE_TYPE changeType)
00219 {
00220     return UpdateConstants();
00221 }
00222
00223 // SetGraph is only called when the number of inputs changes. This never happens as we publish this effect
00224 // as a single input effect.
00225 IFACEMETHODIMP RippleEffect::SetGraph(_In_ ID2D1TransformGraph* pGraph)
00226 {
00227     return E_NOTIMPL;
00228 }
00229
00230 // Called to assign a new render info class, which is used to inform D2D on
00231 // how to set the state of the GPU.
00232 IFACEMETHODIMP RippleEffect::SetDrawInfo(_In_ ID2D1DrawInfo* pDrawInfo)
00233 {
00234     m_drawInfo = pDrawInfo;
00235
00236     return m_drawInfo->SetPixelShader(GUID_RipplePixelShader);
00237 }
00238
00239 // Calculates the mapping between the output and input rects. In this case,
00240 // we want to request an expanded region to account for pixels that the ripple
00241 // may need outside of the bounds of the destination.
00242 IFACEMETHODIMP RippleEffect::MapOutputRectToInputRects(
00243     _In_ const D2D1_RECT_L* pOutputRect,
00244     _Out_writes_(inputRectCount) D2D1_RECT_L* pInputRects,
00245     UINT32 inputRectCount
00246     ) const
00247 {
00248     // This effect has exactly one input, so if there is more than one input rect,
00249     // something is wrong.
00250     if (inputRectCount != 1)
00251     {
00252         return E_INVALIDARG;
00253     }
00254
00255     long expansion = static_cast<long>(Round(m_constants.amplitude));
00256
00257     // Expand the rect out by the amplitude of the ripple animation. SafeAdd
00258     // is a helper function that prevents long over/underflows.
00259     pInputRects[0].left    = SafeAdd(pOutputRect->left, -expansion);
00260     pInputRects[0].top     = SafeAdd(pOutputRect->top, -expansion);
00261     pInputRects[0].right   = SafeAdd(pOutputRect->right, expansion);
00262     pInputRects[0].bottom  = SafeAdd(pOutputRect->bottom, expansion);
00263
00264     return S_OK;
00265 }
00266
00267 IFACEMETHODIMP RippleEffect::MapInputRectsToOutputRect(
00268     _In_reads_(inputRectCount) CONST D2D1_RECT_L* pInputRects,
00269     _In_reads_(inputRectCount) CONST D2D1_RECT_L* pInputOpaqueSubRects,
00270     UINT32 inputRectCount,
00271     _Out_ D2D1_RECT_L* pOutputRect,
00272     _Out_ D2D1_RECT_L* pOutputOpaqueSubRect
00273     )
00274 {
00275     // This effect has exactly one input, so if there is more than one input rect,
00276     // something is wrong.
00277     if (inputRectCount != 1)
00278     {
00279         return E_INVALIDARG;
00280     }
00281
00282     *pOutputRect = pInputRects[0];
00283     m_inputRect = pInputRects[0];
00284
00285     // Indicate that entire output might contain transparency.
00286     ZeroMemory(pOutputOpaqueSubRect, sizeof(*pOutputOpaqueSubRect));
00287
00288     return S_OK;
00289 }
00290
00291 IFACEMETHODIMP RippleEffect::MapInvalidRect(
00292     UINT32 inputIndex,
00293     D2D1_RECT_L invalidInputRect,
00294     _Out_ D2D1_RECT_L* pInvalidOutputRect
00295     ) const
00296 {
00297     HRESULT hr = S_OK;
00298
00299     // Indicate that the entire output may be invalid.
00300     *pInvalidOutputRect = m_inputRect;
00301
00302     return hr;
00303 }
00304
00305 IFACEMETHODIMP_(UINT32) RippleEffect::GetInputCount() const
00306 {
00307     return 1;
00308 }
00309
00310 // D2D ensures that that effects are only referenced from one thread at a time.
00311 // To improve performance, we simply increment/decrement our reference count
00312 // rather than use atomic InterlockedIncrement()/InterlockedDecrement() functions.
00313 IFACEMETHODIMP_(ULONG) RippleEffect::AddRef()
00314 {
00315     m_refCount++;
00316     return m_refCount;
00317 }
00318
00319 IFACEMETHODIMP_(ULONG) RippleEffect::Release()
00320 {
00321     m_refCount--;
00322
00323     if (m_refCount == 0)
00324     {
00325         delete this;
00326         return 0;
00327     }
00328     else
00329     {
00330         return m_refCount;
00331     }
00332 }
00333
00334 // This enables the stack of parent interfaces to be queried. In the instance
00335 // of the Ripple interface, this method simply enables the developer
00336 // to cast a Ripple instance to an ID2D1EffectImpl or IUnknown instance.
00337 IFACEMETHODIMP RippleEffect::QueryInterface(
00338     _In_ REFIID riid,
00339     _Outptr_ void** ppOutput
00340     )
00341 {
00342     *ppOutput = nullptr;
00343     HRESULT hr = S_OK;
00344
00345     if (riid == __uuidof(ID2D1EffectImpl))
00346     {
00347         *ppOutput = reinterpret_cast<ID2D1EffectImpl*>(this);
00348     }
00349     else if (riid == __uuidof(ID2D1DrawTransform))
00350     {
00351         *ppOutput = static_cast<ID2D1DrawTransform*>(this);
00352     }
00353     else if (riid == __uuidof(ID2D1Transform))
00354     {
00355         *ppOutput = static_cast<ID2D1Transform*>(this);
00356     }
00357     else if (riid == __uuidof(ID2D1TransformNode))
00358     {
00359         *ppOutput = static_cast<ID2D1TransformNode*>(this);
00360     }
00361     else if (riid == __uuidof(IUnknown))
00362     {
00363         *ppOutput = this;
00364     }
00365     else
00366     {
00367         hr = E_NOINTERFACE;
00368     }
00369
00370     if (*ppOutput != nullptr)
00371     {
00372         AddRef();
00373     }
00374
00375     return hr;
00376 }
Generated on Sat Nov 23 2024 16:08:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playlist/C++/MainPage.xaml.h Source File

  • Playlist

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:46 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D HLSL fractal generator/C++/pch.h Source File

  • Direct3D HLSL fractal generator

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 <d3d11_1.h>
00012 #include <d2d1_1.h>
00013 #include <d2d1effects.h>
00014 #include <dwrite_1.h>
00015 #include <wincodec.h>
00016 #include <agile.h>
00017 #include "BasicMath.h"
00018 #include "DoublePrecisionMath.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D HLSL fractal generator/C++/BasicLoader.h Source File

  • Direct3D HLSL fractal generator

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 Sat Nov 23 2024 16:08:08 for Win8-Examples by doxygen 1.7.1


Win8-Examples: MediaStreamSource media extension/C#,C++/PcmSource.cs Source File

  • MediaStreamSource media extension
  • C#,C++

PcmSource.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.Text;
00015 using System.Threading.Tasks;
00016
00017 using Windows.Foundation.Collections;
00018 using Windows.Storage.Streams;
00019
00020 namespace MediaStreamSource
00021 {
00022     /// <summary>
00023     /// A simple media source generating audio wave
00024     /// </summary>
00025     public class PcmSource : MediaStreamSource
00026     {
00027         byte[] _pSample;
00028         const uint SampleRate = 44100;
00029         const uint Channels = 1;
00030         const uint BitsPerSample = 16;
00031         const long SampleDuration = 10000000;
00032
00033         long nextTimestamp;
00034
00035         /// <summary>
00036         /// Contructor
00037         /// </summary>
00038         public PcmSource()
00039         {
00040             Frequency = 440;
00041         }
00042
00043         public override void CloseMedia()
00044         {
00045             _pSample = null;
00046         }
00047
00048         public override void GetDiagnosticAsync(MediaStreamSourceDiagnosticKind diagnosticKind)
00049         {
00050             throw new NotImplementedException();
00051         }
00052
00053         public override void GetSampleAsync(MediaStreamType mediaStreamType)
00054         {
00055             Task.Run(() =>
00056             {
00057                 MediaStreamSample sample;
00058                 try
00059                 {
00060                     IBuffer winrtbuf = System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBuffer.Create(_pSample, 0, _pSample.Length, _pSample.Length);
00061                     sample = new MediaStreamSample(null, winrtbuf, 0, _pSample.Length, nextTimestamp, SampleDuration, null);
00062                     nextTimestamp += SampleDuration;
00063                 }
00064                 catch (Exception e)
00065                 {
00066                     ErrorOccurred(e.Message);
00067                     return;
00068                 }
00069
00070                 ReportGetSampleCompleted(sample);
00071             });
00072         }
00073
00074         public override void OpenMediaAsync()
00075         {
00076             Task.Run(() =>
00077             {
00078                 try
00079                 {
00080                     CreateSample();
00081                 }
00082                 catch (Exception e)
00083                 {
00084                     ErrorOccurred(e.Message);
00085                     return;
00086                 }
00087
00088                 PropertySet sourceAttr = new Windows.Foundation.Collections.PropertySet();
00089                 PropertySet streamAttr = new Windows.Foundation.Collections.PropertySet();
00090
00091                 streamAttr.Add("SampleRate", SampleRate);
00092                 streamAttr.Add("Channels", Channels);
00093                 streamAttr.Add("BitsPerSample", BitsPerSample);
00094
00095                 ReportOpenMediaCompleted(
00096                     sourceAttr,
00097                     new IPropertySet[] { streamAttr });
00098             });
00099         }
00100
00101         public override void SeekAsync(long seekToTime)
00102         {
00103             throw new NotImplementedException();
00104         }
00105
00106         public override void SwitchMediaStreamAsync(MediaStreamDescription mediaStreamDescription)
00107         {
00108             throw new NotImplementedException();
00109         }
00110
00111         /// <summary>
00112         /// Creates a audio sample
00113         /// </summary>
00114         private void CreateSample()
00115         {
00116             const uint size = SampleRate * Channels * BitsPerSample / 8;
00117             _pSample = new byte[size];
00118             double period = (double)SampleRate / Frequency;
00119
00120             for (uint i = 0; i < size; i += 2)
00121             {
00122                 double val = Math.IEEERemainder(i, period);
00123
00124                 val = 2 * Math.PI * val;
00125                 short res = (short)(Math.Sin(val) * (double)short.MaxValue);
00126
00127                 _pSample[i] = (byte)(res & 0x00ff);
00128                 _pSample[i] = (byte)((res >> 8) & 0x00ff);
00129             }
00130         }
00131
00132         public double Frequency
00133         {
00134             get;
00135             set;
00136         }
00137     }
00138 }
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application resources and localization/C++/Scenario8.xaml.h Source File

  • Application resources and localization

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 SDKSample
00023 {
00024     namespace ApplicationResources
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 Scenario8 sealed
00031         {
00032         public:
00033             Scenario8();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void Scenario8Button_Show_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX marble maze game/C++/pch.cpp Source File

  • DirectX marble maze game

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D animation/C++/D2DBasicAnimation.cpp Source File

  • Direct2D animation

D2DBasicAnimation.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 "D2DBasicAnimation.h"
00010
00011 using namespace Microsoft::WRL;
00012 using namespace Windows::ApplicationModel;
00013 using namespace Windows::ApplicationModel::Core;
00014 using namespace Windows::ApplicationModel::Activation;
00015 using namespace Windows::UI::Core;
00016 using namespace Windows::System;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Graphics::Display;
00019
00020 static const float AnimationDuration = 20.0f; // Defines how long it takes the triangle to traverse the path.
00021
00022 D2DBasicAnimation::D2DBasicAnimation() :
00023     m_windowClosed(false),
00024     m_windowVisible(true),
00025     m_pathLength(0.0f),
00026     m_elapsedTime(0.0f)
00027 {
00028 }
00029
00030 void D2DBasicAnimation::CreateDeviceIndependentResources()
00031 {
00032     DirectXBase::CreateDeviceIndependentResources();
00033 }
00034
00035 void D2DBasicAnimation::CreateSpiralPathAndTriangle()
00036 {
00037     DX::ThrowIfFailed(
00038         m_d2dFactory->CreatePathGeometry(&m_pathGeometry)
00039         );
00040
00041     {
00042         ComPtr<ID2D1GeometrySink> geometrySink;
00043
00044         // Write to the path geometry using the geometry sink. We are going to create a
00045         // spiral.
00046         DX::ThrowIfFailed(
00047             m_pathGeometry->Open(&geometrySink)
00048             );
00049
00050         D2D1_POINT_2F currentLocation = {0, 0};
00051
00052         geometrySink->BeginFigure(currentLocation, D2D1_FIGURE_BEGIN_FILLED);
00053
00054         D2D1_POINT_2F locDelta = {2, 2};
00055         float radius = 3;
00056
00057         for (UINT i = 0; i < 30; ++i)
00058         {
00059             currentLocation.x += radius * locDelta.x;
00060             currentLocation.y += radius * locDelta.y;
00061
00062             geometrySink->AddArc(
00063                 D2D1::ArcSegment(
00064                     currentLocation,
00065                     D2D1::SizeF(2*radius, 2*radius),    // radius x/y
00066                     0.0f,                               // rotation angle
00067                     D2D1_SWEEP_DIRECTION_CLOCKWISE,
00068                     D2D1_ARC_SIZE_SMALL
00069                     )
00070                 );
00071
00072             locDelta = D2D1::Point2F(-locDelta.y, locDelta.x);
00073
00074             radius += 3;
00075         }
00076
00077         geometrySink->EndFigure(D2D1_FIGURE_END_OPEN);
00078
00079         DX::ThrowIfFailed(
00080             geometrySink->Close()
00081             );
00082     }
00083
00084     DX::ThrowIfFailed(
00085         m_d2dFactory->CreatePathGeometry(&m_objectGeometry)
00086         );
00087
00088     {
00089         ComPtr<ID2D1GeometrySink> geometrySink;
00090
00091         // Create a simple triangle by writing the object geometry using the geometry sink.
00092         DX::ThrowIfFailed(
00093             m_objectGeometry->Open(&geometrySink)
00094             );
00095
00096         geometrySink->BeginFigure(
00097             D2D1::Point2F(0.0f, 0.0f),
00098             D2D1_FIGURE_BEGIN_FILLED
00099             );
00100
00101         const D2D1_POINT_2F triangle[] = {{-10.0f, -10.0f}, {-10.0f, 10.0f}, {0.0f, 0.0f}};
00102         geometrySink->AddLines(triangle, 3);
00103
00104         geometrySink->EndFigure(D2D1_FIGURE_END_OPEN);
00105
00106         DX::ThrowIfFailed(
00107             geometrySink->Close()
00108             );
00109     }
00110
00111     DX::ThrowIfFailed(
00112         m_pathGeometry->ComputeLength(
00113             nullptr,            // Apply no transform.
00114             &m_pathLength
00115             )
00116         );
00117 }
00118
00119 float D2DBasicAnimation::ComputeTriangleLocation(float startPoint, float endPoint, float duration, float elapsedTime)
00120 {
00121     float time = min(max(elapsedTime, 0), duration);
00122     return startPoint + ((endPoint - startPoint) * (time / duration));
00123 }
00124
00125 void D2DBasicAnimation::CreateDeviceResources()
00126 {
00127     DirectXBase::CreateDeviceResources();
00128
00129     this->CreateSpiralPathAndTriangle();
00130
00131     m_sampleOverlay = ref new SampleOverlay();
00132
00133     m_sampleOverlay->Initialize(
00134         m_d2dDevice.Get(),
00135         m_d2dContext.Get(),
00136         m_wicFactory.Get(),
00137         m_dwriteFactory.Get(),
00138         "Direct2D animation sample"
00139         );
00140
00141     DX::ThrowIfFailed(
00142         m_d2dContext->CreateSolidColorBrush(
00143             D2D1::ColorF(D2D1::ColorF::Black),
00144             &m_blackBrush
00145             )
00146         );
00147
00148     DX::ThrowIfFailed(
00149         m_d2dContext->CreateSolidColorBrush(
00150             D2D1::ColorF(D2D1::ColorF::White),
00151             &m_whiteBrush
00152             )
00153         );
00154 }
00155
00156
00157 void D2DBasicAnimation::Render()
00158 {
00159     // Retrieve the size of the render target.
00160     D2D1_SIZE_F renderTargetSize = m_d2dContext->GetSize();
00161
00162     m_d2dContext->BeginDraw();
00163
00164     m_d2dContext->Clear(D2D1::ColorF(D2D1::ColorF::CornflowerBlue));
00165     m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00166
00167     float minWidthHeightScale = min(renderTargetSize.width, renderTargetSize.height) / 512;
00168
00169     D2D1::Matrix3x2F scale = D2D1::Matrix3x2F::Scale(
00170         minWidthHeightScale,
00171         minWidthHeightScale
00172         );
00173
00174     D2D1::Matrix3x2F translation = D2D1::Matrix3x2F::Translation(
00175         renderTargetSize.width / 2.0f,
00176         renderTargetSize.height / 2.0f
00177         );
00178
00179     // Center the path.
00180     m_d2dContext->SetTransform(scale * translation);
00181
00182     // Draw the path in black.
00183     m_d2dContext->DrawGeometry(m_pathGeometry.Get(), m_blackBrush.Get());
00184
00185     float length = ComputeTriangleLocation(0.0f, m_pathLength, AnimationDuration, m_elapsedTime);
00186
00187     // Ask the geometry to give us the point that corresponds with the
00188     // length at the current time.
00189     D2D1_POINT_2F point;
00190     D2D1_POINT_2F tangent;
00191     DX::ThrowIfFailed(
00192         m_pathGeometry->ComputePointAtLength(
00193             length,
00194             nullptr,
00195             &point,
00196             &tangent
00197             )
00198         );
00199
00200     // Reorient the triangle so that it follows the
00201     // direction of the path.
00202     D2D1_MATRIX_3X2_F triangleMatrix;
00203     triangleMatrix = D2D1::Matrix3x2F(
00204         tangent.x, tangent.y,
00205         -tangent.y, tangent.x,
00206         point.x, point.y
00207         );
00208
00209     m_d2dContext->SetTransform(triangleMatrix * scale * translation);
00210
00211     // Draw the white triangle.
00212     m_d2dContext->FillGeometry(m_objectGeometry.Get(), m_whiteBrush.Get());
00213
00214     // When we reach the end of the animation, loop back to the beginning.
00215     if (m_elapsedTime >= AnimationDuration)
00216     {
00217         m_elapsedTime = 0.0f;
00218     }
00219     else
00220     {
00221         m_elapsedTime += 0.0166f; // This controls the number of time units that time is incremented by on every render call.
00222     }
00223
00224     // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00225     // is lost. It will be handled during the next call to Present.
00226     HRESULT hr = m_d2dContext->EndDraw();
00227     if (hr != D2DERR_RECREATE_TARGET)
00228     {
00229         DX::ThrowIfFailed(hr);
00230     }
00231
00232     m_sampleOverlay->Render();
00233 }
00234
00235 void D2DBasicAnimation::Initialize(
00236     _In_ CoreApplicationView^ applicationView
00237     )
00238 {
00239     applicationView->Activated +=
00240         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &D2DBasicAnimation::OnActivated);
00241
00242     CoreApplication::Suspending +=
00243         ref new EventHandler<SuspendingEventArgs^>(this, &D2DBasicAnimation::OnSuspending);
00244
00245     CoreApplication::Resuming +=
00246         ref new EventHandler<Platform::Object^>(this, &D2DBasicAnimation::OnResuming);
00247 }
00248
00249 void D2DBasicAnimation::SetWindow(
00250     _In_ CoreWindow^ window
00251     )
00252 {
00253     window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
00254
00255     window->SizeChanged +=
00256         ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &D2DBasicAnimation::OnWindowSizeChanged);
00257
00258     window->VisibilityChanged +=
00259         ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &D2DBasicAnimation::OnVisibilityChanged);
00260
00261     window->Closed +=
00262         ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &D2DBasicAnimation::OnWindowClosed);
00263
00264     DisplayProperties::LogicalDpiChanged +=
00265         ref new DisplayPropertiesEventHandler(this, &D2DBasicAnimation::OnLogicalDpiChanged);
00266
00267     DirectXBase::Initialize(window, DisplayProperties::LogicalDpi);
00268 }
00269
00270 void D2DBasicAnimation::Load(
00271     _In_ Platform::String^ entryPoint
00272     )
00273 {
00274 }
00275
00276 void D2DBasicAnimation::Run()
00277 {
00278     while (!m_windowClosed)
00279     {
00280         if (m_windowVisible)
00281         {
00282             m_window->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
00283             Render();
00284             Present();
00285         }
00286         else
00287         {
00288             m_window->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
00289         }
00290     }
00291 }
00292
00293 void D2DBasicAnimation::Uninitialize()
00294 {
00295 }
00296
00297 void D2DBasicAnimation::OnWindowSizeChanged(
00298     _In_ CoreWindow^ sender,
00299     _In_ WindowSizeChangedEventArgs^ args
00300     )
00301 {
00302     UpdateForWindowSizeChange();
00303     m_sampleOverlay->UpdateForWindowSizeChange();
00304 }
00305
00306 void D2DBasicAnimation::OnVisibilityChanged(
00307     _In_ CoreWindow^ sender,
00308     _In_ VisibilityChangedEventArgs^ args
00309     )
00310 {
00311     m_windowVisible = args->Visible;
00312 }
00313
00314 void D2DBasicAnimation::OnWindowClosed(
00315     _In_ CoreWindow^ sender,
00316     _In_ CoreWindowEventArgs^ args
00317     )
00318 {
00319     m_windowClosed = true;
00320 }
00321
00322 void D2DBasicAnimation::OnLogicalDpiChanged(
00323     _In_ Platform::Object^ sender
00324     )
00325 {
00326     SetDpi(DisplayProperties::LogicalDpi);
00327 }
00328
00329 void D2DBasicAnimation::OnActivated(
00330     _In_ CoreApplicationView^ applicationView,
00331     _In_ IActivatedEventArgs^ args
00332     )
00333 {
00334     m_window->Activate();
00335 }
00336
00337 void D2DBasicAnimation::OnSuspending(
00338     _In_ Platform::Object^ sender,
00339     _In_ SuspendingEventArgs^ args
00340     )
00341 {
00342 }
00343
00344 void D2DBasicAnimation::OnResuming(
00345     _In_ Platform::Object^ sender,
00346     _In_ Platform::Object^ args
00347     )
00348 {
00349 }
00350
00351 IFrameworkView^ DirectXAppSource::CreateView()
00352 {
00353     return ref new D2DBasicAnimation();
00354 }
00355
00356 [Platform::MTAThread]
00357 int main(Platform::Array<Platform::String^>^)
00358 {
00359     auto directXAppSource = ref new DirectXAppSource();
00360     CoreApplication::Run(directXAppSource);
00361     return 0;
00362 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/SphereMesh.h Source File

  • DirectX 3D shooting game

SphereMesh.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 // SphereMesh:
00011 // This class derives from MeshObject and creates a ID3D11Buffer of
00012 // vertices and indices to represent a canonical sphere that is
00013 // positioned at the origin with a radius of 1.0.
00014
00015 #include "MeshObject.h"
00016
00017 ref class SphereMesh: public MeshObject
00018 {
00019 internal:
00020     SphereMesh(_In_ ID3D11Device *device, uint32 segments);
00021 };
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::TileContent::TileWideText08 Member List

This is the complete list of members for NotificationsExtensions::TileContent::TileWideText08, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
Branding | NotificationsExtensions::TileContent::TileNotificationBase |
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
RequireSquareContent | NotificationsExtensions::TileContent::TileWideBase |
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SquareContent | NotificationsExtensions::TileContent::TileWideBase |
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextColumn2Row1 | NotificationsExtensions::TileContent::TileWideText08 |
TextColumn2Row2 | NotificationsExtensions::TileContent::TileWideText08 |
TextColumn2Row3 | NotificationsExtensions::TileContent::TileWideText08 |
TextColumn2Row4 | NotificationsExtensions::TileContent::TileWideText08 |
TextColumn2Row5 | NotificationsExtensions::TileContent::TileWideText08 |
TextFields | NotificationsExtensions::NotificationBase |
TextShortColumn1Row1 | NotificationsExtensions::TileContent::TileWideText08 |
TextShortColumn1Row2 | NotificationsExtensions::TileContent::TileWideText08 |
TextShortColumn1Row3 | NotificationsExtensions::TileContent::TileWideText08 |
TextShortColumn1Row4 | NotificationsExtensions::TileContent::TileWideText08 |
TextShortColumn1Row5 | NotificationsExtensions::TileContent::TileWideText08 |
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWideText08() | NotificationsExtensions::TileContent::TileWideText08 | [inline]
TileWideText08() | NotificationsExtensions::TileContent::TileWideText08 | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:44 for Win8-Examples by doxygen 1.7.1


Win8-Examples: User domain name/C++/pch.h Source File

  • User domain name

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/DirectXBase.h Source File

  • DirectX 3D shooting game

DirectXBase.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 "DirectXSample.h"
00011
00012 ref class DirectXBase;
00013 delegate void D3DDeviceEventHandler();
00014
00015 // Helper class that initializes DirectX APIs for both 2D and 3D rendering.
00016 // Some of the code in this class may be omitted if only 2D or only 3D rendering is being used.
00017 ref class DirectXBase abstract
00018 {
00019 internal:
00020     DirectXBase();
00021
00022     virtual void Initialize(
00023         Windows::UI::Core::CoreWindow^ window,
00024         float dpi
00025         );
00026     virtual void HandleDeviceLost();
00027     virtual void CreateDeviceIndependentResources();
00028     virtual void CreateDeviceResources();
00029     virtual void SetDpi(float dpi);
00030     virtual void UpdateForWindowSizeChange();
00031     virtual void CreateWindowSizeDependentResources();
00032     virtual void Render() = 0;
00033     virtual void Present();
00034     virtual float ConvertDipsToPixels(float dips);
00035
00036     event D3DDeviceEventHandler^ DeviceLost;
00037     event D3DDeviceEventHandler^ DeviceReset;
00038
00039 protected private:
00040     void OnStereoEnabledChanged(
00041         _In_ Platform::Object^ sender
00042         );
00043     void CheckStereoEnabledStatus();
00044
00045     Platform::Agile<Windows::UI::Core::CoreWindow>  m_window;
00046
00047     // DirectWrite & Windows Imaging Component Objects.
00048     Microsoft::WRL::ComPtr<IDWriteFactory1>         m_dwriteFactory;
00049     Microsoft::WRL::ComPtr<IWICImagingFactory2>     m_wicFactory;
00050
00051     // DirectX Core Objects. Required for 2D and 3D.
00052     Microsoft::WRL::ComPtr<ID3D11Device1>           m_d3dDevice;
00053     Microsoft::WRL::ComPtr<ID3D11DeviceContext1>    m_d3dContext;
00054     Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00055     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00056     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetViewRight;
00057
00058     // Direct2D Rendering Objects. Required for 2D.
00059     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00060     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00061     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00062     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmap;
00063     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmapRight;
00064
00065     // Direct3D Rendering Objects. Required for 3D.
00066     Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00067
00068     // Cached renderer properties.
00069     D3D_FEATURE_LEVEL                               m_featureLevel;
00070     Windows::Foundation::Size                       m_renderTargetSize;
00071     Windows::Foundation::Rect                       m_windowBounds;
00072     float                                           m_dpi;
00073     Windows::Graphics::Display::DisplayOrientations m_orientation;
00074     bool                                            m_stereoEnabled;
00075     bool                                            m_windowSizeChangeInProgress;
00076
00077     // Transforms used for display orientation.
00078     D2D1::Matrix3x2F                                m_rotationTransform2D;
00079     DirectX::XMFLOAT4X4                             m_rotationTransform3D;
00080 };
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Push and periodic notifications client-side/C++/Scenario1.xaml.h Source File

  • Push and periodic notifications client-side

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 #pragma once
00012
00013 #include "pch.h"
00014 #include "Scenario1.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKSample
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       [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         private:
00033             MainPage^ rootPage;
00034             void OpenChannel_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00035             void CloseChannel_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00036         };
00037     }
00038 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML WebView control/C++/Scenario1.xaml.h Source File

  • XAML WebView control

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 SDKSample
00023 {
00024     namespace WebViewControl
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 Scenario1 sealed
00031         {
00032         public:
00033             Scenario1();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040             void Other_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         void NavigateButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00042         void WebView1_LoadCompleted(Platform::Object^ sender, Windows::UI::Xaml::Navigation::NavigationEventArgs^ e);
00043         void Address_KeyUp(Platform::Object^ sender, Windows::UI::Xaml::Input::KeyRoutedEventArgs^ e);
00044       };
00045     }
00046 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/Cylinder.cpp Source File

  • DirectX 3D shooting game

Cylinder.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 "Cylinder.h"
00010
00011 using namespace DirectX;
00012
00013 //----------------------------------------------------------------------
00014
00015 Cylinder::Cylinder()
00016 {
00017     Initialize(XMFLOAT3(0.0f, 0.0f, 0.0f), 1.0f, XMFLOAT3(0.0f, 0.0f, 1.0f));
00018 }
00019
00020 //----------------------------------------------------------------------
00021
00022 Cylinder::Cylinder(
00023     XMFLOAT3 position,
00024     float radius,
00025     XMFLOAT3 direction
00026     )
00027 {
00028     Initialize(position, radius, direction);
00029 }
00030
00031 //----------------------------------------------------------------------
00032
00033 void Cylinder::Initialize(
00034     XMFLOAT3 position,
00035     float radius,
00036     XMFLOAT3 direction
00037     )
00038 {
00039     m_position = position;
00040     m_radius = radius;
00041     m_length = XMVectorGetX(XMVector3Length(XMLoadFloat3(&direction)));
00042     XMStoreFloat3(&m_axis, XMVector3Normalize(XMLoadFloat3(&direction)));
00043
00044     XMVECTOR up = XMVectorSet(0.0f, 0.0f, 1.0f, 1.0f);
00045     float angle1 = XMVectorGetX(
00046         XMVector3AngleBetweenVectors(up, XMLoadFloat3(&m_axis))
00047         );
00048
00049     XMMATRIX mat1 = XMMatrixIdentity();
00050
00051     if ((angle1 * angle1) > 0.025)
00052     {
00053         XMVECTOR axis1 = XMVector3Cross(up, XMLoadFloat3(&m_axis));
00054
00055         mat1 = XMMatrixRotationAxis(axis1, angle1);
00056     }
00057     XMStoreFloat4x4(&m_rotationMatrix, mat1);
00058
00059     XMStoreFloat4x4(
00060         &m_modelMatrix,
00061         XMMatrixScaling(m_radius, m_radius, m_length) *
00062         mat1 *
00063         XMMatrixTranslation(m_position.x, m_position.y, m_position.z)
00064         );
00065 }
00066
00067 //--------------------------------------------------------------------------------
00068
00069 void Cylinder::UpdatePosition()
00070 {
00071     XMStoreFloat4x4(
00072         &m_modelMatrix,
00073         XMMatrixScaling(m_radius, m_radius, m_length) *
00074         XMLoadFloat4x4(&m_rotationMatrix) *
00075         XMMatrixTranslation(m_position.x, m_position.y, m_position.z)
00076         );
00077 }
00078
00079 //--------------------------------------------------------------------------------
00080
00081 bool Cylinder::IsTouching(
00082     XMFLOAT3 point,
00083     float radius,
00084     _Out_ XMFLOAT3 *contact,
00085     _Out_ XMFLOAT3 *normal
00086     )
00087 {
00088     XMVECTOR p0;
00089     XMVECTOR axis;
00090     XMVECTOR p1;
00091     XMVECTOR px;
00092
00093     // Determine if a point is within radius distance of the cylinder and
00094     // return the point of contact (projection of the point onto the cylinder).
00095
00096     p0 = XMLoadFloat3(&m_position);
00097     axis = XMLoadFloat3(&m_axis);
00098     p1 = p0 + axis * m_length;
00099     px = XMLoadFloat3(&point);
00100
00101     float dist = XMVectorGetX(
00102         XMVector3LinePointDistance(p0, p1, px)
00103         );
00104
00105     // Projection of the point onto the Vector.
00106     float dist2 = XMVectorGetX(
00107         XMVector3Dot(px - p0, axis)
00108         );
00109
00110     XMVECTOR ptOnVector =  p0 + dist2 * axis;
00111
00112     XMVECTOR normalVector = XMVector3Normalize(px - ptOnVector);
00113
00114     XMStoreFloat3(normal, normalVector);
00115     XMStoreFloat3(contact, ptOnVector + normalVector * m_radius);
00116
00117     if (dist < 0.0f)
00118     {
00119         dist *= -1.0f;
00120     }
00121
00122     if (dist < (radius + m_radius))
00123     {
00124         if (dist2 >= 0.0f && dist2 <= m_length)
00125         {
00126             return true;
00127         }
00128         else
00129         {
00130             return false;
00131         }
00132     }
00133     return false;
00134 }
00135
00136 //--------------------------------------------------------------------------------
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Removable storage/C++/Constants.cpp Source File

  • Removable storage

Constants.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 "App.xaml.h"
00013 #include "MainPage.xaml.h"
00014 #include "Constants.h"
00015
00016 using namespace SDKSample;
00017
00018 using namespace Windows::ApplicationModel;
00019 using namespace Windows::ApplicationModel::Activation;
00020 using namespace Windows::Storage;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Interop;
00024
00025 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00026 {
00027     { "List removable storage devices", "SDKSample.RemovableStorageCPP.S1_ListStorages" },
00028     { "Send file to storage device", "SDKSample.RemovableStorageCPP.S2_SendToStorage" },
00029     { "Get image file from storage device", "SDKSample.RemovableStorageCPP.S3_GetFromStorage" },
00030     { "Get image file from camera or camera memory (Autoplay)", "SDKSample.RemovableStorageCPP.S4_Autoplay" }
00031 };
00032
00033 int MainPage::autoplayScenarioIndex = 3;
00034
00035 /// <summary>
00036 /// Invoked when the application is launched to open a specific file or to access
00037 /// specific content. This is the entry point for Content Autoplay when camera
00038 /// memory is attached to the PC.
00039 /// </summary>
00040 /// <param name="args">Details about the file activation request.</param>
00041 void App::OnFileActivated(Windows::ApplicationModel::Activation::FileActivatedEventArgs^ args)
00042 {
00043     Frame^ rootFrame = nullptr;
00044     if (Window::Current->Content == nullptr)
00045     {
00046         rootFrame = ref new Frame();
00047         TypeName pageType = { "SDKSample.MainPage", TypeKind::Custom };
00048         rootFrame->Navigate(pageType);
00049         Window::Current->Content = rootFrame;
00050     }
00051     else
00052     {
00053         rootFrame = safe_cast<Frame^>(Window::Current->Content);
00054     }
00055     Window::Current->Activate();
00056     MainPage^ mainPage = safe_cast<MainPage^>(rootFrame->Content);
00057
00058     // Clear any device id so we always use the latest connected device
00059     mainPage->AutoplayNonFileSystemDeviceId = nullptr;
00060
00061     if (args->Verb == "storageDevice")
00062     {
00063         // Launched from Autoplay for content. This will return a single storage folder
00064         // representing that file system device.
00065         mainPage->AutoplayFileSystemDeviceFolder = safe_cast<StorageFolder^>(args->Files->GetAt(0));
00066         mainPage->FileActivationFiles = nullptr;
00067     }
00068     else
00069     {
00070         // Launched to handle a file type.  This will return a list of image files that the user
00071         // requests for this application to handle.
00072         mainPage->FileActivationFiles = args->Files;
00073         mainPage->AutoplayFileSystemDeviceFolder = nullptr;
00074     }
00075
00076     // Select the Autoplay scenario
00077     mainPage->LoadAutoplayScenario();
00078 }
00079
00080 /// <summary>
00081 /// Invoked when the application is activated.
00082 /// This is the entry point for Device Autoplay when a device is attached to the PC.
00083 /// Other activation kinds (such as search and protocol activation) may also be handled here.
00084 /// </summary>
00085 /// <param name="args">Details about the activation request.</param>
00086 void App::OnActivated(Windows::ApplicationModel::Activation::IActivatedEventArgs^ args)
00087 {
00088     if (args->Kind == ActivationKind::Device)
00089     {
00090         Frame^ rootFrame = nullptr;
00091         if (Window::Current->Content == nullptr)
00092         {
00093             rootFrame = ref new Frame();
00094             TypeName pageType = { "SDKSample.MainPage", TypeKind::Custom };
00095             rootFrame->Navigate(pageType);
00096             Window::Current->Content = rootFrame;
00097         }
00098         else
00099         {
00100             rootFrame = safe_cast<Frame^>(Window::Current->Content);
00101         }
00102         Window::Current->Activate();
00103         MainPage^ mainPage = safe_cast<MainPage^>(rootFrame->Content);
00104
00105         // Launched from Autoplay for device, receiving the device information identifier.
00106         DeviceActivatedEventArgs^ deviceArgs = dynamic_cast<DeviceActivatedEventArgs^>(args);
00107         if (deviceArgs != nullptr)
00108         {
00109             mainPage->AutoplayNonFileSystemDeviceId = deviceArgs->DeviceInformationId;
00110
00111             // Clear any saved drive or file so we always use the latest connected device
00112             mainPage->AutoplayFileSystemDeviceFolder = nullptr;
00113             mainPage->FileActivationFiles = nullptr;
00114
00115             // Select the Autoplay scenario
00116             mainPage->LoadAutoplayScenario();
00117         }
00118     }
00119 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DirectXAppSource Member List

This is the complete list of members for DirectXAppSource, including all inherited members.
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
CreateView() | DirectXAppSource | [virtual]
Generated on Sat Nov 23 2024 16:09:11 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application data/C++/App.xaml.cpp Source File

  • Application data

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML ListView and GridView essentials/C++/Scenario2.xaml.cpp Source File

  • XAML ListView and GridView essentials

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 SDKSample::ListViewSimple;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 using namespace Windows::Foundation;
00026 using namespace Windows::Foundation::Collections;
00027 using namespace Windows::Graphics::Display;
00028 using namespace Windows::UI::ViewManagement;
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
00034 using namespace SDKSample::ListViewSampleDataSource;
00035
00036 Scenario2::Scenario2()
00037 {
00038     InitializeComponent();
00039
00040   storeData = ref new StoreData();
00041   GridView2->ItemsSource = storeData->Items;
00042 }
00043
00044 /// <summary>
00045 /// Invoked when this page is about to be displayed in a Frame.
00046 /// </summary>
00047 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00048 /// property is typically used to configure the page.</param>
00049 void Scenario2::OnNavigatedTo(NavigationEventArgs^ e)
00050 {
00051     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00052     // as NotifyUser()
00053     rootPage = MainPage::Current;
00054 }
00055
00056
00057
00058 void SDKSample::ListViewSimple::Scenario2::DoSomething_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00059 {
00060     Button^ b = safe_cast<Button^>(sender);
00061     if (b != nullptr)
00062     {
00063         rootPage->NotifyUser("You clicked the " + b->Name + " button", NotifyType::StatusMessage);
00064     }
00065 }
00066
00067
00068
00069 void SDKSample::ListViewSimple::Scenario2::ItemClickHandler(Platform::Object^ sender, Windows::UI::Xaml::Controls::ItemClickEventArgs^ e)
00070 {
00071      Item^ b = safe_cast<Item^>(e->ClickedItem);
00072     if (b != nullptr)
00073     {
00074     rootPage->NotifyUser("Clicked flavor of " + b->Category + " is: " + b->Title, NotifyType::StatusMessage);
00075     }
00076 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Background Transfer/C++/Constants.h Source File

  • Background Transfer

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"BackgroundTransfer");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041
00042         bool TryGetUri(Platform::String^ uriString, Windows::Foundation::Uri^* uri)
00043         {
00044             // Create a Uri instance and catch exceptions related to invalid input. This method returns 'true'
00045             // if the Uri instance was successfully created and 'false' otherwise.
00046             try
00047             {
00048                 *uri = ref new Windows::Foundation::Uri(StringTrimmer::Trim(uriString));
00049                 return true;
00050             }
00051             catch (Platform::NullReferenceException^ exception)
00052             {
00053                 NotifyUser("Error: URI must not be null or empty.", NotifyType::ErrorMessage);
00054             }
00055             catch (Platform::InvalidArgumentException^ exception)
00056             {
00057                 NotifyUser("Error: Invalid URI", NotifyType::ErrorMessage);
00058             }
00059
00060             return false;
00061         }
00062
00063     private:
00064         static Platform::Array<Scenario>^ scenariosInner;
00065     };
00066
00067     class StringTrimmer
00068     {
00069     public:
00070         static Platform::String^ Trim(Platform::String^ s)
00071         {
00072             const WCHAR* first = s->Begin();
00073             const WCHAR* last = s->End();
00074
00075             while (first != last && iswspace(*first))
00076             {
00077                 ++first;
00078             }
00079
00080             while (first != last && iswspace(last[-1]))
00081             {
00082                 --last;
00083             }
00084
00085             return ref new Platform::String(first, last - first);
00086         }
00087     };
00088 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Raw notifications/C++/SampleBackgroundTask/pch.h Source File

  • Raw notifications
  • SampleBackgroundTask

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
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML FlipView control/C++/Scenario1.xaml.h Source File

  • XAML FlipView control

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 SDKSample
00023 {
00024   namespace FlipViewCPP
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::WebHostHiddenAttribute]
00030     public ref class Scenario1 sealed
00031     {
00032     public:
00033       Scenario1();
00034
00035     protected:
00036       virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037     private:
00038       MainPage^ rootPage;
00039     };
00040   }
00041 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

FPSCounter Member List

This is the complete list of members for FPSCounter, including all inherited members.
__pad0__ | FPSCounter |
DipsToPixelsRoundDown(float value) | FPSCounter | [private]
DipsToPixelsRoundUp(float value) | FPSCounter | [private]
dpi | FPSCounter |
DrawAtlasText(_In_ const AtlasText &atlasText, _In_ D2D1_POINT_2F offset) | FPSCounter | [private]
Initialize() | FPSCounter |
m_cachedDigits | FPSCounter | [private]
m_cachedStaticText | FPSCounter | [private]
m_d2dContext | FPSCounter | [private]
m_dpi | FPSCounter | [private]
m_dwriteFactory | FPSCounter | [private]
m_dxgiDevice | FPSCounter | [private]
m_firstDigitOffset | FPSCounter | [private]
m_position | FPSCounter | [private]
m_staticText | FPSCounter | [private]
m_textAtlasBitmap | FPSCounter | [private]
m_textBrush | FPSCounter | [private]
m_textFormat | FPSCounter | [private]
m_times | FPSCounter | [private]
PixelsToDips(int value) | FPSCounter | [private]
position | FPSCounter |
PositionAtlasText(_In_ Platform::String^text, _In_ D2D1_POINT_2U offsetInAtlas, _Outptr_ IDWriteTextLayout **layout, _Out_ AtlasText *atlasText) | FPSCounter | [private]
Render() | FPSCounter |
text | FPSCounter |
textFormat | FPSCounter |
Generated on Sat Nov 23 2024 16:09:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Geolocation/C++/App.xaml.cpp Source File

  • Geolocation

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: SimpleOrientationSensor/C++/MainPage.xaml.cpp Source File

  • SimpleOrientationSensor

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:44 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX marble maze game/C++/BasicReaderWriter.h Source File

  • DirectX marble maze game

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     Platform::String^ m_locationPath;
00019
00020 internal:
00021     BasicReaderWriter();
00022     BasicReaderWriter(
00023         _In_ Windows::Storage::StorageFolder^ folder
00024         );
00025
00026     Platform::Array<byte>^ ReadData(
00027         _In_ Platform::String^ filename
00028         );
00029
00030     concurrency::task<Platform::Array<byte>^> ReadDataAsync(
00031         _In_ Platform::String^ filename
00032         );
00033
00034     uint32 WriteData(
00035         _In_ Platform::String^ filename,
00036         _In_ const Platform::Array<byte>^ fileData
00037         );
00038
00039     concurrency::task<void> WriteDataAsync(
00040         _In_ Platform::String^ filename,
00041         _In_ const Platform::Array<byte>^ fileData
00042         );
00043 };
Generated on Sat Nov 23 2024 16:08:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::NetworkInformationApi::sealed Member List

This is the complete list of members for SDKSample::NetworkInformationApi::sealed, including all inherited members.
connectionProfileInfo | SDKSample::NetworkInformationApi::sealed | [private]
ConnectionProfileList() | SDKSample::NetworkInformationApi::sealed |
ConnectionProfileList_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::NetworkInformationApi::sealed | [private]
cookie | SDKSample::NetworkInformationApi::sealed | [private]
DisplayLanIdentifierData(LanIdentifier^lanIdentifier) | SDKSample::NetworkInformationApi::sealed | [private]
GetConnectionCostInfo(Windows::Networking::Connectivity::ConnectionCost^connectionCost) | SDKSample::NetworkInformationApi::sealed | [private]
GetConnectionCostInfo(Windows::Networking::Connectivity::ConnectionCost^connectionCost) | SDKSample::NetworkInformationApi::sealed | [private]
GetConnectionCostInfo(Windows::Networking::Connectivity::ConnectionCost^connectionCost) | SDKSample::NetworkInformationApi::sealed | [private]
GetConnectionProfile(Windows::Networking::Connectivity::ConnectionProfile^connectionProfile) | SDKSample::NetworkInformationApi::sealed | [private]
GetConnectionProfile(Windows::Networking::Connectivity::ConnectionProfile^connectionProfile) | SDKSample::NetworkInformationApi::sealed | [private]
GetConnectionProfile(Windows::Networking::Connectivity::ConnectionProfile^connectionProfile) | SDKSample::NetworkInformationApi::sealed | [private]
GetCostBasedSuggestions(Windows::Networking::Connectivity::ConnectionCost^connectionCost) | SDKSample::NetworkInformationApi::sealed | [private]
GetCostBasedSuggestions(Windows::Networking::Connectivity::ConnectionCost^connectionCost) | SDKSample::NetworkInformationApi::sealed | [private]
GetCostBasedSuggestions(Windows::Networking::Connectivity::ConnectionCost^connectionCost) | SDKSample::NetworkInformationApi::sealed | [private]
GetDataPlanStatusInfo(Windows::Networking::Connectivity::DataPlanStatus^dataPlan) | SDKSample::NetworkInformationApi::sealed | [private]
GetDataPlanStatusInfo(Windows::Networking::Connectivity::DataPlanStatus^dataPlan) | SDKSample::NetworkInformationApi::sealed | [private]
GetDataPlanStatusInfo(Windows::Networking::Connectivity::DataPlanStatus^dataPlan) | SDKSample::NetworkInformationApi::sealed | [private]
GetNetworkSecuritySettingsInfo(Windows::Networking::Connectivity::NetworkSecuritySettings^netSecuritySettings) | SDKSample::NetworkInformationApi::sealed | [private]
GetNetworkSecuritySettingsInfo(Windows::Networking::Connectivity::NetworkSecuritySettings^netSecuritySettings) | SDKSample::NetworkInformationApi::sealed | [private]
GetNetworkSecuritySettingsInfo(Windows::Networking::Connectivity::NetworkSecuritySettings^netSecuritySettings) | SDKSample::NetworkInformationApi::sealed | [private]
InternetConnectionProfile() | SDKSample::NetworkInformationApi::sealed |
InternetConnectionProfile_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::NetworkInformationApi::sealed | [private]
internetProfileInfo | SDKSample::NetworkInformationApi::sealed | [private]
LanId() | SDKSample::NetworkInformationApi::sealed |
LanId_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::NetworkInformationApi::sealed | [private]
lanIdInfo | SDKSample::NetworkInformationApi::sealed | [private]
networkInfo | SDKSample::NetworkInformationApi::sealed | [private]
networkStatusCallback | SDKSample::NetworkInformationApi::sealed | [private]
NetworkStatusChange() | SDKSample::NetworkInformationApi::sealed |
NetworkStatusChange_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::NetworkInformationApi::sealed | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::NetworkInformationApi::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::NetworkInformationApi::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::NetworkInformationApi::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::NetworkInformationApi::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::NetworkInformationApi::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::NetworkInformationApi::sealed | [protected, virtual]
OnNetworkStatusChange(Object^sender) | SDKSample::NetworkInformationApi::sealed | [private]
ProfileLocalUsageData() | SDKSample::NetworkInformationApi::sealed |
ProfileLocalUsageData_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::NetworkInformationApi::sealed | [private]
registeredNetworkStatusNotif | SDKSample::NetworkInformationApi::sealed | [private]
rootPage | SDKSample::NetworkInformationApi::sealed | [private]
UnRegisterForNetworkStatusChangeNotif() | SDKSample::NetworkInformationApi::sealed | [private]
Generated on Sat Nov 23 2024 16:09:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKTemplateCS::MainPage Member List

This is the complete list of members for SDKTemplateCS::MainPage, including all inherited members.
__pad0__ | Element |
_extensionManager | SDKTemplateCS::MainPage | [private]
_inputFrame | SDKTemplateCS::MainPage | [private]
_outputFrame | SDKTemplateCS::MainPage | [private]
_rootNamespace | SDKTemplateCS::MainPage | [private]
_scenariosFrame | SDKTemplateCS::MainPage | [private]
AcceptChildNode(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^childXmlNode) override | Page | [virtual]
AddChild(_In_ Element^element) | Element |
AddSibling(_In_ Element^element) | Element |
BindResource(_In_ Element^rootElement) | Element | [virtual]
CheckResolutionAndViewState() | SDKTemplateCS::MainPage | [inline, private]
Create(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^xmlNode) | Element | [static]
DisplayProperties_LogicalDpiChanged(object sender) | SDKTemplateCS::MainPage | [inline, private]
DoNavigation(Type pageType, Frame frame) | SDKTemplateCS::MainPage | [inline]
Draw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
ExtensionManager | SDKTemplateCS::MainPage |
FEATURE_NAME | SDKTemplateCS::MainPage |
Footer_Click(object sender, RoutedEventArgs e) | SDKTemplateCS::MainPage | [inline, private]
GetFirstChild() | Element | [inline]
GetName() | Element | [inline]
GetNextSibling() | Element | [inline]
GetOpacity() | Element | [inline, virtual]
GetParent() | Element | [inline]
GetSize() | Element | [inline]
Initialize(_In_ Document^document, _In_ Windows::Data::Xml::Dom::XmlElement^xmlElement) | Element | [virtual]
InputFrame | SDKTemplateCS::MainPage |
InputFrameLoaded | SDKTemplateCS::MainPage |
MainPage() | SDKTemplateCS::MainPage | [inline]
MainPage_Loaded(object sender, RoutedEventArgs e) | SDKTemplateCS::MainPage | [inline, private]
MainPage_SizeChanged(Object sender, Windows.UI.Core.WindowSizeChangedEventArgs args) | SDKTemplateCS::MainPage | [inline, private]
Measure(_In_ Document^document, D2D1_SIZE_F const &parentSize, _Out_ D2D1_RECT_F *bounds) | Element | [virtual]
NotifyUser(string strMessage, NotifyType type) | SDKTemplateCS::MainPage | [inline]
OutputFrame | SDKTemplateCS::MainPage |
OutputFrameLoaded | SDKTemplateCS::MainPage |
PickSingleFileAndSet(string[] fileTypeFilter, params MediaElement[] mediaElements) | SDKTemplateCS::MainPage | [inline]
PrepareToDraw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
ReleaseParent() | Element | [virtual]
RootNamespace | SDKTemplateCS::MainPage |
ScenariosFrame | SDKTemplateCS::MainPage |
SetFeatureName(string str) | SDKTemplateCS::MainPage | [inline, private]
VideoOnError(Object obj, ExceptionRoutedEventArgs args) | SDKTemplateCS::MainPage | [inline]
Generated on Sat Nov 23 2024 16:09:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: OrientationSensor/C++/MainPage.xaml.h Source File

  • OrientationSensor

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:46 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XInput audio controller playback/C++/BasicTimer.cpp Source File

  • XInput audio controller playback

BasicTimer.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 "BasicTimer.h"
00010
00011 BasicTimer::BasicTimer()
00012 {
00013     if (!QueryPerformanceFrequency(&m_frequency))
00014     {
00015         throw ref new Platform::FailureException();
00016     }
00017     Reset();
00018 }
00019
00020 void BasicTimer::Reset()
00021 {
00022     Update();
00023     m_startTime = m_currentTime;
00024     m_total = 0.0f;
00025     m_delta = 1.0f / 60.0f;
00026 }
00027
00028 void BasicTimer::Update()
00029 {
00030     if (!QueryPerformanceCounter(&m_currentTime))
00031     {
00032         throw ref new Platform::FailureException();
00033     }
00034
00035     m_total = static_cast<float>(
00036         static_cast<double>(m_currentTime.QuadPart-m_startTime.QuadPart) /
00037         static_cast<double>(m_frequency.QuadPart)
00038         );
00039
00040     if (m_lastTime.QuadPart == m_startTime.QuadPart)
00041     {
00042         // If the timer was just reset, report a time delta equivalent to 60Hz frame time.
00043         m_delta = 1.0f / 60.0f;
00044     }
00045     else
00046     {
00047         m_delta = static_cast<float>(
00048             static_cast<double>(m_currentTime.QuadPart-m_lastTime.QuadPart) /
00049             static_cast<double>(m_frequency.QuadPart)
00050             );
00051     }
00052
00053     m_lastTime = m_currentTime;
00054 }
00055
00056 float BasicTimer::Total::get()
00057 {
00058     return m_total;
00059 }
00060
00061 float BasicTimer::Delta::get()
00062 {
00063     return m_delta;
00064 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File access/C++/Scenario2.xaml.h Source File

  • File access

Scenario2.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.xaml.h
00013 // Declaration of the Scenario2 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario2.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace FileAccess
00025     {
00026         /// <summary>
00027         /// An empty page that can be used on its own or navigated to within a Frame.
00028         /// </summary>
00029         public ref class Scenario2 sealed
00030         {
00031         public:
00032             Scenario2();
00033
00034         private:
00035             MainPage^ rootPage;
00036
00037             void WriteTextButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038             void ReadTextButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039         };
00040     }
00041 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/GameObject.h Source File

  • XAML DirectX 3D shooting game

GameObject.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 // GameObject:
00011 // This is the class representing a generic object in the 3D world of the game.  There are
00012 // specific sub-classes that have specific geometric shapes.  This class contains all the
00013 // properties of objects that are common.
00014 //
00015 // During the game physics calculations the IsTouching method will be called to determine
00016 // the object's proximity to a point.  It is expected the sub-classes will replace this method.
00017 // The Render method will be called during rendering to include the object in the generation of
00018 // the scene.
00019
00020 #include "MeshObject.h"
00021 #include "SoundEffect.h"
00022 #include "Animate.h"
00023 #include "Material.h"
00024
00025 ref class GameObject
00026 {
00027 internal:
00028     GameObject();
00029
00030     // Expect the IsTouching method to be overloaded by subclasses.
00031     virtual bool IsTouching(
00032         DirectX::XMFLOAT3 /* point */,
00033         float /* radius */,
00034         _Out_ DirectX::XMFLOAT3 *contact,
00035         _Out_ DirectX::XMFLOAT3 *normal
00036         )
00037     {
00038         *contact = DirectX::XMFLOAT3(0.0f, 0.0f, 0.0f);
00039         *normal = DirectX::XMFLOAT3(0.0f, 0.0f, 1.0f);
00040         return false;
00041     };
00042
00043     void Render(
00044         _In_ ID3D11DeviceContext *context,
00045         _In_ ID3D11Buffer *primitiveConstantBuffer
00046         );
00047
00048     void Active(bool active);
00049     bool Active();
00050     void Target(bool target);
00051     bool Target();
00052     void Hit(bool hit);
00053     bool Hit();
00054     void OnGround(bool ground);
00055     bool OnGround();
00056     void TargetId(int targetId);
00057     int  TargetId();
00058     void HitTime(float t);
00059     float HitTime();
00060
00061     void     AnimatePosition(_In_opt_ Animate^ animate);
00062     Animate^ AnimatePosition();
00063
00064     void         HitSound(_In_ SoundEffect^ hitSound);
00065     SoundEffect^ HitSound();
00066
00067     void PlaySound(float impactSpeed, DirectX::XMFLOAT3 eyePoint);
00068
00069     void Mesh(_In_ MeshObject^ mesh);
00070
00071     void NormalMaterial(_In_ Material^ material);
00072     Material^ NormalMaterial();
00073     void HitMaterial(_In_ Material^ material);
00074     Material^ HitMaterial();
00075
00076     void Position(DirectX::XMFLOAT3 position);
00077     void Position(DirectX::XMVECTOR position);
00078     void Velocity(DirectX::XMFLOAT3 velocity);
00079     void Velocity(DirectX::XMVECTOR velocity);
00080     DirectX::XMMATRIX ModelMatrix();
00081     DirectX::XMFLOAT3 Position();
00082     DirectX::XMVECTOR VectorPosition();
00083     DirectX::XMVECTOR VectorVelocity();
00084     DirectX::XMFLOAT3 Velocity();
00085
00086 protected private:
00087     virtual void UpdatePosition() {};
00088     // Object Data
00089     bool                m_active;
00090     bool                m_target;
00091     int                 m_targetId;
00092     bool                m_hit;
00093     bool                m_ground;
00094
00095     DirectX::XMFLOAT3   m_position;
00096     DirectX::XMFLOAT3   m_velocity;
00097     DirectX::XMFLOAT4X4 m_modelMatrix;
00098
00099     Material^           m_normalMaterial;
00100     Material^           m_hitMaterial;
00101
00102     DirectX::XMFLOAT3   m_defaultXAxis;
00103     DirectX::XMFLOAT3   m_defaultYAxis;
00104     DirectX::XMFLOAT3   m_defaultZAxis;
00105
00106     float               m_hitTime;
00107
00108     Animate^            m_animatePosition;
00109     MeshObject^         m_mesh;
00110
00111     SoundEffect^        m_hitSound;
00112 };
00113
00114
00115 __forceinline void GameObject::Active(bool active)
00116 {
00117     m_active = active;
00118 }
00119
00120 __forceinline bool GameObject::Active()
00121 {
00122     return m_active;
00123 }
00124
00125 __forceinline void GameObject::Target(bool target)
00126 {
00127     m_target = target;
00128 }
00129
00130 __forceinline bool GameObject::Target()
00131 {
00132     return m_target;
00133 }
00134
00135 __forceinline void GameObject::Hit(bool hit)
00136 {
00137     m_hit = hit;
00138 }
00139
00140 __forceinline bool GameObject::Hit()
00141 {
00142     return m_hit;
00143 }
00144
00145 __forceinline void GameObject::OnGround(bool ground)
00146 {
00147     m_ground = ground;
00148 }
00149
00150 __forceinline bool GameObject::OnGround()
00151 {
00152     return m_ground;
00153 }
00154
00155 __forceinline void GameObject::TargetId(int targetId)
00156 {
00157     m_targetId = targetId;
00158 }
00159
00160 __forceinline int GameObject::TargetId()
00161 {
00162     return m_targetId;
00163 }
00164
00165 __forceinline void GameObject::HitTime(float t)
00166 {
00167     m_hitTime = t;
00168 }
00169
00170 __forceinline float GameObject::HitTime()
00171 {
00172     return m_hitTime;
00173 }
00174
00175 __forceinline void GameObject::Position(DirectX::XMFLOAT3 position)
00176 {
00177     m_position = position;
00178     // Update any internal states that are dependent on the position.
00179     // UpdatePosition is a virtual function that is specific to the derived class.
00180     UpdatePosition();
00181 }
00182
00183 __forceinline void GameObject::Position(DirectX::XMVECTOR position)
00184 {
00185     XMStoreFloat3(&m_position, position);
00186     // Update any internal states that are dependent on the position.
00187     // UpdatePosition is a virtual function that is specific to the derived class.
00188     UpdatePosition();
00189 }
00190
00191 __forceinline DirectX::XMFLOAT3 GameObject::Position()
00192 {
00193     return m_position;
00194 }
00195
00196 __forceinline DirectX::XMVECTOR GameObject::VectorPosition()
00197 {
00198     return DirectX::XMLoadFloat3(&m_position);
00199 }
00200
00201 __forceinline void GameObject::Velocity(DirectX::XMFLOAT3 velocity)
00202 {
00203     m_velocity = velocity;
00204 }
00205
00206 __forceinline void GameObject::Velocity(DirectX::XMVECTOR velocity)
00207 {
00208     XMStoreFloat3(&m_velocity, velocity);
00209 }
00210
00211 __forceinline DirectX::XMFLOAT3 GameObject::Velocity()
00212 {
00213     return m_velocity;
00214 }
00215
00216 __forceinline DirectX::XMVECTOR GameObject::VectorVelocity()
00217 {
00218     return DirectX::XMLoadFloat3(&m_velocity);
00219 }
00220
00221 __forceinline void GameObject::AnimatePosition(_In_opt_ Animate^ animate)
00222 {
00223     m_animatePosition = animate;
00224 }
00225
00226 __forceinline Animate^ GameObject::AnimatePosition()
00227 {
00228     return m_animatePosition;
00229 }
00230
00231 __forceinline void GameObject::NormalMaterial(_In_ Material^ material)
00232 {
00233     m_normalMaterial = material;
00234 }
00235
00236 __forceinline Material^ GameObject::NormalMaterial()
00237 {
00238     return m_normalMaterial;
00239 }
00240
00241 __forceinline void GameObject::HitMaterial(_In_ Material^ material)
00242 {
00243     m_hitMaterial = material;
00244 }
00245
00246 __forceinline Material^ GameObject::HitMaterial()
00247 {
00248     return m_hitMaterial;
00249 }
00250
00251 __forceinline void GameObject::Mesh(_In_ MeshObject^ mesh)
00252 {
00253     m_mesh = mesh;
00254 }
00255
00256 __forceinline void GameObject::HitSound(_In_ SoundEffect^ hitSound)
00257 {
00258     m_hitSound = hitSound;
00259 }
00260
00261 __forceinline SoundEffect^ GameObject::HitSound()
00262 {
00263     return m_hitSound;
00264 }
00265
00266 __forceinline DirectX::XMMATRIX GameObject::ModelMatrix()
00267 {
00268     return DirectX::XMLoadFloat4x4(&m_modelMatrix);
00269 }
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Calendar details and math/C++/DisplayCalendarData.xaml.h Source File

  • Calendar details and math

DisplayCalendarData.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 // DisplayCalendarData.xaml.h
00013 // Declaration of the DisplayCalendarData class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "DisplayCalendarData.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace CalendarSample
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 DisplayCalendarData sealed
00031         {
00032         public:
00033             DisplayCalendarData();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void Display_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:07:58 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Background task/C++/Tasks/SampleBackgroundTask.cpp Source File

  • Background task
  • Tasks

SampleBackgroundTask.cpp

Go to the documentation of this file.
00001 ﻿// SampleBackgroundTask.cpp
00002 #include "pch.h"
00003 #include "SampleBackgroundTask.h"
00004
00005 using namespace Tasks;
00006 using namespace Windows::Foundation;
00007 using namespace Windows::Storage;
00008
00009 SampleBackgroundTask::SampleBackgroundTask() :
00010     CancelRequested(false), Deferral(nullptr), PeriodicTimer(nullptr), Progress(0), TaskInstance(nullptr)
00011 {
00012 }
00013
00014 SampleBackgroundTask::~SampleBackgroundTask()
00015 {
00016 }
00017
00018 void SampleBackgroundTask::Run(IBackgroundTaskInstance^ taskInstance)
00019 {
00020     //
00021     // Associate a cancellation handler with the background task.
00022     //
00023     taskInstance->Canceled += ref new BackgroundTaskCanceledEventHandler(this, &SampleBackgroundTask::OnCanceled);
00024
00025     //
00026     // Get the deferral object from the task instance, and take a reference to the taskInstance.
00027     //
00028     Deferral = taskInstance->GetDeferral();
00029     TaskInstance = taskInstance;
00030
00031     auto timerDelegate = [this](ThreadPoolTimer^ timer)
00032     {
00033         if ((CancelRequested == false) &&
00034             (Progress < 100))
00035             {
00036                 Progress += 10;
00037                 TaskInstance->Progress = Progress;
00038             }
00039             else
00040             {
00041                 PeriodicTimer->Cancel();
00042
00043                 //
00044                 // Write to LocalSettings to indicate that this background task ran.
00045                 //
00046                 auto settings = ApplicationData::Current->LocalSettings;
00047                 auto key = TaskInstance->Task->Name;
00048                 settings->Values->Insert(key, (Progress < 100) ? "Canceled" : "Completed");
00049
00050                 //
00051                 // Indicate that the background task has completed.
00052                 //
00053                 Deferral->Complete();
00054             }
00055     };
00056
00057     TimeSpan period;
00058     period.Duration = 500 * 10000; // 500 milliseconds
00059     PeriodicTimer = ThreadPoolTimer::CreatePeriodicTimer(ref new TimerElapsedHandler(timerDelegate), period);
00060 }
00061
00062 //
00063 // Handles background task cancellation.
00064 //
00065 void SampleBackgroundTask::OnCanceled(IBackgroundTaskInstance^ taskInstance, BackgroundTaskCancellationReason reason)
00066 {
00067     //
00068     // Indicate that the background task is canceled.
00069     //
00070     CancelRequested = true;
00071 }
Generated on Sat Nov 23 2024 16:07:58 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Touch keyboard/C++/pch.h Source File

  • Input Touch keyboard

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

BasicSprites::TextureMapElement Member List

This is the complete list of members for BasicSprites::TextureMapElement, including all inherited members.
size | BasicSprites::TextureMapElement
srv | BasicSprites::TextureMapElement
Generated on Sat Nov 23 2024 16:09:36 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/MoveLookController.h Source File

  • DirectX 3D shooting game

MoveLookController.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 // MoveLookController:
00011 // This is the class that handles input events and turns it into player
00012 // intent.  It aggregates, mouse, keyboard, touch and Xbox controller input into
00013 // a unified single controller.
00014 // The controller has three modes of operation:
00015 //     None - the controller is not active and all input is ignored.
00016 //     WaitForInput - the controller is waiting for the player to acknowledge
00017 //         a message from the app.  Only a left mouse click or touch event
00018 //         in the rectangle specified in the WaitForPress method or the
00019 //         'Start' button has been pressed on the Xbox controller will
00020 //         result in IsPressComplete returning true.
00021 //     Active - the controller is in active game play mode.
00022 //
00023 // This class registers input handlers directly with the CoreWindow object
00024 // in the Initialize method.  It installs input handlers for the following events:
00025 //     PointerPressed
00026 //     PointerMoved
00027 //     PointerReleased
00028 //     PointerExited
00029 //     KeyDown
00030 //     KeyUp
00031 //     MouseMoved
00032 //
00033 // During 'Active' mode, the controller will put the mouse into relative mouse
00034 // mode by turning off the pointer cursor.  In this mode the controller separates
00035 // mouse movement from pointer movement and uses the relative mouse movements to
00036 // update the controller for the Look Control.
00037 //
00038 // The touch portion of the MoveLookController divides the window area of the app
00039 // into three distinct regions:
00040 //     MoveRect - the rectangle of the screen where touch input is converted into
00041 //         a virtual joystick where the vertical motion will be translated into
00042 //         forward/backward position motion and horizontal motion will be translated
00043 //         into left/right position motion.
00044 //     FireRect - the rectangle of the screen where touch input will be converted
00045 //         into a fire button.  A touch sequence of PointerPressed will result in
00046 //         IsFiring method to return true in AutoFire mode, otherwise a PointPressed
00047 //         followed by a PointerReleased event in the FireRect will result in the
00048 //         IsFiring method returning true once.
00049 //     Outside MoveRect & FireRect - this area of the screen controls the Look control
00050 //         and updates the LookDirection.
00051 //
00052 // The following controls are mapped from the Xbox controller using XInput:
00053 //     XINPUT_GAMEPAD_START - is mapped to IsPressComplete in the WaitForInput state and
00054 //         IsPauseRequested in the Active state.
00055 //     Left Thumb stick - is mapped to the move control in Active mode
00056 //     Right Thumb stick - is mapped to the look control in Active mode
00057 //     Right Trigger - is mapped to IsFiring in Active mode or "Fire" button.
00058 //
00059 // The keyboard/mouse are used as a pair to provide a typical PC gaming input model in Active
00060 // mode:
00061 //     Mouse - is mapped to the look control.  Left mouse is mapped to IsFiring or 'Fire' button
00062 //     W key - is mapped to the 'forward' motion of the move control
00063 //     S key - is mapped to the 'back' motion of the move control
00064 //     A key - is mapped to the 'left' motion of the move control
00065 //     D key - is mapped to the 'right' motion of the move control
00066 //     <space> key - is mapped to the 'up' motion of the move control
00067 //     X key - is mapped to the 'down' motion of the move control
00068 //     P key - is mapped to IsPauseRequested
00069 //
00070 // The MoveLookController collects input from each of the input events.  On the Update method
00071 // the Xbox Controller is polled for it's current state and all the inputs are coalesced and
00072 // merged to generate a velocity vector and update the Pitch and Yaw values.
00073
00074 // Uncomment the next line to print debug tracing information.
00075 // #define MOVELOOKCONTROLLER_TRACE 1
00076
00077 enum class MoveLookControllerState
00078 {
00079     None,
00080     WaitForInput,
00081     Active,
00082 };
00083
00084 ref class MoveLookController
00085 {
00086 internal:
00087     MoveLookController();
00088
00089     void Initialize(
00090         _In_ Windows::UI::Core::CoreWindow^ window
00091         );
00092     void SetMoveRect(
00093         _In_ DirectX::XMFLOAT2 upperLeft,
00094         _In_ DirectX::XMFLOAT2 lowerRight
00095         );
00096     void SetFireRect(
00097         _In_ DirectX::XMFLOAT2 upperLeft,
00098         _In_ DirectX::XMFLOAT2 lowerRight
00099         );
00100     void WaitForPress(
00101         _In_ DirectX::XMFLOAT2 UpperLeft,
00102         _In_ DirectX::XMFLOAT2 LowerRight
00103         );
00104     void WaitForPress();
00105
00106     void Update();
00107     bool IsFiring();
00108     bool IsPressComplete();
00109     bool IsPauseRequested();
00110
00111     DirectX::XMFLOAT3 Velocity();
00112     DirectX::XMFLOAT3 LookDirection();
00113     float Pitch();
00114     void  Pitch(_In_ float pitch);
00115     float Yaw();
00116     void  Yaw(_In_ float yaw);
00117     bool  Active();
00118     void  Active(_In_ bool active);
00119
00120     bool AutoFire();
00121     void AutoFire(_In_ bool AutoFire);
00122
00123 protected:
00124     void OnPointerPressed(
00125         _In_ Windows::UI::Core::CoreWindow^ sender,
00126         _In_ Windows::UI::Core::PointerEventArgs^ args
00127         );
00128     void OnPointerMoved(
00129         _In_ Windows::UI::Core::CoreWindow^ sender,
00130         _In_ Windows::UI::Core::PointerEventArgs^ args
00131         );
00132     void OnPointerReleased(
00133         _In_ Windows::UI::Core::CoreWindow^ sender,
00134         _In_ Windows::UI::Core::PointerEventArgs^ args
00135         );
00136     void OnPointerExited(
00137         _In_ Windows::UI::Core::CoreWindow^ sender,
00138         _In_ Windows::UI::Core::PointerEventArgs^ args
00139         );
00140     void OnKeyDown(
00141         _In_ Windows::UI::Core::CoreWindow^ sender,
00142         _In_ Windows::UI::Core::KeyEventArgs^ args
00143         );
00144     void OnKeyUp(
00145         _In_ Windows::UI::Core::CoreWindow^ sender,
00146         _In_ Windows::UI::Core::KeyEventArgs^ args
00147         );
00148
00149     void OnMouseMoved(
00150         _In_ Windows::Devices::Input::MouseDevice^ mouseDevice,
00151         _In_ Windows::Devices::Input::MouseEventArgs^ args
00152         );
00153
00154 #ifdef MOVELOOKCONTROLLER_TRACE
00155     void DebugTrace(const wchar_t *format, ...);
00156 #endif
00157
00158 private:
00159     // Properties of the controller object.
00160     MoveLookControllerState     m_state;
00161     DirectX::XMFLOAT3           m_velocity;             // How far we move in this frame.
00162     float                       m_pitch;
00163     float                       m_yaw;                  // Orientation euler angles in radians.
00164
00165     // Properties of the Move control.
00166     DirectX::XMFLOAT2           m_moveUpperLeft;        // Bounding box where this control will activate.
00167     DirectX::XMFLOAT2           m_moveLowerRight;
00168     bool                        m_moveInUse;            // The move control is in use.
00169     uint32                      m_movePointerID;        // Id of the pointer in this control.
00170     DirectX::XMFLOAT2           m_moveFirstDown;        // Point where initial contact occurred.
00171     DirectX::XMFLOAT2           m_movePointerPosition;  // Point where the move pointer is currently located.
00172     DirectX::XMFLOAT3           m_moveCommand;          // The net command from the move control.
00173
00174     // Properties of the Look control.
00175     bool                        m_lookInUse;            // The look control is in use.
00176     uint32                      m_lookPointerID;        // Id of the pointer in this control.
00177     DirectX::XMFLOAT2           m_lookLastPoint;        // Last point (from last frame).
00178     DirectX::XMFLOAT2           m_lookLastDelta;        // The delta used for smoothing between frames.
00179
00180     // Properties of the Fire control.
00181     bool                        m_autoFire;
00182     bool                        m_firePressed;
00183     DirectX::XMFLOAT2           m_fireUpperLeft;        // Bounding box where this control will activate.
00184     DirectX::XMFLOAT2           m_fireLowerRight;
00185     bool                        m_fireInUse;            // The fire control in in use.
00186     UINT32                      m_firePointerID;        // Id of the pointer in this control.
00187     DirectX::XMFLOAT2           m_fireLastPoint;        // Last fire position.
00188
00189     // Properties of the Mouse control.  This is a combination of Look and Fire.
00190     bool                        m_mouseInUse;
00191     uint32                      m_mousePointerID;
00192     DirectX::XMFLOAT2           m_mouseLastPoint;
00193     bool                        m_mouseLeftInUse;
00194     bool                        m_mouseRightInUse;
00195
00196     bool                        m_buttonInUse;
00197     uint32                      m_buttonPointerID;
00198     DirectX::XMFLOAT2           m_buttonUpperLeft;
00199     DirectX::XMFLOAT2           m_buttonLowerRight;
00200     bool                        m_buttonPressed;
00201     bool                        m_pausePressed;
00202
00203     // Xbox Input related members.
00204     bool                        m_isControllerConnected;  // Is the Xbox controller connected.
00205     XINPUT_CAPABILITIES         m_xinputCaps;             // Capabilites of the controller.
00206     XINPUT_STATE                m_xinputState;            // The current state of the controller.
00207     bool                        m_xinputStartButtonInUse;
00208     bool                        m_xinputTriggerInUse;
00209
00210     // Input states for Keyboard.
00211     bool                        m_forward;
00212     bool                        m_back;                    // States for movement.
00213     bool                        m_left;
00214     bool                        m_right;
00215     bool                        m_up;
00216     bool                        m_down;
00217     bool                        m_pause;
00218
00219 private:
00220     void     ResetState();
00221     void     UpdateGameController();
00222 };
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::ToastContent::ToastImageAndText03 Member List

This is the complete list of members for NotificationsExtensions::ToastContent::ToastImageAndText03, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
Audio | NotificationsExtensions::ToastContent::ToastNotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
CreateNotification() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline]
Duration | NotificationsExtensions::ToastContent::ToastNotificationBase |
GetContent() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline, virtual]
GetContent() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline, virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Image | NotificationsExtensions::ToastContent::ToastImageAndText03 |
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
Launch | NotificationsExtensions::ToastContent::ToastNotificationBase |
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextBody | NotificationsExtensions::ToastContent::ToastImageAndText03 |
TextFields | NotificationsExtensions::NotificationBase |
TextHeadingWrap | NotificationsExtensions::ToastContent::ToastImageAndText03 |
ToastImageAndText03() | NotificationsExtensions::ToastContent::ToastImageAndText03 | [inline]
ToastImageAndText03() | NotificationsExtensions::ToastContent::ToastImageAndText03 | [inline]
ToastNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline]
ToastNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Touch keyboard/C++/Constants.h Source File

  • Input Touch keyboard

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"Touch Keyboard");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044
00045
00046 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application resources and localization/C++/Scenario7.xaml.cpp Source File

  • Application resources and localization

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 SDKSample::ApplicationResources;
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 }
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 Scenario7::OnNavigatedTo(NavigationEventArgs^ e)
00042 {
00043     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00044     // as NotifyUser()
00045     rootPage = MainPage::Current;
00046 }
00047
00048 void Scenario7::OnNavigatedFrom(NavigationEventArgs^ e)
00049 {
00050     if (eventToken.Value != 0)
00051     {
00052         ResourceManager::Current->DefaultContext->QualifierValues->MapChanged -= eventToken;
00053         eventToken.Value = 0;
00054     }
00055 }
00056
00057 void Scenario7::ContextChanged(IObservableMap<String^, String^>^ sender, IMapChangedEventArgs<String^>^ eventArg)
00058 {
00059   this->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal,
00060     ref new Windows::UI::Core::DispatchedHandler([this]()
00061     {
00062       this->Scenario7TextBlock->Text = ResourceManager::Current->MainResourceMap->GetValue("Resources/string1")->ValueAsString;
00063     }));
00064 }
00065 void Scenario7::Scenario7Button_Show_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00066 {
00067     if (eventToken.Value == 0)
00068     {
00069         Scenario7TextBlock->Text = ResourceManager::Current->MainResourceMap->GetValue("Resources/string1")->ValueAsString;
00070         eventToken = ResourceManager::Current->DefaultContext->QualifierValues->MapChanged += ref new MapChangedEventHandler<String^, String^>(this, &Scenario7::ContextChanged);
00071     }
00072 }
00073
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite hit testing/C++/DirectXBase.cpp Source File

  • DirectWrite hit testing

DirectXBase.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 "DirectXBase.h"
00010
00011 using namespace Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::Graphics::Display;
00015 using namespace D2D1;
00016
00017 // Constructor.
00018 DirectXBase::DirectXBase() :
00019     m_windowSizeChangeInProgress(false),
00020     m_dpi(-1.0f)
00021 {
00022 }
00023
00024 // Initialize the DirectX resources required to run.
00025 void DirectXBase::Initialize(CoreWindow^ window, float dpi)
00026 {
00027     m_window = window;
00028
00029     CreateDeviceIndependentResources();
00030     CreateDeviceResources();
00031     SetDpi(dpi);
00032 }
00033
00034 // Recreate all device resources and set them back to the current state.
00035 void DirectXBase::HandleDeviceLost()
00036 {
00037     // Reset these member variables to ensure that SetDpi recreates all resources.
00038     float dpi = m_dpi;
00039     m_dpi = -1.0f;
00040     m_windowBounds.Width = 0;
00041     m_windowBounds.Height = 0;
00042     m_swapChain = nullptr;
00043
00044     CreateDeviceResources();
00045     SetDpi(dpi);
00046 }
00047
00048 // These are the resources required independent of the device.
00049 void DirectXBase::CreateDeviceIndependentResources()
00050 {
00051     D2D1_FACTORY_OPTIONS options;
00052     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00053
00054 #if defined(_DEBUG)
00055     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00056     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00057 #endif
00058
00059     DX::ThrowIfFailed(
00060         D2D1CreateFactory(
00061             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00062             __uuidof(ID2D1Factory1),
00063             &options,
00064             &m_d2dFactory
00065             )
00066         );
00067
00068     DX::ThrowIfFailed(
00069         DWriteCreateFactory(
00070             DWRITE_FACTORY_TYPE_SHARED,
00071             __uuidof(IDWriteFactory),
00072             &m_dwriteFactory
00073             )
00074         );
00075
00076     DX::ThrowIfFailed(
00077         CoCreateInstance(
00078             CLSID_WICImagingFactory,
00079             nullptr,
00080             CLSCTX_INPROC_SERVER,
00081             IID_PPV_ARGS(&m_wicFactory)
00082             )
00083         );
00084 }
00085
00086 // These are the resources that depend on the device.
00087 void DirectXBase::CreateDeviceResources()
00088 {
00089     // This flag adds support for surfaces with a different color channel ordering
00090     // than the API default. It is required for compatibility with Direct2D.
00091     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00092     ComPtr<IDXGIDevice> dxgiDevice;
00093
00094 #if defined(_DEBUG)
00095     // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00096     creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00097 #endif
00098
00099     // This array defines the set of DirectX hardware feature levels this app will support.
00100     // Note the ordering should be preserved.
00101     // Don't forget to declare your application's minimum required feature level in its
00102     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00103     D3D_FEATURE_LEVEL featureLevels[] =
00104     {
00105         D3D_FEATURE_LEVEL_11_1,
00106         D3D_FEATURE_LEVEL_11_0,
00107         D3D_FEATURE_LEVEL_10_1,
00108         D3D_FEATURE_LEVEL_10_0,
00109         D3D_FEATURE_LEVEL_9_3,
00110         D3D_FEATURE_LEVEL_9_2,
00111         D3D_FEATURE_LEVEL_9_1
00112     };
00113
00114     // Create the Direct3D 11 API device object and a corresponding context.
00115     ComPtr<ID3D11Device> device;
00116     ComPtr<ID3D11DeviceContext> context;
00117     DX::ThrowIfFailed(
00118         D3D11CreateDevice(
00119             nullptr,                    // Specify nullptr to use the default adapter.
00120             D3D_DRIVER_TYPE_HARDWARE,
00121             0,
00122             creationFlags,              // Set debug and Direct2D compatibility flags.
00123             featureLevels,              // List of feature levels this app can support.
00124             ARRAYSIZE(featureLevels),
00125             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Metro style apps.
00126             &device,                    // Returns the Direct3D device created.
00127             &m_featureLevel,            // Returns feature level of device created.
00128             &context                    // Returns the device immediate context.
00129             )
00130         );
00131
00132     // Get the Direct3D 11.1 API device and context interfaces.
00133     DX::ThrowIfFailed(
00134         device.As(&m_d3dDevice)
00135         );
00136
00137     DX::ThrowIfFailed(
00138         context.As(&m_d3dContext)
00139         );
00140
00141     // Get the underlying DXGI device of the Direct3D device.
00142     DX::ThrowIfFailed(
00143         m_d3dDevice.As(&dxgiDevice)
00144         );
00145
00146     // Create the Direct2D device object and a corresponding context.
00147     DX::ThrowIfFailed(
00148         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00149         );
00150
00151     DX::ThrowIfFailed(
00152         m_d2dDevice->CreateDeviceContext(
00153             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00154             &m_d2dContext
00155             )
00156         );
00157 }
00158
00159 // Helps track the DPI in the helper class.
00160 // This is called in the dpiChanged event handler in the view class.
00161 void DirectXBase::SetDpi(float dpi)
00162 {
00163     if (dpi != m_dpi)
00164     {
00165         // Save the DPI of this display in our class.
00166         m_dpi = dpi;
00167
00168         // Update Direct2D's stored DPI.
00169         m_d2dContext->SetDpi(m_dpi, m_dpi);
00170
00171         // Often a DPI change implies a window size change. In some cases Windows will issue
00172         // both a size changed event and a DPI changed event. In this case, the resulting bounds
00173         // will not change, and the window resize code will only be executed once.
00174         UpdateForWindowSizeChange();
00175     }
00176 }
00177
00178 // This routine is called in the event handler for the view SizeChanged event.
00179 void DirectXBase::UpdateForWindowSizeChange()
00180 {
00181     // Only handle window size changed if there is no pending DPI change.
00182     if (m_dpi != DisplayProperties::LogicalDpi)
00183     {
00184         return;
00185     }
00186
00187     if (m_window->Bounds.Width  != m_windowBounds.Width ||
00188         m_window->Bounds.Height != m_windowBounds.Height)
00189     {
00190         m_d2dContext->SetTarget(nullptr);
00191         m_d2dTargetBitmap = nullptr;
00192         m_d3dRenderTargetView = nullptr;
00193         m_d3dDepthStencilView = nullptr;
00194         m_windowSizeChangeInProgress = true;
00195         CreateWindowSizeDependentResources();
00196     }
00197 }
00198
00199 // Allocate all memory resources that change on a window SizeChanged event.
00200 void DirectXBase::CreateWindowSizeDependentResources()
00201 {
00202     // Store the window bounds so the next time we get a SizeChanged event we can
00203     // avoid rebuilding everything if the size is identical.
00204     m_windowBounds = m_window->Bounds;
00205
00206     if (m_swapChain != nullptr)
00207     {
00208         // If the swap chain already exists, resize it.
00209         HRESULT hr = m_swapChain->ResizeBuffers(2, 0, 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0);
00210
00211         if (hr == DXGI_ERROR_DEVICE_REMOVED)
00212         {
00213             // If the device was removed for any reason, a new device and swapchain will need to be created.
00214             HandleDeviceLost();
00215
00216             // Everything is set up now. Do not continue execution of this method.
00217             return;
00218         }
00219         else
00220         {
00221             DX::ThrowIfFailed(hr);
00222         }
00223     }
00224     else
00225     {
00226         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00227         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00228         swapChainDesc.Width = 0;                                     // Use automatic sizing.
00229         swapChainDesc.Height = 0;
00230         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;           // This is the most common swap chain format.
00231         swapChainDesc.Stereo = false;
00232         swapChainDesc.SampleDesc.Count = 1;                          // Don't use multi-sampling.
00233         swapChainDesc.SampleDesc.Quality = 0;
00234         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00235         swapChainDesc.BufferCount = 2;                               // Use double-buffering to minimize latency.
00236         swapChainDesc.Scaling = DXGI_SCALING_NONE;
00237         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Metro style apps must use this SwapEffect.
00238         swapChainDesc.Flags = 0;
00239
00240         ComPtr<IDXGIDevice1> dxgiDevice;
00241         DX::ThrowIfFailed(
00242             m_d3dDevice.As(&dxgiDevice)
00243             );
00244
00245         ComPtr<IDXGIAdapter> dxgiAdapter;
00246         DX::ThrowIfFailed(
00247             dxgiDevice->GetAdapter(&dxgiAdapter)
00248             );
00249
00250         ComPtr<IDXGIFactory2> dxgiFactory;
00251         DX::ThrowIfFailed(
00252             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00253             );
00254
00255         CoreWindow^ window = m_window.Get();
00256         DX::ThrowIfFailed(
00257             dxgiFactory->CreateSwapChainForCoreWindow(
00258                 m_d3dDevice.Get(),
00259                 reinterpret_cast<IUnknown*>(window),
00260                 &swapChainDesc,
00261                 nullptr,
00262                 &m_swapChain
00263                 )
00264             );
00265
00266         // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
00267         // ensures that the application will only render after each VSync, minimizing power consumption.
00268         DX::ThrowIfFailed(
00269             dxgiDevice->SetMaximumFrameLatency(1)
00270             );
00271     }
00272
00273     // Create a Direct3D render target view of the swap chain back buffer.
00274     ComPtr<ID3D11Texture2D> backBuffer;
00275     DX::ThrowIfFailed(
00276         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00277         );
00278
00279     DX::ThrowIfFailed(
00280         m_d3dDevice->CreateRenderTargetView(
00281             backBuffer.Get(),
00282             nullptr,
00283             &m_d3dRenderTargetView
00284             )
00285         );
00286
00287     // Cache the rendertarget dimensions in our helper class for convenient use.
00288     D3D11_TEXTURE2D_DESC backBufferDesc = {0};
00289     backBuffer->GetDesc(&backBufferDesc);
00290     m_renderTargetSize.Width  = static_cast<float>(backBufferDesc.Width);
00291     m_renderTargetSize.Height = static_cast<float>(backBufferDesc.Height);
00292
00293     // Create a depth stencil view for use with 3D rendering if needed.
00294     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00295         DXGI_FORMAT_D24_UNORM_S8_UINT,
00296         backBufferDesc.Width,
00297         backBufferDesc.Height,
00298         1,
00299         1,
00300         D3D11_BIND_DEPTH_STENCIL
00301         );
00302
00303     ComPtr<ID3D11Texture2D> depthStencil;
00304     DX::ThrowIfFailed(
00305         m_d3dDevice->CreateTexture2D(
00306             &depthStencilDesc,
00307             nullptr,
00308             &depthStencil
00309             )
00310         );
00311
00312     auto viewDesc = CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D);
00313     DX::ThrowIfFailed(
00314         m_d3dDevice->CreateDepthStencilView(
00315             depthStencil.Get(),
00316             &viewDesc,
00317             &m_d3dDepthStencilView
00318             )
00319         );
00320
00321     // Set the 3D rendering viewport to target the entire window.
00322     CD3D11_VIEWPORT viewport(
00323         0.0f,
00324         0.0f,
00325         static_cast<float>(backBufferDesc.Width),
00326         static_cast<float>(backBufferDesc.Height)
00327         );
00328
00329     m_d3dContext->RSSetViewports(1, &viewport);
00330
00331     // Create a Direct2D target bitmap associated with the
00332     // swap chain back buffer and set it as the current target.
00333     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00334         BitmapProperties1(
00335             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00336             PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00337             m_dpi,
00338             m_dpi
00339             );
00340
00341     ComPtr<IDXGISurface> dxgiBackBuffer;
00342     DX::ThrowIfFailed(
00343         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00344         );
00345
00346     DX::ThrowIfFailed(
00347         m_d2dContext->CreateBitmapFromDxgiSurface(
00348             dxgiBackBuffer.Get(),
00349             &bitmapProperties,
00350             &m_d2dTargetBitmap
00351             )
00352         );
00353
00354     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00355
00356     // Grayscale text anti-aliasing is recommended for all Metro style apps.
00357     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00358 }
00359
00360 // Method to deliver the final image to the display.
00361 void DirectXBase::Present()
00362 {
00363     // The application may optionally specify "dirty" or "scroll" rects to improve efficiency
00364     // in certain scenarios.  In this sample, however, we do not utilize those features.
00365     DXGI_PRESENT_PARAMETERS parameters = {0};
00366     parameters.DirtyRectsCount = 0;
00367     parameters.pDirtyRects = nullptr;
00368     parameters.pScrollRect = nullptr;
00369     parameters.pScrollOffset = nullptr;
00370
00371     // The first argument instructs DXGI to block until VSync, putting the application
00372     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00373     // frames that will never be displayed to the screen.
00374     HRESULT hr = m_swapChain->Present1(1, 0, &parameters);
00375
00376     // Discard the contents of the render target.
00377     // This is a valid operation only when the existing contents will be entirely
00378     // overwritten. If dirty or scroll rects are used, this call should be removed.
00379     m_d3dContext->DiscardView(m_d3dRenderTargetView.Get());
00380
00381     // Discard the contents of the depth stencil.
00382     m_d3dContext->DiscardView(m_d3dDepthStencilView.Get());
00383
00384     // If the device was removed either by a disconnect or a driver upgrade, we
00385     // must recreate all device resources.
00386     if (hr == DXGI_ERROR_DEVICE_REMOVED)
00387     {
00388         HandleDeviceLost();
00389     }
00390     else
00391     {
00392         DX::ThrowIfFailed(hr);
00393     }
00394
00395     if (m_windowSizeChangeInProgress)
00396     {
00397         // A window size change has been initiated and the app has just completed presenting
00398         // the first frame with the new size. Notify the resize manager so we can short
00399         // circuit any resize animation and prevent unnecessary delays.
00400         CoreWindowResizeManager::GetForCurrentView()->NotifyLayoutCompleted();
00401         m_windowSizeChangeInProgress = false;
00402     }
00403 }
00404
00405 void DirectXBase::ValidateDevice()
00406 {
00407     // The D3D Device is no longer valid if the default adapter changes or if
00408     // the device has been removed.
00409
00410     // First, get the information for the adapter related to the current device.
00411
00412     ComPtr<IDXGIDevice1> dxgiDevice;
00413     ComPtr<IDXGIAdapter> deviceAdapter;
00414     DXGI_ADAPTER_DESC deviceDesc;
00415     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00416     DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter));
00417     DX::ThrowIfFailed(deviceAdapter->GetDesc(&deviceDesc));
00418
00419     // Next, get the information for the default adapter.
00420
00421     ComPtr<IDXGIFactory2> dxgiFactory;
00422     ComPtr<IDXGIAdapter1> currentAdapter;
00423     DXGI_ADAPTER_DESC currentDesc;
00424     DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)));
00425     DX::ThrowIfFailed(dxgiFactory->EnumAdapters1(0, &currentAdapter));
00426     DX::ThrowIfFailed(currentAdapter->GetDesc(&currentDesc));
00427
00428     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00429     // a new D3D device must be created.
00430
00431     if ((deviceDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart) ||
00432         (deviceDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart) ||
00433         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00434     {
00435         // Release references to resources related to the old device.
00436         dxgiDevice = nullptr;
00437         deviceAdapter = nullptr;
00438
00439         // Create a new device and swap chain.
00440         HandleDeviceLost();
00441     }
00442 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text editing/C++/Constants.h Source File

  • XAML text editing

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"XAML text editing sample");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: ControlChannelTrigger StreamSocket/C++/Background/Background.cpp Source File

  • ControlChannelTrigger StreamSocket
  • Background

Background.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002 #include "Background.h"
00003
00004 using namespace Background;
00005 using namespace Platform;
00006 using namespace StreamSocketTransportHelper;
00007 using namespace StreamSocketTransportHelper::DiagnosticsHelper;
00008 using namespace Windows::ApplicationModel::Background;
00009 using namespace Windows::ApplicationModel::Core;
00010 using namespace Windows::Data::Xml::Dom;
00011 using namespace Windows::Networking::Sockets;
00012 using namespace Windows::UI::Notifications;
00013
00014
00015 void NetworkChangeTask::Run(IBackgroundTaskInstance^ taskInstance)
00016 {
00017     if (taskInstance == nullptr)
00018     {
00019         Diag::DebugPrint("NetworkChangeTask: taskInstance was null");
00020         return;
00021     }
00022
00023     // In this example, the channel name has been hardcoded to lookup the property bag
00024     // for any previous contexts. The channel name may be used in more sophisticated ways
00025     // in case an app has multiple controlchanneltrigger objects.
00026     String^ channelId = "channelOne";
00027     if (CoreApplication::Properties->HasKey(channelId))
00028     {
00029         try
00030         {
00031             auto appContext = dynamic_cast<AppContext^>(CoreApplication::Properties->Lookup(channelId));
00032             if (appContext != nullptr && appContext->CommInstance != nullptr)
00033             {
00034                 CommModule^ commInstance = appContext->CommInstance;
00035
00036                 // Clear any existing channels, sockets etc.
00037                 commInstance->Reset();
00038
00039                 // Create CCT enabled transport
00040                 commInstance->SetupTransport(commInstance->serverName, commInstance->serverPort);
00041             }
00042         }
00043         catch (Exception^ exp)
00044         {
00045             Diag::DebugPrint("Registering with CCT failed with: " + exp->Message);
00046         }
00047     }
00048     else
00049     {
00050         Diag::DebugPrint("Cannot find AppContext key channelOne");
00051     }
00052
00053     Diag::DebugPrint("Systemtask - " + taskInstance->Task->Name + " finished.");
00054 }
00055
00056 void KATask::Run(IBackgroundTaskInstance^ taskInstance)
00057 {
00058     if (taskInstance == nullptr)
00059     {
00060         Diag::DebugPrint("KATask: taskInstance was null");
00061         return;
00062     }
00063
00064     Diag::DebugPrint("KATask " + taskInstance->Task->Name + " Starting...");
00065
00066     // Use the ControlChannelTriggerEventDetails object to derive the context for this background task.
00067     // The context happens to be the channelId that apps can use to differentiate between
00068     // various instances of the channel..
00069     auto channelEventArgs =
00070         dynamic_cast<IControlChannelTriggerEventDetails^>(taskInstance->TriggerDetails);
00071
00072     ControlChannelTrigger^ channel = channelEventArgs->ControlChannelTrigger;
00073     if (channel == nullptr)
00074     {
00075         Diag::DebugPrint("Channel object may have been deleted.");
00076         return;
00077     }
00078
00079     String^ channelId = channel->ControlChannelTriggerId;
00080
00081     if (CoreApplication::Properties->HasKey(channelId))
00082     {
00083         try
00084         {
00085             auto appContext = dynamic_cast<AppContext^>(CoreApplication::Properties->Lookup(channelId));
00086             String^ KeepAliveMessage = "KeepAlive Message";
00087             if (appContext != nullptr && appContext->CommInstance != nullptr)
00088             {
00089                 CommModule^ commModule = appContext->CommInstance;
00090                 bool result = commModule->SendKAMessage(KeepAliveMessage);
00091                 if (result == true)
00092                 {
00093                     // Call FlushTransport on the channel object to ensure
00094                     // the packet is out of the process and on the wire before
00095                     // exiting the keepalive task.
00096                     commModule->channel->FlushTransport();
00097                 }
00098                 else
00099                 {
00100                     // Socket has not been set up. Reconnect the transport and plug in to the controlchanneltrigger object.
00101                     commModule->Reset();
00102
00103                     // Create CCT enabled transport.
00104                     commModule->SetupTransport(commModule->serverName, commModule->serverPort);
00105                 }
00106             }
00107         }
00108         catch (Exception^ exp)
00109         {
00110             Diag::DebugPrint("KA Task failed with: " + exp->Message);
00111         }
00112     }
00113     else
00114     {
00115         Diag::DebugPrint("Cannot find AppContext key channelOne");
00116     }
00117
00118     Diag::DebugPrint("KATask " + taskInstance->Task->Name + " finished.");
00119 }
00120
00121 void PushNotifyTask::InvokeSimpleToast(String^ msgReceived)
00122 {
00123     // GetTemplateContent returns a Windows.Data.Xml.Dom.XmlDocument object containing
00124     // the toast XML.
00125     XmlDocument^ toastXml = ToastNotificationManager::GetTemplateContent(ToastTemplateType::ToastImageAndText02);
00126
00127     // You can use the methods from the XML document to specify all of the
00128     // required parameters for the toast.
00129     XmlNodeList^ stringElements = toastXml->GetElementsByTagName("text");
00130     stringElements->Item(0)->AppendChild(toastXml->CreateTextNode("Push notification message:"));
00131     stringElements->Item(1)->AppendChild(toastXml->CreateTextNode(msgReceived));
00132
00133     // Audio tags are not included by default, so must be added to the
00134     // XML document.
00135     String^ audioSrc = "ms-winsoundevent:Notification.IM";
00136     XmlElement^ audioElement = toastXml->CreateElement("audio");
00137     audioElement->SetAttribute("src", audioSrc);
00138
00139     IXmlNode^ toastNode = toastXml->SelectSingleNode("/toast");
00140     toastNode->AppendChild(audioElement);
00141
00142     // Create a toast from the Xml, then create a ToastNotifier object to show the toast.
00143     ToastNotification^ toast = ref new ToastNotification(toastXml);
00144     ToastNotificationManager::CreateToastNotifier()->Show(toast);
00145 }
00146
00147 void PushNotifyTask::Run(IBackgroundTaskInstance^ taskInstance)
00148 {
00149     if (taskInstance == nullptr)
00150     {
00151         Diag::DebugPrint("PushNotifyTask: taskInstance was null");
00152         return;
00153     }
00154
00155     Diag::DebugPrint("PushNotifyTask " + taskInstance->Task->Name + " Starting...");
00156
00157     // Use the ControlChannelTriggerEventDetails object to derive the context for this background task.
00158     // The context happens to be the channelId that apps can use to differentiate between
00159     // various instances of the channel..
00160     auto channelEventArgs = dynamic_cast<IControlChannelTriggerEventDetails^>(taskInstance->TriggerDetails);
00161
00162     ControlChannelTrigger^ channel = channelEventArgs->ControlChannelTrigger;
00163     if (channel == nullptr)
00164     {
00165         Diag::DebugPrint("Channel object may have been deleted.");
00166         return;
00167     }
00168
00169     String^ channelId = channel->ControlChannelTriggerId;
00170
00171     if (CoreApplication::Properties->HasKey(channelId))
00172     {
00173         try
00174         {
00175             auto appContext = dynamic_cast<AppContext^>(CoreApplication::Properties->Lookup(channelId));
00176
00177             // Process any messages that have been enqueued by the receive completion handler.
00178             String^ messageReceived = appContext->messageQueue->Dequeue();
00179             if (messageReceived != nullptr)
00180             {
00181                 Diag::DebugPrint("Message: " + messageReceived);
00182                 InvokeSimpleToast(messageReceived);
00183             }
00184             else
00185             {
00186                 Diag::DebugPrint("There was no message for this push notification: ");
00187             }
00188         }
00189         catch (Exception^ exp)
00190         {
00191             Diag::DebugPrint("PushNotifyTask failed with: " + exp->Message);
00192         }
00193     }
00194     else
00195     {
00196         Diag::DebugPrint("Cannot find AppContext key " + channelId);
00197     }
00198
00199     Diag::DebugPrint("PushNotifyTask " + taskInstance->Task->Name + " finished.");
00200 }
Generated on Sat Nov 23 2024 16:07:59 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML AppBar control/C++/Scenario2.xaml.cpp Source File

  • XAML AppBar control

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 AppBarControl;
00020
00021 using namespace Platform;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Navigation;
00025
00026 Scenario2::Scenario2()
00027 {
00028     InitializeComponent();
00029   rootPage = MainPage::Current;
00030 }
00031
00032
00033 // Invoked when this page is about to be displayed in a Frame.
00034 void Scenario2::OnNavigatedTo(NavigationEventArgs^ e)
00035 {
00036      rootPage = MainPage::Current;
00037  }
00038
00039 // Handler for "Is Sticky" check box
00040 void AppBarControl::Scenario2::IsSticky_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00041 {
00042     auto cb = (CheckBox^) sender;
00043
00044     auto myAppBar = (AppBar^) rootPage->FindName(L"BottomAppBar1");
00045         if (myAppBar != nullptr)
00046         {
00047       myAppBar->IsSticky = cb->IsChecked->Value;
00048     }
00049 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Secondary tiles/C#,C++/LaunchedFromSecondaryTile.xaml.h Source File

  • Secondary tiles
  • C#,C++

LaunchedFromSecondaryTile.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 // LaunchedFromSecondaryTile.xaml.h
00013 // Declaration of the LaunchedFromSecondaryTile class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "LaunchedFromSecondaryTile.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SecondaryTiles
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 LaunchedFromSecondaryTile sealed
00029     {
00030     public:
00031         LaunchedFromSecondaryTile();
00032
00033     protected:
00034         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00035         virtual void OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^ e) override;
00036     private:
00037         MainPage^ rootPage;
00038         Windows::UI::Xaml::Controls::AppBar^ appBar;
00039     };
00040 }
Generated on Sat Nov 23 2024 16:08:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

GameConfig Member List

This is the complete list of members for GameConfig, including all inherited members.
autoFire | GameConfig
backgroundAvailable | GameConfig
isTrial | GameConfig
Generated on Sat Nov 23 2024 16:09:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML high contrast style/C++/MainPage.xaml.cpp Source File

  • XAML high contrast style

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Credential picker/C++/MainPage.xaml.h Source File

  • Credential picker

MainPage.xaml.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 //
00009 // MainPage.xaml.h
00010 // Declaration of the MainPage.xaml class.
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "MainPage.g.h"
00017
00018 namespace CredentialPickerCPP
00019 {
00020     public enum class NotifyType
00021     {
00022         StatusMessage,
00023         ErrorMessage
00024     };
00025
00026   [Windows::Foundation::Metadata::WebHostHidden]
00027     public ref class MainPage sealed
00028     {
00029     public:
00030         MainPage();
00031
00032         property Windows::UI::Xaml::Controls::Frame^ ScenariosFrame
00033         {
00034             Windows::UI::Xaml::Controls::Frame^ get() { return _scenariosFrame; }
00035         }
00036         property Windows::UI::Xaml::Controls::Frame^ InputFrame
00037         {
00038             Windows::UI::Xaml::Controls::Frame^ get() { return _inputFrame; }
00039         }
00040         property Windows::UI::Xaml::Controls::Frame^ OutputFrame
00041         {
00042             Windows::UI::Xaml::Controls::Frame^ get() { return _outputFrame; }
00043         }
00044
00045         event Windows::Foundation::EventHandler<Platform::Object^>^ InputFrameLoaded;
00046         event Windows::Foundation::EventHandler<Platform::Object^>^ OutputFrameLoaded;
00047     void NotifyUserFromAsyncThread(Platform::String^ strMessage, NotifyType type);
00048         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00049         void DoNavigation(Windows::UI::Xaml::Interop::TypeName inPageType, Windows::UI::Xaml::Controls::Frame^ inFrame, Windows::UI::Xaml::Interop::TypeName outPageType, Windows::UI::Xaml::Controls::Frame^ outFrame);
00050         Platform::String^ ConvertViewState(Windows::UI::ViewManagement::ApplicationViewState state);
00051         Platform::String^ ConvertResolution(Windows::Graphics::Display::ResolutionScale scale);
00052
00053     private:
00054         Windows::UI::Xaml::Controls::Frame^ _scenariosFrame;
00055         Windows::UI::Xaml::Controls::Frame^ _inputFrame;
00056         Windows::UI::Xaml::Controls::Frame^ _outputFrame;
00057         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00058         Windows::Foundation::EventRegistrationToken _displayHandlerToken;
00059         Windows::Foundation::EventRegistrationToken _layoutHandlerToken;
00060         Windows::Foundation::EventRegistrationToken _pageLoadedHandlerToken;
00061         Windows::Foundation::EventRegistrationToken _logicalDpiChangedToken;
00062         Windows::Foundation::EventRegistrationToken _inputFrameLoadedToken;
00063         Windows::Foundation::EventRegistrationToken _outputFrameLoadedToken;
00064         void Page_SizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00065         void DisplayProperties_LogicalDpiChanged(Object^ sender);
00066         void Page_Loaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00067         void CheckResolutionAndViewState();
00068         void SetFeatureName(Platform::String^ strFeature);
00069         void inputFrameNavigated(Object^ sender, Windows::UI::Xaml::Navigation::NavigationEventArgs^ e);
00070         void outputFrameNavigated(Object^ sender,  Windows::UI::Xaml::Navigation::NavigationEventArgs^ e);
00071         ~MainPage();
00072     };
00073 }
Generated on Sat Nov 23 2024 16:07:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text display/C++/Constants.cpp Source File

  • XAML text display

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully qualified name for the class that implements the scenario" }
00021     { "Tracking (character spacing)", "SDKSample.TextDisplay.Scenario1" },
00022     { "Leading (line height)", "SDKSample.TextDisplay.Scenario2" },
00023     { "OpenType", "SDKSample.TextDisplay.Scenario3" },
00024   { "Linked text containers", "SDKSample.TextDisplay.Scenario4" },
00025 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Association launching/C++/LaunchUriInput.xaml.cpp Source File

  • Association launching

LaunchUriInput.xaml.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 //
00009 // LaunchUriInput.xaml.cpp
00010 // Implementation of the LaunchUriInput class
00011 //
00012
00013 #include "pch.h"
00014 #include "LaunchUriInput.xaml.h"
00015
00016 using namespace AssociationLaunching;
00017
00018 using namespace concurrency;
00019 using namespace CppSamplesUtils;
00020 using namespace Platform;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Foundation::Collections;
00023 using namespace Windows::Graphics::Display;
00024 using namespace Windows::UI::ViewManagement;
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 Platform::String^ LaunchUriInput::uriToLaunch = "http://www.bing.com";
00034
00035 LaunchUriInput::LaunchUriInput()
00036 {
00037     InitializeComponent();
00038 }
00039
00040 LaunchUriInput::~LaunchUriInput()
00041 {
00042 }
00043
00044 #pragma region Template-Related Code - Do not remove
00045 void LaunchUriInput::OnNavigatedTo(NavigationEventArgs^ e)
00046 {
00047     // Get a pointer to our main page.
00048     rootPage = dynamic_cast<MainPage^>(e->Parameter);
00049 }
00050
00051 void LaunchUriInput::OnNavigatedFrom(NavigationEventArgs^ e)
00052 {
00053 }
00054
00055 #pragma endregion
00056
00057 void LaunchUriInput::LaunchUriButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00058 {
00059     auto page = this->rootPage;
00060
00061     // Create the URI from a string.
00062     auto uri = ref new Uri(uriToLaunch);
00063
00064     // Launch the URI.
00065     create_task(Windows::System::Launcher::LaunchUriAsync(uri)).then([page](bool launchResult)
00066     {
00067         if (launchResult)
00068         {
00069             page->NotifyUser("Uri launch succeeded.", NotifyType::StatusMessage);
00070         }
00071         else
00072         {
00073             page->NotifyUser("Uri launch failed.", NotifyType::ErrorMessage);
00074         }
00075     });
00076 }
00077
00078 void LaunchUriInput::LaunchUriWithWarningButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00079 {
00080     auto page = this->rootPage;
00081
00082     // Create the URI from a string.
00083     auto uri = ref new Uri(uriToLaunch);
00084
00085     // Configure the warning prompt.
00086     auto launchOptions = ref new Windows::System::LauncherOptions();
00087     launchOptions->TreatAsUntrusted = true;
00088
00089     // Launch the URI.
00090     create_task(Windows::System::Launcher::LaunchUriAsync(uri, launchOptions)).then([page](bool launchResult)
00091     {
00092         if (launchResult)
00093         {
00094             page->NotifyUser("Uri launch succeeded.", NotifyType::StatusMessage);
00095         }
00096         else
00097         {
00098             page->NotifyUser("Uri launch failed.", NotifyType::ErrorMessage);
00099         }
00100     });
00101 }
00102
00103 void LaunchUriInput::LaunchUriOpenWithButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00104 {
00105     auto page = this->rootPage;
00106     auto button = LaunchUriOpenWithButton;
00107
00108     // Create the URI from a string.
00109     auto uri = ref new Uri(uriToLaunch);
00110
00111     // Calulcate the position for the Open With dialog.
00112     Point openWithPosition = GetOpenWithPosition(button);
00113     auto launchOptions = ref new Windows::System::LauncherOptions();
00114     launchOptions->DisplayApplicationPicker = true;
00115     launchOptions->UI->InvocationPoint = dynamic_cast<IBox<Point>^>(PropertyValue::CreatePoint(openWithPosition));
00116     launchOptions->UI->PreferredPlacement = Windows::UI::Popups::Placement::Below;
00117
00118     // Launch the URI.
00119     create_task(Windows::System::Launcher::LaunchUriAsync(uri, launchOptions)).then([page](bool launchResult)
00120     {
00121         if (launchResult)
00122         {
00123             page->NotifyUser("Uri launch succeeded.", NotifyType::StatusMessage);
00124         }
00125         else
00126         {
00127             page->NotifyUser("Uri launch failed.", NotifyType::ErrorMessage);
00128         }
00129     });
00130 }
00131
00132 // The Open With dialog will be displayed just under the element that triggered them.
00133 // An alternative to using the point is to set the rect of the bounding element.
00134 Point LaunchUriInput::GetOpenWithPosition(FrameworkElement^ element)
00135 {
00136     Windows::UI::Xaml::Media::GeneralTransform^ buttonTransform = element->TransformToVisual(nullptr);
00137     Point origin(0, 0);
00138
00139     Point desiredLocation = buttonTransform->TransformPoint(origin);
00140     desiredLocation.Y = desiredLocation.Y + safe_cast<float>(element->ActualHeight);
00141
00142     return desiredLocation;
00143 }
Generated on Sat Nov 23 2024 16:07:57 for Win8-Examples by doxygen 1.7.1


Win8-Examples: App settings/C++/pch.h Source File

  • App settings

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Sharing content target app/C++/DefaultPage.xaml.cpp Source File

  • Sharing content target app

DefaultPage.xaml.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 //
00009 // DefaultPage.xaml.cpp
00010 // Implementation of the DefaultPage class
00011 //
00012
00013 #include "pch.h"
00014 #include "DefaultPage.xaml.h"
00015
00016 using namespace ShareTarget;
00017
00018 using namespace Platform;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Controls;
00022
00023 DefaultPage::DefaultPage()
00024 {
00025     InitializeComponent();
00026 }
00027
00028 void DefaultPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00029 {
00030     auto uri = ref new Uri(safe_cast<String^>(safe_cast<HyperlinkButton^>(sender)->Tag));
00031     Windows::System::Launcher::LaunchUriAsync(uri);
00032 }
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Store device app for camera/C++/Wrapper/pch.cpp Source File

  • Windows Store device app for camera
  • Wrapper

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
00009 // pch.cpp : source file that includes just the standard includes
00010 //   pch.pch will be the pre-compiled header
00011 //   pch.obj will contain the pre-compiled type information
00012
00013 #include "pch.h"
00014
00015 // TODO: reference any additional headers you need in PCH.H and not in this file
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application resources and localization/C++/Scenario11.xaml.cpp Source File

  • Application resources and localization

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 SDKSample::ApplicationResources;
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 SDKSample::ApplicationResources::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 = ref new ResourceLoader();
00048         this->Scenario11TextBlock->Text = "http://api.contoso.com/Feed?lang=" + resourceLoader->GetString("webservicelang");
00049     }
00050
00051 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C#,C++/ScenarioList.xaml.cs Source File

  • Media extensions
  • C#,C++

ScenarioList.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 System;
00009 using System.Linq;
00010 using System.Collections.Generic;
00011 using Windows.Foundation;
00012 using Windows.Foundation.Collections;
00013 using Windows.Graphics.Display;
00014 using Windows.UI.ViewManagement;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Controls.Primitives;
00018 using Windows.UI.Xaml.Data;
00019 using Windows.UI.Xaml.Input;
00020 using Windows.UI.Xaml.Media;
00021 using Windows.UI.Xaml.Navigation;
00022 using SDKTemplateCS;
00023
00024 namespace MediaExtensionsCS
00025 {
00026     public sealed partial class ScenarioList : Page
00027     {
00028         // A pointer back to the main page which is used to gain access to the input and output frames and their content.
00029         MainPage rootPage = null;
00030
00031         public ScenarioList()
00032         {
00033             InitializeComponent();
00034         }
00035
00036         #region Template-Related Code - Do not remove
00037         void Scenarios_SelectionChanged(object sender, SelectionChangedEventArgs e)
00038         {
00039             if (Scenarios.SelectedItem != null)
00040             {
00041                 rootPage.NotifyUser("", NotifyType.StatusMessage);
00042
00043                 ListBoxItem selectedListBoxItem = Scenarios.SelectedItem as ListBoxItem;
00044                 SuspensionManager.SessionState["SelectedScenario"] = selectedListBoxItem.Name;
00045
00046                 if (rootPage.InputFrame != null && rootPage.OutputFrame != null)
00047                 {
00048                     // Load the input and output pages for the current scenario into their respective frames.
00049
00050                     rootPage.DoNavigation(Type.GetType(typeof(ScenarioList).Namespace + "." + "ScenarioInput" + ((Scenarios.SelectedIndex + 1).ToString())), rootPage.InputFrame);
00051                     rootPage.DoNavigation(Type.GetType(typeof(ScenarioList).Namespace + "." + "ScenarioOutput" + ((Scenarios.SelectedIndex + 1).ToString())), rootPage.OutputFrame);
00052                 }
00053             }
00054         }
00055
00056         protected override void OnNavigatedTo(NavigationEventArgs e)
00057         {
00058             rootPage = e.Parameter as MainPage;
00059             Scenarios.SelectionChanged += new SelectionChangedEventHandler(Scenarios_SelectionChanged);
00060
00061             // Starting scenario is the first or based upon a previous selection.
00062             ListBoxItem startingScenario = null;
00063             if (SuspensionManager.SessionState.ContainsKey("SelectedScenario"))
00064             {
00065                 String selectedScenarioName = SuspensionManager.SessionState["SelectedScenario"] as string;
00066                 startingScenario = this.FindName(selectedScenarioName) as ListBoxItem;
00067             }
00068
00069             Scenarios.SelectedItem = startingScenario != null ? startingScenario : Scenario1;
00070         }
00071         #endregion
00072     }
00073 }
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Portable device API/C++/S6_DeviceStatus.xaml.cpp Source File

  • Portable device API

S6_DeviceStatus.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 // S6_DeviceStatus.xaml.cpp
00013 // Implementation of the S6_DeviceStatus class
00014 //
00015
00016 #include "pch.h"
00017
00018 // Status device service declarations
00019 #include <initguid.h>
00020 #include <guiddef.h>
00021 #include <propkeydef.h>
00022 #define DEFINE_DEVSVCGUID DEFINE_GUID
00023 #define DEFINE_DEVSVCPROPKEY DEFINE_PROPERTYKEY
00024 #include <StatusDeviceService.h>
00025
00026 #include "S6_DeviceStatus.xaml.h"
00027
00028 using namespace SDKSample::PortableDeviceCPP;
00029
00030 using namespace concurrency;
00031 using namespace Microsoft::WRL;
00032 using namespace Platform;
00033 using namespace Platform::Collections;
00034 using namespace Windows::Devices::Enumeration;
00035 using namespace Windows::Devices::Portable;
00036 using namespace Windows::Foundation;
00037 using namespace Windows::UI::Core;
00038 using namespace Windows::UI::Xaml;
00039 using namespace Windows::UI::Xaml::Controls;
00040 using namespace Windows::UI::Xaml::Navigation;
00041
00042 S6_DeviceStatus::S6_DeviceStatus() : rootPage(MainPage::Current)
00043 {
00044     InitializeComponent();
00045 }
00046
00047 /// <summary>
00048 /// Invoked when this page is about to be displayed in a Frame.
00049 /// </summary>
00050 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00051 /// property is typically used to configure the page.</param>
00052 void S6_DeviceStatus::OnNavigatedTo(NavigationEventArgs^ e)
00053 {
00054     ScenarioOutput->Text = "";
00055     DeviceSelector->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00056 }
00057
00058 /// <summary>
00059 /// This is the click handler for the 'Run' button.
00060 /// </summary>
00061 /// <param name="sender"></param>
00062 /// <param name="e"></param>
00063 void S6_DeviceStatus::Run_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00064 {
00065     ShowDeviceSelectorAsync();
00066 }
00067
00068 /// <summary>
00069 /// Enumerates all MTP device services and populates the device selection list.
00070 /// </summary>
00071 void S6_DeviceStatus::ShowDeviceSelectorAsync()
00072 {
00073     ScenarioOutput->Text = "";
00074     _deviceInfoCollection = nullptr;
00075
00076     // Find all portable devices
00077     String^ aqsFilter = ServiceDevice::GetDeviceSelector(ServiceDeviceType::DeviceStatusService);
00078     create_task(DeviceInformation::FindAllAsync(aqsFilter)).then([this] (DeviceInformationCollection^ deviceInfoCollection)
00079     {
00080         _deviceInfoCollection = deviceInfoCollection;
00081         if (_deviceInfoCollection->Size > 0)
00082         {
00083             auto items = ref new Vector<String^>();
00084             std::for_each(begin(_deviceInfoCollection), end(_deviceInfoCollection), [items](IDeviceInformation^ deviceInfoElement)
00085             {
00086                 items->Append(ref new String(deviceInfoElement->Name->Begin()));
00087             });
00088             cvs->Source = items;
00089             DeviceSelector->Visibility = Windows::UI::Xaml::Visibility::Visible;
00090         }
00091         else
00092         {
00093             rootPage->NotifyUser("No portable devices were found. Please attach a portable device to the system that supports the MTP Device Status service (e.g. the MTP Device Simulator)", NotifyType::ErrorMessage);
00094         }
00095     });
00096 }
00097
00098 /// <summary>
00099 /// This is the tapped handler for the device selection list. It runs the scenario
00100 /// for the selected portable device.
00101 /// </summary>
00102 /// <param name="sender"></param>
00103 /// <param name="e"></param>
00104 void S6_DeviceStatus::DeviceList_Tapped(Platform::Object^ sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^ e)
00105 {
00106     DeviceSelector->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00107     if (_deviceInfoCollection == nullptr)
00108     {
00109         return; // not yet populated
00110     }
00111
00112     auto deviceInfo = _deviceInfoCollection->GetAt(DeviceList->SelectedIndex);
00113     DisplayDeviceStatusAsync(deviceInfo);
00114 }
00115
00116 /// <summary>
00117 /// Gets device status from the selected MTP device status service.
00118 /// </summary>
00119 /// <param name="deviceInfoElement">Contains information about a selected device status service.</param>
00120 void S6_DeviceStatus::DisplayDeviceStatusAsync(DeviceInformation^ deviceInfoElement)
00121 {
00122     ComPtr<IPortableDeviceService> service;
00123     ThrowIfFailed(CoCreateInstance(CLSID_PortableDeviceServiceFTM, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&service)));
00124
00125     ComPtr<IPortableDeviceServiceActivation> activator;
00126     ThrowIfFailed(service.As(&activator));
00127
00128     OnServiceOpenComplete^ openCallback = ref new OnServiceOpenComplete([this, deviceInfoElement, service] (HRESULT hr)
00129     {
00130         if (SUCCEEDED(hr))
00131         {
00132             rootPage->DispatcherNotifyUser("Successfully opened MTP device status service for " + deviceInfoElement->Name, NotifyType::StatusMessage);
00133             DisplayDeviceStatusServiceProperties(service.Get());
00134         }
00135         else
00136         {
00137             if (hr == E_ACCESSDENIED)
00138             {
00139                 rootPage->DispatcherNotifyUser("Access to the MTP device status service for " + deviceInfoElement->Name + " is denied. Only a Privileged Application may access this device.", NotifyType::ErrorMessage);
00140             }
00141             else
00142             {
00143                 rootPage->DispatcherNotifyUser("Accessing the MTP device status service for " + deviceInfoElement->Name + " failed with error code: " + hr.ToString(), NotifyType::ErrorMessage);
00144             }
00145         }
00146     });
00147
00148     auto clientInfo = GetClientInfo();
00149     ThrowIfFailed(activator->OpenAsync(deviceInfoElement->Id->Begin(), clientInfo.Get(), reinterpret_cast<IPortableDeviceServiceOpenCallback*>(openCallback)));
00150 }
00151
00152 /// <summary>
00153 /// Retrieves and displays the device status, which is available as properties of the MTP device status service.
00154 /// </summary>
00155 /// <param name="device">Pointer to the IPortableDeviceService for the MTP status service.</param>
00156 void S6_DeviceStatus::DisplayDeviceStatusServiceProperties(_In_ IPortableDeviceService* service)
00157 {
00158     PWSTR serviceObjectId = nullptr;
00159     HRESULT hr = service->GetServiceObjectID(&serviceObjectId);
00160     CoTaskMemString serviceObjectIdPtr(serviceObjectId);
00161     ThrowIfFailed(hr);
00162
00163     ComPtr<IPortableDeviceContent2> content;
00164     ThrowIfFailed(service->Content(&content));
00165
00166     ComPtr<IPortableDeviceProperties> properties;
00167     ThrowIfFailed(content->Properties(&properties));
00168
00169     ComPtr<IPortableDeviceKeyCollection> propertiesToRead;
00170     ThrowIfFailed(CoCreateInstance(CLSID_PortableDeviceKeyCollection, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&propertiesToRead)));
00171
00172     // device status values are properties on the device's Status service
00173     ThrowIfFailed(propertiesToRead->Add(PKEY_StatusSvc_SignalStrength));
00174     ThrowIfFailed(propertiesToRead->Add(PKEY_StatusSvc_VoiceMail));
00175     ThrowIfFailed(propertiesToRead->Add(PKEY_StatusSvc_NetworkName));
00176     ThrowIfFailed(propertiesToRead->Add(PKEY_StatusSvc_NetworkType));
00177
00178     ComPtr<IPortableDeviceValues> deviceStatusProperties;
00179     ThrowIfFailed(properties->GetValues(serviceObjectId, propertiesToRead.Get(), &deviceStatusProperties));
00180
00181     DWORD statusNumericValue = 0;
00182     PWSTR statusStringValue = nullptr;
00183     String^ statusResult = "Device Status\n";
00184     if (SUCCEEDED(deviceStatusProperties->GetUnsignedIntegerValue(PKEY_StatusSvc_SignalStrength, &statusNumericValue)))
00185     {
00186         statusResult += "Signal Strength: " + statusNumericValue.ToString() + "\n";
00187     }
00188
00189     if (SUCCEEDED(deviceStatusProperties->GetUnsignedIntegerValue(PKEY_StatusSvc_VoiceMail, &statusNumericValue)))
00190     {
00191         statusResult += "New Voice Mails: " + statusNumericValue.ToString() + "\n";
00192     }
00193
00194     if (SUCCEEDED(deviceStatusProperties->GetStringValue(PKEY_StatusSvc_NetworkName, &statusStringValue)))
00195     {
00196         statusResult += "Network Name: " + ref new String(statusStringValue) + "\n";
00197     }
00198     CoTaskMemFree(statusStringValue);
00199     statusStringValue = nullptr;
00200
00201     if (SUCCEEDED(deviceStatusProperties->GetStringValue(PKEY_StatusSvc_NetworkType, &statusStringValue)))
00202     {
00203         statusResult += "Network Type: " + ref new String(statusStringValue) + "\n";
00204     }
00205     CoTaskMemFree(statusStringValue);
00206     statusStringValue = nullptr;
00207
00208     Dispatcher->RunAsync(CoreDispatcherPriority::Normal,
00209         ref new DispatchedHandler(
00210             [this, statusResult]()
00211             {
00212                 ScenarioOutput->Text = statusResult;
00213             },
00214             CallbackContext::Any
00215         )
00216     );
00217 }
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Hilo::HiloPage Member List

This is the complete list of members for Hilo::HiloPage, including all inherited members.
__pad0__ | Hilo::HiloPage |
__pad1__ | Hilo::HiloPage |
AttachNavigationHandlers(Hilo::ViewModelBase^viewModel) | Hilo::HiloPage | [private]
DetachNavigationHandlers(Hilo::ViewModelBase^viewModel) | Hilo::HiloPage | [private]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | Hilo::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Hilo::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Hilo::Common::LayoutAwarePage | [virtual]
InvalidateVisualState() | Hilo::Common::LayoutAwarePage |
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) override | Hilo::HiloPage | [virtual]
m_hasHandlers | Hilo::HiloPage | [private]
m_navigateBackEventToken | Hilo::HiloPage | [private]
m_navigateHomeEventToken | Hilo::HiloPage | [private]
m_navigateToPageEventToken | Hilo::HiloPage | [private]
NavigateHome() | Hilo::HiloPage | [virtual]
NavigateToPage(PageType page, Platform::Object^parameter) | Hilo::HiloPage | [virtual]
OnHiloDataContextPropertyChanged(Windows::UI::Xaml::DependencyObject^element, Windows::UI::Xaml::DependencyPropertyChangedEventArgs^e) | Hilo::HiloPage | [static]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | Hilo::HiloPage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | Hilo::HiloPage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) override | Hilo::HiloPage | [virtual]
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Hilo::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Hilo::Common::LayoutAwarePage |
Generated on Sat Nov 23 2024 16:09:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite paragraph text/C++/DirectXBase.cpp Source File

  • DirectWrite paragraph text

DirectXBase.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 "DirectXBase.h"
00010
00011 using namespace Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::Graphics::Display;
00015 using namespace D2D1;
00016
00017 // Constructor.
00018 DirectXBase::DirectXBase() :
00019     m_windowSizeChangeInProgress(false),
00020     m_dpi(-1.0f)
00021 {
00022 }
00023
00024 // Initialize the DirectX resources required to run.
00025 void DirectXBase::Initialize(CoreWindow^ window, float dpi)
00026 {
00027     m_window = window;
00028
00029     CreateDeviceIndependentResources();
00030     CreateDeviceResources();
00031     SetDpi(dpi);
00032 }
00033
00034 // Recreate all device resources and set them back to the current state.
00035 void DirectXBase::HandleDeviceLost()
00036 {
00037     // Reset these member variables to ensure that SetDpi recreates all resources.
00038     float dpi = m_dpi;
00039     m_dpi = -1.0f;
00040     m_windowBounds.Width = 0;
00041     m_windowBounds.Height = 0;
00042     m_swapChain = nullptr;
00043
00044     CreateDeviceResources();
00045     SetDpi(dpi);
00046 }
00047
00048 // These are the resources required independent of the device.
00049 void DirectXBase::CreateDeviceIndependentResources()
00050 {
00051     D2D1_FACTORY_OPTIONS options;
00052     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00053
00054 #if defined(_DEBUG)
00055     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00056     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00057 #endif
00058
00059     DX::ThrowIfFailed(
00060         D2D1CreateFactory(
00061             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00062             __uuidof(ID2D1Factory1),
00063             &options,
00064             &m_d2dFactory
00065             )
00066         );
00067
00068     DX::ThrowIfFailed(
00069         DWriteCreateFactory(
00070             DWRITE_FACTORY_TYPE_SHARED,
00071             __uuidof(IDWriteFactory),
00072             &m_dwriteFactory
00073             )
00074         );
00075
00076     DX::ThrowIfFailed(
00077         CoCreateInstance(
00078             CLSID_WICImagingFactory,
00079             nullptr,
00080             CLSCTX_INPROC_SERVER,
00081             IID_PPV_ARGS(&m_wicFactory)
00082             )
00083         );
00084 }
00085
00086 // These are the resources that depend on the device.
00087 void DirectXBase::CreateDeviceResources()
00088 {
00089     // This flag adds support for surfaces with a different color channel ordering
00090     // than the API default. It is required for compatibility with Direct2D.
00091     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00092     ComPtr<IDXGIDevice> dxgiDevice;
00093
00094 #if defined(_DEBUG)
00095     // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00096     creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00097 #endif
00098
00099     // This array defines the set of DirectX hardware feature levels this app will support.
00100     // Note the ordering should be preserved.
00101     // Don't forget to declare your application's minimum required feature level in its
00102     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00103     D3D_FEATURE_LEVEL featureLevels[] =
00104     {
00105         D3D_FEATURE_LEVEL_11_1,
00106         D3D_FEATURE_LEVEL_11_0,
00107         D3D_FEATURE_LEVEL_10_1,
00108         D3D_FEATURE_LEVEL_10_0,
00109         D3D_FEATURE_LEVEL_9_3,
00110         D3D_FEATURE_LEVEL_9_2,
00111         D3D_FEATURE_LEVEL_9_1
00112     };
00113
00114     // Create the Direct3D 11 API device object and a corresponding context.
00115     ComPtr<ID3D11Device> device;
00116     ComPtr<ID3D11DeviceContext> context;
00117     DX::ThrowIfFailed(
00118         D3D11CreateDevice(
00119             nullptr,                    // Specify nullptr to use the default adapter.
00120             D3D_DRIVER_TYPE_HARDWARE,
00121             0,
00122             creationFlags,              // Set debug and Direct2D compatibility flags.
00123             featureLevels,              // List of feature levels this app can support.
00124             ARRAYSIZE(featureLevels),
00125             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Metro style apps.
00126             &device,                    // Returns the Direct3D device created.
00127             &m_featureLevel,            // Returns feature level of device created.
00128             &context                    // Returns the device immediate context.
00129             )
00130         );
00131
00132     // Get the Direct3D 11.1 API device and context interfaces.
00133     DX::ThrowIfFailed(
00134         device.As(&m_d3dDevice)
00135         );
00136
00137     DX::ThrowIfFailed(
00138         context.As(&m_d3dContext)
00139         );
00140
00141     // Get the underlying DXGI device of the Direct3D device.
00142     DX::ThrowIfFailed(
00143         m_d3dDevice.As(&dxgiDevice)
00144         );
00145
00146     // Create the Direct2D device object and a corresponding context.
00147     DX::ThrowIfFailed(
00148         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00149         );
00150
00151     DX::ThrowIfFailed(
00152         m_d2dDevice->CreateDeviceContext(
00153             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00154             &m_d2dContext
00155             )
00156         );
00157 }
00158
00159 // Helps track the DPI in the helper class.
00160 // This is called in the dpiChanged event handler in the view class.
00161 void DirectXBase::SetDpi(float dpi)
00162 {
00163     if (dpi != m_dpi)
00164     {
00165         // Save the DPI of this display in our class.
00166         m_dpi = dpi;
00167
00168         // Update Direct2D's stored DPI.
00169         m_d2dContext->SetDpi(m_dpi, m_dpi);
00170
00171         // Often a DPI change implies a window size change. In some cases Windows will issue
00172         // both a size changed event and a DPI changed event. In this case, the resulting bounds
00173         // will not change, and the window resize code will only be executed once.
00174         UpdateForWindowSizeChange();
00175     }
00176 }
00177
00178 // This routine is called in the event handler for the view SizeChanged event.
00179 void DirectXBase::UpdateForWindowSizeChange()
00180 {
00181     // Only handle window size changed if there is no pending DPI change.
00182     if (m_dpi != DisplayProperties::LogicalDpi)
00183     {
00184         return;
00185     }
00186
00187     if (m_window->Bounds.Width  != m_windowBounds.Width ||
00188         m_window->Bounds.Height != m_windowBounds.Height)
00189     {
00190         m_d2dContext->SetTarget(nullptr);
00191         m_d2dTargetBitmap = nullptr;
00192         m_d3dRenderTargetView = nullptr;
00193         m_d3dDepthStencilView = nullptr;
00194         m_windowSizeChangeInProgress = true;
00195         CreateWindowSizeDependentResources();
00196     }
00197 }
00198
00199 // Allocate all memory resources that change on a window SizeChanged event.
00200 void DirectXBase::CreateWindowSizeDependentResources()
00201 {
00202     // Store the window bounds so the next time we get a SizeChanged event we can
00203     // avoid rebuilding everything if the size is identical.
00204     m_windowBounds = m_window->Bounds;
00205
00206     if (m_swapChain != nullptr)
00207     {
00208         // If the swap chain already exists, resize it.
00209         HRESULT hr = m_swapChain->ResizeBuffers(2, 0, 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0);
00210
00211         if (hr == DXGI_ERROR_DEVICE_REMOVED)
00212         {
00213             // If the device was removed for any reason, a new device and swapchain will need to be created.
00214             HandleDeviceLost();
00215
00216             // Everything is set up now. Do not continue execution of this method.
00217             return;
00218         }
00219         else
00220         {
00221             DX::ThrowIfFailed(hr);
00222         }
00223     }
00224     else
00225     {
00226         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00227         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00228         swapChainDesc.Width = 0;                                     // Use automatic sizing.
00229         swapChainDesc.Height = 0;
00230         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;           // This is the most common swap chain format.
00231         swapChainDesc.Stereo = false;
00232         swapChainDesc.SampleDesc.Count = 1;                          // Don't use multi-sampling.
00233         swapChainDesc.SampleDesc.Quality = 0;
00234         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00235         swapChainDesc.BufferCount = 2;                               // Use double-buffering to minimize latency.
00236         swapChainDesc.Scaling = DXGI_SCALING_NONE;
00237         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Metro style apps must use this SwapEffect.
00238         swapChainDesc.Flags = 0;
00239
00240         ComPtr<IDXGIDevice1> dxgiDevice;
00241         DX::ThrowIfFailed(
00242             m_d3dDevice.As(&dxgiDevice)
00243             );
00244
00245         ComPtr<IDXGIAdapter> dxgiAdapter;
00246         DX::ThrowIfFailed(
00247             dxgiDevice->GetAdapter(&dxgiAdapter)
00248             );
00249
00250         ComPtr<IDXGIFactory2> dxgiFactory;
00251         DX::ThrowIfFailed(
00252             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00253             );
00254
00255         CoreWindow^ window = m_window.Get();
00256         DX::ThrowIfFailed(
00257             dxgiFactory->CreateSwapChainForCoreWindow(
00258                 m_d3dDevice.Get(),
00259                 reinterpret_cast<IUnknown*>(window),
00260                 &swapChainDesc,
00261                 nullptr,
00262                 &m_swapChain
00263                 )
00264             );
00265
00266         // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
00267         // ensures that the application will only render after each VSync, minimizing power consumption.
00268         DX::ThrowIfFailed(
00269             dxgiDevice->SetMaximumFrameLatency(1)
00270             );
00271     }
00272
00273     // Create a Direct3D render target view of the swap chain back buffer.
00274     ComPtr<ID3D11Texture2D> backBuffer;
00275     DX::ThrowIfFailed(
00276         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00277         );
00278
00279     DX::ThrowIfFailed(
00280         m_d3dDevice->CreateRenderTargetView(
00281             backBuffer.Get(),
00282             nullptr,
00283             &m_d3dRenderTargetView
00284             )
00285         );
00286
00287     // Cache the rendertarget dimensions in our helper class for convenient use.
00288     D3D11_TEXTURE2D_DESC backBufferDesc = {0};
00289     backBuffer->GetDesc(&backBufferDesc);
00290     m_renderTargetSize.Width  = static_cast<float>(backBufferDesc.Width);
00291     m_renderTargetSize.Height = static_cast<float>(backBufferDesc.Height);
00292
00293     // Create a depth stencil view for use with 3D rendering if needed.
00294     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00295         DXGI_FORMAT_D24_UNORM_S8_UINT,
00296         backBufferDesc.Width,
00297         backBufferDesc.Height,
00298         1,
00299         1,
00300         D3D11_BIND_DEPTH_STENCIL
00301         );
00302
00303     ComPtr<ID3D11Texture2D> depthStencil;
00304     DX::ThrowIfFailed(
00305         m_d3dDevice->CreateTexture2D(
00306             &depthStencilDesc,
00307             nullptr,
00308             &depthStencil
00309             )
00310         );
00311
00312     auto viewDesc = CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D);
00313     DX::ThrowIfFailed(
00314         m_d3dDevice->CreateDepthStencilView(
00315             depthStencil.Get(),
00316             &viewDesc,
00317             &m_d3dDepthStencilView
00318             )
00319         );
00320
00321     // Set the 3D rendering viewport to target the entire window.
00322     CD3D11_VIEWPORT viewport(
00323         0.0f,
00324         0.0f,
00325         static_cast<float>(backBufferDesc.Width),
00326         static_cast<float>(backBufferDesc.Height)
00327         );
00328
00329     m_d3dContext->RSSetViewports(1, &viewport);
00330
00331     // Create a Direct2D target bitmap associated with the
00332     // swap chain back buffer and set it as the current target.
00333     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00334         BitmapProperties1(
00335             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00336             PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00337             m_dpi,
00338             m_dpi
00339             );
00340
00341     ComPtr<IDXGISurface> dxgiBackBuffer;
00342     DX::ThrowIfFailed(
00343         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00344         );
00345
00346     DX::ThrowIfFailed(
00347         m_d2dContext->CreateBitmapFromDxgiSurface(
00348             dxgiBackBuffer.Get(),
00349             &bitmapProperties,
00350             &m_d2dTargetBitmap
00351             )
00352         );
00353
00354     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00355
00356     // Grayscale text anti-aliasing is recommended for all Metro style apps.
00357     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00358 }
00359
00360 // Method to deliver the final image to the display.
00361 void DirectXBase::Present()
00362 {
00363     // The application may optionally specify "dirty" or "scroll" rects to improve efficiency
00364     // in certain scenarios.  In this sample, however, we do not utilize those features.
00365     DXGI_PRESENT_PARAMETERS parameters = {0};
00366     parameters.DirtyRectsCount = 0;
00367     parameters.pDirtyRects = nullptr;
00368     parameters.pScrollRect = nullptr;
00369     parameters.pScrollOffset = nullptr;
00370
00371     // The first argument instructs DXGI to block until VSync, putting the application
00372     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00373     // frames that will never be displayed to the screen.
00374     HRESULT hr = m_swapChain->Present1(1, 0, &parameters);
00375
00376     // Discard the contents of the render target.
00377     // This is a valid operation only when the existing contents will be entirely
00378     // overwritten. If dirty or scroll rects are used, this call should be removed.
00379     m_d3dContext->DiscardView(m_d3dRenderTargetView.Get());
00380
00381     // Discard the contents of the depth stencil.
00382     m_d3dContext->DiscardView(m_d3dDepthStencilView.Get());
00383
00384     // If the device was removed either by a disconnect or a driver upgrade, we
00385     // must recreate all device resources.
00386     if (hr == DXGI_ERROR_DEVICE_REMOVED)
00387     {
00388         HandleDeviceLost();
00389     }
00390     else
00391     {
00392         DX::ThrowIfFailed(hr);
00393     }
00394
00395     if (m_windowSizeChangeInProgress)
00396     {
00397         // A window size change has been initiated and the app has just completed presenting
00398         // the first frame with the new size. Notify the resize manager so we can short
00399         // circuit any resize animation and prevent unnecessary delays.
00400         CoreWindowResizeManager::GetForCurrentView()->NotifyLayoutCompleted();
00401         m_windowSizeChangeInProgress = false;
00402     }
00403 }
00404
00405 void DirectXBase::ValidateDevice()
00406 {
00407     // The D3D Device is no longer valid if the default adapter changes or if
00408     // the device has been removed.
00409
00410     // First, get the information for the adapter related to the current device.
00411
00412     ComPtr<IDXGIDevice1> dxgiDevice;
00413     ComPtr<IDXGIAdapter> deviceAdapter;
00414     DXGI_ADAPTER_DESC deviceDesc;
00415     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00416     DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter));
00417     DX::ThrowIfFailed(deviceAdapter->GetDesc(&deviceDesc));
00418
00419     // Next, get the information for the default adapter.
00420
00421     ComPtr<IDXGIFactory2> dxgiFactory;
00422     ComPtr<IDXGIAdapter1> currentAdapter;
00423     DXGI_ADAPTER_DESC currentDesc;
00424     DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)));
00425     DX::ThrowIfFailed(dxgiFactory->EnumAdapters1(0, &currentAdapter));
00426     DX::ThrowIfFailed(currentAdapter->GetDesc(&currentDesc));
00427
00428     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00429     // a new D3D device must be created.
00430
00431     if ((deviceDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart) ||
00432         (deviceDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart) ||
00433         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00434     {
00435         // Release references to resources related to the old device.
00436         dxgiDevice = nullptr;
00437         deviceAdapter = nullptr;
00438
00439         // Create a new device and swap chain.
00440         HandleDeviceLost();
00441     }
00442 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CryptoWinRT/C++/Scenario1.xaml.h Source File

  • CryptoWinRT

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 SDKSample
00023 {
00024     namespace CryptoWinRT
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 Scenario1 sealed
00031         {
00032         public:
00033             Scenario1();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void RunSample_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-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.
__pad0__ FaceMesh
Generated on Sat Nov 23 2024 16:09:12 for Win8-Examples by doxygen 1.7.1


Win8-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.
__pad0__ | Level4 |
Initialize(std::vector< GameObject^> objects) override | Level4 | [virtual]
Initialize(std::vector< GameObject^> objects) override | Level4 | [virtual]
LoadState(PersistentState^state) override | Level4 | [virtual]
LoadState(PersistentState^state) override | Level4 | [virtual]
m_nextId | Level4 | [private]
SaveState(PersistentState^state) override | Level4 | [virtual]
SaveState(PersistentState^state) override | Level4 | [virtual]
Update(float time, float elapsedTime, float timeRemaining, std::vector< GameObject^> objects) override | Level4 | [virtual]
Update(float time, float elapsedTime, float timeRemaining, std::vector< GameObject^> objects) override | Level4 | [virtual]
Generated on Sat Nov 23 2024 16:09:15 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Certificate enrollment/C++/Constants.cpp Source File

  • Certificate enrollment

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
00021     { "Enroll for a certificate", "SDKSample.CertificateEnrollment.Scenario_Enroll" },
00022     { "Import an existing certificate", "SDKSample.CertificateEnrollment.Scenario_Import" },
00023 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Real-time communication/C++/MediaExtensions/Common/AsyncCB.h Source File

  • Real-time communication
  • MediaExtensions
  • Common

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 Sat Nov 23 2024 16:08:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CryptoWinRT/C++/Scenario5.xaml.h Source File

  • CryptoWinRT

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 SDKSample
00023 {
00024     namespace CryptoWinRT
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 Scenario5 sealed
00031         {
00032         public:
00033             Scenario5();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040             void RunSample_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         };
00042     }
00043 }
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Touch keyboard text input/C++/pch.h Source File

  • Input Touch keyboard text input

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Splash screen/C++/MainPage.xaml.cpp Source File

  • Splash screen

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "ExtendedSplash.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace SDKSample;
00023 using namespace SDKSample::SplashScreen;
00024
00025 using namespace Windows::UI::Xaml;
00026 using namespace Windows::UI::Xaml::Controls;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Platform;
00030 using namespace Windows::UI::Xaml::Navigation;
00031 using namespace Windows::UI::Xaml::Interop;
00032 using namespace Windows::Graphics::Display;
00033 using namespace Windows::UI::ViewManagement;
00034
00035 MainPage^ MainPage::Current = nullptr;
00036
00037 MainPage::MainPage()
00038 {
00039     InitializeComponent();
00040
00041     // This frame is hidden, meaning it is never shown.  It is simply used to load
00042     // each scenario page and then pluck out the input and output sections and
00043     // place them into the UserControls on the main page.
00044     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00045     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00046     LayoutRoot->Children->Append(HiddenFrame);
00047
00048     FeatureName->Text = FEATURE_NAME;
00049
00050     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00051     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00052
00053     MainPage::Current = this;
00054     autoSizeInputSectionWhenSnapped = true;
00055 }
00056
00057 /// <summary>
00058 /// We need to handle SizeChanged so that we can make the sample layout property
00059 /// in the various layouts.
00060 /// </summary>
00061 /// <param name="sender"></param>
00062 /// <param name="e"></param>
00063 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00064 {
00065     InvalidateSize();
00066     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00067     args->ViewState = ApplicationView::Value;
00068     MainPageResized(this, args);
00069
00070 }
00071
00072 void MainPage::InvalidateSize()
00073 {
00074     // Get the window width
00075     double windowWidth = this->ActualWidth;
00076
00077     if (windowWidth != 0.0)
00078     {
00079         // Get the width of the ListBox.
00080         double listBoxWidth = Scenarios->ActualWidth;
00081
00082         // Is the ListBox using any margins that we need to consider?
00083         double listBoxMarginLeft = Scenarios->Margin.Left;
00084         double listBoxMarginRight = Scenarios->Margin.Right;
00085
00086         // Figure out how much room is left after considering the list box width
00087         double availableWidth = windowWidth - listBoxWidth;
00088
00089         // Is the top most child using margins?
00090         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00091         double layoutRootMarginRight = ContentRoot->Margin.Right;
00092
00093         // We have different widths to use depending on the view state
00094         if (ApplicationView::Value != ApplicationViewState::Snapped)
00095         {
00096             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00097             // and the LayoutRoot's margins
00098             InputSection->Width = ((availableWidth) -
00099                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00100         }
00101         else
00102         {
00103             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00104             if (autoSizeInputSectionWhenSnapped)
00105             {
00106                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00107             }
00108         }
00109     }
00110     InvalidateViewState();
00111 }
00112
00113 void MainPage::InvalidateViewState()
00114 {
00115     // Are we going to snapped mode?
00116     if (ApplicationView::Value == ApplicationViewState::Snapped)
00117     {
00118         Grid::SetRow(DescriptionText, 3);
00119         Grid::SetColumn(DescriptionText, 0);
00120
00121         Grid::SetRow(InputSection, 4);
00122         Grid::SetColumn(InputSection, 0);
00123
00124         Grid::SetRow(FooterPanel, 2);
00125         Grid::SetColumn(FooterPanel, 0);
00126     }
00127     else
00128     {
00129         Grid::SetRow(DescriptionText, 1);
00130         Grid::SetColumn(DescriptionText, 1);
00131
00132         Grid::SetRow(InputSection, 2);
00133         Grid::SetColumn(InputSection, 1);
00134
00135         Grid::SetRow(FooterPanel, 1);
00136         Grid::SetColumn(FooterPanel, 1);
00137     }
00138
00139     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00140     // input and output sections from the page) we need to ensure that any VSM code used
00141     // by the scenario's input and output sections is fired.
00142     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00143     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00144 }
00145
00146 void MainPage::PopulateScenarios()
00147 {
00148     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00149
00150     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00151     for (unsigned int i = 0; i < scenarios->Length; ++i)
00152     {
00153         Scenario s = scenarios[i];
00154         ListBoxItem^ item = ref new ListBoxItem();
00155         item->Name = s.ClassName;
00156         item->Content = (i + 1).ToString() + ") " + s.Title;
00157         ScenarioList->Append(item);
00158     }
00159
00160     // Bind the ListBox to the scenario list.
00161     Scenarios->ItemsSource = ScenarioList;
00162 }
00163
00164 /// <summary>
00165 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00166 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00167 /// and output sections into the respective UserControl on the main page.
00168 /// </summary>
00169 /// <param name="scenarioName"></param>
00170 void MainPage::LoadScenario(String^ scenarioName)
00171 {
00172     autoSizeInputSectionWhenSnapped = true;
00173
00174     // Load the ScenarioX.xaml file into the Frame.
00175     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00176     HiddenFrame->Navigate(scenarioType, this);
00177
00178     // Get the top element, the Page, so we can look up the elements
00179     // that represent the input and output sections of the ScenarioX file.
00180     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00181
00182     // Get each element.
00183     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00184     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00185
00186     if (input == nullptr)
00187     {
00188         // Malformed input section.
00189         NotifyUser("Cannot load scenario input section for " + scenarioName +
00190             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00191         return;
00192     }
00193
00194     if (output == nullptr)
00195     {
00196         // Malformed output section.
00197         NotifyUser("Cannot load scenario output section for " + scenarioName +
00198             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00199         return;
00200     }
00201
00202     // Find the LayoutRoot which parents the input and output sections in the main page.
00203     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00204
00205     if (panel != nullptr)
00206     {
00207         unsigned int index = 0;
00208         UIElementCollection^ collection = panel->Children;
00209
00210         // Get rid of the content that is currently in the intput and output sections.
00211         collection->IndexOf(input, &index);
00212         collection->RemoveAt(index);
00213
00214         collection->IndexOf(output, &index);
00215         collection->RemoveAt(index);
00216
00217         // Populate the input and output sections with the newly loaded content.
00218         InputSection->Content = input;
00219         OutputSection->Content = output;
00220
00221         ScenarioLoaded(this, nullptr);
00222     }
00223     else
00224     {
00225         // Malformed Scenario file.
00226         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00227             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00228     }
00229 }
00230
00231 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00232 {
00233     if (Scenarios->SelectedItem != nullptr)
00234     {
00235         NotifyUser("", NotifyType::StatusMessage);
00236
00237         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00238         InvalidateSize();
00239     }
00240 }
00241
00242 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00243 {
00244     switch (type)
00245     {
00246     case NotifyType::StatusMessage:
00247         // Use the status message style.
00248         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00249         break;
00250     case NotifyType::ErrorMessage:
00251         // Use the error message style.
00252         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00253         break;
00254     default:
00255         break;
00256     }
00257     StatusBlock->Text = strMessage;
00258
00259     // Collapsed the StatusBlock if it has no text to conserve real estate.
00260     if (StatusBlock->Text != "")
00261     {
00262         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00263     }
00264     else
00265     {
00266         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00267     }
00268 }
00269
00270 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00271 {
00272     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00273     Windows::System::Launcher::LaunchUriAsync(uri);
00274 }
00275
00276
00277 /// <summary>
00278 /// Populates the page with content passed during navigation.  Any saved state is also
00279 /// provided when recreating a page from a prior session.
00280 /// </summary>
00281 /// <param name="navigationParameter">The parameter value passed to
00282 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00283 /// </param>
00284 /// <param name="pageState">A map of state preserved by this page during an earlier
00285 /// session.  This will be null the first time a page is visited.</param>
00286 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00287 {
00288     (void) navigationParameter;    // Unused parameter
00289
00290     PopulateScenarios();
00291
00292     // Starting scenario is the first or based upon a previous state.
00293     ListBoxItem^ startingScenario = nullptr;
00294     int startingScenarioIndex = -1;
00295
00296     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00297     {
00298         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00299     }
00300
00301     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00302
00303     InvalidateViewState();
00304 }
00305
00306 /// <summary>
00307 /// Preserves state associated with this page in case the application is suspended or the
00308 /// page is discarded from the navigation cache.  Values must conform to the serialization
00309 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00310 /// </summary>
00311 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00312 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00313 {
00314     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00315     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00316 }
00317
00318 void MainPage::SetExtendedSplashInfo(Rect splashRect, bool dismissStat)
00319 {
00320     SplashImageRect = splashRect;
00321     Dismissed = dismissStat;
00322     LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00323 }
Generated on Sat Nov 23 2024 16:07:44 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML AppBar control/C++/common/LayoutAwarePage.cpp Source File

  • XAML AppBar control
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013
00014 using namespace AppBarControl::Common;
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::UI::ViewManagement;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Interop;
00024
00025 /// <summary>
00026 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00027 /// </summary>
00028 LayoutAwarePage::LayoutAwarePage()
00029 {
00030     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled) return;
00031
00032     // Create an empty default view model
00033     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00034
00035     // Map application view state to visual state for this page when it is part of the visual tree
00036     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::StartLayoutUpdates);
00037     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::StopLayoutUpdates);
00038 }
00039
00040 static TypeName _thisType = { LayoutAwarePage::typeid->FullName, TypeKind::Custom };
00041 static TypeName _observableMapType = { IObservableMap<Platform::String^, Object^>::typeid->FullName, TypeKind::Metadata };
00042 static Windows::UI::Xaml::DependencyProperty^ _defaultViewModelProperty =
00043     DependencyProperty::Register("DefaultViewModel", _observableMapType, _thisType, nullptr);
00044
00045 /// <summary>
00046 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00047 /// </summary>
00048 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00049 {
00050     return _defaultViewModelProperty;
00051 }
00052
00053 /// <summary>
00054 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00055 /// used as a trivial view model.
00056 /// </summary>
00057 IObservableMap<Platform::String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00058 {
00059     return safe_cast<Windows::Foundation::Collections::IObservableMap<Platform::String^, Object^>^>(GetValue(DefaultViewModelProperty));
00060 }
00061
00062 /// <summary>
00063 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00064 /// used as a trivial view model.
00065 /// </summary>
00066 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<Platform::String^, Object^>^ value)
00067 {
00068     SetValue(DefaultViewModelProperty, value);
00069 }
00070
00071 /// <summary>
00072 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00073 /// until it reaches the top of the navigation stack.
00074 /// </summary>
00075 /// <param name="sender">Instance that triggered the event.</param>
00076 /// <param name="e">Event data describing the conditions that led to the event.</param>
00077 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00078 {
00079     // Use the navigation frame to return to the topmost page
00080     if (Frame != nullptr)
00081     {
00082         while (Frame->CanGoBack) Frame->GoBack();
00083     }
00084 }
00085
00086 /// <summary>
00087 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00088 /// to go back one step on the navigation stack.
00089 /// </summary>
00090 /// <param name="sender">Instance that triggered the event.</param>
00091 /// <param name="e">Event data describing the conditions that led to the event.</param>
00092 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00093 {
00094     // Use the navigation frame to return to the previous page
00095     if (Frame != nullptr && Frame->CanGoBack) Frame->GoBack();
00096 }
00097
00098 /// <summary>
00099 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00100 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00101 /// visual state management changes that correspond to application view state changes.
00102 /// </summary>
00103 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00104 /// corresponding to view states.</param>
00105 /// <param name="e">Event data that describes how the request was made.</param>
00106 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00107 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00108 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00109 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00110 /// events.</remarks>
00111 /// <seealso cref="DetermineVisualState"/>
00112 /// <seealso cref="InvalidateVisualState"/>
00113 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00114 {
00115     auto control = safe_cast<Control^>(sender);
00116     if (_layoutAwareControls == nullptr) {
00117         // Start listening to view state changes when there are controls interested in updates
00118         _layoutAwareControls = ref new Vector<Control^>();
00119         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00120     }
00121     _layoutAwareControls->Append(control);
00122
00123     // Set the initial visual state of the control
00124     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00125 }
00126
00127 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00128 {
00129     InvalidateVisualState();
00130 }
00131
00132 /// <summary>
00133 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00134 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00135 /// management changes that correspond to application view state changes.
00136 /// </summary>
00137 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00138 /// corresponding to view states.</param>
00139 /// <param name="e">Event data that describes how the request was made.</param>
00140 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00141 /// when layout updates are requested.</remarks>
00142 /// <seealso cref="StartLayoutUpdates"/>
00143 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00144 {
00145     auto control = safe_cast<Control^>(sender);
00146     unsigned int index;
00147     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00148     {
00149         _layoutAwareControls->RemoveAt(index);
00150         if (_layoutAwareControls->Size == 0)
00151         {
00152             // Stop listening to view state changes when no controls are interested in updates
00153             Window::Current->SizeChanged -= _windowSizeEventToken;
00154             _layoutAwareControls = nullptr;
00155         }
00156     }
00157 }
00158
00159 /// <summary>
00160 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00161 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00162 /// override this method to control the mapping scheme used.
00163 /// </summary>
00164 /// <param name="viewState">View state for which a visual state is desired.</param>
00165 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00166 /// <seealso cref="InvalidateVisualState"/>
00167 Platform::String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00168 {
00169     switch (viewState)
00170     {
00171     case ApplicationViewState::Filled: return "Filled";
00172     case ApplicationViewState::Snapped: return "Snapped";
00173     case ApplicationViewState::FullScreenPortrait: return "FullScreenPortrait";
00174     default: case ApplicationViewState::FullScreenLandscape: return "FullScreenLandscape";
00175     }
00176 }
00177
00178 /// <summary>
00179 /// Updates all controls that are listening for visual state changes with the correct visual
00180 /// state.
00181 /// </summary>
00182 /// <remarks>
00183 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00184 /// signal that a different value may be returned even though the view state has not changed.
00185 /// </remarks>
00186 void LayoutAwarePage::InvalidateVisualState()
00187 {
00188     if (_layoutAwareControls != nullptr)
00189     {
00190         String^ visualState = DetermineVisualState(ApplicationView::Value);
00191         auto controlIterator = _layoutAwareControls->First();
00192         while (controlIterator->HasCurrent)
00193         {
00194             auto control = controlIterator->Current;
00195             VisualStateManager::GoToState(control, visualState, false);
00196             controlIterator->MoveNext();
00197         }
00198     }
00199 }
Generated on Sat Nov 23 2024 16:07:33 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File picker contracts/C++/CachedFileUpdaterPage.xaml.cpp Source File

  • File picker contracts

CachedFileUpdaterPage.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 // CachedFileUpdaterPage.xaml.cpp
00013 // Implementation of the CachedFileUpdaterPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "CachedFileUpdaterPage.xaml.h"
00018 #include "Constants.h"
00019 #include "App.xaml.h"
00020
00021 #include <collection.h>
00022
00023 using namespace SDKSample;
00024 using namespace SDKSample::Common;
00025 using namespace SDKSample::FilePickerContracts;
00026 using namespace Platform;
00027 using namespace Windows::ApplicationModel::Activation;
00028 using namespace Windows::Foundation;
00029 using namespace Windows::Foundation::Collections;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::Storage::Provider;
00032 using namespace Windows::UI::ViewManagement;
00033 using namespace Windows::UI::Xaml;
00034 using namespace Windows::UI::Xaml::Controls;
00035 using namespace Windows::UI::Xaml::Interop;
00036 using namespace Windows::UI::Xaml::Navigation;
00037
00038 CachedFileUpdaterPage^ CachedFileUpdaterPage::Current = nullptr;
00039
00040 CachedFileUpdaterPage::CachedFileUpdaterPage()
00041 {
00042     InitializeComponent();
00043
00044     // This frame is hidden, meaning it is never shown.  It is simply used to load
00045     // each scenario page and then pluck out the input and output sections and
00046     // place them into the UserControls on the main page.
00047     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00048     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00049     LayoutRoot->Children->Append(HiddenFrame);
00050
00051     FeatureName->Text = FEATURE_NAME;
00052
00053     this->SizeChanged += ref new SizeChangedEventHandler(this, &CachedFileUpdaterPage::CachedFileUpdaterPage_SizeChanged);
00054     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &CachedFileUpdaterPage::Scenarios_SelectionChanged);
00055
00056     CachedFileUpdaterPage::Current = this;
00057     autoSizeInputSectionWhenSnapped = true;
00058 }
00059
00060 /// <summary>
00061 /// We need to handle SizeChanged so that we can make the sample layout property
00062 /// in the various layouts.
00063 /// </summary>
00064 /// <param name="sender"></param>
00065 /// <param name="e"></param>
00066 void CachedFileUpdaterPage::CachedFileUpdaterPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00067 {
00068     InvalidateSize();
00069     PageSizeChangedEventArgs^ args = ref new PageSizeChangedEventArgs();
00070     args->ViewState = ApplicationView::Value;
00071     PageResized(this, args);
00072 }
00073
00074 void CachedFileUpdaterPage::InvalidateSize()
00075 {
00076     // Get the window width
00077     double windowWidth = this->ActualWidth;
00078
00079     if (windowWidth != 0.0)
00080     {
00081         // Get the width of the ListBox.
00082         double listBoxWidth = Scenarios->ActualWidth;
00083
00084         // Is the ListBox using any margins that we need to consider?
00085         double listBoxMarginLeft = Scenarios->Margin.Left;
00086         double listBoxMarginRight = Scenarios->Margin.Right;
00087
00088         // Figure out how much room is left after considering the list box width
00089         double availableWidth = windowWidth - listBoxWidth;
00090
00091         // Is the top most child using margins?
00092         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00093         double layoutRootMarginRight = ContentRoot->Margin.Right;
00094
00095         // We have different widths to use depending on the view state
00096         if (ApplicationView::Value != ApplicationViewState::Snapped)
00097         {
00098             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00099             // and the LayoutRoot's margins
00100             InputSection->Width = availableWidth - (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight);
00101         }
00102         else
00103         {
00104             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00105             if (autoSizeInputSectionWhenSnapped)
00106             {
00107                 InputSection->Width = windowWidth - (layoutRootMarginLeft + layoutRootMarginRight);
00108             }
00109         }
00110     }
00111     InvalidateViewState();
00112 }
00113
00114 void CachedFileUpdaterPage::InvalidateViewState()
00115 {
00116     // Are we going to snapped mode?
00117     if (ApplicationView::Value == ApplicationViewState::Snapped)
00118     {
00119         Grid::SetRow(DescriptionText, 3);
00120         Grid::SetColumn(DescriptionText, 0);
00121
00122         Grid::SetRow(InputSection, 4);
00123         Grid::SetColumn(InputSection, 0);
00124
00125         Grid::SetRow(FooterPanel, 2);
00126         Grid::SetColumn(FooterPanel, 0);
00127     }
00128     else
00129     {
00130         Grid::SetRow(DescriptionText, 1);
00131         Grid::SetColumn(DescriptionText, 1);
00132
00133         Grid::SetRow(InputSection, 2);
00134         Grid::SetColumn(InputSection, 1);
00135
00136         Grid::SetRow(FooterPanel, 1);
00137         Grid::SetColumn(FooterPanel, 1);
00138     }
00139
00140     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00141     // input and output sections from the page) we need to ensure that any VSM code used
00142     // by the scenario's input and output sections is fired.
00143     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00144     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00145 }
00146
00147 void CachedFileUpdaterPage::PopulateScenarios()
00148 {
00149     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00150
00151     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00152     for (unsigned int i = 0; i < scenarios->Length; ++i)
00153     {
00154         Scenario s = scenarios[i];
00155         ListBoxItem^ item = ref new ListBoxItem();
00156         item->Name = s.ClassName;
00157         item->Content = (i + 1).ToString() + ") " + s.Title;
00158         ScenarioList->Append(item);
00159     }
00160
00161     // Bind the ListBox to the scenario list.
00162     Scenarios->ItemsSource = ScenarioList;
00163 }
00164
00165 /// <summary>
00166 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00167 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00168 /// and output sections into the respective UserControl on the main page.
00169 /// </summary>
00170 /// <param name="scenarioName"></param>
00171 void CachedFileUpdaterPage::LoadScenario(String^ scenarioName)
00172 {
00173     autoSizeInputSectionWhenSnapped = true;
00174
00175     // Load the ScenarioX.xaml file into the Frame.
00176     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00177     HiddenFrame->Navigate(scenarioType, this);
00178
00179     // Get the top element, the Page, so we can look up the elements
00180     // that represent the input and output sections of the ScenarioX file.
00181     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00182
00183     // Get each element.
00184     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00185     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00186
00187     if (input == nullptr)
00188     {
00189         // Malformed input section.
00190         NotifyUser("Cannot load scenario input section for " + scenarioName +
00191             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00192         return;
00193     }
00194
00195     if (output == nullptr)
00196     {
00197         // Malformed output section.
00198         NotifyUser("Cannot load scenario output section for " + scenarioName +
00199             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00200         return;
00201     }
00202
00203     // Find the LayoutRoot which parents the input and output sections in the main page.
00204     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00205
00206     if (panel != nullptr)
00207     {
00208         unsigned int index = 0;
00209         UIElementCollection^ collection = panel->Children;
00210
00211         // Get rid of the content that is currently in the intput and output sections.
00212         collection->IndexOf(input, &index);
00213         collection->RemoveAt(index);
00214
00215         collection->IndexOf(output, &index);
00216         collection->RemoveAt(index);
00217
00218         // Populate the input and output sections with the newly loaded content.
00219         InputSection->Content = input;
00220         OutputSection->Content = output;
00221
00222         ScenarioLoaded(this, nullptr);
00223     }
00224     else
00225     {
00226         // Malformed Scenario file.
00227         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00228             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00229     }
00230 }
00231
00232 void CachedFileUpdaterPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00233 {
00234     if (Scenarios->SelectedItem != nullptr)
00235     {
00236         NotifyUser("", NotifyType::StatusMessage);
00237
00238         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00239         InvalidateSize();
00240     }
00241 }
00242
00243 void CachedFileUpdaterPage::NotifyUser(String^ strMessage, NotifyType type)
00244 {
00245     switch (type)
00246     {
00247     case NotifyType::StatusMessage:
00248         // Use the status message style.
00249         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00250         break;
00251     case NotifyType::ErrorMessage:
00252         // Use the error message style.
00253         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00254         break;
00255     default:
00256         break;
00257     }
00258     StatusBlock->Text = strMessage;
00259
00260     // Collapsed the StatusBlock if it has no text to conserve real estate.
00261     if (StatusBlock->Text != "")
00262     {
00263         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00264     }
00265     else
00266     {
00267         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00268     }
00269 }
00270
00271 void CachedFileUpdaterPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00272 {
00273     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00274     Windows::System::Launcher::LaunchUriAsync(uri);
00275 }
00276
00277 /// <summary>
00278 /// Populates the page with content passed during navigation.  Any saved state is also
00279 /// provided when recreating a page from a prior session.
00280 /// </summary>
00281 /// <param name="navigationParameter">The parameter value passed to
00282 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00283 /// </param>
00284 /// <param name="pageState">A map of state preserved by this page during an earlier
00285 /// session.  This will be null the first time a page is visited.</param>
00286 void CachedFileUpdaterPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00287 {
00288     (void) navigationParameter; // Unused parameter
00289
00290     PopulateScenarios();
00291
00292     // Starting scenario is the first or based upon a previous state.
00293     ListBoxItem^ startingScenario = nullptr;
00294     int startingScenarioIndex = -1;
00295
00296     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00297     {
00298         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00299     }
00300
00301     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00302
00303     InvalidateViewState();
00304 }
00305
00306 /// <summary>
00307 /// Preserves state associated with this page in case the application is suspended or the
00308 /// page is discarded from the navigation cache.  Values must conform to the serialization
00309 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00310 /// </summary>
00311 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00312 void CachedFileUpdaterPage::SaveState(IMap<String^, Object^>^ pageState)
00313 {
00314     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00315     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00316 }
00317
00318 bool CachedFileUpdaterPage::EnsureUnsnapped()
00319 {
00320     // FilePicker APIs will not work if the application is in a snapped state.
00321     // If an app wants to show a FilePicker while snapped, it must attempt to unsnap first
00322     bool unsnapped = ((ApplicationView::Value != ApplicationViewState::Snapped) || ApplicationView::TryUnsnap());
00323     if (!unsnapped)
00324     {
00325         NotifyUser("Cannot unsnap the sample application", NotifyType::StatusMessage);
00326     }
00327
00328     return unsnapped;
00329 }
00330
00331 void CachedFileUpdaterPage::Activate(CachedFileUpdaterActivatedEventArgs^ args)
00332 {
00333     // cache CachedFileUpdaterUI
00334     cachedFileUpdaterUI = args->CachedFileUpdaterUI;
00335
00336     cachedFileUpdaterUI->FileUpdateRequested += ref new TypedEventHandler<CachedFileUpdaterUI^, FileUpdateRequestedEventArgs^>(this, &CachedFileUpdaterPage::OnFileUpdateRequested, CallbackContext::Same);
00337     cachedFileUpdaterUI->UIRequested += ref new TypedEventHandler<CachedFileUpdaterUI^, Platform::Object^>(this, &CachedFileUpdaterPage::OnUIRequested, CallbackContext::Same);
00338
00339     Window::Current->Activate();
00340 }
00341
00342 void CachedFileUpdaterPage::OnFileUpdateRequested(CachedFileUpdaterUI^ sender, FileUpdateRequestedEventArgs^ e)
00343 {
00344     fileUpdateRequest = e->Request;
00345     fileUpdateRequestDeferral = fileUpdateRequest->GetDeferral();
00346     switch (cachedFileUpdaterUI->UIStatus)
00347     {
00348     case UIStatus::Hidden:
00349         fileUpdateRequest->Status = FileUpdateStatus::UserInputNeeded;
00350         fileUpdateRequestDeferral->Complete();
00351         break;
00352     case UIStatus::Visible:
00353         break;
00354     case UIStatus::Unavailable:
00355         fileUpdateRequest->Status = FileUpdateStatus::Failed;
00356         fileUpdateRequestDeferral->Complete();
00357         break;
00358     }
00359 }
00360
00361 void CachedFileUpdaterPage::OnUIRequested(Windows::Storage::Provider::CachedFileUpdaterUI^ sender, Platform::Object^ e)
00362 {
00363     Window::Current->Content = this;
00364     LoadState(nullptr, nullptr);
00365 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML two-dimensional transforms/C++/Scenario1.xaml.cpp Source File

  • XAML two-dimensional transforms

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::Transforms;
00020
00021 using namespace Windows::Foundation;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Navigation;
00025 using namespace Windows::UI::Xaml::Data;
00026 using namespace Windows::UI::Xaml::Media;
00027
00028
00029 Scenario1::Scenario1()
00030 {
00031     InitializeComponent();
00032 }
00033
00034 // Invoked when this page is about to be displayed in a Frame.
00035 void Scenario1::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     rootPage->AutoSizeInputSectionWhenSnapped = false;
00041
00042   // Set up the bindings
00043   SetUpBinding(ScaleXSlider, CompositeTransform::ScaleXProperty);
00044   SetUpBinding(ScaleYSlider, CompositeTransform::ScaleYProperty);
00045   SetUpBinding(SkewXSlider, CompositeTransform::SkewXProperty);
00046   SetUpBinding(SkewYSlider, CompositeTransform::SkewYProperty);
00047   SetUpBinding(TranslateXSlider, CompositeTransform::TranslateXProperty);
00048   SetUpBinding(TranslateYSlider, CompositeTransform::TranslateYProperty);
00049   SetUpBinding(RotationSlider, CompositeTransform::RotationProperty);
00050 }
00051
00052 // Handlder for resizing of MainPage
00053 void SDKSample::Transforms::Scenario1::rootPage_MainPageResized(Platform::Object^ sender, MainPageSizeChangedEventArgs^ e)
00054 {
00055   if(e->ViewState == Windows::UI::ViewManagement::ApplicationViewState::Snapped)
00056   {
00057     InputTextBlock1->MaxWidth = 300;
00058   }
00059 }
00060
00061 // Sets up a binding
00062 void SDKSample::Transforms::Scenario1::SetUpBinding(Windows::UI::Xaml::Controls::Slider^ slider, Windows::UI::Xaml::DependencyProperty^ dp)
00063 {
00064   auto binding = ref new Binding();
00065   binding->Source = slider;
00066   binding->Path = ref new PropertyPath("Value");
00067   BindingOperations::SetBinding(ImageTransform, dp, binding);
00068 }
Generated on Sat Nov 23 2024 16:07:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DatagramSocket/C++/Scenario3.xaml.h Source File

  • DatagramSocket

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 DatagramSocketSample
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         void SendHello_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038     };
00039 }
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Bluetooth call control/C++/common/suspensionmanager.cpp Source File

  • Bluetooth call control
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CryptoWinRT/C++/pch.cpp Source File

  • CryptoWinRT

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 Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Splash screen/C++/ExtendedSplash.xaml.h Source File

  • Splash screen

ExtendedSplash.xaml.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
00009 #pragma once
00010
00011 #include "pch.h"
00012 #include "ExtendedSplash.g.h"
00013
00014 namespace SDKSample
00015 {
00016     namespace SplashScreen
00017     {
00018         [Windows::Foundation::Metadata::WebHostHidden]
00019         public ref class ExtendedSplash sealed
00020         {
00021         public:
00022             ExtendedSplash(Windows::ApplicationModel::Activation::SplashScreen^ splash, bool loadState);
00023
00024         private:
00025             Windows::ApplicationModel::Activation::SplashScreen^ splash; // Variable to hold the splash screen object.
00026             void DismissedEventHandler(Windows::ApplicationModel::Activation::SplashScreen^ sender, Object^ e);
00027             void LearnMoreButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00028             void ExtendedSplash_OnResize(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00029             void PositionImage();
00030
00031         internal:
00032             Windows::Foundation::Rect splashImageRect; // Rect to store splash screen image coordinates.
00033             bool dismissed; // Variable to track splash screen dismissal status.
00034             Windows::UI::Xaml::Controls::Frame^ rootFrame;
00035         };
00036     }
00037 }
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML FlipView control/C++/Scenario2.xaml.cpp Source File

  • XAML FlipView control

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 "SampleDataSource.h"
00019
00020 using namespace SDKSample::FlipViewCPP;
00021 using namespace SDKSample::FlipViewData;
00022
00023 using namespace Windows::UI::Xaml;
00024 using namespace Windows::UI::Xaml::Controls;
00025 using namespace Windows::UI::Xaml::Navigation;
00026
00027 Scenario2::Scenario2(): bHorizontal(true)
00028 {
00029     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 void Scenario2::OnNavigatedTo(NavigationEventArgs^ e)
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     rootPage = MainPage::Current;
00042
00043   SampleDataSource^ sampleData = ref new FlipViewData::SampleDataSource();
00044   FlipView2Horizontal->ItemsSource = sampleData->Items;
00045   FlipView2Vertical->ItemsSource = sampleData->Items;
00046 }
00047
00048 void Scenario2::Orientation_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00049 {
00050   bHorizontal = !bHorizontal;
00051     if (bHorizontal)
00052     {
00053         Orientation->Content = "Vertical";
00054         FlipView2Horizontal->SelectedIndex = FlipView2Vertical->SelectedIndex;
00055         FlipView2Horizontal->Visibility = Windows::UI::Xaml::Visibility::Visible;
00056         FlipView2Vertical->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00057     }
00058     else
00059     {
00060         Orientation->Content = "Horizontal";
00061         FlipView2Vertical->SelectedIndex = FlipView2Horizontal->SelectedIndex;
00062         FlipView2Vertical->Visibility =  Windows::UI::Xaml::Visibility::Visible;
00063         FlipView2Horizontal->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00064     }
00065 }
00066
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/texconv/BC.h Source File

  • Direct3D resource loading
  • texconv

BC.h

Go to the documentation of this file.
00001 //-------------------------------------------------------------------------------------
00002 // BC.h
00003 //
00004 // Block-compression (BC) functionality
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 #if defined(_MSC_VER) && (_MSC_VER > 1000)
00015 #pragma once
00016 #endif
00017
00018 #include <assert.h>
00019 #include <directxmath.h>
00020 #include <directxpackedvector.h>
00021 #include <float.h>
00022
00023 #pragma warning(push)
00024 #pragma warning(disable : 4005)
00025 #include <stdint.h>
00026 #pragma warning(pop)
00027
00028 namespace DirectX
00029 {
00030
00031 //-------------------------------------------------------------------------------------
00032 // Constants
00033 //-------------------------------------------------------------------------------------
00034
00035 const uint16_t F16S_MASK    = 0x8000;   // f16 sign mask
00036 const uint16_t F16EM_MASK   = 0x7fff;   // f16 exp & mantissa mask
00037 const uint16_t F16MAX       = 0x7bff;   // MAXFLT bit pattern for XMHALF
00038
00039 #define SIGN_EXTEND(x,nb) ((((x)&(1<<((nb)-1)))?((~0)<<(nb)):0)|(x))
00040
00041 // Because these are used in SAL annotations, they need to remain macros rather than const values
00042 #define NUM_PIXELS_PER_BLOCK 16
00043 #define BC6H_MAX_REGIONS 2
00044 #define BC6H_MAX_INDICES 16
00045 #define BC7_MAX_REGIONS 3
00046 #define BC7_MAX_INDICES 16
00047
00048 const size_t BC6H_NUM_CHANNELS = 3;
00049 const size_t BC6H_MAX_SHAPES = 32;
00050
00051 const size_t BC7_NUM_CHANNELS = 4;
00052 const size_t BC7_MAX_SHAPES = 64;
00053
00054 const uint32_t BC67_WEIGHT_MAX = 64;
00055 const uint32_t BC67_WEIGHT_SHIFT = 6;
00056 const uint32_t BC67_WEIGHT_ROUND = 32;
00057
00058 extern const int g_aWeights2[4];
00059 extern const int g_aWeights3[8];
00060 extern const int g_aWeights4[16];
00061
00062 enum BC_FLAGS
00063 {
00064     BC_FLAGS_NONE       = 0x0,
00065     BC_FLAGS_DITHER_RGB = 0x10000,  // Enables dithering for RGB colors for BC1-3
00066     BC_FLAGS_DITHER_A   = 0x20000,  // Enables dithering for Alpha channel for BC1-3
00067     BC_FLAGS_UNIFORM    = 0x40000,  // By default, uses perceptual weighting for BC1-3; this flag makes it a uniform weighting
00068 };
00069
00070 //-------------------------------------------------------------------------------------
00071 // Structures
00072 //-------------------------------------------------------------------------------------
00073 class HDRColorA;
00074
00075 class LDRColorA
00076 {
00077 public:
00078     uint8_t r, g, b, a;
00079
00080     LDRColorA() {}
00081     LDRColorA(uint8_t _r, uint8_t _g, uint8_t _b, uint8_t _a) : r(_r), g(_g), b(_b), a(_a) {}
00082
00083     const uint8_t& operator [] (_In_range_(0,3) size_t uElement) const
00084     {
00085         switch(uElement)
00086         {
00087         case 0: return r;
00088         case 1: return g;
00089         case 2: return b;
00090         case 3: return a;
00091         default: assert(false); return r;
00092         }
00093     }
00094
00095     uint8_t& operator [] (_In_range_(0,3) size_t uElement)
00096     {
00097         switch(uElement)
00098         {
00099         case 0: return r;
00100         case 1: return g;
00101         case 2: return b;
00102         case 3: return a;
00103         default: assert(false); return r;
00104         }
00105     }
00106
00107     LDRColorA operator = (_In_ const HDRColorA& c);
00108
00109     static void InterpolateRGB(_In_ const LDRColorA& c0, _In_ const LDRColorA& c1, _In_ size_t wc, _In_ _In_range_(2, 4) size_t wcprec, _Out_ LDRColorA& out)
00110     {
00111         const int* aWeights = nullptr;
00112         switch(wcprec)
00113         {
00114         case 2: aWeights = g_aWeights2; assert( wc < 4 ); _Analysis_assume_( wc < 4 ); break;
00115         case 3: aWeights = g_aWeights3; assert( wc < 8 ); _Analysis_assume_( wc < 8 ); break;
00116         case 4: aWeights = g_aWeights4; assert( wc < 16 ); _Analysis_assume_( wc < 16 ); break;
00117         default: assert(false); out.r = out.g = out.b = 0; return;
00118         }
00119         out.r = uint8_t((uint32_t(c0.r) * uint32_t(BC67_WEIGHT_MAX - aWeights[wc]) + uint32_t(c1.r) * uint32_t(aWeights[wc]) + BC67_WEIGHT_ROUND) >> BC67_WEIGHT_SHIFT);
00120         out.g = uint8_t((uint32_t(c0.g) * uint32_t(BC67_WEIGHT_MAX - aWeights[wc]) + uint32_t(c1.g) * uint32_t(aWeights[wc]) + BC67_WEIGHT_ROUND) >> BC67_WEIGHT_SHIFT);
00121         out.b = uint8_t((uint32_t(c0.b) * uint32_t(BC67_WEIGHT_MAX - aWeights[wc]) + uint32_t(c1.b) * uint32_t(aWeights[wc]) + BC67_WEIGHT_ROUND) >> BC67_WEIGHT_SHIFT);
00122     }
00123
00124     static void InterpolateA(_In_ const LDRColorA& c0, _In_ const LDRColorA& c1, _In_ size_t wa, _In_range_(2, 4) _In_ size_t waprec, _Out_ LDRColorA& out)
00125     {
00126         const int* aWeights = nullptr;
00127         switch(waprec)
00128         {
00129         case 2: aWeights = g_aWeights2; assert( wa < 4 ); _Analysis_assume_( wa < 4 ); break;
00130         case 3: aWeights = g_aWeights3; assert( wa < 8 ); _Analysis_assume_( wa < 8 ); break;
00131         case 4: aWeights = g_aWeights4; assert( wa < 16 ); _Analysis_assume_( wa < 16 ); break;
00132         default: assert(false); out.a = 0; return;
00133         }
00134         out.a = uint8_t((uint32_t(c0.a) * uint32_t(BC67_WEIGHT_MAX - aWeights[wa]) + uint32_t(c1.a) * uint32_t(aWeights[wa]) + BC67_WEIGHT_ROUND) >> BC67_WEIGHT_SHIFT);
00135     }
00136
00137     static void Interpolate(_In_ const LDRColorA& c0, _In_ const LDRColorA& c1, _In_ size_t wc, _In_ size_t wa, _In_ _In_range_(2, 4) size_t wcprec, _In_ _In_range_(2, 4) size_t waprec, _Out_ LDRColorA& out)
00138     {
00139         InterpolateRGB(c0, c1, wc, wcprec, out);
00140         InterpolateA(c0, c1, wa, waprec, out);
00141     }
00142 };
00143
00144 class HDRColorA
00145 {
00146 public:
00147     float r, g, b, a;
00148
00149 public:
00150     HDRColorA() {}
00151     HDRColorA(float _r, float _g, float _b, float _a) : r(_r), g(_g), b(_b), a(_a) {}
00152     HDRColorA(const HDRColorA& c) : r(c.r), g(c.g), b(c.b), a(c.a) {}
00153     HDRColorA(const LDRColorA& c)
00154     {
00155         r = float(c.r) * (1.0f/255.0f);
00156         g = float(c.g) * (1.0f/255.0f);
00157         b = float(c.b) * (1.0f/255.0f);
00158         a = float(c.a) * (1.0f/255.0f);
00159     }
00160
00161     // binary operators
00162     HDRColorA operator + ( _In_ const HDRColorA& c ) const
00163     {
00164         return HDRColorA(r + c.r, g + c.g, b + c.b, a + c.a);
00165     }
00166
00167     HDRColorA operator - ( _In_ const HDRColorA& c ) const
00168     {
00169         return HDRColorA(r - c.r, g - c.g, b - c.b, a - c.a);
00170     }
00171
00172     HDRColorA operator * ( _In_ float f ) const
00173     {
00174         return HDRColorA(r * f, g * f, b * f, a * f);
00175     }
00176
00177     HDRColorA operator / ( _In_ float f ) const
00178     {
00179         float fInv = 1.0f / f;
00180         return HDRColorA(r * fInv, g * fInv, b * fInv, a * fInv);
00181     }
00182
00183     float operator * ( _In_ const HDRColorA& c ) const
00184     {
00185         return r * c.r + g * c.g + b * c.b + a * c.a;
00186     }
00187
00188     // assignment operators
00189     HDRColorA& operator += ( _In_ const HDRColorA& c )
00190     {
00191         r += c.r;
00192         g += c.g;
00193         b += c.b;
00194         a += c.a;
00195         return *this;
00196     }
00197
00198     HDRColorA& operator -= ( _In_ const HDRColorA& c )
00199     {
00200         r -= c.r;
00201         g -= c.g;
00202         b -= c.b;
00203         a -= c.a;
00204         return *this;
00205     }
00206
00207     HDRColorA& operator *= ( _In_ float f )
00208     {
00209         r *= f;
00210         g *= f;
00211         b *= f;
00212         a *= f;
00213         return *this;
00214     }
00215
00216     HDRColorA& operator /= ( _In_ float f )
00217     {
00218         float fInv = 1.0f / f;
00219         r *= fInv;
00220         g *= fInv;
00221         b *= fInv;
00222         a *= fInv;
00223         return *this;
00224     }
00225
00226     HDRColorA& operator = (_In_ const LDRColorA& c)
00227     {
00228         r = (float) c.r;
00229         g = (float) c.g;
00230         b = (float) c.b;
00231         a = (float) c.a;
00232         return *this;
00233     }
00234
00235     HDRColorA& Clamp(_In_ float fMin, _In_ float fMax)
00236     {
00237         r = std::min<float>(fMax, std::max<float>(fMin, r));
00238         g = std::min<float>(fMax, std::max<float>(fMin, g));
00239         b = std::min<float>(fMax, std::max<float>(fMin, b));
00240         a = std::min<float>(fMax, std::max<float>(fMin, a));
00241         return *this;
00242     }
00243
00244     LDRColorA ToLDRColorA() const
00245     {
00246         return LDRColorA((uint8_t) (r + 0.01f), (uint8_t) (g + 0.01f), (uint8_t) (b + 0.01f), (uint8_t) (a + 0.01f));
00247     }
00248 };
00249
00250 inline LDRColorA LDRColorA::operator = (_In_ const HDRColorA& c)
00251 {
00252     LDRColorA ret;
00253     HDRColorA tmp(c);
00254     tmp = tmp.Clamp(0.0f, 1.0f) * 255.0f;
00255     ret.r = uint8_t(tmp.r + 0.001f);
00256     ret.g = uint8_t(tmp.g + 0.001f);
00257     ret.b = uint8_t(tmp.b + 0.001f);
00258     ret.a = uint8_t(tmp.a + 0.001f);
00259     return ret;
00260 }
00261
00262 struct LDREndPntPair
00263 {
00264     LDRColorA A;
00265     LDRColorA B;
00266 };
00267
00268 struct HDREndPntPair
00269 {
00270     HDRColorA A;
00271     HDRColorA B;
00272 };
00273
00274 inline HDRColorA* HDRColorALerp(_Out_ HDRColorA *pOut, _In_ const HDRColorA *pC1, _In_ const HDRColorA *pC2, _In_ float s)
00275 {
00276     pOut->r = pC1->r + s * (pC2->r - pC1->r);
00277     pOut->g = pC1->g + s * (pC2->g - pC1->g);
00278     pOut->b = pC1->b + s * (pC2->b - pC1->b);
00279     pOut->a = pC1->a + s * (pC2->a - pC1->a);
00280     return pOut;
00281 }
00282
00283 #pragma pack(push,1)
00284 // BC1/DXT1 compression (4 bits per texel)
00285 struct D3DX_BC1
00286 {
00287     uint16_t    rgb[2]; // 565 colors
00288     uint32_t    bitmap; // 2bpp rgb bitmap
00289 };
00290
00291 // BC2/DXT2/3 compression (8 bits per texel)
00292 struct D3DX_BC2
00293 {
00294     uint32_t    bitmap[2];  // 4bpp alpha bitmap
00295     D3DX_BC1    bc1;        // BC1 rgb data
00296 };
00297
00298 // BC3/DXT4/5 compression (8 bits per texel)
00299 struct D3DX_BC3
00300 {
00301     uint8_t     alpha[2];   // alpha values
00302     uint8_t     bitmap[6];  // 3bpp alpha bitmap
00303     D3DX_BC1    bc1;        // BC1 rgb data
00304 };
00305 #pragma pack(pop)
00306
00307 class INTColor
00308 {
00309 public:
00310     int r, g, b;
00311
00312 public:
00313     INTColor() {}
00314     INTColor(int nr, int ng, int nb) {r = nr; g = ng; b = nb;}
00315     INTColor(const INTColor& c) {r = c.r; g = c.g; b = c.b;}
00316
00317     INTColor operator - ( _In_ const INTColor& c ) const
00318     {
00319         return INTColor(r - c.r, g - c.g, b - c.b);
00320     }
00321
00322     INTColor& operator += ( _In_ const INTColor& c )
00323     {
00324         r += c.r;
00325         g += c.g;
00326         b += c.b;
00327         return *this;
00328     }
00329
00330     INTColor& operator -= ( _In_ const INTColor& c )
00331     {
00332         r -= c.r;
00333         g -= c.g;
00334         b -= c.b;
00335         return *this;
00336     }
00337
00338     INTColor& operator &= ( _In_ const INTColor& c )
00339     {
00340         r &= c.r;
00341         g &= c.g;
00342         b &= c.b;
00343         return *this;
00344     }
00345
00346     int& operator [] ( _In_ uint8_t i )
00347     {
00348         assert(i < sizeof(INTColor) / sizeof(int));
00349         _Analysis_assume_(i < sizeof(INTColor) / sizeof(int));
00350         return ((int*) this)[i];
00351     }
00352
00353     void Set(_In_ const HDRColorA& c, _In_ bool bSigned)
00354     {
00355         PackedVector::XMHALF4 aF16;
00356
00357         XMVECTOR v = XMLoadFloat4( (const XMFLOAT4*)& c );
00358         XMStoreHalf4( &aF16, v );
00359
00360         r = F16ToINT(aF16.x, bSigned);
00361         g = F16ToINT(aF16.y, bSigned);
00362         b = F16ToINT(aF16.z, bSigned);
00363     }
00364
00365     INTColor& Clamp(_In_ int iMin, _In_ int iMax)
00366     {
00367         r = std::min<int>(iMax, std::max<int>(iMin, r));
00368         g = std::min<int>(iMax, std::max<int>(iMin, g));
00369         b = std::min<int>(iMax, std::max<int>(iMin, b));
00370         return *this;
00371     }
00372
00373     INTColor& SignExtend(_In_ const LDRColorA& Prec)
00374     {
00375         r = SIGN_EXTEND(r, Prec.r);
00376         g = SIGN_EXTEND(g, Prec.g);
00377         b = SIGN_EXTEND(b, Prec.b);
00378         return *this;
00379     }
00380
00381     void ToF16(_Out_writes_(3) PackedVector::HALF aF16[3], _In_ bool bSigned) const
00382     {
00383         aF16[0] = INT2F16(r, bSigned);
00384         aF16[1] = INT2F16(g, bSigned);
00385         aF16[2] = INT2F16(b, bSigned);
00386     }
00387
00388 private:
00389     static int F16ToINT(_In_ const PackedVector::HALF& f, _In_ bool bSigned)
00390     {
00391         uint16_t input = *((const uint16_t*) &f);
00392         int out, s;
00393         if(bSigned)
00394         {
00395             s = input & F16S_MASK;
00396             input &= F16EM_MASK;
00397             if(input > F16MAX) out = F16MAX;
00398             else out = input;
00399             out = s ? -out : out;
00400         }
00401         else
00402         {
00403             if(input & F16S_MASK) out = 0;
00404             else out = input;
00405         }
00406         return out;
00407     }
00408
00409     static PackedVector::HALF INT2F16(_In_ int input, _In_ bool bSigned)
00410     {
00411         PackedVector::HALF h;
00412         uint16_t out;
00413         if(bSigned)
00414         {
00415             int s = 0;
00416             if(input < 0)
00417             {
00418                 s = F16S_MASK;
00419                 input = -input;
00420             }
00421             out = uint16_t(s | input);
00422         }
00423         else
00424         {
00425             assert(input >= 0 && input <= F16MAX);
00426             out = (uint16_t) input;
00427         }
00428
00429         *((uint16_t*) &h) = out;
00430         return h;
00431     }
00432 };
00433
00434 struct INTEndPntPair
00435 {
00436     INTColor A;
00437     INTColor B;
00438 };
00439
00440 template< size_t SizeInBytes >
00441 class CBits
00442 {
00443 public:
00444     uint8_t GetBit(_Inout_ size_t& uStartBit) const
00445     {
00446         assert(uStartBit < 128);
00447         _Analysis_assume_(uStartBit < 128);
00448         size_t uIndex = uStartBit >> 3;
00449         uint8_t ret = (m_uBits[uIndex] >> (uStartBit - (uIndex << 3))) & 0x01;
00450         uStartBit++;
00451         return ret;
00452     }
00453
00454     uint8_t GetBits(_Inout_ size_t& uStartBit, _In_ size_t uNumBits) const
00455     {
00456         if(uNumBits == 0) return 0;
00457         assert(uStartBit + uNumBits <= 128 && uNumBits <= 8);
00458         _Analysis_assume_(uStartBit + uNumBits <= 128 && uNumBits <= 8);
00459         uint8_t ret;
00460         size_t uIndex = uStartBit >> 3;
00461         size_t uBase = uStartBit - (uIndex << 3);
00462         if(uBase + uNumBits > 8)
00463         {
00464             size_t uFirstIndexBits = 8 - uBase;
00465             size_t uNextIndexBits = uNumBits - uFirstIndexBits;
00466             ret = (m_uBits[uIndex] >> uBase) | ((m_uBits[uIndex+1] & ((1 << uNextIndexBits) - 1)) << uFirstIndexBits);
00467         }
00468         else
00469         {
00470             ret = (m_uBits[uIndex] >> uBase) & ((1 << uNumBits) - 1);
00471         }
00472         assert(ret < (1 << uNumBits));
00473         uStartBit += uNumBits;
00474         return ret;
00475     }
00476
00477     void SetBit(_Inout_ size_t& uStartBit, _In_ uint8_t uValue)
00478     {
00479         assert(uStartBit < 128 && uValue < 2);
00480         _Analysis_assume_(uStartBit < 128 && uValue < 2);
00481         size_t uIndex = uStartBit >> 3;
00482         size_t uBase = uStartBit - (uIndex << 3);
00483         m_uBits[uIndex] &= ~(1 << uBase);
00484         m_uBits[uIndex] |= uValue << uBase;
00485         uStartBit++;
00486     }
00487
00488     void SetBits(_Inout_ size_t& uStartBit, _In_ size_t uNumBits, _In_ uint8_t uValue)
00489     {
00490         if(uNumBits == 0)
00491             return;
00492         assert(uStartBit + uNumBits <= 128 && uNumBits <= 8);
00493         _Analysis_assume_(uStartBit + uNumBits <= 128 && uNumBits <= 8);
00494         assert(uValue < (1 << uNumBits));
00495         size_t uIndex = uStartBit >> 3;
00496         size_t uBase = uStartBit - (uIndex << 3);
00497         if(uBase + uNumBits > 8)
00498         {
00499             size_t uFirstIndexBits = 8 - uBase;
00500             size_t uNextIndexBits = uNumBits - uFirstIndexBits;
00501             m_uBits[uIndex] &= ~(((1 << uFirstIndexBits) - 1) << uBase);
00502             m_uBits[uIndex] |= uValue << uBase;
00503             m_uBits[uIndex+1] &= ~((1 << uNextIndexBits) - 1);
00504             m_uBits[uIndex+1] |= uValue >> uFirstIndexBits;
00505         }
00506         else
00507         {
00508             m_uBits[uIndex] &= ~(((1 << uNumBits) - 1) << uBase);
00509             m_uBits[uIndex] |= uValue << uBase;
00510         }
00511         uStartBit += uNumBits;
00512     }
00513
00514 private:
00515     uint8_t m_uBits[ SizeInBytes ];
00516 };
00517
00518 #pragma warning(push)
00519 #pragma warning(disable : 4127 4480 4512)
00520
00521 // BC6H compression (16 bits per texel)
00522 class D3DX_BC6H : private CBits< 16 >
00523 {
00524 public:
00525     void Decode(_In_ bool bSigned, _Out_writes_(NUM_PIXELS_PER_BLOCK) HDRColorA* pOut) const;
00526     void Encode(_In_ bool bSigned, _In_reads_(NUM_PIXELS_PER_BLOCK) const HDRColorA* const pIn);
00527
00528 private:
00529     enum EField : uint8_t
00530     {
00531         NA, // N/A
00532         M,  // Mode
00533         D,  // Shape
00534         RW,
00535         RX,
00536         RY,
00537         RZ,
00538         GW,
00539         GX,
00540         GY,
00541         GZ,
00542         BW,
00543         BX,
00544         BY,
00545         BZ,
00546     };
00547
00548     struct ModeDescriptor
00549     {
00550         EField m_eField;
00551         uint8_t   m_uBit;
00552     };
00553
00554     struct ModeInfo
00555     {
00556         uint8_t uMode;
00557         uint8_t uPartitions;
00558         bool bTransformed;
00559         uint8_t uIndexPrec;
00560         LDRColorA RGBAPrec[BC6H_MAX_REGIONS][2];
00561     };
00562
00563     struct EncodeParams
00564     {
00565         float fBestErr;
00566         const bool bSigned;
00567         uint8_t uMode;
00568         uint8_t uShape;
00569         const HDRColorA* const aHDRPixels;
00570         INTEndPntPair aUnqEndPts[BC6H_MAX_SHAPES][BC6H_MAX_REGIONS];
00571         INTColor aIPixels[NUM_PIXELS_PER_BLOCK];
00572
00573         EncodeParams(const HDRColorA* const aOriginal, bool bSignedFormat) :
00574             aHDRPixels(aOriginal), fBestErr(FLT_MAX), bSigned(bSignedFormat)
00575         {
00576             for(size_t i = 0; i < NUM_PIXELS_PER_BLOCK; ++i)
00577             {
00578                 aIPixels[i].Set(aOriginal[i], bSigned);
00579             }
00580         }
00581     };
00582
00583     static int Quantize(_In_ int iValue, _In_ int prec, _In_ bool bSigned);
00584     static int Unquantize(_In_ int comp, _In_ uint8_t uBitsPerComp, _In_ bool bSigned);
00585     static int FinishUnquantize(_In_ int comp, _In_ bool bSigned);
00586
00587     static bool EndPointsFit(_In_ const EncodeParams* pEP, _In_reads_(BC6H_MAX_REGIONS) const INTEndPntPair aEndPts[]);
00588
00589     void GeneratePaletteQuantized(_In_ const EncodeParams* pEP, _In_ const INTEndPntPair& endPts,
00590                                   _Out_writes_(BC6H_MAX_INDICES) INTColor aPalette[]) const;
00591     float MapColorsQuantized(_In_ const EncodeParams* pEP, _In_reads_(np) const INTColor aColors[], _In_ size_t np, _In_ const INTEndPntPair &endPts) const;
00592     float PerturbOne(_In_ const EncodeParams* pEP, _In_reads_(np) const INTColor aColors[], _In_ size_t np, _In_ uint8_t ch,
00593                      _In_ const INTEndPntPair& oldEndPts, _Out_ INTEndPntPair& newEndPts, _In_ float fOldErr, _In_ int do_b) const;
00594     void OptimizeOne(_In_ const EncodeParams* pEP, _In_reads_(np) const INTColor aColors[], _In_ size_t np, _In_ float aOrgErr,
00595                      _In_ const INTEndPntPair &aOrgEndPts, _Out_ INTEndPntPair &aOptEndPts) const;
00596     void OptimizeEndPoints(_In_ const EncodeParams* pEP, _In_reads_(BC6H_MAX_REGIONS) const float aOrgErr[],
00597                            _In_reads_(BC6H_MAX_REGIONS) const INTEndPntPair aOrgEndPts[],
00598                            _Inout_updates_all_(BC6H_MAX_REGIONS) INTEndPntPair aOptEndPts[]) const;
00599     static void SwapIndices(_In_ const EncodeParams* pEP, _Inout_updates_all_(BC6H_MAX_REGIONS) INTEndPntPair aEndPts[],
00600                             _In_reads_(NUM_PIXELS_PER_BLOCK) size_t aIndices[]);
00601     void AssignIndices(_In_ const EncodeParams* pEP, _In_reads_(BC6H_MAX_REGIONS) const INTEndPntPair aEndPts[],
00602                         _Out_writes_(NUM_PIXELS_PER_BLOCK) size_t aIndices[],
00603                         _Out_writes_(BC6H_MAX_REGIONS) float aTotErr[]) const;
00604     void QuantizeEndPts(_In_ const EncodeParams* pEP, _Out_writes_(BC6H_MAX_REGIONS) INTEndPntPair* qQntEndPts) const;
00605     void EmitBlock(_In_ const EncodeParams* pEP, _In_reads_(BC6H_MAX_REGIONS) const INTEndPntPair aEndPts[],
00606                    _In_reads_(NUM_PIXELS_PER_BLOCK) const size_t aIndices[]);
00607     void Refine(_Inout_ EncodeParams* pEP);
00608
00609     static void GeneratePaletteUnquantized(_In_ const EncodeParams* pEP, _In_ size_t uRegion, _Out_writes_(BC6H_MAX_INDICES) INTColor aPalette[]);
00610     float MapColors(_In_ const EncodeParams* pEP, _In_ size_t uRegion, _In_ size_t np, _In_reads_(np) const size_t* auIndex) const;
00611     float RoughMSE(_Inout_ EncodeParams* pEP) const;
00612
00613 private:
00614     const static ModeDescriptor ms_aDesc[][82];
00615     const static ModeInfo ms_aInfo[];
00616     const static int ms_aModeToInfo[];
00617 };
00618
00619 // BC67 compression (16b bits per texel)
00620 class D3DX_BC7 : private CBits< 16 >
00621 {
00622 public:
00623     void Decode(_Out_writes_(NUM_PIXELS_PER_BLOCK) HDRColorA* pOut) const;
00624     void Encode(_In_reads_(NUM_PIXELS_PER_BLOCK) const HDRColorA* const pIn);
00625
00626 private:
00627     struct ModeInfo
00628     {
00629         uint8_t uPartitions;
00630         uint8_t uPartitionBits;
00631         uint8_t uPBits;
00632         uint8_t uRotationBits;
00633         uint8_t uIndexModeBits;
00634         uint8_t uIndexPrec;
00635         uint8_t uIndexPrec2;
00636         LDRColorA RGBAPrec;
00637         LDRColorA RGBAPrecWithP;
00638     };
00639
00640     struct EncodeParams
00641     {
00642         uint8_t uMode;
00643         LDREndPntPair aEndPts[BC7_MAX_SHAPES][BC7_MAX_REGIONS];
00644         LDRColorA aLDRPixels[NUM_PIXELS_PER_BLOCK];
00645         const HDRColorA* const aHDRPixels;
00646
00647         EncodeParams(const HDRColorA* const aOriginal) : aHDRPixels(aOriginal) {}
00648     };
00649
00650     static uint8_t Quantize(_In_ uint8_t comp, _In_ uint8_t uPrec)
00651     {
00652         assert(0 < uPrec && uPrec <= 8);
00653         uint8_t rnd = (uint8_t) std::min<uint16_t>(255, uint16_t(comp) + (1 << (7 - uPrec)));
00654         return rnd >> (8 - uPrec);
00655     }
00656
00657     static LDRColorA Quantize(_In_ const LDRColorA& c, _In_ const LDRColorA& RGBAPrec)
00658     {
00659         LDRColorA q;
00660         q.r = Quantize(c.r, RGBAPrec.r);
00661         q.g = Quantize(c.g, RGBAPrec.g);
00662         q.b = Quantize(c.b, RGBAPrec.b);
00663         if(RGBAPrec.a)
00664             q.a = Quantize(c.a, RGBAPrec.a);
00665         else
00666             q.a = 255;
00667         return q;
00668     }
00669
00670     static uint8_t Unquantize(_In_ uint8_t comp, _In_ size_t uPrec)
00671     {
00672         assert(0 < uPrec && uPrec <= 8);
00673         comp = comp << (8 - uPrec);
00674         return comp | (comp >> uPrec);
00675     }
00676
00677     static LDRColorA Unquantize(_In_ const LDRColorA& c, _In_ const LDRColorA& RGBAPrec)
00678     {
00679         LDRColorA q;
00680         q.r = Unquantize(c.r, RGBAPrec.r);
00681         q.g = Unquantize(c.g, RGBAPrec.g);
00682         q.b = Unquantize(c.b, RGBAPrec.b);
00683         q.a = RGBAPrec.a > 0 ? Unquantize(c.a, RGBAPrec.a) : 255;
00684         return q;
00685     }
00686
00687     void GeneratePaletteQuantized(_In_ const EncodeParams* pEP, _In_ size_t uIndexMode, _In_ const LDREndPntPair& endpts,
00688                                   _Out_writes_(BC7_MAX_INDICES) LDRColorA aPalette[]) const;
00689     float PerturbOne(_In_ const EncodeParams* pEP, _In_reads_(np) const LDRColorA colors[], _In_ size_t np, _In_ size_t uIndexMode,
00690                      _In_ size_t ch, _In_ const LDREndPntPair &old_endpts,
00691                      _Out_ LDREndPntPair &new_endpts, _In_ float old_err, _In_ uint8_t do_b) const;
00692     void Exhaustive(_In_ const EncodeParams* pEP, _In_reads_(np) const LDRColorA aColors[], _In_ size_t np, _In_ size_t uIndexMode,
00693                     _In_ size_t ch, _Inout_ float& fOrgErr, _Inout_ LDREndPntPair& optEndPt) const;
00694     void OptimizeOne(_In_ const EncodeParams* pEP, _In_reads_(np) const LDRColorA colors[], _In_ size_t np, _In_ size_t uIndexMode,
00695                      _In_ float orig_err, _In_ const LDREndPntPair &orig_endpts, _Out_ LDREndPntPair &opt_endpts) const;
00696     void OptimizeEndPoints(_In_ const EncodeParams* pEP, _In_ size_t uShape, _In_ size_t uIndexMode,
00697                            _In_reads_(BC7_MAX_REGIONS) const float orig_err[],
00698                            _In_reads_(BC7_MAX_REGIONS) const LDREndPntPair orig_endpts[],
00699                            _Out_writes_(BC7_MAX_REGIONS) LDREndPntPair opt_endpts[]) const;
00700     void AssignIndices(_In_ const EncodeParams* pEP, _In_ size_t uShape, _In_ size_t uIndexMode,
00701                        _In_reads_(BC7_MAX_REGIONS) LDREndPntPair endpts[],
00702                        _Inout_updates_all_(NUM_PIXELS_PER_BLOCK) size_t aIndices[], _Inout_updates_all_(NUM_PIXELS_PER_BLOCK) size_t aIndices2[],
00703                        _Out_writes_(BC7_MAX_REGIONS) float afTotErr[]) const;
00704     void EmitBlock(_In_ const EncodeParams* pEP, _In_ size_t uShape, _In_ size_t uRotation, _In_ size_t uIndexMode,
00705                    _In_reads_(BC7_MAX_REGIONS) const LDREndPntPair aEndPts[],
00706                    _In_reads_(NUM_PIXELS_PER_BLOCK) const size_t aIndex[],
00707                    _In_reads_(NUM_PIXELS_PER_BLOCK) const size_t aIndex2[]);
00708     float Refine(_In_ const EncodeParams* pEP, _In_ size_t uShape, _In_ size_t uRotation, _In_ size_t uIndexMode);
00709
00710     float MapColors(_In_ const EncodeParams* pEP, _In_reads_(np) const LDRColorA aColors[], _In_ size_t np, _In_ size_t uIndexMode,
00711                     _In_ const LDREndPntPair& endPts, _In_ float fMinErr) const;
00712     static float RoughMSE(_Inout_ EncodeParams* pEP, _In_ size_t uShape, _In_ size_t uIndexMode);
00713
00714 private:
00715     const static ModeInfo ms_aInfo[];
00716 };
00717
00718 //-------------------------------------------------------------------------------------
00719 template <bool bRange> void OptimizeAlpha(float *pX, float *pY, const float *pPoints, size_t cSteps)
00720 {
00721     static const float pC6[] = { 5.0f/5.0f, 4.0f/5.0f, 3.0f/5.0f, 2.0f/5.0f, 1.0f/5.0f, 0.0f/5.0f };
00722     static const float pD6[] = { 0.0f/5.0f, 1.0f/5.0f, 2.0f/5.0f, 3.0f/5.0f, 4.0f/5.0f, 5.0f/5.0f };
00723     static const float pC8[] = { 7.0f/7.0f, 6.0f/7.0f, 5.0f/7.0f, 4.0f/7.0f, 3.0f/7.0f, 2.0f/7.0f, 1.0f/7.0f, 0.0f/7.0f };
00724     static const float pD8[] = { 0.0f/7.0f, 1.0f/7.0f, 2.0f/7.0f, 3.0f/7.0f, 4.0f/7.0f, 5.0f/7.0f, 6.0f/7.0f, 7.0f/7.0f };
00725
00726     const float *pC = (6 == cSteps) ? pC6 : pC8;
00727     const float *pD = (6 == cSteps) ? pD6 : pD8;
00728
00729     float MAX_VALUE = 1.0f;
00730     float MIN_VALUE;
00731     if (bRange)
00732     {
00733         MIN_VALUE = -1.0f;
00734     }
00735     else
00736     {
00737         MIN_VALUE = 0.0f;
00738     }
00739
00740     // Find Min and Max points, as starting point
00741     float fX = MAX_VALUE;
00742     float fY = MIN_VALUE;
00743
00744     if(8 == cSteps)
00745     {
00746         for(size_t iPoint = 0; iPoint < NUM_PIXELS_PER_BLOCK; iPoint++)
00747         {
00748             if(pPoints[iPoint] < fX)
00749                 fX = pPoints[iPoint];
00750
00751             if(pPoints[iPoint] > fY)
00752                 fY = pPoints[iPoint];
00753         }
00754     }
00755     else
00756     {
00757         for(size_t iPoint = 0; iPoint < NUM_PIXELS_PER_BLOCK; iPoint++)
00758         {
00759             if(pPoints[iPoint] < fX && pPoints[iPoint] > MIN_VALUE)
00760                 fX = pPoints[iPoint];
00761
00762             if(pPoints[iPoint] > fY && pPoints[iPoint] < MAX_VALUE)
00763                 fY = pPoints[iPoint];
00764         }
00765
00766         if (fX == fY)
00767         {
00768             fY = MAX_VALUE;
00769         }
00770     }
00771
00772     // Use Newton's Method to find local minima of sum-of-squares error.
00773     float fSteps = (float) (cSteps - 1);
00774
00775     for(size_t iIteration = 0; iIteration < 8; iIteration++)
00776     {
00777         float fScale;
00778
00779         if((fY - fX) < (1.0f / 256.0f))
00780             break;
00781
00782         fScale = fSteps / (fY - fX);
00783
00784         // Calculate new steps
00785         float pSteps[8];
00786
00787         for(size_t iStep = 0; iStep < cSteps; iStep++)
00788             pSteps[iStep] = pC[iStep] * fX + pD[iStep] * fY;
00789
00790         if(6 == cSteps)
00791         {
00792             pSteps[6] = MIN_VALUE;
00793             pSteps[7] = MAX_VALUE;
00794         }
00795
00796         // Evaluate function, and derivatives
00797         float dX  = 0.0f;
00798         float dY  = 0.0f;
00799         float d2X = 0.0f;
00800         float d2Y = 0.0f;
00801
00802         for(size_t iPoint = 0; iPoint < NUM_PIXELS_PER_BLOCK; iPoint++)
00803         {
00804             float fDot = (pPoints[iPoint] - fX) * fScale;
00805
00806             size_t iStep;
00807
00808             if(fDot <= 0.0f)
00809                 iStep = ((6 == cSteps) && (pPoints[iPoint] <= fX * 0.5f)) ? 6 : 0;
00810             else if(fDot >= fSteps)
00811                 iStep = ((6 == cSteps) && (pPoints[iPoint] >= (fY + 1.0f) * 0.5f)) ? 7 : (cSteps - 1);
00812             else
00813                 iStep = static_cast<int32_t>(fDot + 0.5f);
00814
00815
00816             if(iStep < cSteps)
00817             {
00818                 // D3DX had this computation backwards (pPoints[iPoint] - pSteps[iStep])
00819                 // this fix improves RMS of the alpha component
00820                 float fDiff = pSteps[iStep] - pPoints[iPoint];
00821
00822                 dX  += pC[iStep] * fDiff;
00823                 d2X += pC[iStep] * pC[iStep];
00824
00825                 dY  += pD[iStep] * fDiff;
00826                 d2Y += pD[iStep] * pD[iStep];
00827             }
00828         }
00829
00830         // Move endpoints
00831         if(d2X > 0.0f)
00832             fX -= dX / d2X;
00833
00834         if(d2Y > 0.0f)
00835             fY -= dY / d2Y;
00836
00837         if(fX > fY)
00838         {
00839             float f = fX; fX = fY; fY = f;
00840         }
00841
00842         if((dX * dX < (1.0f / 64.0f)) && (dY * dY < (1.0f / 64.0f)))
00843             break;
00844     }
00845
00846     *pX = (fX < MIN_VALUE) ? MIN_VALUE : (fX > MAX_VALUE) ? MAX_VALUE : fX;
00847     *pY = (fY < MIN_VALUE) ? MIN_VALUE : (fY > MAX_VALUE) ? MAX_VALUE : fY;
00848 }
00849 #pragma warning(pop)
00850
00851
00852 //-------------------------------------------------------------------------------------
00853 // Functions
00854 //-------------------------------------------------------------------------------------
00855
00856 typedef void (*BC_DECODE)(XMVECTOR *pColor, const uint8_t *pBC);
00857 typedef void (*BC_ENCODE)(uint8_t *pDXT, const XMVECTOR *pColor, DWORD flags);
00858
00859 void D3DXDecodeBC1(_Out_writes_(NUM_PIXELS_PER_BLOCK) XMVECTOR *pColor, _In_reads_(8) const uint8_t *pBC);
00860 void D3DXDecodeBC2(_Out_writes_(NUM_PIXELS_PER_BLOCK) XMVECTOR *pColor, _In_reads_(16) const uint8_t *pBC);
00861 void D3DXDecodeBC3(_Out_writes_(NUM_PIXELS_PER_BLOCK) XMVECTOR *pColor, _In_reads_(16) const uint8_t *pBC);
00862 void D3DXDecodeBC4U(_Out_writes_(NUM_PIXELS_PER_BLOCK) XMVECTOR *pColor, _In_reads_(8) const uint8_t *pBC);
00863 void D3DXDecodeBC4S(_Out_writes_(NUM_PIXELS_PER_BLOCK) XMVECTOR *pColor, _In_reads_(8) const uint8_t *pBC);
00864 void D3DXDecodeBC5U(_Out_writes_(NUM_PIXELS_PER_BLOCK) XMVECTOR *pColor, _In_reads_(16) const uint8_t *pBC);
00865 void D3DXDecodeBC5S(_Out_writes_(NUM_PIXELS_PER_BLOCK) XMVECTOR *pColor, _In_reads_(16) const uint8_t *pBC);
00866 void D3DXDecodeBC6HU(_Out_writes_(NUM_PIXELS_PER_BLOCK) XMVECTOR *pColor, _In_reads_(16) const uint8_t *pBC);
00867 void D3DXDecodeBC6HS(_Out_writes_(NUM_PIXELS_PER_BLOCK) XMVECTOR *pColor, _In_reads_(16) const uint8_t *pBC);
00868 void D3DXDecodeBC7(_Out_writes_(NUM_PIXELS_PER_BLOCK) XMVECTOR *pColor, _In_reads_(16) const uint8_t *pBC);
00869
00870 void D3DXEncodeBC1(_Out_writes_(8) uint8_t *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const XMVECTOR *pColor, _In_ float alphaRef, _In_ DWORD flags);
00871     // BC1 requires one additional parameter, so it doesn't match signature of BC_ENCODE above
00872
00873 void D3DXEncodeBC2(_Out_writes_(16) uint8_t *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const XMVECTOR *pColor, _In_ DWORD flags);
00874 void D3DXEncodeBC3(_Out_writes_(16) uint8_t *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const XMVECTOR *pColor, _In_ DWORD flags);
00875 void D3DXEncodeBC4U(_Out_writes_(8) uint8_t *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const XMVECTOR *pColor, _In_ DWORD flags);
00876 void D3DXEncodeBC4S(_Out_writes_(8) uint8_t *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const XMVECTOR *pColor, _In_ DWORD flags);
00877 void D3DXEncodeBC5U(_Out_writes_(16) uint8_t *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const XMVECTOR *pColor, _In_ DWORD flags);
00878 void D3DXEncodeBC5S(_Out_writes_(16) uint8_t *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const XMVECTOR *pColor, _In_ DWORD flags);
00879 void D3DXEncodeBC6HU(_Out_writes_(16) uint8_t *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const XMVECTOR *pColor, _In_ DWORD flags);
00880 void D3DXEncodeBC6HS(_Out_writes_(16) uint8_t *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const XMVECTOR *pColor, _In_ DWORD flags);
00881 void D3DXEncodeBC7(_Out_writes_(16) uint8_t *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const XMVECTOR *pColor, _In_ DWORD flags);
00882
00883 }; // namespace
Generated on Sat Nov 23 2024 16:08:11 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML FlipView control/C++/MainPage.xaml.h Source File

  • XAML FlipView control

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/texconv/DDS.h Source File

  • Direct3D resource loading
  • texconv

DDS.h

Go to the documentation of this file.
00001 //--------------------------------------------------------------------------------------
00002 // dds.h
00003 //
00004 // This header defines constants and structures that are useful when parsing
00005 // DDS files.  DDS files were originally designed to use several structures
00006 // and constants that are native to DirectDraw and are defined in ddraw.h,
00007 // such as DDSURFACEDESC2 and DDSCAPS2.  This file defines similar
00008 // (compatible) constants and structures so that one can use DDS files
00009 // without needing to include ddraw.h.
00010 //
00011 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00012 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00013 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00014 // PARTICULAR PURPOSE.
00015 //
00016 // Copyright (c) Microsoft Corporation. All rights reserved.
00017 //--------------------------------------------------------------------------------------
00018
00019 #if defined(_MSC_VER) && (_MSC_VER > 1000)
00020 #pragma once
00021 #endif
00022
00023 #include <dxgiformat.h>
00024
00025 #pragma warning(push)
00026 #pragma warning(disable : 4005)
00027 #include <stdint.h>
00028 #pragma warning(pop)
00029
00030 namespace DirectX
00031 {
00032
00033 #pragma pack(push,1)
00034
00035 const uint32_t DDS_MAGIC = 0x20534444; // "DDS "
00036
00037 struct DDS_PIXELFORMAT
00038 {
00039     uint32_t    dwSize;
00040     uint32_t    dwFlags;
00041     uint32_t    dwFourCC;
00042     uint32_t    dwRGBBitCount;
00043     uint32_t    dwRBitMask;
00044     uint32_t    dwGBitMask;
00045     uint32_t    dwBBitMask;
00046     uint32_t    dwABitMask;
00047 };
00048
00049 #define DDS_FOURCC      0x00000004  // DDPF_FOURCC
00050 #define DDS_RGB         0x00000040  // DDPF_RGB
00051 #define DDS_RGBA        0x00000041  // DDPF_RGB | DDPF_ALPHAPIXELS
00052 #define DDS_LUMINANCE   0x00020000  // DDPF_LUMINANCE
00053 #define DDS_LUMINANCEA  0x00020001  // DDPF_LUMINANCE | DDPF_ALPHAPIXELS
00054 #define DDS_ALPHA       0x00000002  // DDPF_ALPHA
00055 #define DDS_PAL8        0x00000020  // DDPF_PALETTEINDEXED8
00056
00057 #ifndef MAKEFOURCC
00058     #define MAKEFOURCC(ch0, ch1, ch2, ch3)                              \
00059                 ((uint32_t)(uint8_t)(ch0) | ((uint32_t)(uint8_t)(ch1) << 8) |       \
00060                 ((uint32_t)(uint8_t)(ch2) << 16) | ((uint32_t)(uint8_t)(ch3) << 24 ))
00061 #endif /* defined(MAKEFOURCC) */
00062
00063 extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT1 =
00064     { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','1'), 0, 0, 0, 0, 0 };
00065
00066 extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT2 =
00067     { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','2'), 0, 0, 0, 0, 0 };
00068
00069 extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT3 =
00070     { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','3'), 0, 0, 0, 0, 0 };
00071
00072 extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT4 =
00073     { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','4'), 0, 0, 0, 0, 0 };
00074
00075 extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT5 =
00076     { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','5'), 0, 0, 0, 0, 0 };
00077
00078 extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_BC4_UNORM =
00079     { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','4','U'), 0, 0, 0, 0, 0 };
00080
00081 extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_BC4_SNORM =
00082     { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','4','S'), 0, 0, 0, 0, 0 };
00083
00084 extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_BC5_UNORM =
00085     { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','5','U'), 0, 0, 0, 0, 0 };
00086
00087 extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_BC5_SNORM =
00088     { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','5','S'), 0, 0, 0, 0, 0 };
00089
00090 extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_R8G8_B8G8 =
00091     { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('R','G','B','G'), 0, 0, 0, 0, 0 };
00092
00093 extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_G8R8_G8B8 =
00094     { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('G','R','G','B'), 0, 0, 0, 0, 0 };
00095
00096 extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8R8G8B8 =
00097     { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000 };
00098
00099 extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_X8R8G8B8 =
00100     { sizeof(DDS_PIXELFORMAT), DDS_RGB,  0, 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0x00000000 };
00101
00102 extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8B8G8R8 =
00103     { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000 };
00104
00105 extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_X8B8G8R8 =
00106     { sizeof(DDS_PIXELFORMAT), DDS_RGB,  0, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0x00000000 };
00107
00108 extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_G16R16 =
00109     { sizeof(DDS_PIXELFORMAT), DDS_RGB,  0, 32, 0x0000ffff, 0xffff0000, 0x00000000, 0x00000000 };
00110
00111 extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_R5G6B5 =
00112     { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 16, 0x0000f800, 0x000007e0, 0x0000001f, 0x00000000 };
00113
00114 extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A1R5G5B5 =
00115     { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 16, 0x00007c00, 0x000003e0, 0x0000001f, 0x00008000 };
00116
00117 extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A4R4G4B4 =
00118     { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 16, 0x00000f00, 0x000000f0, 0x0000000f, 0x0000f000 };
00119
00120 extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_R8G8B8 =
00121     { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 24, 0x00ff0000, 0x0000ff00, 0x000000ff, 0x00000000 };
00122
00123 extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_L8 =
00124     { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCE, 0,  8, 0xff, 0x00, 0x00, 0x00 };
00125
00126 extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_L16 =
00127     { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCE, 0, 16, 0xffff, 0x0000, 0x0000, 0x0000 };
00128
00129 extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8L8 =
00130     { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCEA, 0, 16, 0x00ff, 0x0000, 0x0000, 0xff00 };
00131
00132 extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8 =
00133     { sizeof(DDS_PIXELFORMAT), DDS_ALPHA, 0, 8, 0x00, 0x00, 0x00, 0xff };
00134
00135 // D3DFMT_A2R10G10B10/D3DFMT_A2B10G10R10 should be written using DX10 extension to avoid D3DX 10:10:10:2 reversal issue
00136
00137 // This indicates the DDS_HEADER_DXT10 extension is present (the format is in dxgiFormat)
00138 extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DX10 =
00139     { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','1','0'), 0, 0, 0, 0, 0 };
00140
00141 #define DDS_HEADER_FLAGS_TEXTURE        0x00001007  // DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT
00142 #define DDS_HEADER_FLAGS_MIPMAP         0x00020000  // DDSD_MIPMAPCOUNT
00143 #define DDS_HEADER_FLAGS_VOLUME         0x00800000  // DDSD_DEPTH
00144 #define DDS_HEADER_FLAGS_PITCH          0x00000008  // DDSD_PITCH
00145 #define DDS_HEADER_FLAGS_LINEARSIZE     0x00080000  // DDSD_LINEARSIZE
00146
00147 #define DDS_HEIGHT 0x00000002 // DDSD_HEIGHT
00148 #define DDS_WIDTH  0x00000004 // DDSD_WIDTH
00149
00150 #define DDS_SURFACE_FLAGS_TEXTURE 0x00001000 // DDSCAPS_TEXTURE
00151 #define DDS_SURFACE_FLAGS_MIPMAP  0x00400008 // DDSCAPS_COMPLEX | DDSCAPS_MIPMAP
00152 #define DDS_SURFACE_FLAGS_CUBEMAP 0x00000008 // DDSCAPS_COMPLEX
00153
00154 #define DDS_CUBEMAP_POSITIVEX 0x00000600 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEX
00155 #define DDS_CUBEMAP_NEGATIVEX 0x00000a00 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEX
00156 #define DDS_CUBEMAP_POSITIVEY 0x00001200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEY
00157 #define DDS_CUBEMAP_NEGATIVEY 0x00002200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEY
00158 #define DDS_CUBEMAP_POSITIVEZ 0x00004200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEZ
00159 #define DDS_CUBEMAP_NEGATIVEZ 0x00008200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEZ
00160
00161 #define DDS_CUBEMAP_ALLFACES ( DDS_CUBEMAP_POSITIVEX | DDS_CUBEMAP_NEGATIVEX |\
00162                                DDS_CUBEMAP_POSITIVEY | DDS_CUBEMAP_NEGATIVEY |\
00163                                DDS_CUBEMAP_POSITIVEZ | DDS_CUBEMAP_NEGATIVEZ )
00164
00165 #define DDS_CUBEMAP 0x00000200 // DDSCAPS2_CUBEMAP
00166
00167 #define DDS_FLAGS_VOLUME 0x00200000 // DDSCAPS2_VOLUME
00168
00169 // Subset here matches D3D10_RESOURCE_DIMENSION and D3D11_RESOURCE_DIMENSION
00170 typedef enum DDS_RESOURCE_DIMENSION
00171 {
00172     DDS_DIMENSION_TEXTURE1D = 2,
00173     DDS_DIMENSION_TEXTURE2D = 3,
00174     DDS_DIMENSION_TEXTURE3D = 4,
00175 } DDS_RESOURCE_DIMENSION;
00176
00177 // Subset here matches D3D10_RESOURCE_MISC_FLAG and D3D11_RESOURCE_MISC_FLAG
00178 typedef enum DDS_RESOURCE_MISC_FLAG
00179 {
00180    DDS_RESOURCE_MISC_TEXTURECUBE = 0x4L,
00181 } DDS_RESOURCE_MISC_FLAG;
00182
00183 typedef struct
00184 {
00185     uint32_t    dwSize;
00186     uint32_t    dwFlags;
00187     uint32_t    dwHeight;
00188     uint32_t    dwWidth;
00189     uint32_t    dwPitchOrLinearSize;
00190     uint32_t    dwDepth; // only if DDS_HEADER_FLAGS_VOLUME is set in dwFlags
00191     uint32_t    dwMipMapCount;
00192     uint32_t    dwReserved1[11];
00193     DDS_PIXELFORMAT ddspf;
00194     uint32_t    dwCaps;
00195     uint32_t    dwCaps2;
00196     uint32_t    dwCaps3;
00197     uint32_t    dwCaps4;
00198     uint32_t    dwReserved2;
00199 } DDS_HEADER;
00200
00201 typedef struct
00202 {
00203     DXGI_FORMAT dxgiFormat;
00204     uint32_t    resourceDimension;
00205     uint32_t    miscFlag; // see DDS_RESOURCE_MISC_FLAG
00206     uint32_t    arraySize;
00207     uint32_t    reserved;
00208 } DDS_HEADER_DXT10;
00209
00210 #pragma pack(pop)
00211
00212 }; // namespace
Generated on Sat Nov 23 2024 16:08:11 for Win8-Examples by doxygen 1.7.1


Win8-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 | [private]
__pad1__ | ManipulatableObject |
_backgroundBrush | sealed | [private]
_backgroundColor | sealed | [private]
_color | sealed | [private]
_currentBuffer | sealed | [private]
_descPosition | sealed | [private]
_descText | sealed | [private]
_deviceDesc | sealed | [private]
_drawingAttributes | sealed | [private]
_eventTextFormat | sealed | [private]
_frameReference | sealed | [private]
_initColor | sealed | [private]
_initDX | sealed | [private]
_initDY | sealed | [private]
_initX | sealed | [private]
_initY | sealed | [private]
_inkBrush | sealed | [private]
_inkStyle | sealed | [private]
_manipulationMode | sealed | [private]
_manipulationPoints | sealed | [private]
_messageBrush | sealed | [private]
_pointerDevice | sealed | [private]
_pointerId | sealed | [private]
_previousBuffer | sealed | [private]
_recognitionText | sealed | [private]
_recognizer | sealed | [private]
_recognizerContainer | sealed | [private]
_recognizerId | sealed | [private]
_renderer | sealed | [private]
_renderingMode | sealed | [private]
_selectionBrush | sealed | [private]
_selectionStyle | sealed | [private]
_statusMessage | sealed | [private]
_strokeBuilder | sealed | [private]
_strokeContainer | sealed | [private]
_tokenHolding | sealed | [private]
_tokenManipulationCompleted | sealed | [private]
_tokenManipulationInertiaStarting | sealed | [private]
_tokenManipulationStarted | sealed | [private]
_tokenManipulationUpdated | sealed | [private]
_tokenRightTapped | sealed | [private]
_tokenTapped | sealed | [private]
Attach(_In_ Windows::UI::Input::GestureRecognizer^gestureRecognizer) | sealed |
Attach(_In_ Windows::UI::Input::GestureRecognizer^gestureRecognizer) | sealed |
BackgroundObject(_In_opt_ ManipulatableObject^parent, _In_ IRenderer^renderer) | sealed |
BezierRender() | sealed | [protected]
Blue | sealed |
ControlRect([out, retval] Windows.Foundation.Rect *prc) | UiaCoreWindowProvider::ITriColorControlInternal |
ControlValue([in] TriColorValue value) | UiaCoreWindowProvider::ITriColorControlInternal |
ControlValue([out, retval] TriColorValue *pvalue) | UiaCoreWindowProvider::ITriColorControlInternal |
CreateDeviceIndependentResources() override | sealed | [virtual]
CreateDeviceIndependentResources() override | sealed | [virtual]
CreateDeviceResources() override | sealed | [virtual]
CreateDeviceResources() override | sealed | [virtual]
CreateDeviceResources() override | sealed | [virtual]
CreateThemeSpecificResources() | sealed | [private]
CreateView() | sealed | [virtual]
CreateView() | sealed | [inline, virtual]
CreateWindowSizeDependentResources() override | sealed | [virtual]
CreateWindowSizeDependentResources() override | sealed | [virtual]
CreateWindowSizeDependentResources() override | sealed | [virtual]
CTriColorWindow() | sealed |
Decoder | sealed |
Deserialize(_In_ Windows::Foundation::Collections::IPropertySet^properties) override | sealed | [virtual]
Detach(_In_ Windows::UI::Input::GestureRecognizer^gestureRecognizer) | sealed |
Detach(_In_ Windows::UI::Input::GestureRecognizer^gestureRecognizer) | sealed |
DiscardThemeSpecificResources() | sealed | [private]
Draw(_In_ ID2D1DeviceContext *deviceContext, _In_ ID2D1SolidColorBrush *brush) | sealed |
DrawBackground(_In_ ID2D1DeviceContext *deviceContext, _In_ ID2D1SolidColorBrush *brush) | sealed |
DrawingObject(_In_opt_ ManipulatableObject^parent, _In_ IRenderer^renderer) | sealed |
DrawOverlay(_In_ ID2D1DeviceContext *deviceContext, _In_ IDWriteTextFormat *textFormat, _In_ ID2D1SolidColorBrush *brush) | sealed |
DrawOverlay(_In_ ID2D1DeviceContext *deviceContext, _In_ IDWriteTextFormat *textFormat, _In_ ID2D1SolidColorBrush *brush) | sealed |
Encoder | sealed |
EnsureAppWindowProviderCreated() | sealed | [private]
EnsureControlProviderCreated() | sealed | [private]
EnsureFragmentProviderCreated(_In_ UiaCoreWindowProvider::TriColorValue value) | sealed | [private]
FrameworkView() | sealed |
FrameworkViewSource() | sealed | [inline]
geometry | sealed | [protected]
GetAppWindowProvider() | sealed | [virtual]
UiaCoreWindowProvider::ITriColorControlInternal::GetAppWindowProvider([out, retval] IInspectable **provider) | UiaCoreWindowProvider::ITriColorControlInternal |
GetColor() | sealed | [inline]
GetDeviceDescription() | sealed | [private]
GetGreenRect() | sealed | [private]
GetObjectDescription() | sealed | [private]
GetRedRect() | sealed | [private]
GetTriColorControlProvider() | sealed | [virtual]
UiaCoreWindowProvider::ITriColorControlInternal::GetTriColorControlProvider([out, retval] IInspectable **provider) | UiaCoreWindowProvider::ITriColorControlInternal |
GetTriColorFragmentProvider(_In_ UiaCoreWindowProvider::TriColorValue value) | sealed | [virtual]
UiaCoreWindowProvider::ITriColorControlInternal::GetTriColorFragmentProvider([in] TriColorValue value,[out, retval] IInspectable **provider) | UiaCoreWindowProvider::ITriColorControlInternal |
GetYellowRect() | sealed | [private]
Green | sealed |
HasFocus([out, retval] VARIANT_BOOL *hasFocus) | UiaCoreWindowProvider::ITriColorControlInternal |
HitTest(_In_ Windows::Foundation::Point position) | sealed |
Initialize() | sealed |
Initialize(_In_ Color color, _In_ float x, _In_ float y, _In_ float dx, _In_ float dy) | sealed |
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | sealed | [virtual]
Initialize(Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | sealed | [virtual]
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | sealed | [virtual]
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | sealed | [virtual]
LimitManipulationScale(_In_ Windows::UI::Input::ManipulationDelta delta, _In_ float minScale, _In_ float maxScale) | ManipulatableObject |
Load(_In_ Platform::String^entryPoint) | sealed | [virtual]
Load(Platform::String^entryPoint) | sealed | [virtual]
Load(Platform::String^entryPoint) | sealed | [virtual]
Load(_In_ Platform::String^entryPoint) | sealed | [virtual]
LocalTransform() | ManipulatableObject | [inline]
m_accSettings | sealed | [private]
m_activated | sealed | [private]
m_activationEntryPoint | sealed | [private]
m_applicationView | sealed | [private]
m_appWindowProvider | sealed | [private]
m_blackBrush | sealed | [private]
m_controlProvider | sealed | [private]
m_controlRect | sealed | [private]
m_greenBrush | sealed | [private]
m_greenProvider | sealed | [private]
m_labelFormat | sealed | [private]
m_program | sealed | [private]
m_redBrush | sealed | [private]
m_redProvider | sealed | [private]
m_sampleOverlay | sealed | [private]
m_titleFormat | sealed | [private]
m_uiSettings | sealed | [private]
m_value | sealed | [private]
m_whiteBrush | sealed | [private]
m_window | sealed | [private]
m_windowTextBrush | sealed | [private]
m_yellowBrush | sealed | [private]
m_yellowProvider | sealed | [private]
ManipulatableObjectTransform(_In_opt_ ManipulatableObject^referentObject) | sealed |
ManipulationTransform() | ManipulatableObject | [inline]
MaxCount | sealed |
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | sealed | [protected]
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | sealed |
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | sealed | [private]
OnAutomationProviderRequested(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::AutomationProviderRequestedEventArgs^e) | sealed | [private]
OnChangeDrawingAttributes() | sealed | [protected]
OnChangeRecognizer() | sealed | [protected]
OnCharacterReceived(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::CharacterReceivedEventArgs^args) | sealed | [protected]
OnCopyTextToClipboard() | sealed | [protected]
OnCopyToClipboard() | sealed | [protected]
OnDelete() | sealed | [protected]
OnDisplayContentsInvalidated(_In_ Platform::Object^sender) | sealed | [protected]
OnDisplayContentsInvalidated(_In_ Platform::Object^sender) | sealed |
OnDisplayContentsInvalidated(_In_ Platform::Object^sender) | sealed | [private]
OnHighContrastChanged(_In_ Windows::UI::ViewManagement::AccessibilitySettings^sender, _In_ Platform::Object^e) | sealed | [private]
OnHolding(_In_ Windows::UI::Input::GestureRecognizer^sender, _In_ Windows::UI::Input::HoldingEventArgs^args) | sealed | [private]
OnHolding(_In_ Windows::UI::Input::GestureRecognizer^sender, _In_ Windows::UI::Input::HoldingEventArgs^args) | sealed | [private]
OnKeyDown(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::KeyEventArgs^e) | sealed | [private]
OnLoad() | sealed | [protected]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | sealed | [protected]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | sealed |
OnLogicalDpiChanged(_In_ Platform::Object^sender) | sealed | [private]
OnManipulationCompleted(_In_ Windows::UI::Input::GestureRecognizer^sender, _In_ Windows::UI::Input::ManipulationCompletedEventArgs^args) | sealed | [private]
OnManipulationCompleted(_In_ Windows::UI::Input::GestureRecognizer^sender, _In_ Windows::UI::Input::ManipulationCompletedEventArgs^args) | sealed | [private]
OnManipulationInertiaStarting(_In_ Windows::UI::Input::GestureRecognizer^sender, _In_ Windows::UI::Input::ManipulationInertiaStartingEventArgs^args) | sealed | [private]
OnManipulationInertiaStarting(_In_ Windows::UI::Input::GestureRecognizer^sender, _In_ Windows::UI::Input::ManipulationInertiaStartingEventArgs^args) | sealed | [private]
OnManipulationStarted(_In_ Windows::UI::Input::GestureRecognizer^sender, _In_ Windows::UI::Input::ManipulationStartedEventArgs^args) | sealed | [private]
OnManipulationStarted(_In_ Windows::UI::Input::GestureRecognizer^sender, _In_ Windows::UI::Input::ManipulationStartedEventArgs^args) | sealed | [private]
OnManipulationUpdated(_In_ Windows::UI::Input::GestureRecognizer^sender, _In_ Windows::UI::Input::ManipulationUpdatedEventArgs^args) | sealed | [private]
OnManipulationUpdated(_In_ Windows::UI::Input::GestureRecognizer^sender, _In_ Windows::UI::Input::ManipulationUpdatedEventArgs^args) | sealed | [private]
OnPasteFromClipboard() | sealed | [protected]
OnPointerMoved(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | sealed | [protected]
OnPointerMoved(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | sealed |
OnPointerPressed(_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 |
OnPointerReleased(_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 |
OnPointerReleased(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^e) | sealed | [private]
OnRecognize() | sealed | [protected]
OnResuming(_In_ Platform::Object^sender, _In_ Platform::Object^args) | sealed |
OnResuming(_In_ Platform::Object^sender, _In_ Platform::Object^args) | sealed | [private]
OnRightTapped(_In_ Windows::UI::Input::GestureRecognizer^sender, _In_ Windows::UI::Input::RightTappedEventArgs^args) | sealed | [private]
OnRightTapped(_In_ Windows::UI::Input::GestureRecognizer^sender, _In_ Windows::UI::Input::RightTappedEventArgs^args) | sealed | [private]
OnSave() | sealed | [protected]
OnSelectAll() | sealed | [protected]
OnSuspending(_In_ Platform::Object^sender, _In_ Windows::ApplicationModel::SuspendingEventArgs^args) | sealed |
OnSuspending(_In_ Platform::Object^sender, _In_ Windows::ApplicationModel::SuspendingEventArgs^args) | sealed | [private]
OnTapped(_In_ Windows::UI::Input::GestureRecognizer^sender, _In_ Windows::UI::Input::TappedEventArgs^args) | sealed | [private]
OnWindowActivated(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowActivatedEventArgs^e) | sealed | [private]
OnWindowClosed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::CoreWindowEventArgs^e) | sealed | [private]
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | sealed | [protected]
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | sealed |
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | sealed | [private]
Orange | sealed |
OutputStream | sealed |
Parent() | ManipulatableObject | [inline]
ParentTransform() | ManipulatableObject | [inline]
PhotoStorage | sealed |
PointInRect(_In_ Windows::Foundation::Rect rect, _In_ Windows::Foundation::Point pt) | sealed | [private, static]
Present() override | sealed | [virtual]
Purple | sealed |
RectFromValue([in] TriColorValue value,[out, retval] Windows.Foundation.Rect *prc) | UiaCoreWindowProvider::ITriColorControlInternal |
Red | sealed |
ReencodeState() | sealed | [inline]
Render() override | sealed | [virtual]
Render() override | sealed | [virtual]
Render() override | sealed | [virtual]
Run() | sealed | [virtual]
Run() | sealed | [virtual]
Run() | sealed | [virtual]
Run() | sealed | [virtual]
Serialize(_In_ Windows::Foundation::Collections::IPropertySet^properties) override | sealed | [virtual]
SetDevice(_In_opt_ Windows::Devices::Input::IPointerDevice^pointerDevice) | sealed |
SetInitialPosition(_In_ D2D1_POINT_2F ptInit) | ManipulatableObject | [inline]
SetManipulationTransform(_In_ D2D1::Matrix3x2F mxManip) | ManipulatableObject | [inline]
SetValue(_In_ UiaCoreWindowProvider::TriColorValue newValue) | sealed | [private]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | sealed | [virtual]
SetWindow(Windows::UI::Core::CoreWindow^window) | sealed | [virtual]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | sealed | [virtual]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | sealed | [virtual]
ShapesPuzzle() | sealed |
simpleInk() | sealed |
SingleFingerRotation(_In_ Windows::UI::Input::GestureRecognizer^gestureRecognizer, _In_ Windows::Foundation::Point position, _In_ float pivotRadius) | ManipulatableObject |
TransformBounds(_In_ Windows::Foundation::Rect rect) | sealed | [virtual]
TryTransform(_In_ Windows::Foundation::Point inPoint, _Out_ Windows::Foundation::Point *outPoint) | sealed | [virtual]
Uninitialize() | sealed | [virtual]
Uninitialize() | sealed | [virtual]
Uninitialize() | sealed | [virtual]
Uninitialize() | sealed | [virtual]
UpdateManipulationTransform(_In_ Windows::UI::Input::ManipulationDelta delta, _In_ Windows::Foundation::Point position) | ManipulatableObject |
ValueFromPoint(_In_ Windows::Foundation::Point pt) | sealed | [virtual]
ValueFromPoint(_In_ Windows::Foundation::Point pt, _Out_ UiaCoreWindowProvider::TriColorValue *value) | sealed | [private]
UiaCoreWindowProvider::ITriColorControlInternal::ValueFromPoint([in] Windows.Foundation.Point pt,[out, retval] TriColorValue *value) | UiaCoreWindowProvider::ITriColorControlInternal |
Yellow | sealed |
~BackgroundObject() | sealed | [private]
~CTriColorWindow() | sealed | [private]
~DrawingObject() | sealed | [private]
~ReencodeState() | sealed | [inline, virtual]
Generated on Sat Nov 23 2024 16:09:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite hello world/C++/DirectXBase.h Source File

  • DirectWrite hello world

DirectXBase.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 "DirectXSample.h"
00011
00012 // Helper class that initializes DirectX APIs for both 2D and 3D rendering.
00013 // Some of the code in this class may be omitted if only 2D or only 3D rendering is being used.
00014 ref class DirectXBase abstract
00015 {
00016 internal:
00017     DirectXBase();
00018
00019     virtual void Initialize(Windows::UI::Core::CoreWindow^ window, float dpi);
00020     virtual void HandleDeviceLost();
00021     virtual void CreateDeviceIndependentResources();
00022     virtual void CreateDeviceResources();
00023     virtual void SetDpi(float dpi);
00024     virtual void UpdateForWindowSizeChange();
00025     virtual void CreateWindowSizeDependentResources();
00026     virtual void Render() = 0;
00027     virtual void Present();
00028     void ValidateDevice();
00029
00030 protected private:
00031     Platform::Agile<Windows::UI::Core::CoreWindow>  m_window;
00032
00033     // DirectWrite & Windows Imaging Component Objects.
00034     Microsoft::WRL::ComPtr<IDWriteFactory1>         m_dwriteFactory;
00035     Microsoft::WRL::ComPtr<IWICImagingFactory2>     m_wicFactory;
00036
00037     // DirectX Core Objects. Required for 2D and 3D.
00038     Microsoft::WRL::ComPtr<ID3D11Device1>           m_d3dDevice;
00039     Microsoft::WRL::ComPtr<ID3D11DeviceContext1>    m_d3dContext;
00040     Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00041     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00042
00043     // Direct2D Rendering Objects. Required for 2D.
00044     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00046     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00047     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmap;
00048
00049     // Direct3D Rendering Objects. Required for 3D.
00050     Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00051
00052     // Cached renderer properties.
00053     D3D_FEATURE_LEVEL                               m_featureLevel;
00054     Windows::Foundation::Size                       m_renderTargetSize;
00055     Windows::Foundation::Rect                       m_windowBounds;
00056     float                                           m_dpi;
00057     bool                                            m_windowSizeChangeInProgress;
00058 };
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Touch keyboard/C++/common/LayoutAwarePage.h Source File

  • Input Touch keyboard
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Check if current session is remote/C++/common/LayoutAwarePage.h Source File

  • Check if current session is remote
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite inline object/C++/SampleOverlay.h Source File

  • DirectWrite inline object

SampleOverlay.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 "DirectXSample.h"
00011
00012 // This class is responsible for initializing and rendering the title overlay visible
00013 // at the top of the DirectX SDK samples.
00014 ref class SampleOverlay
00015 {
00016 internal:
00017     SampleOverlay();
00018
00019     void Initialize(
00020         _In_ ID2D1Device*         d2dDevice,
00021         _In_ ID2D1DeviceContext*  d2dContext,
00022         _In_ IWICImagingFactory*  wicFactory,
00023         _In_ IDWriteFactory*      dwriteFactory,
00024         _In_ Platform::String^    caption
00025         );
00026
00027     void ResetDirectXResources();
00028
00029     void UpdateForWindowSizeChange();
00030
00031     void Render();
00032
00033     float GetTitleHeightInDips();
00034
00035 private:
00036
00037     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00038     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00039     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00040     Microsoft::WRL::ComPtr<IDWriteFactory>          m_dwriteFactory;
00041     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_whiteBrush;
00042     Microsoft::WRL::ComPtr<ID2D1DrawingStateBlock>  m_stateBlock;
00043
00044     Microsoft::WRL::ComPtr<IWICImagingFactory>      m_wicFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Bitmap>             m_logoBitmap;
00046     Microsoft::WRL::ComPtr<IDWriteTextLayout>       m_textLayout;
00047
00048     UINT                                            m_idIncrement;
00049     bool                                            m_drawOverlay;
00050     Platform::String^                               m_sampleName;
00051     float                                           m_padding;
00052     float                                           m_textVerticalOffset;
00053     D2D1_SIZE_F                                     m_logoSize;
00054     float                                           m_overlayWidth;
00055 };
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: LightSensor/C++/MainPage.xaml.h Source File

  • LightSensor

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:46 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Lock screen apps/C#,C++/pch.cpp Source File

  • Lock screen apps
  • C#,C++

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: HttpClient/C++/common/LayoutAwarePage.cpp Source File

  • HttpClient
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:31 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML high contrast style/C++/Constants.h Source File

  • XAML high contrast style

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"XAML high contrast style sample");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

UiaCoreWindowProvider::ITriColorFragmentProvider Member List

This is the complete list of members for UiaCoreWindowProvider::ITriColorFragmentProvider, including all inherited members.
Initialize([in] ITriColorControlInternal *pControl,[in] TriColorValue value) UiaCoreWindowProvider::ITriColorFragmentProvider
Generated on Sat Nov 23 2024 16:09:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML AppBar control/C++/MainPage.xaml.h Source File

  • XAML AppBar control

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace AppBarControl
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     [Windows::Foundation::Metadata::WebHostHidden]
00052     public ref class MainPage sealed
00053     {
00054     public:
00055         MainPage();
00056
00057         property bool AutoSizeInputSectionWhenSnapped
00058         {
00059             bool get()
00060             {
00061                 return autoSizeInputSectionWhenSnapped;
00062             }
00063
00064             void set(bool value)
00065             {
00066                 autoSizeInputSectionWhenSnapped = value;
00067             }
00068         }
00069
00070         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00071
00072         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00073         void LoadScenario(Platform::String^ scenarioName);
00074         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00075         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00076
00077     private:
00078         void SetFeatureName(Platform::String^ strFeature);
00079         void PopulateScenarios();
00080         void InvalidateSize();
00081         void InvalidateViewState();
00082     void RegisterAppBarButtons();
00083         ~MainPage();
00084
00085         Platform::Collections::Vector<Object^>^ ScenarioList;
00086         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00087         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00088         bool autoSizeInputSectionWhenSnapped;
00089
00090
00091     protected:
00092         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00093         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00094         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00095     void BottonAppBar_Loaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096
00097     internal:
00098         static MainPage^ Current;
00099
00100     };
00101
00102 }
Generated on Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D command list/C++/CommandListSample.cpp Source File

  • Direct2D command list

CommandListSample.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 "CommandListSample.h"
00010 #include "BasicTimer.h"
00011
00012 using namespace D2D1;
00013
00014 using namespace Microsoft::WRL;
00015 using namespace Windows::ApplicationModel;
00016 using namespace Windows::ApplicationModel::Activation;
00017 using namespace Windows::ApplicationModel::Core;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::Graphics::Display;
00021 using namespace Windows::UI::Core;
00022 using namespace Windows::UI::Input;
00023 using namespace Windows::Storage;
00024 using namespace Windows::System;
00025
00026 static const float MinZoom = 0.0625f;
00027 static const float MaxZoom = 8.0f;
00028
00029 CommandListRenderer::CommandListRenderer():
00030     m_zoom(1.0f),
00031     m_recenterStartTime(0.0f),
00032     m_recenter(false),
00033     m_recenterStartZoom(1.0f),
00034     m_windowClosed(false),
00035     m_windowVisible(true)
00036 {
00037     m_recenterStartPosition.x = 0;
00038     m_recenterStartPosition.y = 0;
00039     m_viewPosition.X = 0;
00040     m_viewPosition.Y = 0;
00041 }
00042
00043 void CommandListRenderer::CreateDeviceResources()
00044 {
00045     DirectXBase::CreateDeviceResources();
00046
00047     m_sampleOverlay = ref new SampleOverlay();
00048
00049     m_sampleOverlay->Initialize(
00050         m_d2dDevice.Get(),
00051         m_d2dContext.Get(),
00052         m_wicFactory.Get(),
00053         m_dwriteFactory.Get(),
00054         "Direct2D command list and image brush sample"
00055         );
00056
00057     DX::ThrowIfFailed(
00058         m_d2dContext->CreateSolidColorBrush(
00059             D2D1::ColorF(D2D1::ColorF::DarkBlue),
00060             &m_blueBrush
00061             )
00062         );
00063
00064     DX::ThrowIfFailed(
00065         m_d2dContext->CreateCommandList(&m_commandList)
00066         );
00067
00068     m_d2dContext->SetTarget(m_commandList.Get());
00069     m_d2dContext->BeginDraw();
00070     DrawPattern();
00071
00072     // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00073     // is lost. It will be handled during the next call to Present.
00074     HRESULT hr = m_d2dContext->EndDraw();
00075     if (hr != D2DERR_RECREATE_TARGET)
00076     {
00077         DX::ThrowIfFailed(hr);
00078     }
00079
00080     DX::ThrowIfFailed(
00081         m_commandList->Close()
00082         );
00083
00084     DX::ThrowIfFailed(
00085         m_d2dContext->CreateImageBrush(
00086             m_commandList.Get(),
00087             D2D1::ImageBrushProperties(
00088                 D2D1::RectF(198, 298, 370, 470),
00089                 D2D1_EXTEND_MODE_WRAP,
00090                 D2D1_EXTEND_MODE_WRAP,
00091                 D2D1_INTERPOLATION_MODE_LINEAR
00092                 ),
00093             &m_imageBrush
00094             )
00095         );
00096 }
00097
00098 void CommandListRenderer::Render()
00099 {
00100     D2D1_SIZE_F size = m_d2dContext->GetSize();
00101
00102     m_d2dContext->BeginDraw();
00103
00104     m_d2dContext->Clear(D2D1::ColorF(D2D1::ColorF::CornflowerBlue));
00105     Matrix3x2F translation = Matrix3x2F::Translation(m_viewPosition.X / m_zoom, m_viewPosition.Y / m_zoom);
00106     Matrix3x2F zoom = Matrix3x2F::Scale(m_zoom, m_zoom);
00107
00108     m_imageBrush->SetTransform(translation * zoom);
00109
00110     m_d2dContext->FillRectangle(
00111         D2D1::RectF(0, 0, size.width, size.height),
00112         m_imageBrush.Get()
00113         );
00114
00115     // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00116     // is lost. It will be handled during the next call to Present.
00117     HRESULT hr = m_d2dContext->EndDraw();
00118     if (hr != D2DERR_RECREATE_TARGET)
00119     {
00120         DX::ThrowIfFailed(hr);
00121     }
00122
00123     m_sampleOverlay->Render();
00124 }
00125
00126 void CommandListRenderer::DrawPattern()
00127 {
00128     Microsoft::WRL::ComPtr<ID2D1LinearGradientBrush>        linearGradientBrush;
00129     Microsoft::WRL::ComPtr<ID2D1GradientStopCollection>     gradientStopCollection;
00130     D2D1_GRADIENT_STOP gradientStops[4];
00131     gradientStops[0].color = D2D1::ColorF(D2D1::ColorF::Aqua, 0.7f);
00132     gradientStops[0].position = 0.0f;
00133     gradientStops[1].color = D2D1::ColorF(D2D1::ColorF::DarkMagenta, 0.5f);
00134     gradientStops[1].position = 0.3f;
00135     gradientStops[2].color = D2D1::ColorF(D2D1::ColorF::Olive, 0.5f);
00136     gradientStops[2].position = 0.6f;
00137     gradientStops[3].color = D2D1::ColorF(D2D1::ColorF::Aqua, 0.7f);
00138     gradientStops[3].position = 1.0f;
00139
00140     DX::ThrowIfFailed(
00141         m_d2dContext->CreateGradientStopCollection(
00142             gradientStops,
00143             ARRAYSIZE(gradientStops),
00144             &gradientStopCollection
00145             )
00146         );
00147
00148     DX::ThrowIfFailed(
00149         m_d2dContext->CreateLinearGradientBrush(
00150             D2D1::LinearGradientBrushProperties(
00151                 D2D1::Point2F(250, 350),
00152                 D2D1::Point2F(275, 375)
00153                 ),
00154             gradientStopCollection.Get(),
00155             &linearGradientBrush
00156             )
00157         );
00158
00159     m_d2dContext->FillEllipse(
00160         D2D1::Ellipse(
00161             D2D1::Point2F(287.5, 387.5),
00162             75.0f,
00163             75.0f
00164             ),
00165         m_blueBrush.Get()
00166         );
00167
00168     m_d2dContext->FillEllipse(
00169         D2D1::Ellipse(
00170             D2D1::Point2F(262.5f, 362.5f),
00171             12.5f,
00172             12.5f
00173             ),
00174         linearGradientBrush.Get()
00175         );
00176
00177     linearGradientBrush->SetTransform(
00178         D2D1::Matrix3x2F::Translation(D2D1::SizeF(50, 50))
00179         );
00180
00181     m_d2dContext->FillEllipse(
00182         D2D1::Ellipse(
00183             D2D1::Point2F(312.5f, 412.5f),
00184             12.5f,
00185             12.5f
00186             ),
00187         linearGradientBrush.Get()
00188         );
00189
00190     linearGradientBrush->SetTransform(
00191         D2D1::Matrix3x2F::Translation(D2D1::SizeF(50, 0))
00192         );
00193
00194     m_d2dContext->FillEllipse(
00195         D2D1::Ellipse(
00196             D2D1::Point2F(312.5f, 362.5f),
00197             12.5f,
00198             12.5f
00199             ),
00200         linearGradientBrush.Get()
00201         );
00202
00203     linearGradientBrush->SetTransform(
00204         D2D1::Matrix3x2F::Translation(D2D1::SizeF(0, 50))
00205         );
00206
00207     m_d2dContext->FillEllipse(
00208         D2D1::Ellipse(
00209             D2D1::Point2F(262.5f, 412.5f),
00210             12.5f,
00211             12.5f
00212             ),
00213         linearGradientBrush.Get()
00214         );
00215 }
00216
00217 void CommandListRenderer::Update(float timeTotal)
00218 {
00219     // A douple tap will set this variable to true, meaning we should start recentering.
00220     if (m_recenter)
00221     {
00222         // If the start time of the animation isn't known yet, set it to the current time.
00223         if (m_recenterStartTime == 0.0f)
00224         {
00225             m_recenterStartTime = timeTotal;
00226         }
00227
00228         // Determine how far along in the animation we should be (we want the animation to take a
00229         // quarter of a second)
00230         float delta = (timeTotal - m_recenterStartTime) * 4.0f;
00231
00232         // If we're at the end of the animation, ensure we've completely reset the position and zoom,
00233         // and clear the animation flag
00234         if (delta > 1.0f)
00235         {
00236             m_viewPosition.X = 0;
00237             m_viewPosition.Y = 0;
00238             m_zoom = 1.0f;
00239             m_recenterStartTime = 0.0f;
00240             m_recenter = false;
00241         }
00242
00243         // Otherwise, linearly interpolate between the starting position and the reset position.
00244         else
00245         {
00246             m_viewPosition.X = LinearInterpolate(m_recenterStartPosition.x, 0, delta);
00247             m_viewPosition.Y = LinearInterpolate(m_recenterStartPosition.y, 0, delta);
00248             m_zoom = LinearInterpolate(m_recenterStartZoom, 1.0f, delta);
00249         }
00250     }
00251 }
00252
00253 void CommandListRenderer::HandlePointerDoubleTapped(Point position)
00254 {
00255     // A double tap means we should recenter.
00256     m_recenter = true;
00257     m_recenterStartPosition.x = m_viewPosition.X;
00258     m_recenterStartPosition.y = m_viewPosition.Y;
00259     m_recenterStartZoom = m_zoom;
00260 }
00261
00262 void CommandListRenderer::Initialize(
00263     _In_ CoreApplicationView^ applicationView
00264     )
00265 {
00266     applicationView->Activated +=
00267         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &CommandListRenderer::OnActivated);
00268
00269     CoreApplication::Suspending +=
00270         ref new EventHandler<SuspendingEventArgs^>(this, &CommandListRenderer::OnSuspending);
00271
00272     CoreApplication::Resuming +=
00273         ref new EventHandler<Platform::Object^>(this, &CommandListRenderer::OnResuming);
00274 }
00275
00276 void CommandListRenderer::SetWindow(
00277     _In_ CoreWindow^ window
00278     )
00279 {
00280     window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
00281
00282     window->SizeChanged +=
00283         ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &CommandListRenderer::OnWindowSizeChanged);
00284
00285     window->VisibilityChanged +=
00286         ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &CommandListRenderer::OnVisibilityChanged);
00287
00288     window->PointerPressed +=
00289         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &CommandListRenderer::OnPointerPressed);
00290
00291     window->PointerReleased +=
00292         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &CommandListRenderer::OnPointerReleased);
00293
00294     window->PointerMoved +=
00295         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &CommandListRenderer::OnPointerMoved);
00296
00297     window->PointerWheelChanged +=
00298         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &CommandListRenderer::OnPointerWheelChanged);
00299
00300     window->Closed +=
00301         ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &CommandListRenderer::OnWindowClosed);
00302
00303     DisplayProperties::LogicalDpiChanged +=
00304         ref new DisplayPropertiesEventHandler(this, &CommandListRenderer::OnLogicalDpiChanged);
00305
00306     DirectXBase::Initialize(window, DisplayProperties::LogicalDpi);
00307
00308     m_gestureRecognizer = ref new GestureRecognizer();
00309
00310     m_gestureRecognizer->AutoProcessInertia = true;
00311
00312     m_gestureRecognizer->GestureSettings =
00313         GestureSettings::DoubleTap                     |
00314         GestureSettings::ManipulationTranslateX        |
00315         GestureSettings::ManipulationTranslateY        |
00316         GestureSettings::ManipulationScale             |
00317         GestureSettings::ManipulationTranslateInertia  |
00318         GestureSettings::ManipulationScaleInertia;
00319
00320     m_gestureRecognizer->Tapped +=
00321         ref new TypedEventHandler<GestureRecognizer^, TappedEventArgs^>(this, &CommandListRenderer::OnTapped);
00322
00323     m_gestureRecognizer->ManipulationUpdated +=
00324         ref new TypedEventHandler<GestureRecognizer^, ManipulationUpdatedEventArgs^>(this, &CommandListRenderer::OnManipulationUpdated);
00325 }
00326
00327 void CommandListRenderer::Load(
00328     _In_ Platform::String^ entryPoint
00329     )
00330 {
00331     // Retrieve stored variables from the LocalSettings collection if the app was terminated after suspension.
00332     IPropertySet^ settingsValues = ApplicationData::Current->LocalSettings->Values;
00333
00334     if (settingsValues->HasKey("m_zoom"))
00335     {
00336         m_zoom = safe_cast<IPropertyValue^>(settingsValues->Lookup("m_zoom"))->GetSingle();
00337     }
00338
00339     if (settingsValues->HasKey("m_viewPosition"))
00340     {
00341         m_viewPosition = safe_cast<IPropertyValue^>(settingsValues->Lookup("m_viewPosition"))->GetPoint();
00342     }
00343 }
00344
00345 void CommandListRenderer::Run()
00346 {
00347     BasicTimer^ timer = ref new BasicTimer();
00348
00349     while (!m_windowClosed)
00350     {
00351         if (m_windowVisible)
00352         {
00353             timer->Update();
00354             m_window->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
00355             Update(timer->Total);
00356             Render();
00357             Present(); // This call is synchronized to the display frame rate.
00358         }
00359         else
00360         {
00361             m_window->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
00362         }
00363     }
00364 }
00365
00366 void CommandListRenderer::Uninitialize()
00367 {
00368 }
00369
00370 void CommandListRenderer::OnWindowSizeChanged(
00371     _In_ CoreWindow^ sender,
00372     _In_ WindowSizeChangedEventArgs^ args
00373     )
00374 {
00375     UpdateForWindowSizeChange();
00376     m_sampleOverlay->UpdateForWindowSizeChange();
00377 }
00378
00379 void CommandListRenderer::OnVisibilityChanged(
00380     _In_ CoreWindow^ sender,
00381     _In_ VisibilityChangedEventArgs^ args
00382     )
00383 {
00384     m_windowVisible = args->Visible;
00385 }
00386
00387 void CommandListRenderer::OnLogicalDpiChanged(
00388     _In_ Platform::Object^ sender
00389     )
00390 {
00391     SetDpi(DisplayProperties::LogicalDpi);
00392 }
00393
00394 void CommandListRenderer::OnActivated(
00395     _In_ CoreApplicationView^ applicationView,
00396     _In_ IActivatedEventArgs^ args
00397     )
00398 {
00399     m_window->Activate();
00400 }
00401
00402 void CommandListRenderer::OnSuspending(
00403     _In_ Platform::Object^ sender,
00404     _In_ SuspendingEventArgs^ args
00405     )
00406 {
00407     // Store user-manipulated properties in the LocalSettings collection.
00408     IPropertySet^ settingsValues = ApplicationData::Current->LocalSettings->Values;
00409
00410     // Check to ensure each key is not already in the collection. If it is present, remove
00411     // it before storing in the new value. These values will be retrieved in the Load method.
00412
00413     if (settingsValues->HasKey("m_zoom"))
00414     {
00415         settingsValues->Remove("m_zoom");
00416     }
00417     settingsValues->Insert("m_zoom", PropertyValue::CreateSingle(m_zoom));
00418
00419     if (settingsValues->HasKey("m_viewPosition"))
00420     {
00421         settingsValues->Remove("m_viewPosition");
00422     }
00423     settingsValues->Insert("m_viewPosition", PropertyValue::CreatePoint(m_viewPosition));
00424 }
00425
00426 void CommandListRenderer::OnResuming(
00427     _In_ Platform::Object^ sender,
00428     _In_ Platform::Object^ args
00429     )
00430 {
00431 }
00432
00433 void CommandListRenderer::OnWindowClosed(
00434     _In_ CoreWindow^ sender,
00435     _In_ CoreWindowEventArgs^ args
00436     )
00437 {
00438     m_windowClosed = true;
00439 }
00440
00441 void CommandListRenderer::OnPointerPressed(
00442     _In_ CoreWindow^ window,
00443     _In_ PointerEventArgs^ args
00444     )
00445 {
00446     m_gestureRecognizer->ProcessDownEvent(args->CurrentPoint);
00447 }
00448
00449 void CommandListRenderer::OnPointerReleased(
00450     _In_ CoreWindow^ window,
00451     _In_ PointerEventArgs^ args
00452     )
00453 {
00454     m_gestureRecognizer->ProcessUpEvent(args->CurrentPoint);
00455 }
00456
00457 void CommandListRenderer::OnPointerMoved(
00458     _In_ CoreWindow^ window,
00459     _In_ PointerEventArgs^ args
00460     )
00461 {
00462     m_gestureRecognizer->ProcessMoveEvents(args->GetIntermediatePoints());
00463 }
00464
00465 void CommandListRenderer::OnPointerWheelChanged(
00466     _In_ CoreWindow^ window,
00467     _In_ PointerEventArgs^ args
00468     )
00469 {
00470     // We are ignoring the gesture that wheel movement means panning.
00471     // Zooming is indicated by holding the Control key down, so we
00472     // override this method always to detect a zoom wheel event.
00473     m_gestureRecognizer->ProcessMouseWheelEvent(args->CurrentPoint, FALSE, TRUE);
00474 }
00475
00476 void CommandListRenderer::OnTapped(
00477     _In_ GestureRecognizer^ gestureRecognizer,
00478     _In_ TappedEventArgs^ args
00479     )
00480 {
00481     if (args->TapCount == 2)
00482     {
00483         HandlePointerDoubleTapped(args->Position);
00484     }
00485 }
00486
00487 void CommandListRenderer::OnManipulationUpdated(
00488     _In_ GestureRecognizer^ gestureRecognizer,
00489     _In_ ManipulationUpdatedEventArgs^ args
00490     )
00491 {
00492     Point position = args->Position;
00493     Point positionDelta = args->Delta.Translation;
00494     float zoomDelta = args->Delta.Scale;
00495
00496     // In this method, we simply update the transformation variables to reflect how the user is manipulating the scene.
00497     // The gesture recognizer does the majority of the math; we simply need to update our internal variables.
00498
00499     // Reposition the view to reflect translations.
00500     m_viewPosition.X += positionDelta.X;
00501     m_viewPosition.Y += positionDelta.Y;
00502
00503     // We want to have any zoom operation be "centered" around the pointer position, which
00504     // requires recalculating the view position based on the new zoom and pointer position.
00505     // Step 1: Calculate the absolute pointer position (image position).
00506     D2D1_POINT_2F pointerAbsolutePosition = D2D1::Point2F(
00507         (m_viewPosition.X - position.X) / m_zoom,
00508         (m_viewPosition.Y - position.Y) / m_zoom
00509         );
00510
00511     // Step 2: Apply the zoom operation and clamp to the min/max zoom.
00512     // zoomDelta is a coefficient for the change in zoom.
00513     m_zoom *= zoomDelta;
00514     m_zoom = Clamp(m_zoom, MinZoom, MaxZoom);
00515
00516     // Step 3: Adjust the view position based on the new m_zoom value.
00517     m_viewPosition.X = pointerAbsolutePosition.x * m_zoom + position.X;
00518     m_viewPosition.Y = pointerAbsolutePosition.y * m_zoom + position.Y;
00519 }
00520
00521 IFrameworkView^ DirectXAppSource::CreateView()
00522 {
00523     return ref new CommandListRenderer();
00524 }
00525
00526 [Platform::MTAThread]
00527 int main(Platform::Array<Platform::String^>^)
00528 {
00529     auto directXAppSource = ref new DirectXAppSource();
00530     CoreApplication::Run(directXAppSource);
00531     return 0;
00532 }
Generated on Sat Nov 23 2024 16:08:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Device capabilities/C++/Keyboard.xaml.h Source File

  • Input Device capabilities

Keyboard.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 // Keyboard.xaml.h
00013 // Declaration of the Keyboard class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Keyboard.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace DeviceCaps
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 Keyboard sealed
00031         {
00032         public:
00033             Keyboard();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void KeyboardGetSettings_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D magazine app/C++/pch.h Source File

  • Direct2D magazine app

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 <objidl.h>
00011 #include <strsafe.h>
00012 #include <wrl.h>
00013 #include <windows.ui.xaml.media.dxinterop.h>
00014 #include <ppltasks.h>
00015 #include <agile.h>
00016
00017 #include "Renderer.h"
00018 #include "Document.h"
00019 #include "FontFileStream.h"
00020 #include "FontLoader.h"
00021 #include "TreeIterator.h"
00022 #include "Element.h"
00023 #include "Resource.h"
00024 #include "ImageFile.h"
00025 #include "Image.h"
00026 #include "Text.h"
00027 #include "Story.h"
00028 #include "Design.h"
00029 #include "PageRoll.h"
00030 #include "Page.h"
00031 #include "Layer.h"
00032 #include "List.h"
00033 #include "Rectangle.h"
00034 #include "TextFrame.h"
00035 #include "ImageFrame.h"
00036 #include "ContentImageSource.h"
00037 #include "PageModel.h"
00038 #include "MainPage.xaml.h"
00039 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

TGA_HEADER Member List

This is the complete list of members for TGA_HEADER, including all inherited members.
bBitsPerPixel | TGA_HEADER
bColorMapSize | TGA_HEADER
bColorMapType | TGA_HEADER
bDescriptor | TGA_HEADER
bIDLength | TGA_HEADER
bImageType | TGA_HEADER
wColorMapFirst | TGA_HEADER
wColorMapLength | TGA_HEADER
wHeight | TGA_HEADER
wWidth | TGA_HEADER
wXOrigin | TGA_HEADER
wYOrigin | TGA_HEADER
Generated on Sat Nov 23 2024 16:09:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D tutorial/C++/Lesson1.Basics/DirectXSample.h Source File

  • Direct3D tutorial
  • Lesson1.Basics

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
00010 // This header defines helper utilities to make DirectX APIs work with exceptions.
00011 namespace DX
00012 {
00013     inline void ThrowIfFailed(HRESULT hr)
00014     {
00015         if (FAILED(hr))
00016         {
00017             // Set a breakpoint on this line to catch DX API errors.
00018             throw Platform::Exception::CreateException(hr);
00019         }
00020     }
00021 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File picker contracts/C++/CachedFileUpdater_Remote.xaml.h Source File

  • File picker contracts

CachedFileUpdater_Remote.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 // CachedFileUpdater_Remote.xaml.h
00013 // Declaration of the CachedFileUpdater_Remote class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "CachedFileUpdater_Remote.g.h"
00020
00021 namespace SDKSample
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 ref class CachedFileUpdater_Remote sealed
00029         {
00030         public:
00031             CachedFileUpdater_Remote();
00032
00033         private:
00034             void OverwriteButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00035             void RenameButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00036             void UpdateUI(Windows::Storage::Provider::UIStatus uiStatus);
00037             void OutputFileAsync(Windows::Storage::StorageFile^ file);
00038         };
00039     }
00040 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C#,C++/MediaExtensions/Polar/dllmain.cpp Source File

  • Media extensions
  • C#,C++
  • MediaExtensions
  • Polar

dllmain.cpp

Go to the documentation of this file.
00001 //////////////////////////////////////////////////////////////////////////
00002 //
00003 // dllmain.cpp
00004 //
00005 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00007 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00008 // PARTICULAR PURPOSE.
00009 //
00010 // Copyright (c) Microsoft Corporation. All rights reserved.
00011 //
00012 //////////////////////////////////////////////////////////////////////////
00013
00014 #include <initguid.h>
00015 #include "PolarEffect.h"
00016
00017 namespace Microsoft { namespace Samples {
00018     ActivatableClass(CPolarEffect);
00019 }}
00020
00021 BOOL WINAPI DllMain( _In_ HINSTANCE hInstance, _In_ DWORD dwReason, _In_opt_ LPVOID lpReserved )
00022 {
00023     if( DLL_PROCESS_ATTACH == dwReason )
00024     {
00025         //
00026         //  Don't need per-thread callbacks
00027         //
00028         DisableThreadLibraryCalls( hInstance );
00029
00030         Module<InProc>::GetModule().Create();
00031     }
00032     else if( DLL_PROCESS_DETACH == dwReason )
00033     {
00034         Module<InProc>::GetModule().Terminate();
00035     }
00036
00037     return TRUE;
00038 }
00039
00040 HRESULT WINAPI DllGetActivationFactory( _In_ HSTRING activatibleClassId, _Outptr_ IActivationFactory** factory )
00041 {
00042     auto &module = Microsoft::WRL::Module< Microsoft::WRL::InProc >::GetModule();
00043     return module.GetActivationFactory( activatibleClassId, factory );
00044 }
00045
00046 HRESULT WINAPI DllCanUnloadNow()
00047 {
00048     auto &module = Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule();
00049     return (module.Terminate()) ? S_OK : S_FALSE;
00050 }
00051
00052 STDAPI DllGetClassObject( _In_ REFCLSID rclsid, _In_ REFIID riid, _Outptr_ LPVOID FAR* ppv )
00053 {
00054     auto &module = Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule();
00055     return module.GetClassObject( rclsid, riid, ppv );
00056 }
Generated on Sat Nov 23 2024 16:08:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DirectXApp Member List

This is the complete list of members for DirectXApp, including all inherited members.
__pad0__ | DirectXApp |
HideGameInfoOverlay() | DirectXApp | [private]
HideSnapped() | DirectXApp | [private]
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | DirectXApp | [virtual]
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | DirectXApp | [virtual]
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | DirectXApp | [virtual]
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | DirectXApp | [virtual]
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | DirectXApp | [virtual]
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | DirectXApp | [virtual]
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | DirectXApp | [virtual]
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | DirectXApp | [virtual]
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | DirectXApp | [virtual]
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | DirectXApp | [virtual]
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | DirectXApp | [virtual]
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | DirectXApp | [virtual]
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | DirectXApp | [virtual]
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | DirectXApp | [virtual]
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | DirectXApp | [virtual]
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | DirectXApp | [virtual]
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | DirectXApp | [virtual]
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | DirectXApp | [virtual]
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | DirectXApp | [virtual]
InitializeGameState() | DirectXApp | [private]
InitPrintManager() | DirectXApp | [private]
InitPrintManager() | DirectXApp | [private]
Load(_In_ Platform::String^entryPoint) | DirectXApp | [virtual]
Load(_In_ Platform::String^entryPoint) | DirectXApp | [virtual]
Load(_In_ Platform::String^entryPoint) | DirectXApp | [virtual]
Load(_In_ Platform::String^entryPoint) | DirectXApp | [virtual]
Load(_In_ Platform::String^entryPoint) | DirectXApp | [virtual]
Load(_In_ Platform::String^entryPoint) | DirectXApp | [virtual]
Load(_In_ Platform::String^entryPoint) | DirectXApp | [virtual]
Load(_In_ Platform::String^entryPoint) | DirectXApp | [virtual]
Load(_In_ Platform::String^entryPoint) | DirectXApp | [virtual]
Load(_In_ Platform::String^entryPoint) | DirectXApp | [virtual]
Load(_In_ Platform::String^entryPoint) | DirectXApp | [virtual]
Load(_In_ Platform::String^entryPoint) | DirectXApp | [virtual]
Load(_In_ Platform::String^entryPoint) | DirectXApp | [virtual]
Load(_In_ Platform::String^entryPoint) | DirectXApp | [virtual]
Load(_In_ Platform::String^entryPoint) | DirectXApp | [virtual]
Load(_In_ Platform::String^entryPoint) | DirectXApp | [virtual]
Load(_In_ Platform::String^entryPoint) | DirectXApp | [virtual]
Load(_In_ Platform::String^entryPoint) | DirectXApp | [virtual]
Load(_In_ Platform::String^entryPoint) | DirectXApp | [virtual]
m_controller | DirectXApp | [private]
m_game | DirectXApp | [private]
m_gameInfoOverlayCommand | DirectXApp | [private]
m_gameInfoOverlayState | DirectXApp | [private]
m_gestureRecognizer | DirectXApp | [private]
m_haveFocus | DirectXApp | [private]
m_loadingCount | DirectXApp | [private]
m_pressResult | DirectXApp | [private]
m_printManager | DirectXApp | [private]
m_renderer | DirectXApp | [private]
m_renderer | DirectXApp | [private]
m_renderer | DirectXApp | [private]
m_renderer | DirectXApp | [private]
m_renderer | DirectXApp | [private]
m_renderer | DirectXApp | [private]
m_renderer | DirectXApp | [private]
m_renderer | DirectXApp | [private]
m_renderer | DirectXApp | [private]
m_renderer | DirectXApp | [private]
m_renderer | DirectXApp | [private]
m_renderer | DirectXApp | [private]
m_renderer | DirectXApp | [private]
m_renderer | DirectXApp | [private]
m_renderer | DirectXApp | [private]
m_renderer | DirectXApp | [private]
m_renderer | DirectXApp | [private]
m_renderer | DirectXApp | [private]
m_renderNeeded | DirectXApp | [private]
m_rotationKeyDown | DirectXApp | [private]
m_updateState | DirectXApp | [private]
m_updateStateNext | DirectXApp | [private]
m_visible | DirectXApp | [private]
m_windowClosed | DirectXApp | [private]
m_windowVisible | DirectXApp | [private]
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | DirectXApp | [private]
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | DirectXApp | [private]
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | DirectXApp | [private]
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | DirectXApp | [private]
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | DirectXApp | [private]
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | DirectXApp | [private]
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | DirectXApp | [private]
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | DirectXApp | [private]
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | DirectXApp | [private]
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | DirectXApp | [private]
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | DirectXApp | [private]
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | DirectXApp | [private]
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | DirectXApp | [private]
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | DirectXApp | [private]
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | DirectXApp | [private]
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | DirectXApp | [private]
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | DirectXApp | [private]
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | DirectXApp | [private]
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | DirectXApp | [private]
OnDeviceLost() | DirectXApp | [private]
OnDeviceReset() | DirectXApp | [private]
OnDisplayContentsInvalidated(_In_ Platform::Object^sender) | DirectXApp | [private]
OnKeyDown(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::KeyEventArgs^args) | DirectXApp | [private]
OnKeyDown(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::KeyEventArgs^args) | DirectXApp | [private]
OnKeyDown(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::KeyEventArgs^args) | DirectXApp | [private]
OnKeyUp(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::KeyEventArgs^args) | DirectXApp | [private]
OnKeyUp(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::KeyEventArgs^args) | DirectXApp | [private]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | DirectXApp | [private]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | DirectXApp | [private]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | DirectXApp | [private]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | DirectXApp | [private]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | DirectXApp | [private]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | DirectXApp | [private]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | DirectXApp | [private]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | DirectXApp | [private]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | DirectXApp | [private]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | DirectXApp | [private]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | DirectXApp | [private]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | DirectXApp | [private]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | DirectXApp | [private]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | DirectXApp | [private]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | DirectXApp | [private]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | DirectXApp | [private]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | DirectXApp | [private]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | DirectXApp | [private]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | DirectXApp | [private]
OnManipulationUpdated(_In_ Windows::UI::Input::GestureRecognizer^sender, _In_ Windows::UI::Input::ManipulationUpdatedEventArgs^args) | DirectXApp | [private]
OnOrientationChanged(_In_ Platform::Object^sender) | DirectXApp | [private]
OnPointerMoved(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | DirectXApp | [private]
OnPointerMoved(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | DirectXApp | [private]
OnPointerMoved(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | DirectXApp | [private]
OnPointerPressed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | DirectXApp | [private]
OnPointerPressed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | DirectXApp | [private]
OnPointerPressed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | DirectXApp | [private]
OnPointerPressed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | DirectXApp | [private]
OnPointerReleased(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | DirectXApp | [private]
OnPointerReleased(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | DirectXApp | [private]
OnPointerReleased(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | DirectXApp | [private]
OnPointerWheelChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | DirectXApp | [private]
OnResuming(_In_ Platform::Object^sender, _In_ Platform::Object^args) | DirectXApp | [private]
OnResuming(_In_ Platform::Object^sender, _In_ Platform::Object^args) | DirectXApp | [private]
OnResuming(_In_ Platform::Object^sender, _In_ Platform::Object^args) | DirectXApp | [private]
OnResuming(_In_ Platform::Object^sender, _In_ Platform::Object^args) | DirectXApp | [private]
OnResuming(_In_ Platform::Object^sender, _In_ Platform::Object^args) | DirectXApp | [private]
OnResuming(_In_ Platform::Object^sender, _In_ Platform::Object^args) | DirectXApp | [private]
OnResuming(_In_ Platform::Object^sender, _In_ Platform::Object^args) | DirectXApp | [private]
OnResuming(_In_ Platform::Object^sender, _In_ Platform::Object^args) | DirectXApp | [private]
OnResuming(_In_ Platform::Object^sender, _In_ Platform::Object^args) | DirectXApp | [private]
OnResuming(_In_ Platform::Object^sender, _In_ Platform::Object^args) | DirectXApp | [private]
OnResuming(_In_ Platform::Object^sender, _In_ Platform::Object^args) | DirectXApp | [private]
OnResuming(_In_ Platform::Object^sender, _In_ Platform::Object^args) | DirectXApp | [private]
OnResuming(_In_ Platform::Object^sender, _In_ Platform::Object^args) | DirectXApp | [private]
OnSuspending(_In_ Platform::Object^sender, _In_ Windows::ApplicationModel::SuspendingEventArgs^args) | DirectXApp | [private]
OnSuspending(_In_ Platform::Object^sender, _In_ Windows::ApplicationModel::SuspendingEventArgs^args) | DirectXApp | [private]
OnSuspending(_In_ Platform::Object^sender, _In_ Windows::ApplicationModel::SuspendingEventArgs^args) | DirectXApp | [private]
OnSuspending(_In_ Platform::Object^sender, _In_ Windows::ApplicationModel::SuspendingEventArgs^args) | DirectXApp | [private]
OnSuspending(_In_ Platform::Object^sender, _In_ Windows::ApplicationModel::SuspendingEventArgs^args) | DirectXApp | [private]
OnSuspending(_In_ Platform::Object^sender, _In_ Windows::ApplicationModel::SuspendingEventArgs^args) | DirectXApp | [private]
OnSuspending(_In_ Platform::Object^sender, _In_ Windows::ApplicationModel::SuspendingEventArgs^args) | DirectXApp | [private]
OnSuspending(_In_ Platform::Object^sender, _In_ Windows::ApplicationModel::SuspendingEventArgs^args) | DirectXApp | [private]
OnSuspending(_In_ Platform::Object^sender, _In_ Windows::ApplicationModel::SuspendingEventArgs^args) | DirectXApp | [private]
OnSuspending(_In_ Platform::Object^sender, _In_ Windows::ApplicationModel::SuspendingEventArgs^args) | DirectXApp | [private]
OnSuspending(_In_ Platform::Object^sender, _In_ Windows::ApplicationModel::SuspendingEventArgs^args) | DirectXApp | [private]
OnSuspending(_In_ Platform::Object^sender, _In_ Windows::ApplicationModel::SuspendingEventArgs^args) | DirectXApp | [private]
OnSuspending(_In_ Platform::Object^sender, _In_ Windows::ApplicationModel::SuspendingEventArgs^args) | DirectXApp | [private]
OnSuspending(_In_ Platform::Object^sender, _In_ Windows::ApplicationModel::SuspendingEventArgs^args) | DirectXApp | [private]
OnSuspending(_In_ Platform::Object^sender, _In_ Windows::ApplicationModel::SuspendingEventArgs^args) | DirectXApp | [private]
OnVisibilityChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::VisibilityChangedEventArgs^args) | DirectXApp | [private]
OnVisibilityChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::VisibilityChangedEventArgs^args) | DirectXApp | [private]
OnVisibilityChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::VisibilityChangedEventArgs^args) | DirectXApp | [private]
OnVisibilityChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::VisibilityChangedEventArgs^args) | DirectXApp | [private]
OnVisibilityChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::VisibilityChangedEventArgs^args) | DirectXApp | [private]
OnVisibilityChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::VisibilityChangedEventArgs^args) | DirectXApp | [private]
OnVisibilityChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::VisibilityChangedEventArgs^args) | DirectXApp | [private]
OnVisibilityChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::VisibilityChangedEventArgs^args) | DirectXApp | [private]
OnVisibilityChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::VisibilityChangedEventArgs^args) | DirectXApp | [private]
OnVisibilityChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::VisibilityChangedEventArgs^args) | DirectXApp | [private]
OnVisibilityChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::VisibilityChangedEventArgs^args) | DirectXApp | [private]
OnVisibilityChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::VisibilityChangedEventArgs^args) | DirectXApp | [private]
OnVisibilityChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::VisibilityChangedEventArgs^args) | DirectXApp | [private]
OnVisibilityChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::VisibilityChangedEventArgs^args) | DirectXApp | [private]
OnVisibilityChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::VisibilityChangedEventArgs^args) | DirectXApp | [private]
OnVisibilityChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::VisibilityChangedEventArgs^args) | DirectXApp | [private]
OnVisibilityChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::VisibilityChangedEventArgs^args) | DirectXApp | [private]
OnVisibilityChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::VisibilityChangedEventArgs^args) | DirectXApp | [private]
OnVisibilityChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::VisibilityChangedEventArgs^args) | DirectXApp | [private]
OnWindowActivationChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowActivatedEventArgs^args) | DirectXApp | [private]
OnWindowActivationChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowActivatedEventArgs^args) | DirectXApp | [private]
OnWindowClosed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::CoreWindowEventArgs^args) | DirectXApp | [private]
OnWindowClosed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::CoreWindowEventArgs^args) | DirectXApp | [private]
OnWindowClosed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::CoreWindowEventArgs^args) | DirectXApp | [private]
OnWindowClosed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::CoreWindowEventArgs^args) | DirectXApp | [private]
OnWindowClosed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::CoreWindowEventArgs^args) | DirectXApp | [private]
OnWindowClosed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::CoreWindowEventArgs^args) | DirectXApp | [private]
OnWindowClosed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::CoreWindowEventArgs^args) | DirectXApp | [private]
OnWindowClosed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::CoreWindowEventArgs^args) | DirectXApp | [private]
OnWindowClosed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::CoreWindowEventArgs^args) | DirectXApp | [private]
OnWindowClosed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::CoreWindowEventArgs^args) | DirectXApp | [private]
OnWindowClosed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::CoreWindowEventArgs^args) | DirectXApp | [private]
OnWindowClosed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::CoreWindowEventArgs^args) | DirectXApp | [private]
OnWindowClosed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::CoreWindowEventArgs^args) | DirectXApp | [private]
OnWindowClosed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::CoreWindowEventArgs^args) | DirectXApp | [private]
OnWindowClosed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::CoreWindowEventArgs^args) | DirectXApp | [private]
OnWindowClosed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::CoreWindowEventArgs^args) | DirectXApp | [private]
OnWindowClosed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::CoreWindowEventArgs^args) | DirectXApp | [private]
OnWindowClosed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::CoreWindowEventArgs^args) | DirectXApp | [private]
OnWindowClosed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::CoreWindowEventArgs^args) | DirectXApp | [private]
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | DirectXApp | [private]
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | DirectXApp | [private]
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | DirectXApp | [private]
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | DirectXApp | [private]
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | DirectXApp | [private]
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | DirectXApp | [private]
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | DirectXApp | [private]
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | DirectXApp | [private]
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | DirectXApp | [private]
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | DirectXApp | [private]
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | DirectXApp | [private]
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | DirectXApp | [private]
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | DirectXApp | [private]
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | DirectXApp | [private]
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | DirectXApp | [private]
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | DirectXApp | [private]
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | DirectXApp | [private]
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | DirectXApp | [private]
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | DirectXApp | [private]
Run() | DirectXApp | [virtual]
Run() | DirectXApp | [virtual]
Run() | DirectXApp | [virtual]
Run() | DirectXApp | [virtual]
Run() | DirectXApp | [virtual]
Run() | DirectXApp | [virtual]
Run() | DirectXApp | [virtual]
Run() | DirectXApp | [virtual]
Run() | DirectXApp | [virtual]
Run() | DirectXApp | [virtual]
Run() | DirectXApp | [virtual]
Run() | DirectXApp | [virtual]
Run() | DirectXApp | [virtual]
Run() | DirectXApp | [virtual]
Run() | DirectXApp | [virtual]
Run() | DirectXApp | [virtual]
Run() | DirectXApp | [virtual]
Run() | DirectXApp | [virtual]
Run() | DirectXApp | [virtual]
SetAction(GameInfoOverlayCommand command) | DirectXApp | [private]
SetGameInfoOverlay(GameInfoOverlayState state) | DirectXApp | [private]
SetPrintTask(_In_ Windows::Graphics::Printing::PrintManager^sender, _In_ Windows::Graphics::Printing::PrintTaskRequestedEventArgs^args) | DirectXApp | [private]
SetPrintTask(_In_ Windows::Graphics::Printing::PrintManager^sender, _In_ Windows::Graphics::Printing::PrintTaskRequestedEventArgs^args) | DirectXApp | [private]
SetSnapped() | DirectXApp | [private]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | DirectXApp | [virtual]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | DirectXApp | [virtual]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | DirectXApp | [virtual]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | DirectXApp | [virtual]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | DirectXApp | [virtual]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | DirectXApp | [virtual]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | DirectXApp | [virtual]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | DirectXApp | [virtual]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | DirectXApp | [virtual]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | DirectXApp | [virtual]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | DirectXApp | [virtual]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | DirectXApp | [virtual]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | DirectXApp | [virtual]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | DirectXApp | [virtual]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | DirectXApp | [virtual]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | DirectXApp | [virtual]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | DirectXApp | [virtual]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | DirectXApp | [virtual]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | DirectXApp | [virtual]
ShowGameInfoOverlay() | DirectXApp | [private]
Uninitialize() | DirectXApp | [virtual]
Uninitialize() | DirectXApp | [virtual]
Uninitialize() | DirectXApp | [virtual]
Uninitialize() | DirectXApp | [virtual]
Uninitialize() | DirectXApp | [virtual]
Uninitialize() | DirectXApp | [virtual]
Uninitialize() | DirectXApp | [virtual]
Uninitialize() | DirectXApp | [virtual]
Uninitialize() | DirectXApp | [virtual]
Uninitialize() | DirectXApp | [virtual]
Uninitialize() | DirectXApp | [virtual]
Uninitialize() | DirectXApp | [virtual]
Uninitialize() | DirectXApp | [virtual]
Uninitialize() | DirectXApp | [virtual]
Uninitialize() | DirectXApp | [virtual]
Uninitialize() | DirectXApp | [virtual]
Uninitialize() | DirectXApp | [virtual]
Uninitialize() | DirectXApp | [virtual]
Uninitialize() | DirectXApp | [virtual]
Update() | DirectXApp | [private]
UpdateViewState() | DirectXApp | [private]
Generated on Sat Nov 23 2024 16:09:11 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

CustomDeviceAccess::DeviceAsync Member List

This is the complete list of members for CustomDeviceAccess::DeviceAsync, including all inherited members.
__pad0__ | Element |
AcceptChildNode(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^childXmlNode) override | Page | [virtual]
AddChild(_In_ Element^element) | Element |
AddSibling(_In_ Element^element) | Element |
BindResource(_In_ Element^rootElement) | Element | [virtual]
ClearBarGraphTable() | CustomDeviceAccess::DeviceAsync | [inline, private]
Create(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^xmlNode) | Element | [static]
DefaultViewModel | SDKTemplate::Common::LayoutAwarePage | [protected]
DefaultViewModelProperty | SDKTemplate::Common::LayoutAwarePage | [static]
DetermineVisualState(ApplicationViewState viewState) | SDKTemplate::Common::LayoutAwarePage | [inline, protected, virtual]
DetermineVisualState(ApplicationViewState viewState) | SDKTemplate::Common::LayoutAwarePage | [inline, protected, virtual]
DeviceAsync() | CustomDeviceAccess::DeviceAsync | [inline]
deviceAsyncGet_Click_1(object sender, RoutedEventArgs e) | CustomDeviceAccess::DeviceAsync | [inline, private]
deviceAsyncSet_Click_1(object sender, RoutedEventArgs e) | CustomDeviceAccess::DeviceAsync | [inline, private]
Draw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
GetFirstChild() | Element | [inline]
GetName() | Element | [inline]
GetNextSibling() | Element | [inline]
GetOpacity() | Element | [inline, virtual]
GetParent() | Element | [inline]
GetSize() | Element | [inline]
GoBack(object sender, RoutedEventArgs e) | SDKTemplate::Common::LayoutAwarePage | [inline, protected, virtual]
GoBack(object sender, RoutedEventArgs e) | SDKTemplate::Common::LayoutAwarePage | [inline, protected, virtual]
GoHome(object sender, RoutedEventArgs e) | SDKTemplate::Common::LayoutAwarePage | [inline, protected, virtual]
GoHome(object sender, RoutedEventArgs e) | SDKTemplate::Common::LayoutAwarePage | [inline, protected, virtual]
Initialize(_In_ Document^document, _In_ Windows::Data::Xml::Dom::XmlElement^xmlElement) | Element | [virtual]
InvalidateVisualState() | SDKTemplate::Common::LayoutAwarePage | [inline]
InvalidateVisualState() | SDKTemplate::Common::LayoutAwarePage | [inline]
LayoutAwarePage() | SDKTemplate::Common::LayoutAwarePage | [inline]
LayoutAwarePage() | SDKTemplate::Common::LayoutAwarePage | [inline]
Measure(_In_ Document^document, D2D1_SIZE_F const &parentSize, _Out_ D2D1_RECT_F *bounds) | Element | [virtual]
OnNavigatedTo(NavigationEventArgs e) | CustomDeviceAccess::DeviceAsync | [inline, protected]
PrepareToDraw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
ReleaseParent() | Element | [virtual]
rootPage | CustomDeviceAccess::DeviceAsync | [private]
StartLayoutUpdates(object sender, RoutedEventArgs e) | SDKTemplate::Common::LayoutAwarePage | [inline]
StartLayoutUpdates(object sender, RoutedEventArgs e) | SDKTemplate::Common::LayoutAwarePage | [inline]
StopLayoutUpdates(object sender, RoutedEventArgs e) | SDKTemplate::Common::LayoutAwarePage | [inline]
StopLayoutUpdates(object sender, RoutedEventArgs e) | SDKTemplate::Common::LayoutAwarePage | [inline]
UpdateBarGraphTable(bool[] barGraphArray) | CustomDeviceAccess::DeviceAsync | [inline, private]
Generated on Sat Nov 23 2024 16:09:37 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML ListView and GridView essentials/C++/MainPage.xaml.cpp Source File

  • XAML ListView and GridView essentials

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Collision Member List

This is the complete list of members for Collision, including all inherited members.
AccumulateSphereTriangleIntersections(FXMVECTOR sphere, FXMVECTOR radius, FXMVECTOR path, MeshID mesh, const std::vector< Triangle > &triList) | Collision | [private]
BuildCollisionListForSphere(const Sphere &meshLocalSpace, FXMVECTOR path) | Collision |
Collision() | Collision | [inline]
FindWorstInterpenetration() | Collision |
IntersectsWithGround() const | Collision | [inline]
m_collisions | Collision |
m_floorTriList | Collision |
m_groundTriList | Collision |
m_intersectsGround | Collision | [private]
m_wallTriList | Collision |
MergeSharedEdgeCoplanarContacts(FXMVECTOR sphere, FXMVECTOR radius, FXMVECTOR path) | Collision | [private]
UpdateInterpenetrations(FXMVECTOR newPosition, FXMVECTOR radius, FXMVECTOR path) | Collision |
Generated on Sat Nov 23 2024 16:09:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Account picture name/C++/MainPage.xaml.cpp Source File

  • Account picture name

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Platform;
00026 using namespace AccountPictureName;
00027 using namespace CppSamplesUtils;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     LayoutRoot->Children->Append(HiddenFrame);
00045
00046     // Populate the sample title from the constant in the GlobalVariables.cs file.
00047     SetAccountPictureName(FEATURE_NAME);
00048
00049     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00050     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00051
00052     MainPage::Current = this;
00053     autoSizeInputSectionWhenSnapped = true;
00054 }
00055
00056 MainPage::~MainPage()
00057 {
00058 }
00059
00060 /// <summary>
00061 /// Invoked when this page is about to be displayed in a Frame.
00062 /// </summary>
00063 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00064 /// property is typically used to configure the page.</param>
00065 void MainPage::OnNavigatedTo(NavigationEventArgs^ e)
00066 {
00067     PopulateScenarios();
00068     InvalidateViewState();
00069 }
00070
00071 /// <summary>
00072 /// We need to handle SizeChanged so that we can make the sample layout property
00073 /// in the various layouts.
00074 /// </summary>
00075 /// <param name="sender"></param>
00076 /// <param name="e"></param>
00077 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00078 {
00079     InvalidateSize();
00080     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00081     args->ViewState = ApplicationView::Value;
00082     MainPageResized(this, args);
00083 }
00084
00085 void MainPage::InvalidateSize()
00086 {
00087     // Get the window width
00088     double windowWidth = this->ActualWidth;
00089
00090     if (windowWidth != 0.0)
00091     {
00092         // Get the width of the ListBox.
00093         double listBoxWidth = Scenarios->ActualWidth;
00094
00095         // Is the ListBox using any margins that we need to consider?
00096         double listBoxMarginLeft = Scenarios->Margin.Left;
00097         double listBoxMarginRight = Scenarios->Margin.Right;
00098
00099         // Figure out how much room is left after considering the list box width
00100         double availableWidth = windowWidth - listBoxWidth;
00101
00102         // Is the top most child using margins?
00103         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00104         double layoutRootMarginRight = ContentRoot->Margin.Right;
00105
00106         // We have different widths to use depending on the view state
00107         if (ApplicationView::Value != ApplicationViewState::Snapped)
00108         {
00109             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00110             // and the LayoutRoot's margins
00111             InputSection->Width = ((availableWidth) -
00112                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00113         }
00114         else
00115         {
00116             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00117             if (autoSizeInputSectionWhenSnapped)
00118             {
00119                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00120             }
00121         }
00122     }
00123     InvalidateViewState();
00124 }
00125
00126 void MainPage::InvalidateViewState()
00127 {
00128     // Are we going to snapped mode?
00129     if (ApplicationView::Value == ApplicationViewState::Snapped)
00130     {
00131         Grid::SetRow(DescriptionText, 3);
00132         Grid::SetColumn(DescriptionText, 0);
00133
00134         Grid::SetRow(InputSection, 4);
00135         Grid::SetColumn(InputSection, 0);
00136
00137         Grid::SetRow(FooterPanel, 2);
00138         Grid::SetColumn(FooterPanel, 0);
00139     }
00140     else
00141     {
00142         Grid::SetRow(DescriptionText, 1);
00143         Grid::SetColumn(DescriptionText, 1);
00144
00145         Grid::SetRow(InputSection, 2);
00146         Grid::SetColumn(InputSection, 1);
00147
00148         Grid::SetRow(FooterPanel, 1);
00149         Grid::SetColumn(FooterPanel, 1);
00150     }
00151 }
00152
00153 #pragma optimize("", off)
00154 void MainPage::PopulateScenarios()
00155 {
00156     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00157
00158     // Populate the ListBox with the list of scenarios as defined in Constants.cs.
00159     for (unsigned int i = 0; i < scenarios->Length; ++i)
00160     {
00161         Scenario s = scenarios[i];
00162         ListBoxItem^ item = ref new ListBoxItem();
00163         item->Name = s.ClassName;
00164         item->Content = (i + 1).ToString() + ") " + s.Title;
00165         ScenarioList->Append(item);
00166     }
00167
00168     // Bind the ListBox to the scenario list.
00169     Scenarios->ItemsSource = ScenarioList;
00170
00171     // Starting scenario is the first or based upon a previous selection.
00172     ListBoxItem^ startingScenario = nullptr;
00173
00174     // Starting scenario is the first or based upon a previous selection.
00175     int startingScenarioIndex = -1;
00176
00177     auto ps = SuspensionManager::SessionState();
00178     if (ps->HasKey("SelectedScenarioIndex"))
00179     {
00180         int selectedScenarioIndex = safe_cast<int>(ps->Lookup("SelectedScenarioIndex"));
00181         startingScenarioIndex = selectedScenarioIndex;
00182     }
00183
00184     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00185 }
00186 #pragma optimize("", on)
00187
00188 /// <summary>
00189 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00190 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00191 /// and output sections into the respective UserControl on the main page.
00192 /// </summary>
00193 /// <param name="scenarioName"></param>
00194 void MainPage::LoadScenario(String^ scenarioName)
00195 {
00196     autoSizeInputSectionWhenSnapped = true;
00197
00198     // Load the ScenarioX.xaml file into the Frame.
00199     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00200     HiddenFrame->Navigate(scenarioType, this);
00201
00202     // Get the top element, the Page, so we can look up the elements
00203     // that represent the input and output sections of the ScenarioX file.
00204     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00205
00206     // Get each element.
00207     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00208     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00209
00210     if (input == nullptr)
00211     {
00212         // Malformed input section.
00213         NotifyUser("Cannot load scenario input section for " + scenarioName +
00214             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00215         return;
00216     }
00217
00218     if (output == nullptr)
00219     {
00220         // Malformed output section.
00221         NotifyUser("Cannot load scenario output section for " + scenarioName +
00222             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00223         return;
00224     }
00225
00226     // Find the LayoutRoot which parents the input and output sections in the main page.
00227     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00228
00229     if (panel != nullptr)
00230     {
00231         unsigned int index = 0;
00232         UIElementCollection^ collection = panel->Children;
00233
00234         // Get rid of the content that is currently in the intput and output sections.
00235         collection->IndexOf(input, &index);
00236         collection->RemoveAt(index);
00237
00238         collection->IndexOf(output, &index);
00239         collection->RemoveAt(index);
00240
00241         // Populate the input and output sections with the newly loaded content.
00242         InputSection->Content = input;
00243         OutputSection->Content = output;
00244
00245         ScenarioLoaded(this, nullptr);
00246     }
00247     else
00248     {
00249         // Malformed Scenario file.
00250         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00251             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00252     }
00253 }
00254
00255 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00256 {
00257     if (Scenarios->SelectedItem != nullptr)
00258     {
00259         NotifyUser("", NotifyType::StatusMessage);
00260
00261         int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00262         SuspensionManager::SessionState()->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00263
00264         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00265         InvalidateSize();
00266     }
00267 }
00268
00269 void MainPage::SetAccountPictureName(String^ strFeature)
00270 {
00271     AccountPictureName->Text = strFeature;
00272 }
00273
00274 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00275 {
00276     switch (type)
00277     {
00278     case NotifyType::StatusMessage:
00279         // Use the status message style.
00280         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00281         break;
00282     case NotifyType::ErrorMessage:
00283         // Use the error message style.
00284         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00285         break;
00286     default:
00287         break;
00288     }
00289     StatusBlock->Text = strMessage;
00290
00291     // Collapsed the StatusBlock if it has no text to conserve real estate.
00292     if (StatusBlock->Text != "")
00293         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00294     else
00295         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00296 }
00297
00298 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00299 {
00300     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00301     Windows::System::Launcher::LaunchUriAsync(uri);
00302 }
00303
00304
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAudio2 audio file playback/C++/pch.h Source File

  • XAudio2 audio file playback

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 <d3d11_1.h>
00012 #include <d2d1_1.h>
00013 #include <d2d1effects.h>
00014 #include <dwrite_1.h>
00015 #include <wincodec.h>
00016 #include <agile.h>
00017 #include "BasicMath.h"
00018 #include <vector>
00019 #include "strsafe.h"
00020 #include <memory>
00021 #include <xaudio2.h>
00022
00023 #include <mmreg.h>
00024
00025
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::Transforms::sealed Member List

This is the complete list of members for SDKSample::Transforms::sealed, including all inherited members.
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Transforms::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Transforms::sealed | [protected, virtual]
rootPage | SDKSample::Transforms::sealed | [private]
rootPage_MainPageResized(Platform::Object^sender, MainPageSizeChangedEventArgs^e) | SDKSample::Transforms::sealed | [private]
Scenario1() | SDKSample::Transforms::sealed |
Scenario2() | SDKSample::Transforms::sealed |
SetUpBinding(Windows::UI::Xaml::Controls::Slider^slider, Windows::UI::Xaml::DependencyProperty^dp) | SDKSample::Transforms::sealed | [private]
Generated on Sat Nov 23 2024 16:09:53 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX marble maze game/C++/DirectXApp.cpp Source File

  • DirectX marble maze game

DirectXApp.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
00010 using namespace DirectX;
00011
00012 #include "DirectXApp.h"
00013 #include "BasicTimer.h"
00014
00015 using namespace Windows::ApplicationModel;
00016 using namespace Windows::ApplicationModel::Core;
00017 using namespace Windows::ApplicationModel::Activation;
00018 using namespace Windows::UI::Core;
00019 using namespace Windows::System;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Graphics::Display;
00022 using namespace Windows::UI::ViewManagement;
00023 using namespace concurrency;
00024
00025 DirectXApp::DirectXApp() :
00026     m_windowClosed(false),
00027     m_windowVisible(false)
00028 {
00029 }
00030
00031 // <snippet3>
00032 void DirectXApp::Initialize(
00033     _In_ CoreApplicationView^ applicationView
00034     )
00035 {
00036     applicationView->Activated +=
00037         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &DirectXApp::OnActivated);
00038
00039     // <snippet13>
00040     CoreApplication::Suspending +=
00041         ref new EventHandler<SuspendingEventArgs^>(this, &DirectXApp::OnSuspending);
00042
00043     CoreApplication::Resuming +=
00044         ref new EventHandler<Platform::Object^>(this, &DirectXApp::OnResuming);
00045     // </snippet13>
00046
00047     m_renderer = ref new MarbleMaze();
00048 }
00049 // </snippet3>
00050
00051 // <snippet4>
00052 void DirectXApp::SetWindow(
00053     _In_ CoreWindow^ window
00054     )
00055 {
00056     window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
00057
00058     // <snippet8>
00059     window->SizeChanged +=
00060         ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &DirectXApp::OnWindowSizeChanged);
00061     // </snippet8>
00062
00063     // <snippet113>
00064
00065     window->VisibilityChanged +=
00066         ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &DirectXApp::OnVisibilityChanged);
00067     // </snippet113>
00068
00069     window->Closed +=
00070         ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &DirectXApp::OnWindowClosed);
00071
00072     // <snippet52>
00073     window->PointerPressed +=
00074         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &DirectXApp::OnPointerPressed);
00075
00076     window->PointerReleased +=
00077         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &DirectXApp::OnPointerReleased);
00078
00079     window->PointerMoved +=
00080         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &DirectXApp::OnPointerMoved);
00081     // </snippet52>
00082
00083     window->KeyDown +=
00084         ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &DirectXApp::OnKeyDown);
00085
00086     window->KeyUp +=
00087         ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &DirectXApp::OnKeyUp);
00088
00089     DisplayProperties::LogicalDpiChanged +=
00090         ref new DisplayPropertiesEventHandler(this, &DirectXApp::OnLogicalDpiChanged);
00091
00092     m_renderer->Initialize(window, DisplayProperties::LogicalDpi);
00093 }
00094 // </snippet4>
00095
00096 // <snippet112>
00097 void DirectXApp::Load(
00098     _In_ Platform::String^ entryPoint
00099     )
00100 {
00101     task<void>([=]()
00102     {
00103         m_renderer->LoadDeferredResources(true, false);
00104     });
00105 }
00106 // </snippet112>
00107
00108
00109 // <snippet6>
00110 void DirectXApp::Run()
00111 {
00112     BasicTimer^ timer = ref new BasicTimer();
00113
00114     while (!m_windowClosed)
00115     {
00116         timer->Update();
00117
00118         if (m_windowVisible)
00119         {
00120             // <snippet67>
00121             // Process windowing events.
00122             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
00123             // </snippet67>
00124
00125             // Update and render this frame.
00126             m_renderer->Update(timer->Total, timer->Delta);
00127             m_renderer->Render();
00128
00129             // Present the frame. This call is synchronized to the display frame rate.
00130             m_renderer->Present();
00131         }
00132         else
00133         {
00134             // The window is not visible, so just wait for next event and respond to it.
00135             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
00136         }
00137     }
00138
00139     // The app is exiting so do the same thing as would if app was being suspended.
00140     m_renderer->OnSuspending();
00141 }
00142 // </snippet6>
00143
00144 void DirectXApp::Uninitialize()
00145 {
00146 }
00147
00148 // <snippet9>
00149 void DirectXApp::OnWindowSizeChanged(
00150     _In_ CoreWindow^ sender,
00151     _In_ WindowSizeChangedEventArgs^ args
00152     )
00153 {
00154     // Query for the current ApplicationView state to make sure the most current
00155     // ApplicationViewState is known before resizing all the resources.
00156
00157     m_renderer->OnViewChange(ApplicationView::Value);
00158     m_renderer->UpdateForWindowSizeChange();
00159 }
00160 // </snippet9>
00161
00162 // <snippet114>
00163 void DirectXApp::OnVisibilityChanged(
00164     _In_ CoreWindow^ sender,
00165     _In_ VisibilityChangedEventArgs^ args
00166     )
00167 {
00168     m_windowVisible = args->Visible;
00169 }
00170 // </snippet114>
00171
00172
00173 void DirectXApp::OnWindowClosed(
00174     _In_ CoreWindow^ sender,
00175     _In_ CoreWindowEventArgs^ args
00176     )
00177 {
00178     m_windowClosed = true;
00179 }
00180
00181 void DirectXApp::OnLogicalDpiChanged(
00182     _In_ Platform::Object^ sender
00183     )
00184 {
00185     m_renderer->SetDpi(DisplayProperties::LogicalDpi);
00186 }
00187
00188 void DirectXApp::OnActivated(
00189     _In_ CoreApplicationView^ applicationView,
00190     _In_ IActivatedEventArgs^ args
00191     )
00192 {
00193     CoreWindow::GetForCurrentThread()->Activated +=
00194         ref new TypedEventHandler<CoreWindow^, WindowActivatedEventArgs^>(this, &DirectXApp::OnWindowActivationChanged);
00195     CoreWindow::GetForCurrentThread()->Activate();
00196     m_windowVisible = true;
00197 }
00198
00199 void DirectXApp::OnWindowActivationChanged(
00200     _In_ Windows::UI::Core::CoreWindow^ sender,
00201     _In_ Windows::UI::Core::WindowActivatedEventArgs^ args
00202     )
00203 {
00204     if (args->WindowActivationState == CoreWindowActivationState::Deactivated)
00205     {
00206         m_renderer->OnFocusChange(false);
00207     }
00208     else if (args->WindowActivationState == CoreWindowActivationState::CodeActivated
00209         || args->WindowActivationState == CoreWindowActivationState::PointerActivated)
00210     {
00211         m_renderer->OnFocusChange(true);
00212     }
00213 }
00214
00215 // <snippet68>
00216 void DirectXApp::OnPointerPressed(
00217     _In_ Windows::UI::Core::CoreWindow^ sender,
00218     _In_ Windows::UI::Core::PointerEventArgs^ args
00219     )
00220 {
00221     m_renderer->AddTouch(args->CurrentPoint->PointerId, args->CurrentPoint->Position);
00222 }
00223
00224 void DirectXApp::OnPointerReleased(
00225     _In_ Windows::UI::Core::CoreWindow^ sender,
00226     _In_ Windows::UI::Core::PointerEventArgs^ args
00227     )
00228 {
00229     m_renderer->RemoveTouch(args->CurrentPoint->PointerId);
00230 }
00231
00232 void DirectXApp::OnPointerMoved(
00233     _In_ Windows::UI::Core::CoreWindow^ sender,
00234     _In_ Windows::UI::Core::PointerEventArgs^ args
00235     )
00236 {
00237     m_renderer->UpdateTouch(args->CurrentPoint->PointerId, args->CurrentPoint->Position);
00238 }
00239 // </snippet68>
00240
00241 void DirectXApp::OnKeyDown(
00242     _In_ Windows::UI::Core::CoreWindow^ sender,
00243     _In_ Windows::UI::Core::KeyEventArgs^ args
00244     )
00245 {
00246     m_renderer->KeyDown(args->VirtualKey);
00247 }
00248
00249 void DirectXApp::OnKeyUp(
00250     _In_ Windows::UI::Core::CoreWindow^ sender,
00251     _In_ Windows::UI::Core::KeyEventArgs^ args
00252     )
00253 {
00254     m_renderer->KeyUp(args->VirtualKey);
00255 }
00256
00257 // <snippet14>
00258 void DirectXApp::OnSuspending(
00259     _In_ Platform::Object^ sender,
00260     _In_ SuspendingEventArgs^ args
00261     )
00262 {
00263     m_renderer->OnSuspending();
00264 }
00265 // </snippet14>
00266
00267 // <snippet15>
00268 void DirectXApp::OnResuming(
00269     _In_ Platform::Object^ sender,
00270     _In_ Platform::Object^ args
00271     )
00272 {
00273     m_renderer->OnResuming();
00274 }
00275 // </snippet15>
00276
00277 // <snippet2>
00278 IFrameworkView^ DirectXAppSource::CreateView()
00279 {
00280     return ref new DirectXApp();
00281 }
00282 // </snippet2>
00283
00284 // <snippet5>
00285 [Platform::MTAThread]
00286 int main(Platform::Array<Platform::String^>^)
00287 {
00288     auto directXAppSource = ref new DirectXAppSource();
00289     CoreApplication::Run(directXAppSource);
00290     return 0;
00291 }
00292 // </snippet5>
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite inline object/C++/pch.cpp Source File

  • DirectWrite inline object

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Real-time communication/C++/pch.h Source File

  • Real-time communication

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <agile.h>
00019 #include <ppltasks.h>
00020 #include <concrt.h>
00021
00022 #include "Sample-Utils\CppSamplesUtils.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML AppBar control/C++/Scenario3.xaml.cpp Source File

  • XAML AppBar control

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 "GlobalPage.xaml.h"
00018 #include "Scenario3.xaml.h"
00019
00020 using namespace AppBarControl;
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Interop;
00025 using namespace Windows::UI::Xaml::Navigation;
00026
00027
00028 Scenario3::Scenario3()
00029 {
00030     InitializeComponent();
00031 }
00032
00033 // Invoked when this page is about to be displayed in a Frame.
00034 void Scenario3::OnNavigatedTo(NavigationEventArgs^ e)
00035 {
00036     rootPage = MainPage::Current;
00037 }
00038
00039 // Navigate to the global page
00040 void AppBarControl::Scenario3::ShowMe_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00041 {
00042   TypeName pageType = {GlobalPage::typeid->FullName, TypeKind::Custom};
00043   rootPage->Frame->Navigate(pageType, rootPage);
00044 }
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D bump mapping/C++/pch.cpp Source File

  • Direct3D bump mapping

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML data binding/C++/Scenario1.xaml.cpp Source File

  • XAML data binding

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::DataBinding;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 Scenario1::Scenario1()
00026 {
00027   InitializeComponent();
00028 }
00029
00030 void SDKSample::DataBinding::Scenario1::Scenario1Reset(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00031 {
00032   sliderOneWayDataSource->Value = 10;
00033   sliderTwoWayDataSource->Value = 50;
00034   sliderOneTimeDataSource->Value = 100;
00035
00036 }
00037
Generated on Sat Nov 23 2024 16:07:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Clipboard::Scenario Member List

This is the complete list of members for Clipboard::Scenario, including all inherited members.
ClassName | Clipboard::Scenario
Title | Clipboard::Scenario
Generated on Sat Nov 23 2024 16:09:36 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

TreeIterator< T > Member List

This is the complete list of members for TreeIterator< T >, including all inherited members.
GetCurrentNode() | TreeIterator< T > | [inline]
m_currentNode | TreeIterator< T > | [private]
operator++() | TreeIterator< T > | [inline]
TreeIterator(T^rootNode) | TreeIterator< T > | [inline]
Generated on Sat Nov 23 2024 16:09:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Background Transfer/C++/Scenario2.xaml.h Source File

  • Background Transfer

Scenario2.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.xaml.h
00013 // Declaration of the Scenario2 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario2.g.h"
00020 #include "MainPage.xaml.h"
00021 #include "Collection.h"
00022
00023 namespace SDKSample
00024 {
00025     namespace BackgroundTransfer
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
00039         private:
00040             MainPage^ rootPage;
00041             Concurrency::cancellation_token_source* cancellationToken;
00042
00043             void StartUpload_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00044             void StartMultipartUpload_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00045             void CancelAll_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00046             void DiscoverActiveUploads();
00047             void UploadProgress(
00048                 Windows::Foundation::IAsyncOperationWithProgress<Windows::Networking::BackgroundTransfer::UploadOperation^, Windows::Networking::BackgroundTransfer::UploadOperation^>^ operation,
00049                 Windows::Networking::BackgroundTransfer::UploadOperation^);
00050             void HandleUploadAsync(Windows::Networking::BackgroundTransfer::UploadOperation^ upload, bool start);
00051             void LogException(Platform::String^ title, Platform::Exception^ ex);
00052             void MarshalLog(Platform::String^ value);
00053             void Log(Platform::String^ message);
00054             void LogStatus(Platform::String^ message, NotifyType type);
00055             ~Scenario2();
00056         };
00057     }
00058 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Device capabilities/C++/Touch.xaml.cpp Source File

  • Input Device capabilities

Touch.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 // Touch.xaml.cpp
00013 // Implementation of the Touch class
00014 //
00015
00016 #include "pch.h"
00017 #include "Touch.xaml.h"
00018
00019 using namespace SDKSample::DeviceCaps;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 using namespace Windows::Devices::Input;
00026
00027 Touch::Touch()
00028 {
00029     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 void Touch::OnNavigatedTo(NavigationEventArgs^ e)
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     rootPage = MainPage::Current;
00042 }
00043
00044 void SDKSample::DeviceCaps::Touch::TouchGetSettings_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00045 {
00046     Button^ b = safe_cast<Button^>(sender);
00047     if (b != nullptr)
00048     {
00049         TouchCapabilities^ pTouchCapabilities = ref new TouchCapabilities();
00050         Platform::String^ Buffer;
00051
00052         Buffer = "There is " + (pTouchCapabilities->TouchPresent != 0 ? "a" : "no") + " digitizer present\n";
00053         Buffer += "The digitizer supports " + pTouchCapabilities->Contacts.ToString() + " contacts\n";
00054
00055         TouchOutputTextBlock->Text = Buffer;
00056     }
00057 }
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XInput game controller/C++/DirectXSample.h Source File

  • XInput game controller

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
00010 // This header defines helper utilities to make DirectX APIs work with exceptions.
00011 namespace DX
00012 {
00013     inline void ThrowIfFailed(HRESULT hr)
00014     {
00015         if (FAILED(hr))
00016         {
00017             // Set a breakpoint on this line to catch DX API errors.
00018             throw Platform::Exception::CreateException(hr);
00019         }
00020     }
00021 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Mobile broadband account provisioning/C++/pch.h Source File

  • Mobile broadband account provisioning

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <windows.h>
00019 #include <strsafe.h>
00020 #include <stdio.h>
00021 #include <string.h>
00022 #include <collection.h>
00023 #include <ppltasks.h>
00024 #include "Common\LayoutAwarePage.h"
00025 #include "Common\SuspensionManager.h"
00026 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Store device app for camera/C++/pch.h Source File

  • Windows Store device app for camera

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include "Sample-Utils\CppSamplesUtils.h"
00019 #include <ppltasks.h>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CameraCaptureUI/C++/App.xaml.cpp Source File

  • CameraCaptureUI

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/SphereMesh.cpp Source File

  • XAML DirectX 3D shooting game

SphereMesh.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 "SphereMesh.h"
00010 #include "DirectXSample.h"
00011 #include "ConstantBuffers.h"
00012
00013 using namespace Microsoft::WRL;
00014 using namespace DirectX;
00015
00016 SphereMesh::SphereMesh(_In_ ID3D11Device *device, uint32 segments)
00017 {
00018     D3D11_BUFFER_DESC bd = {0};
00019     D3D11_SUBRESOURCE_DATA initData = {0};
00020
00021     uint32 slices = segments / 2;
00022     uint32 numVertices = (slices + 1) * (segments + 1) + 1;
00023     uint32 numIndices = slices * segments * 3 * 2;
00024
00025     std::vector<PNTVertex> point(numVertices);
00026     std::vector<uint16> index(numIndices);
00027
00028     // To make the texture look right on the top and bottom of the sphere
00029     // each slice will have 'segments + 1' vertices.  The top and bottom
00030     // vertices will all be coincident, but have different U texture cooordinates.
00031     uint32 p = 0;
00032     for (uint32 a = 0; a <= slices; a++)
00033     {
00034         float angle1 = static_cast<float>(a) / static_cast<float>(slices) * XM_PI;
00035         float z = cos(angle1);
00036         float r = sin(angle1);
00037         for (uint32 b = 0; b <= segments; b++)
00038         {
00039             float angle2 = static_cast<float>(b) / static_cast<float>(segments) * XM_2PI;
00040             point[p].position = XMFLOAT3(r * cos(angle2), r * sin(angle2), z);
00041             point[p].normal = point[p].position;
00042             point[p].textureCoordinate = XMFLOAT2((1.0f-z) / 2.0f, static_cast<float>(b) / static_cast<float>(segments));
00043             p++;
00044         }
00045     }
00046     m_vertexCount = p;
00047
00048     p = 0;
00049     for (uint16 a = 0; a < slices; a++)
00050     {
00051         uint16 p1 = a * (segments + 1);
00052         uint16 p2 = (a + 1) * (segments + 1);
00053
00054         // Generate two triangles for each segment around the slice.
00055         for (uint16 b = 0; b < segments; b++)
00056         {
00057             if (a < (slices - 1))
00058             {
00059                 // For all but the bottom slice add the triangle with one
00060                 // vertex in the a slice and two vertices in the a + 1 slice.
00061                 // Skip it for the bottom slice since the triangle would be
00062                 // degenerate as all the vertices in the bottom slice are coincident.
00063                 index[p] = b + p1;
00064                 index[p+1] = b + p2;
00065                 index[p+2] = b + p2 + 1;
00066                 p = p + 3;
00067             }
00068             if (a > 0)
00069             {
00070                 // For all but the top slice add the triangle with two
00071                 // vertices in the a slice and one vertex in the a + 1 slice.
00072                 // Skip it for the top slice since the triangle would be
00073                 // degenerate as all the vertices in the top slice are coincident.
00074                 index[p] = b + p1;
00075                 index[p+1] = b + p2 + 1;
00076                 index[p+2] = b + p1 + 1;
00077                 p = p + 3;
00078             }
00079         }
00080     }
00081     m_indexCount = p;
00082
00083     bd.Usage = D3D11_USAGE_DEFAULT;
00084     bd.ByteWidth = sizeof(PNTVertex) * m_vertexCount;
00085     bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
00086     bd.CPUAccessFlags = 0;
00087     initData.pSysMem = point.data();
00088     DX::ThrowIfFailed(
00089         device->CreateBuffer(&bd, &initData, &m_vertexBuffer)
00090         );
00091
00092     bd.Usage = D3D11_USAGE_DEFAULT;
00093     bd.ByteWidth = sizeof(uint16) * m_indexCount;
00094     bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
00095     bd.CPUAccessFlags = 0;
00096     initData.pSysMem = index.data();
00097     DX::ThrowIfFailed(
00098         device->CreateBuffer(&bd, &initData, &m_indexBuffer)
00099         );
00100 }
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

LanguageFontCPP::sealed Member List

This is the complete list of members for LanguageFontCPP::sealed, including all inherited members.
_displayHandlerToken | LanguageFontCPP::sealed | [private]
_fontFamily | LanguageFontCPP::sealed | [private]
_fontStretch | LanguageFontCPP::sealed | [private]
_fontStyle | LanguageFontCPP::sealed | [private]
_fontWeight | LanguageFontCPP::sealed | [private]
_frameLoadedToken | LanguageFontCPP::sealed | [private]
_inputFrame | LanguageFontCPP::sealed | [private]
_inputFrameLoadedToken | LanguageFontCPP::sealed | [private]
_layoutHandlerToken | LanguageFontCPP::sealed | [private]
_logicalDpiChangedToken | LanguageFontCPP::sealed | [private]
_oriHeadingUI | LanguageFontCPP::sealed | [private]
_oriTextUI | LanguageFontCPP::sealed | [private]
_outputFrame | LanguageFontCPP::sealed | [private]
_outputFrameLoadedToken | LanguageFontCPP::sealed | [private]
_pageLoadedHandlerToken | LanguageFontCPP::sealed | [private]
_scenariosFrame | LanguageFontCPP::sealed | [private]
App() | LanguageFontCPP::sealed |
ApplyFont_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | LanguageFontCPP::sealed | [private]
ApplyFont_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | LanguageFontCPP::sealed | [private]
CheckResolutionAndViewState() | LanguageFontCPP::sealed | [private]
ConvertResolution(Windows::Graphics::Display::ResolutionScale scale) | LanguageFontCPP::sealed |
ConvertViewState(Windows::UI::ViewManagement::ApplicationViewState state) | LanguageFontCPP::sealed |
DisplayProperties_LogicalDpiChanged(Object^sender) | LanguageFontCPP::sealed | [private]
DoNavigation(Windows::UI::Xaml::Interop::TypeName inPageType, Windows::UI::Xaml::Controls::Frame^inFrame, Windows::UI::Xaml::Interop::TypeName outPageType, Windows::UI::Xaml::Controls::Frame^outFrame) | LanguageFontCPP::sealed |
Footer_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | LanguageFontCPP::sealed | [private]
inputFrameNavigated(Object^sender, Windows::UI::Xaml::Navigation::NavigationEventArgs^e) | LanguageFontCPP::sealed | [private]
MainPage() | LanguageFontCPP::sealed |
NotifyUser(Platform::String^strMessage, NotifyType type) | LanguageFontCPP::sealed |
OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^pArgs) override | LanguageFontCPP::sealed | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | LanguageFontCPP::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | LanguageFontCPP::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | LanguageFontCPP::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | LanguageFontCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | LanguageFontCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | LanguageFontCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | LanguageFontCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | LanguageFontCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | LanguageFontCPP::sealed | [protected, virtual]
OnSuspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^pArgs) | LanguageFontCPP::sealed | [virtual]
OutputFrameLoaded | LanguageFontCPP::sealed |
outputFrameNavigated(Object^sender, Windows::UI::Xaml::Navigation::NavigationEventArgs^e) | LanguageFontCPP::sealed | [private]
Page_Loaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | LanguageFontCPP::sealed | [private]
Page_SizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | LanguageFontCPP::sealed | [private]
Reset(Windows::UI::Xaml::Controls::TextBlock^textBlock) | LanguageFontCPP::sealed |
rootPage | LanguageFontCPP::sealed | [private]
rootPage_InputFrameLoaded(Object^sender, Object^e) | LanguageFontCPP::sealed | [private]
rootPage_InputFrameLoaded(Object^sender, Object^e) | LanguageFontCPP::sealed | [private]
rootPage_OutputFrameLoaded(Object^sender, Object^e) | LanguageFontCPP::sealed | [private]
rootPage_OutputFrameLoaded(Object^sender, Object^e) | LanguageFontCPP::sealed | [private]
ScenarioInput1() | LanguageFontCPP::sealed |
ScenarioInput2() | LanguageFontCPP::sealed |
ScenarioList() | LanguageFontCPP::sealed |
ScenarioOutput1() | LanguageFontCPP::sealed |
ScenarioOutput2() | LanguageFontCPP::sealed |
Scenarios_SelectionChanged(Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | LanguageFontCPP::sealed | [protected]
Set(Windows::UI::Xaml::Controls::TextBlock^textBlock) | LanguageFontCPP::sealed |
SetFeatureName(Platform::String^strFeature) | LanguageFontCPP::sealed | [private]
SetFont(Windows::UI::Xaml::Controls::TextBlock^textBlock, Windows::Globalization::Fonts::LanguageFont^languageFont) | LanguageFontCPP::sealed | [static]
~MainPage() | LanguageFontCPP::sealed | [private]
~ScenarioInput1() | LanguageFontCPP::sealed | [private]
~ScenarioInput2() | LanguageFontCPP::sealed | [private]
~ScenarioList() | LanguageFontCPP::sealed | [private]
~ScenarioOutput1() | LanguageFontCPP::sealed | [private]
~ScenarioOutput2() | LanguageFontCPP::sealed | [private]
Generated on Sat Nov 23 2024 16:09:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/BasicCamera.cpp Source File

  • Direct3D resource loading

BasicCamera.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 "BasicCamera.h"
00010
00011 void BasicCamera::GetViewMatrix(_Out_ float4x4 *viewMatrix)
00012 {
00013     *viewMatrix = m_view;
00014 }
00015
00016 void BasicCamera::GetProjectionMatrix(_Out_ float4x4 *projectionMatrix)
00017 {
00018     *projectionMatrix = m_projection;
00019 }
00020
00021 // this method updates the view matrix based on new position and focus coordinates
00022 void BasicCamera::SetViewParameters(
00023     _In_ float3 eyePosition,    // the position of the camera
00024     _In_ float3 lookPosition,   // the point the camera should look at
00025     _In_ float3 up              // the durection vector for up
00026     )
00027 {
00028     m_position = eyePosition;
00029     m_direction = normalize(lookPosition - eyePosition);
00030     float3 zAxis = -m_direction;
00031     float3 xAxis = normalize(cross(up, zAxis));
00032     float3 yAxis = cross(zAxis, xAxis);
00033     float xOffset = -dot(xAxis, m_position);
00034     float yOffset = -dot(yAxis, m_position);
00035     float zOffset = -dot(zAxis, m_position);
00036     m_view = float4x4(
00037         xAxis.x, xAxis.y, xAxis.z, xOffset,
00038         yAxis.x, yAxis.y, yAxis.z, yOffset,
00039         zAxis.x, zAxis.y, zAxis.z, zOffset,
00040         0.0f,    0.0f,    0.0f,    1.0f
00041         );
00042 }
00043     // this method updates the projection matrix based on new parameters
00044 void BasicCamera::SetProjectionParameters(
00045     _In_ float minimumFieldOfView,  // the minimum horizontal or vertical field of view, in degrees
00046     _In_ float aspectRatio,         // the aspect ratio of the projection (width / height)
00047     _In_ float nearPlane,           // depth to map to 0
00048     _In_ float farPlane             // depth to map to 1
00049     )
00050 {
00051     float minScale = 1.0f / tan(minimumFieldOfView * PI_F / 360.0f);
00052     float xScale = 1.0f;
00053     float yScale = 1.0f;
00054     if (aspectRatio < 1.0f)
00055     {
00056         xScale = minScale;
00057         yScale = minScale * aspectRatio;
00058     }
00059     else
00060     {
00061         xScale = minScale / aspectRatio;
00062         yScale = minScale;
00063     }
00064     float zScale = farPlane / (farPlane - nearPlane);
00065     m_projection = float4x4(
00066         xScale, 0.0f,   0.0f,    0.0f,
00067         0.0f,   yScale, 0.0f,    0.0f,
00068         0.0f,   0.0f,   -zScale, -nearPlane*zScale,
00069         0.0f,   0.0f,   -1.0f,   0.0f
00070         );
00071 }
Generated on Sat Nov 23 2024 16:08:07 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML Direct2D lighting effects/C++/MainPage.xaml.h Source File

  • XAML Direct2D lighting effects

MainPage.xaml.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 "MainPage.g.h"
00011 #include "D2DLightingEffectsRenderer.h"
00012
00013 namespace D2DLightingEffects
00014 {
00015     public ref class MainPage sealed
00016     {
00017     public:
00018         MainPage();
00019
00020         void InitializeValues();
00021         void ResetValues();
00022
00023         void OnSuspending(
00024             Object^ sender,
00025             Windows::ApplicationModel::SuspendingEventArgs^ args
00026             );
00027
00028     private:
00029         void SetLightingEffect(LightingEffect lightingEffect);
00030         void SetLightingProperty(LightingProperty lightingProperty, float value);
00031
00032         void OnEffectSelectorSelectionChanged(
00033             Object^ sender,
00034             Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e
00035             );
00036
00037         void OnLightPositionZValueChanged(
00038             Object^ sender,
00039             Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e
00040             );
00041
00042         void OnSpecularConstantValueChanged(
00043             Object^ sender,
00044             Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e
00045             );
00046
00047         void OnSpecularExponentValueChanged(
00048             Object^ sender,
00049             Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e
00050             );
00051
00052         void OnDiffuseConstantValueChanged(
00053             Object^ sender,
00054             Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e
00055             );
00056
00057         void OnSpotFocusValueChanged(
00058             Object^ sender,
00059             Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e
00060             );
00061
00062         void OnLimitingConeAngleValueChanged(
00063             Object^ sender,
00064             Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e
00065             );
00066
00067         void OnAzimuthValueChanged(
00068             Object^ sender,
00069             Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e
00070             );
00071
00072         void OnElevationValueChanged(
00073             Object^ sender,
00074             Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e
00075             );
00076
00077         void OnSurfaceScaleValueChanged(
00078             Object^ sender,
00079             Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e
00080             );
00081
00082         void OnRestoreDefaultsClick(
00083             Object^ sender,
00084             Windows::UI::Xaml::RoutedEventArgs^ e
00085             );
00086
00087         void OnSwapChainPointerMoved(
00088             Object^ sender,
00089             Windows::UI::Xaml::Input::PointerRoutedEventArgs^ args
00090             );
00091
00092         void OnLogicalDpiChanged(
00093             Object^ sender
00094             );
00095
00096         void OnDisplayContentsInvalidated(
00097             Object^ sender
00098             );
00099
00100         void OnWindowSizeChanged(
00101             Windows::UI::Core::CoreWindow^ sender,
00102             Windows::UI::Core::WindowSizeChangedEventArgs^ args
00103             );
00104
00105         D2DLightingEffectsRenderer^ m_renderer;
00106     };
00107 }
Generated on Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Lock screen apps/C#,C++/ScenarioOutput1.xaml.cpp Source File

  • Lock screen apps
  • C#,C++

ScenarioOutput1.xaml.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 //
00009 // Scenario1Output.xaml.cpp
00010 // Implementation of the Scenario1Output class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioOutput1.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace LockScreenAppsCPP;
00018
00019 using namespace Platform;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Graphics::Display;
00023 using namespace Windows::UI::ViewManagement;
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 ScenarioOutput1::ScenarioOutput1()
00033 {
00034     InitializeComponent();
00035 }
00036
00037 ScenarioOutput1::~ScenarioOutput1()
00038 {
00039 }
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::WASAPIAudio::DEVICEPROPS Member List

This is the complete list of members for SDKSample::WASAPIAudio::DEVICEPROPS, including all inherited members.
ContentStream | SDKSample::WASAPIAudio::DEVICEPROPS
Frequency | SDKSample::WASAPIAudio::DEVICEPROPS
hnsBufferDuration | SDKSample::WASAPIAudio::DEVICEPROPS
IsBackground | SDKSample::WASAPIAudio::DEVICEPROPS
IsHWOffload | SDKSample::WASAPIAudio::DEVICEPROPS
IsTonePlayback | SDKSample::WASAPIAudio::DEVICEPROPS
Generated on Sat Nov 23 2024 16:09:53 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Date and time formatting/C++/LongAndShortFormats.xaml.cpp Source File

  • Date and time formatting

LongAndShortFormats.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 // LongAndShortFormats.xaml.cpp
00013 // Implementation of the LongAndShortFormats class
00014 //
00015
00016 #include "pch.h"
00017 #include "LongAndShortFormats.xaml.h"
00018
00019 using namespace SDKSample::DateTimeFormatting;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024 using namespace Platform;
00025 using namespace Windows::Foundation;
00026 using namespace Windows::Foundation::Collections;
00027 using namespace Windows::Globalization;
00028 using namespace Windows::Globalization::DateTimeFormatting;
00029
00030
00031 LongAndShortFormats::LongAndShortFormats()
00032 {
00033     InitializeComponent();
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 LongAndShortFormats::OnNavigatedTo(NavigationEventArgs^ e)
00042 {
00043     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00044     // as NotifyUser()
00045     rootPage = MainPage::Current;
00046 }
00047
00048 void SDKSample::DateTimeFormatting::LongAndShortFormats::Display_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00049 {
00050   // This scenario uses the Windows.Globalization.DateTimeFormatting.DateTimeFormatter class
00051   // in order to display dates and times using basic formatters.
00052
00053   //Get the current application context language
00054   String^ currentLanguage = ApplicationLanguages::Languages->GetAt(0);
00055
00056   // Formatters for dates and times
00057     Array<DateTimeFormatter^> ^dateFormatters = {
00058         ref new DateTimeFormatter("shortdate"),
00059         ref new DateTimeFormatter("longdate"),
00060         ref new DateTimeFormatter("shorttime"),
00061         ref new DateTimeFormatter("longtime")
00062     };
00063
00064   // Obtain the date that will be formatted.
00065   Windows::Globalization::Calendar^ cal = ref new Windows::Globalization::Calendar();
00066     Windows::Foundation::DateTime dateToFormat = cal->GetDateTime();
00067
00068     // Keep the results here
00069     String^ results = "";
00070   results = results + "Current application context language: " + currentLanguage + "\n\n";
00071
00072   // Generate the results.
00073     for (unsigned int i = 0; i < dateFormatters->Length; i++)
00074     {
00075         // Perform the actual formatting.
00076         try
00077         {
00078             results = results + dateFormatters[i]->Template + ": " + dateFormatters[i]->Format(dateToFormat) + "\n";
00079         }
00080         catch(Platform::Exception^)
00081         {
00082             // Retrieve and display formatter properties.
00083             results = results + "Unable to format using formatter with template: " +
00084                 dateFormatters[i]->Template + ", language: " +
00085                 dateFormatters[i]->Languages->GetAt(0) + ", region: " +
00086                 dateFormatters[i]->GeographicRegion + ", calendar: " +
00087                 dateFormatters[i]->Calendar + ", clock:" +
00088                 dateFormatters[i]->Clock + "\n";
00089         }
00090     }
00091
00092   // Display the results.
00093     rootPage->NotifyUser(results, NotifyType::StatusMessage);
00094 }
Generated on Sat Nov 23 2024 16:08:02 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML accessibility/C++/Scenario4.xaml.cpp Source File

  • XAML accessibility

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 //#include "Sample-Utils\CppSamplesUtils.h"
00019
00020 using namespace SDKSample::Accessibility;
00021
00022 //using namespace CppSamplesUtils;
00023 using namespace Windows::UI::Xaml;
00024 using namespace Windows::UI::Xaml::Controls;
00025 using namespace Windows::UI::Xaml::Navigation;
00026 using namespace Windows::UI::Xaml::Automation;
00027 using namespace Windows::UI::Xaml::Data;
00028
00029 using namespace SDKSample::Accessibility;
00030
00031 Scenario4::Scenario4()
00032 {
00033     InitializeComponent();
00034   DataBoundList->ItemsSource = DataHelper::GeneratePersonNamesSource();
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 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/MediaExtensions/Mpeg1Source/dllmain.cpp Source File

  • Media extensions
  • MediaExtensions
  • Mpeg1Source

dllmain.cpp

Go to the documentation of this file.
00001 //////////////////////////////////////////////////////////////////////////
00002 //
00003 // dllmain.cpp
00004 //
00005 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00007 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00008 // PARTICULAR PURPOSE.
00009 //
00010 // Copyright (c) Microsoft Corporation. All rights reserved.
00011 //
00012 //////////////////////////////////////////////////////////////////////////
00013
00014 #include <wrl\module.h>
00015 #include "MPEG1Src.h"
00016 #include "MPEG1ByteStreamHandler.h"
00017
00018 using namespace Microsoft::WRL;
00019
00020 namespace Microsoft { namespace Samples {
00021     ActivatableClass(CMPEG1ByteStreamHandler);
00022 }}
00023
00024 BOOL WINAPI DllMain( _In_ HINSTANCE hInstance, _In_ DWORD dwReason, _In_opt_ LPVOID lpReserved )
00025 {
00026     if( DLL_PROCESS_ATTACH == dwReason )
00027     {
00028         //
00029         //  Don't need per-thread callbacks
00030         //
00031         DisableThreadLibraryCalls( hInstance );
00032
00033         Module<InProc>::GetModule().Create();
00034     }
00035     else if( DLL_PROCESS_DETACH == dwReason )
00036     {
00037         Module<InProc>::GetModule().Terminate();
00038     }
00039
00040     return TRUE;
00041 }
00042
00043 HRESULT WINAPI DllGetActivationFactory( _In_ HSTRING activatibleClassId, _Outptr_ IActivationFactory** factory )
00044 {
00045     auto &module = Microsoft::WRL::Module< Microsoft::WRL::InProc >::GetModule();
00046     return module.GetActivationFactory( activatibleClassId, factory );
00047 }
00048
00049 HRESULT WINAPI DllCanUnloadNow()
00050 {
00051     auto &module = Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule();
00052     return (module.Terminate()) ? S_OK : S_FALSE;
00053 }
00054
00055 STDAPI DllGetClassObject( _In_ REFCLSID rclsid, _In_ REFIID riid, _Outptr_ LPVOID FAR* ppv )
00056 {
00057     auto &module = Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule();
00058     return module.GetClassObject( rclsid, riid, ppv );
00059 }
Generated on Sat Nov 23 2024 16:08:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML user and custom controls/C++/Constants.h Source File

  • XAML user and custom controls

Constants.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 namespace SDKSample
00016 {
00017   public value struct Scenario
00018   {
00019     Platform::String^ Title;
00020     Platform::String^ ClassName;
00021   };
00022
00023   partial ref class MainPage
00024   {
00025   public:
00026     static property Platform::String^ FEATURE_NAME
00027     {
00028       Platform::String^ get()
00029       {
00030         return ref new Platform::String(L"XAML user and custom controls sample");
00031       }
00032     }
00033
00034     static property Platform::String^ EXTENSION_SDK_LINK
00035     {
00036       Platform::String^ get()
00037       {
00038         return ref new Platform::String(L"http://go.microsoft.com/fwlink/?LinkID=235409");
00039       }
00040     }
00041
00042     static property Platform::Array<Scenario>^ scenarios
00043     {
00044       Platform::Array<Scenario>^ get()
00045       {
00046         return scenariosInner;
00047       }
00048     }
00049   private:
00050     static Platform::Array<Scenario>^ scenariosInner;
00051   };
00052
00053
00054 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Store device app for camera/C#,C++/App.xaml.cs Source File

  • Windows Store device app for camera
  • C#,C++

App.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.ApplicationModel;
00012 using Windows.ApplicationModel.Activation;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Navigation;
00016 using SDKTemplate;
00017
00018 namespace SDKTemplate
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             this.Suspending += new SuspendingEventHandler(OnSuspending);
00033         }
00034
00035        async void OnSuspending(object sender, SuspendingEventArgs args)
00036        {
00037            SuspendingDeferral deferral = args.SuspendingOperation.GetDeferral();
00038            await SuspensionManager.SaveAsync();
00039            deferral.Complete();
00040        }
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="args">Details about the launch request and process.</param>
00049         async protected override void OnLaunched(LaunchActivatedEventArgs args)
00050         {
00051             if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
00052             {
00053                 // Do an asynchronous restore
00054                 await SuspensionManager.RestoreAsync();
00055
00056             }
00057             if (Window.Current.Content == null)
00058             {
00059                 var rootFrame = new Frame();
00060                 rootFrame.Navigate(typeof(MainPage));
00061                 ((MainPage)rootFrame.Content).LaunchArgs = args;
00062                 Window.Current.Content = rootFrame;
00063             }
00064             Window.Current.Activate();
00065         }
00066
00067         /// <summary>
00068         /// Invoked when the application is activated.
00069         /// </summary>
00070         /// <param name="args">Details about the activated request and process.</param>
00071         protected override void OnActivated(IActivatedEventArgs args)
00072         {
00073             if (args.Kind == ActivationKind.CameraSettings)
00074             {
00075                 base.OnActivated(args);
00076                 DeviceAppPage page = new DeviceAppPage();
00077                 Window.Current.Content = page;
00078                 page.Initialize((CameraSettingsActivatedEventArgs)args);
00079
00080                 Window.Current.Activate();
00081             }
00082         }
00083     }
00084 }
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKMESH_INDEX_BUFFER_HEADER Member List

This is the complete list of members for SDKMESH_INDEX_BUFFER_HEADER, including all inherited members.
DataOffset | SDKMESH_INDEX_BUFFER_HEADER
IndexBuffer | SDKMESH_INDEX_BUFFER_HEADER
IndexType | SDKMESH_INDEX_BUFFER_HEADER
NumIndices | SDKMESH_INDEX_BUFFER_HEADER
SizeBytes | SDKMESH_INDEX_BUFFER_HEADER
Generated on Sat Nov 23 2024 16:09:21 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Globalization preferences/C++/App.xaml.h Source File

  • Globalization preferences

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Device auto rotation preferences/C++/Constants.cpp Source File

  • Device auto rotation preferences

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
00021     { "Clear Preferences", "SDKSample.Rotation.None" },
00022     { "Landscape Only", "SDKSample.Rotation.Landscape" },
00023     { "Portrait Only", "SDKSample.Rotation.Portrait" },
00024     { "Landscape Flipped Only", "SDKSample.Rotation.LandscapeFlipped" },
00025     { "Portrait Flipped Only", "SDKSample.Rotation.PortraitFlipped" }
00026 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/obj2vbo/BasicMath.h Source File

  • Direct3D resource loading
  • obj2vbo

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 Sat Nov 23 2024 16:08:08 for Win8-Examples by doxygen 1.7.1


Win8-Examples: AtomPub/C++/Constants.h Source File

  • AtomPub

Constants.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 Windows::Security::Credentials;
00016 using namespace Windows::UI::Xaml::Controls;
00017 using namespace Windows::Web::Syndication;
00018 using namespace Windows::Web::AtomPub;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Data::Html;
00021
00022 namespace SDKSample
00023 {
00024     public value struct Scenario
00025     {
00026         Platform::String^ Title;
00027         Platform::String^ ClassName;
00028     };
00029
00030     [Windows::Foundation::Metadata::WebHostHidden]
00031     partial ref class MainPage
00032     {
00033     public:
00034         static property Platform::String^ FEATURE_NAME
00035         {
00036             Platform::String^ get()
00037             {
00038                 return ref new Platform::String(L"AtomPub");
00039             }
00040         }
00041
00042         static property Platform::Array<Scenario>^ scenarios
00043         {
00044             Platform::Array<Scenario>^ get()
00045             {
00046                 return scenariosInner;
00047             }
00048         }
00049
00050         bool TryGetUri(Platform::String^ uriString, Windows::Foundation::Uri^* uri)
00051         {
00052             // Create a Uri instance and catch exceptions related to invalid input. This method returns 'true'
00053             // if the Uri instance was successfully created and 'false' otherwise.
00054             try
00055             {
00056                 *uri = ref new Windows::Foundation::Uri(StringHelper::Trim(uriString));
00057                 return true;
00058             }
00059             catch (Platform::NullReferenceException^ exception)
00060             {
00061                 NotifyUser("Error: URI must not be null or empty.", NotifyType::ErrorMessage);
00062             }
00063             catch (Platform::InvalidArgumentException^ exception)
00064             {
00065                 NotifyUser("Error: Invalid URI", NotifyType::ErrorMessage);
00066             }
00067
00068             return false;
00069         }
00070
00071         bool HandleException(Platform::Exception^ exception, Windows::UI::Xaml::Controls::TextBox^ outputField)
00072         {
00073             SyndicationErrorStatus syndicationError = SyndicationError::GetStatus(exception->HResult);
00074             if (syndicationError != SyndicationErrorStatus::Unknown)
00075             {
00076                 outputField->Text += "The response content is not valid. " +
00077                     "Please make sure to use a URI that points to an Atom feed.\r\n";
00078             }
00079             else
00080             {
00081                 Windows::Web::WebErrorStatus webError = Windows::Web::WebError::GetStatus(exception->HResult);
00082                 if (webError == Windows::Web::WebErrorStatus::Unauthorized)
00083                 {
00084                     outputField->Text += "Incorrect username or password.\r\n";
00085                 }
00086                 else if (webError == Windows::Web::WebErrorStatus::Unknown)
00087                 {
00088                     // Neither a syndication nor a web error.
00089                     return false;
00090                 }
00091             }
00092
00093             NotifyUser(exception->Message, NotifyType::ErrorMessage);
00094
00095             return true;
00096         }
00097
00098     private:
00099         static Platform::Array<Scenario>^ scenariosInner;
00100     };
00101
00102     class StringHelper
00103     {
00104     public:
00105         static Platform::String^ Trim(Platform::String^ s)
00106         {
00107             const WCHAR* first = s->Begin();
00108             const WCHAR* last = s->End();
00109
00110             while (first != last && iswspace(*first))
00111             {
00112                 ++first;
00113             }
00114
00115             while (first != last && iswspace(last[-1]))
00116             {
00117                 --last;
00118             }
00119
00120             return ref new Platform::String(first, last - first);
00121         }
00122
00123         static Platform::String^ Join(Platform::String^ separator, Windows::Foundation::Collections::IVectorView<Platform::String^>^ iv)
00124         {
00125             const std::wstring sep(separator->Begin(), separator->End());
00126             std::wstring ret;
00127
00128             for (unsigned int i = 0, n = iv->Size; i < n; ++i)
00129             {
00130                 if (i > 0)
00131                 {
00132                     ret += sep;
00133                 }
00134
00135                 Platform::String^ elem = iv->GetAt(i);
00136
00137                 ret.append(elem->Begin(), elem->End());
00138             }
00139
00140             return ref new Platform::String(ret.data(), ret.size());
00141         }
00142     };
00143
00144     [Windows::Foundation::Metadata::WebHostHidden]
00145     public ref class CommonData sealed
00146     {
00147     public:
00148         static void Restore(Page^ inputFrame)
00149         {
00150             // Set authentication fields.
00151             ((TextBox^)inputFrame->FindName("ServiceAddressField"))->Text = baseUri;
00152             ((TextBox^)inputFrame->FindName("UserNameField"))->Text = user;
00153             ((PasswordBox^)inputFrame->FindName("PasswordField"))->Password = password;
00154         }
00155
00156         static void Save(Platform::String^ baseUri, Platform::String^ user, Platform::String^ password)
00157         {
00158             // Keep values of authentication fields.
00159             CommonData::baseUri = baseUri;
00160             CommonData::user = user;
00161             CommonData::password = password;
00162         }
00163
00164         static AtomPubClient^ GetClient()
00165         {
00166             AtomPubClient^ client;
00167
00168             client = ref new AtomPubClient();
00169             client->BypassCacheOnRetrieve = true;
00170
00171             if ((user != nullptr) && (password != nullptr))
00172             {
00173                 client->ServerCredential = ref new PasswordCredential();
00174                 client->ServerCredential->UserName = user;
00175                 client->ServerCredential->Password = password;
00176             }
00177             else
00178             {
00179                 client->ServerCredential = nullptr;
00180             }
00181
00182             return client;
00183         }
00184
00185         static property Platform::String^ EditUri
00186         {
00187             Platform::String^ get()
00188             {
00189                 return editUri;
00190             }
00191         }
00192
00193         static property Platform::String^ ServiceDocUri
00194         {
00195             Platform::String^ get()
00196             {
00197                 return serviceDocUri;
00198             }
00199         }
00200
00201         static property Platform::String^ FeedUri
00202         {
00203             Platform::String^ get()
00204             {
00205                 return feedUri;
00206             }
00207         }
00208
00209     private:
00210         static Platform::String^ baseUri;
00211         static Platform::String^ user;
00212         static Platform::String^ password;
00213
00214         // The default Service Document and Edit 'URIs' for WordPress.
00215         static Platform::String^ editUri;
00216         static Platform::String^ serviceDocUri;
00217         static Platform::String^ feedUri;
00218     };
00219
00220     [Windows::Foundation::Metadata::WebHostHidden]
00221     public ref class SyndicationItemIterator sealed
00222     {
00223     private:
00224         SyndicationFeed^ feed;
00225         unsigned int index;
00226
00227     public:
00228         SyndicationItemIterator()
00229         {
00230             this->feed = nullptr;
00231             this->index = 0;
00232         }
00233
00234         void AttachFeed(SyndicationFeed^ feed)
00235         {
00236             this->feed = feed;
00237             this->index = 0;
00238         }
00239
00240         void MoveNext()
00241         {
00242             if (feed != nullptr && index < feed->Items->Size - 1)
00243             {
00244                 index++;
00245             }
00246         }
00247
00248         void MovePrevious()
00249         {
00250             if (feed != nullptr && index > 0)
00251             {
00252                 index--;
00253             }
00254         }
00255
00256         bool HasElements()
00257         {
00258             return feed != nullptr && feed->Items->Size > 0;
00259         }
00260
00261         Platform::String^ GetTitle()
00262         {
00263             // Nothing to return yet.
00264             if (!HasElements())
00265             {
00266                 return "(no title)";
00267             }
00268
00269             if (feed->Items->GetAt(index)->Title != nullptr)
00270             {
00271                 return HtmlUtilities::ConvertToText(feed->Items->GetAt(index)->Title->Text);
00272             }
00273
00274             return "(no title)";
00275         }
00276
00277         Platform::String^ GetContent()
00278         {
00279             // Nothing to return yet.
00280             if (!HasElements())
00281             {
00282                 return "(no value)";
00283             }
00284
00285             if ((feed->Items->GetAt(index)->Content != nullptr) && (feed->Items->GetAt(index)->Content->Text != nullptr))
00286             {
00287                 return feed->Items->GetAt(index)->Content->Text;
00288             }
00289
00290             return "(no value)";
00291         }
00292
00293         Platform::String^ GetIndexDescription()
00294         {
00295             // Nothing to return yet.
00296             if (!HasElements())
00297             {
00298                 return "0 of 0";
00299             }
00300
00301             return (index + 1).ToString() + " of " + feed->Items->Size.ToString();
00302         }
00303
00304         Uri^ GetEditUri()
00305         {
00306             // Nothing to return yet.
00307             if (!HasElements())
00308             {
00309                 return nullptr;
00310             }
00311
00312             return feed->Items->GetAt(index)->EditUri;
00313         }
00314
00315         SyndicationItem^ GetSyndicationItem()
00316         {
00317             // Nothing to return yet.
00318             if (!HasElements())
00319             {
00320                 return nullptr;
00321             }
00322
00323             return feed->Items->GetAt(index);
00324         }
00325     };
00326 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text editing/C++/Scenario4.xaml.h Source File

  • XAML text editing

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
00022 namespace SDKSample
00023 {
00024     namespace TextEditing
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 Scenario4 sealed
00031         {
00032         public:
00033             Scenario4();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040             void Other_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         };
00042     }
00043 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Print/C++/ScenarioInput4.xaml.cpp Source File

  • Print

ScenarioInput4.xaml.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 //
00009 // ScenarioInput4.xaml.cpp
00010 // Implementation of the ScenarioInput4 class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioOutput4.xaml.h"
00015 #include "ScenarioInput4.xaml.h"
00016
00017 using namespace PrintSample;
00018
00019 using namespace Platform;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Graphics::Display;
00023 using namespace Windows::Graphics::Printing;
00024 using namespace Windows::Graphics::Printing::OptionDetails;
00025 using namespace Windows::UI;
00026 using namespace Windows::UI::Text;
00027 using namespace Windows::UI::Xaml;
00028 using namespace Windows::UI::Xaml::Controls;
00029 using namespace Windows::UI::Xaml::Documents;
00030 using namespace Windows::UI::Xaml::Media;
00031 using namespace Windows::UI::Xaml::Media::Imaging;
00032 using namespace Windows::UI::Xaml::Navigation;
00033 using namespace Windows::UI::Xaml::Printing;
00034
00035 DisplayContent GetDisplayContent(int option)
00036 {
00037     DisplayContent displayContent;
00038     switch (option)
00039     {
00040     case 1:
00041         displayContent = DisplayContent::Text;
00042         break;
00043     case 2:
00044         displayContent = DisplayContent::Images;
00045         break;
00046     default:
00047         displayContent = DisplayContent::TextAndImages;
00048         break;
00049     }
00050
00051     return displayContent;
00052 }
00053
00054 ScenarioInput4::ScenarioInput4()
00055 {
00056     InitializeComponent();
00057 }
00058
00059 /// <summary>
00060 /// Provide print content for scenario 4 first page
00061 /// </summary>
00062 void ScenarioInput4::PreparetPrintContent()
00063 {
00064     if (FirstPage == nullptr)
00065     {
00066         FirstPage = ref new ScenarioOutput4();
00067         StackPanel^ header = safe_cast<StackPanel^>(FirstPage->FindName("header"));
00068         header->Visibility = Windows::UI::Xaml::Visibility::Visible;
00069     }
00070
00071     // Add the (newley created) page to the printing root which is part of the visual tree and force it to go
00072     // through layout so that the linked containers correctly distribute the content inside them.
00073     PrintingRoot->Children->Append(FirstPage);
00074     PrintingRoot->InvalidateMeasure();
00075     PrintingRoot->UpdateLayout();
00076 }
00077
00078 /// <summary>
00079 /// This is the event handler for PrintManager.PrintTaskRequested.
00080 /// 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.
00081 /// Therefore, we use this handler to only create the print task.
00082 /// The print settings customization can be done when the print document source is requested.
00083 /// </summary>
00084 /// <param name="sender">PrintManager</param>
00085 /// <param name="e">PrintTaskRequestedEventArgs</param>
00086 void ScenarioInput4::PrintTaskRequested(PrintManager^ sender, PrintTaskRequestedEventArgs^ e)
00087 {
00088     auto printTaskRef = std::make_shared<PrintTask^>(nullptr);
00089     *printTaskRef = e->Request->CreatePrintTask("C++ Printing SDK Sample",
00090                                                 ref new PrintTaskSourceRequestedHandler([this, printTaskRef](PrintTaskSourceRequestedArgs^ args)
00091                                                 {
00092                                                     PrintTask^ printTask = *printTaskRef;
00093                                                     IVector<String^>^ displayedOptions = printTask->Options->DisplayedOptions;
00094
00095                                                     // clear the print options that are displayed beacuse adding the same one multiple times will throw an exception
00096                                                     displayedOptions->Clear();
00097
00098                                                     PrintTaskOptionDetails^ printDetailedOptions = PrintTaskOptionDetails::GetFromPrintTaskOptions(printTask->Options);
00099
00100                                                     // Choose the printer options to be shown.
00101                                                     // The order in which the options are appended determines the order in which they appear in the UI
00102                                                     displayedOptions->Clear();
00103
00104                                                     displayedOptions->Append(StandardPrintTaskOptions::Copies);
00105                                                     displayedOptions->Append(StandardPrintTaskOptions::Orientation);
00106                                                     displayedOptions->Append(StandardPrintTaskOptions::ColorMode);
00107
00108                                                     // Create a new list option
00109
00110                                                     PrintCustomItemListOptionDetails^ pageFormat = printDetailedOptions->CreateItemListOption(L"PageContent", L"Pictures");
00111                                                     pageFormat->AddItem(L"PicturesText", L"Pictures and text");
00112                                                     pageFormat->AddItem(L"PicturesOnly", L"Pictures only");
00113                                                     pageFormat->AddItem(L"TextOnly", L"Text only");
00114
00115                                                     // Add the custom option to the option list
00116                                                     displayedOptions->Append(L"PageContent");
00117
00118                                                     printDetailedOptions->OptionChanged += ref new TypedEventHandler<PrintTaskOptionDetails^, PrintTaskOptionChangedEventArgs^>(this, &ScenarioInput4::printDetailedOptions_OptionChanged);
00119
00120                                                     // Print Task event handler is invoked when the print job is completed.
00121                                                     printTask->Completed += ref new TypedEventHandler<PrintTask^, PrintTaskCompletedEventArgs^>(
00122                                                     [=](PrintTask^ sender, PrintTaskCompletedEventArgs^ e)
00123                                                     {
00124                                                         // Notify the user when the print operation fails.
00125                                                         if (e->Completion == Windows::Graphics::Printing::PrintTaskCompletion::Failed)
00126                                                         {
00127                                                             auto callback = ref new Windows::UI::Core::DispatchedHandler(
00128                                                             [=]()
00129                                                             {
00130                                                                 RootPage->NotifyUser(ref new String(L"Failed to print."), NotifyType::ErrorMessage);
00131                                                             });
00132
00133                                                             Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, callback);
00134                                                         }
00135                                                     });
00136
00137                                                     args->SetSource(PrintDocumentSource);
00138                                                 }));
00139 }
00140
00141 /// <summary>
00142 /// Option change event handler
00143 /// </summary>
00144 /// <param name="sender">PrintTaskOptionsDetails object</param>
00145 /// <param name="args">the event arguments containing the changed option id</param>
00146 void ScenarioInput4::printDetailedOptions_OptionChanged(PrintTaskOptionDetails^ sender, PrintTaskOptionChangedEventArgs^ args)
00147 {
00148     // Listen for PageContent changes
00149     String^ optionId = safe_cast<String^>(args->OptionId);
00150
00151     if (optionId != nullptr && optionId == L"PageContent")
00152     {
00153         RefreshPreview();
00154     }
00155 }
00156
00157 /// <summary>
00158 /// Helper function used to triger a preview refresh
00159 /// </summary>
00160 void ScenarioInput4::RefreshPreview()
00161 {
00162     auto callback = ref new Windows::UI::Core::DispatchedHandler([this]()
00163                                                                   {
00164                                                                     CurrentPrintDocument->InvalidatePreview();
00165                                                                   });
00166
00167     Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, callback);
00168 }
00169
00170 /// <summary>
00171 /// This is the event handler for PrintDocument.Paginate. It creates print preview pages for the app.
00172 /// </summary>
00173 /// <param name="sender"></param>
00174 /// <param name="e">Paginate Event Arguments</param>
00175 void ScenarioInput4::CreatePrintPreviewPages(Object^ sender, PaginateEventArgs^ e)
00176 {
00177     // Get PageContent property
00178     PrintTaskOptionDetails^ printDetailedOptions = PrintTaskOptionDetails::GetFromPrintTaskOptions(e->PrintTaskOptions);
00179     IPrintOptionDetails^ printOptionDetails = printDetailedOptions->Options->Lookup(ref new String(L"PageContent"));
00180     String^ pageContent = safe_cast<String^>(printOptionDetails->Value);
00181
00182     // Set the text & image display flag
00183     int result = (wcsstr(pageContent->Data(), L"Pictures")!=nullptr) << 1 | (wcsstr(pageContent->Data(), L"Text")!=nullptr);
00184     m_imageText = GetDisplayContent(result);
00185
00186     BasePrintPage::CreatePrintPreviewPages(sender, e);
00187 }
00188
00189 /// <summary>
00190 /// This function creates and adds one print preview page to the internal cache of print preview
00191 /// pages stored in m_printPreviewPages.
00192 /// </summary>
00193 /// <param name="lastRTBOAdded">Last RichTextBlockOverflow element added in the current content</param>
00194 /// <param name="printPageDescription">Printer's page description</param>
00195 RichTextBlockOverflow^ ScenarioInput4::AddOnePrintPreviewPage(RichTextBlockOverflow^ lastRTBOAdded, PrintPageDescription printPageDescription)
00196 {
00197     // Check if we need to hide/show text & images for this scenario
00198     // Since all is rulled by the first page (page flow), here is where we must start
00199     if (lastRTBOAdded == nullptr)
00200     {
00201         // Get a refference to page objects
00202         Grid^ pageContent = safe_cast<Grid^>(FirstPage->FindName("printableArea"));
00203         Image^ scenarioImage = safe_cast<Image^>(FirstPage->FindName("scenarioImage"));
00204         RichTextBlock^ mainText = safe_cast<RichTextBlock^>(FirstPage->FindName("textContent"));
00205         RichTextBlockOverflow^ firstLink = safe_cast<RichTextBlockOverflow^>(FirstPage->FindName("firstLinkedContainer"));
00206         RichTextBlockOverflow^ continuationLink = safe_cast<RichTextBlockOverflow^>(FirstPage->FindName("continuationPageLinkedContainer"));
00207
00208         // Hide(collapse) and move elements in different grid cells depending by the viewable content(only text, only pictures)
00209
00210         scenarioImage->Visibility = ShowImage ? Windows::UI::Xaml::Visibility::Visible : Windows::UI::Xaml::Visibility::Collapsed;
00211         firstLink->SetValue(Grid::ColumnSpanProperty, ShowImage ? 1 : 2);
00212
00213         scenarioImage->SetValue(Grid::RowProperty, ShowText ? 2 : 1);
00214         scenarioImage->SetValue(Grid::ColumnProperty, ShowText ? 1 : 0);
00215
00216         pageContent->ColumnDefinitions->GetAt(0)->Width = Windows::UI::Xaml::GridLengthHelper::FromValueAndType(ShowText ? 6 : 4, GridUnitType::Star);
00217         pageContent->ColumnDefinitions->GetAt(1)->Width = Windows::UI::Xaml::GridLengthHelper::FromValueAndType(ShowText ? 4 : 6, GridUnitType::Star);
00218
00219         // Break the text flow if the app is not printing text in order not to spawn pages with blank content
00220         mainText->Visibility = ShowText ? Windows::UI::Xaml::Visibility::Visible : Windows::UI::Xaml::Visibility::Collapsed;
00221         continuationLink->Visibility = ShowText ? Windows::UI::Xaml::Visibility::Visible : Windows::UI::Xaml::Visibility::Collapsed;
00222
00223         // Hide header if printing only images
00224         StackPanel^ header = safe_cast<StackPanel^>(FirstPage->FindName("header"));
00225         header->Visibility = ShowText ? Windows::UI::Xaml::Visibility::Visible : Windows::UI::Xaml::Visibility::Collapsed;
00226     }
00227
00228     //Continue with the rest of the base printing layout processing (paper size, printable page size)
00229     return BasePrintPage::AddOnePrintPreviewPage(lastRTBOAdded, printPageDescription);
00230 }
00231
00232 void ScenarioInput4::OnNavigatedTo(NavigationEventArgs^ e)
00233 {
00234     BasePrintPage::OnNavigatedTo(e);
00235
00236     RegisterForPrinting();
00237 }
00238
00239 void ScenarioInput4::OnNavigatedFrom(NavigationEventArgs^ e)
00240 {
00241     UnregisterForPrinting() ;
00242 }
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/pch.cpp Source File

  • Direct3D resource loading

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application resources and localization/C++/Scenario4.xaml.h Source File

  • Application resources and localization

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
00022 namespace SDKSample
00023 {
00024     namespace ApplicationResources
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 Scenario4 sealed
00031         {
00032         public:
00033             Scenario4();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039       };
00040     }
00041 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML accessibility/C++/pch.h Source File

  • XAML accessibility

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/MediaExtensions/Common/BufferLock.h Source File

  • Media extensions
  • MediaExtensions
  • Common

BufferLock.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
00009 #pragma once
00010
00011
00012 //////////////////////////////////////////////////////////////////////////
00013 //  VideoBufferLock
00014 //
00015 //  Description:
00016 //  Locks a video buffer that might or might not support IMF2DBuffer.
00017 //
00018 //////////////////////////////////////////////////////////////////////////
00019
00020 class VideoBufferLock
00021 {
00022 public:
00023     VideoBufferLock(IMFMediaBuffer *pBuffer) : m_p2DBuffer(NULL)
00024     {
00025         m_pBuffer = pBuffer;
00026         m_pBuffer->AddRef();
00027
00028         // Query for the 2-D buffer interface. OK if this fails.
00029         m_pBuffer->QueryInterface(IID_PPV_ARGS(&m_p2DBuffer));
00030     }
00031
00032     ~VideoBufferLock()
00033     {
00034         UnlockBuffer();
00035         SafeRelease(&m_pBuffer);
00036         SafeRelease(&m_p2DBuffer);
00037     }
00038
00039     // LockBuffer:
00040     // Locks the buffer. Returns a pointer to scan line 0 and returns the stride.
00041
00042     // The caller must provide the default stride as an input parameter, in case
00043     // the buffer does not expose IMF2DBuffer. You can calculate the default stride
00044     // from the media type.
00045
00046     HRESULT LockBuffer(
00047         LONG  lDefaultStride,    // Minimum stride (with no padding).
00048         DWORD dwHeightInPixels,  // Height of the image, in pixels.
00049         BYTE  **ppbScanLine0,    // Receives a pointer to the start of scan line 0.
00050         LONG  *plStride          // Receives the actual stride.
00051         )
00052     {
00053         HRESULT hr = S_OK;
00054
00055         // Use the 2-D version if available.
00056         if (m_p2DBuffer)
00057         {
00058             hr = m_p2DBuffer->Lock2D(ppbScanLine0, plStride);
00059         }
00060         else
00061         {
00062             // Use non-2D version.
00063             BYTE *pData = NULL;
00064
00065             hr = m_pBuffer->Lock(&pData, NULL, NULL);
00066             if (SUCCEEDED(hr))
00067             {
00068                 *plStride = lDefaultStride;
00069                 if (lDefaultStride < 0)
00070                 {
00071                     // Bottom-up orientation. Return a pointer to the start of the
00072                     // last row *in memory* which is the top row of the image.
00073                     *ppbScanLine0 = pData + abs(lDefaultStride) * (dwHeightInPixels - 1);
00074                 }
00075                 else
00076                 {
00077                     // Top-down orientation. Return a pointer to the start of the
00078                     // buffer.
00079                     *ppbScanLine0 = pData;
00080                 }
00081             }
00082         }
00083         return hr;
00084     }
00085
00086     HRESULT UnlockBuffer()
00087     {
00088         if (m_p2DBuffer)
00089         {
00090             return m_p2DBuffer->Unlock2D();
00091         }
00092         else
00093         {
00094             return m_pBuffer->Unlock();
00095         }
00096     }
00097
00098 private:
00099     IMFMediaBuffer  *m_pBuffer;
00100     IMF2DBuffer     *m_p2DBuffer;
00101 };
00102
Generated on Sat Nov 23 2024 16:08:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Mobile broadband account provisioning/C++/ProvisionMno.xaml.cpp Source File

  • Mobile broadband account provisioning

ProvisionMno.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 // ProvisionMno.xaml.cpp
00013 // Implementation of the ProvisionMno class
00014 //
00015
00016 #include "pch.h"
00017 #include "ProvisionMno.xaml.h"
00018
00019 using namespace SDKSample::ProvisioningAgent;
00020
00021 using namespace concurrency;
00022 using namespace Platform;
00023 using namespace Windows::UI::Xaml;
00024 using namespace Windows::UI::Xaml::Controls;
00025 using namespace Windows::UI::Xaml::Navigation;
00026 using namespace Windows::Networking::NetworkOperators;
00027
00028 ProvisionMno::ProvisionMno()
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 ProvisionMno::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     util = ref new Util();
00044 }
00045
00046 void ProvisionMno::ProvisionMno_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00047 {
00048     if (provXmlText->Text == L"")
00049     {
00050         rootPage->NotifyUser("Provisioning XML cannot be empty", NotifyType::ErrorMessage);
00051         return;
00052     }
00053
00054     auto provisioningXML = provXmlText->Text;
00055
00056     // Get the network account ID.
00057     auto networkAccIds = MobileBroadbandAccount::AvailableNetworkAccountIds;
00058     if (networkAccIds->Size == 0)
00059     {
00060         rootPage->NotifyUser("No network account ID found", NotifyType::ErrorMessage);
00061         return;
00062     }
00063
00064     ProvisionMnoButton->IsEnabled = false;
00065
00066     // For the sake of simplicity, assume we want to use the first account.
00067     // Refer to the MobileBroadbandAccount API's for how to select a specific account ID.
00068     auto networkAccountId = networkAccIds->GetAt(0);
00069
00070     // Create provisioning agent for specified network account ID
00071     auto provisioningAgent = Windows::Networking::NetworkOperators::ProvisioningAgent::CreateFromNetworkAccountId(networkAccountId);
00072
00073     // Provision using XML
00074     task<ProvisionFromXmlDocumentResults^> getProvisioningResult(provisioningAgent->ProvisionFromXmlDocumentAsync(provisioningXML));
00075     getProvisioningResult.then([this](task<ProvisionFromXmlDocumentResults^> resultTask)
00076     {
00077         try
00078         {
00079             // Get will throw an exception if the task failed with an error.
00080             auto result = resultTask.get();
00081
00082             if (result->AllElementsProvisioned)
00083             {
00084                 // Provisioning is done successfully
00085                 rootPage->NotifyUser("Device was successfully configured", NotifyType::StatusMessage);
00086             }
00087             else
00088             {
00089                 // Error has occured during provisioning
00090                 // And hence displaying result XML containing
00091                 // errors
00092                 rootPage->NotifyUser(util->ParseResultXML(result->ProvisionResultsXml), NotifyType::StatusMessage);
00093             }
00094         }
00095         catch (Platform::Exception^ ex)
00096         {
00097             // Handle errors
00098             rootPage->NotifyUser(util->PrintExceptionCode(ex), NotifyType::ErrorMessage);
00099         }
00100     });
00101     ProvisionMnoButton->IsEnabled = true;
00102 }
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

ConstantBufferLayoutForDX9BrightPassPixelShader Member List

This is the complete list of members for ConstantBufferLayoutForDX9BrightPassPixelShader, including all inherited members.
pixelHeight | ConstantBufferLayoutForDX9BrightPassPixelShader
pixelWidth | ConstantBufferLayoutForDX9BrightPassPixelShader
Generated on Sat Nov 23 2024 16:09:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: HomeGroup app/C++/MainPage.xaml.cpp Source File

  • HomeGroup app

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:42 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Scaling according to DPI/C++/MainPage.xaml.cpp Source File

  • Scaling according to DPI

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:43 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Certificate enrollment/C++/Constants.h Source File

  • Certificate enrollment

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"Certificate Enrollment");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044
00045
00046 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CameraOptionsUI/C++/App.xaml.h Source File

  • CameraOptionsUI

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX swap chain implementation/C++/SampleOverlay.h Source File

  • DirectX swap chain implementation

SampleOverlay.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 "DirectXSample.h"
00011
00012 // This class is responsible for initializing and rendering the title overlay visible
00013 // at the top of the DirectX SDK samples.
00014 ref class SampleOverlay
00015 {
00016 internal:
00017     SampleOverlay();
00018
00019     void Initialize(
00020         _In_ ID2D1Device*         d2dDevice,
00021         _In_ ID2D1DeviceContext*  d2dContext,
00022         _In_ IWICImagingFactory*  wicFactory,
00023         _In_ IDWriteFactory*      dwriteFactory,
00024         _In_ Platform::String^    caption
00025         );
00026
00027     void ResetDirectXResources();
00028
00029     void UpdateForWindowSizeChange();
00030
00031     void Render();
00032
00033     float GetTitleHeightInDips();
00034
00035 private:
00036
00037     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00038     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00039     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00040     Microsoft::WRL::ComPtr<IDWriteFactory>          m_dwriteFactory;
00041     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_whiteBrush;
00042     Microsoft::WRL::ComPtr<ID2D1DrawingStateBlock>  m_stateBlock;
00043
00044     Microsoft::WRL::ComPtr<IWICImagingFactory>      m_wicFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Bitmap>             m_logoBitmap;
00046     Microsoft::WRL::ComPtr<IDWriteTextLayout>       m_textLayout;
00047
00048     UINT                                            m_idIncrement;
00049     bool                                            m_drawOverlay;
00050     Platform::String^                               m_sampleName;
00051     float                                           m_padding;
00052     float                                           m_textVerticalOffset;
00053     D2D1_SIZE_F                                     m_logoSize;
00054     float                                           m_overlayWidth;
00055 };
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: HomeGroup app/C++/HomeGroupAdvancedSearch.xaml.cpp Source File

  • HomeGroup app

HomeGroupAdvancedSearch.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 // HomeGroupAdvancedSearch.xaml.cpp
00013 // Implementation of the HomeGroupAdvancedSearch class
00014 //
00015
00016 #include "pch.h"
00017 #include "HomeGroupAdvancedSearch.xaml.h"
00018
00019 using namespace SDKSample::HomeGroup;
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::UI::Xaml::Media::Imaging;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Storage;
00028 using namespace Windows::Storage::Search;
00029 using namespace concurrency;
00030 using namespace Windows::System;
00031 using namespace Windows::Foundation;
00032 using namespace Windows::Foundation::Collections;
00033 using namespace std;
00034 using namespace Windows::Storage::FileProperties;
00035 using namespace Windows::Storage::Streams;
00036
00037
00038 HomeGroupAdvancedSearch::HomeGroupAdvancedSearch()
00039 {
00040     InitializeComponent();
00041 }
00042
00043 /// <summary>
00044 /// Scenario 4 initialization.  Find the homegroup users and their thumbnails and draw them as input options.
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 HomeGroupAdvancedSearch::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     SetButtons();
00054 }
00055
00056 void HomeGroupAdvancedSearch::SetButtons()
00057 {
00058     // This try/catch block is for scenarios where the Homegroup Known Folder is not available.
00059     try
00060     {
00061         auto homeGroupFolder = KnownFolders::HomeGroup;
00062         // Enumerate the homegroup first-level folders, which represent the homegroup users, and get the thumbnails, which is the user tiles.
00063         create_task(homeGroupFolder->GetFoldersAsync()).then(
00064             [this, homeGroupFolder](IVectorView<StorageFolder^>^ folders)
00065         {
00066             if (folders)
00067             {
00068                 // HomeGroup can have more than 4 users. Iterating and limiting it to '4'
00069                 // for this sample.
00070                 int userCount = ((folders->Size < 4) ? folders->Size : 4);
00071                 Vector<Windows::UI::Xaml::Controls::Button^>^ buttons = ref new Vector<Windows::UI::Xaml::Controls::Button^>;
00072                 buttons->InsertAt(0, user1Button);
00073                 buttons->InsertAt(1, user2Button);
00074                 buttons->InsertAt(2, user3Button);
00075                 buttons->InsertAt(3, user4Button);
00076                 for (int userIndex = 0; userIndex < userCount; userIndex++)
00077                 {
00078                     buttons->GetAt(userIndex)->Content = folders->GetAt(userIndex)->Name;
00079                     buttons->GetAt(userIndex)->Visibility = Windows::UI::Xaml::Visibility::Visible;
00080                 }
00081             }
00082             else
00083             {
00084                 rootPage->NotifyUser("No homegroup users could be found.  Make sure you are joined to a homegroup and there is someone sharing", NotifyType::ErrorMessage);
00085             }
00086         });
00087     }
00088     catch (Exception^ ex)
00089     {
00090         rootPage->NotifyUser(ex->Message, NotifyType::StatusMessage);
00091     }
00092 }
00093
00094
00095 void SDKSample::HomeGroup::HomeGroupAdvancedSearch::Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00096 {
00097     Button^ button = safe_cast<Button^>(sender);
00098     if (button != nullptr)
00099     {
00100         // This try/catch block is for scenarios where the Homegroup Known Folder is not available.
00101         try
00102         {
00103             StorageFolder^ homeGroupFolder = KnownFolders::HomeGroup;
00104             Platform::String^ userName = button->Content->ToString();
00105             create_task(homeGroupFolder->GetFoldersAsync()).then(
00106                 [this, userName](IVectorView<StorageFolder^>^ folders)
00107             {
00108                 std::for_each(begin(folders), end(folders), [this, userName](StorageFolder ^folder)
00109                 {
00110                     if (folder->Name->Equals(userName))
00111                     {
00112                         auto fileTypeFilter = ref new Vector<Platform::String^>();
00113                         fileTypeFilter->Append("*");
00114                         auto queryOptions = ref new QueryOptions(CommonFileQuery::OrderBySearchRank, fileTypeFilter);
00115                         auto queryResult = folder->CreateFileQueryWithOptions(queryOptions);
00116                         create_task(queryResult->GetFilesAsync()).then(
00117                             [this, queryOptions, userName](IVectorView<StorageFile^>^ files)
00118                         {
00119                             if (files->Size == 0)
00120                             {
00121                                 rootPage->NotifyUser("No files found for " + userName, NotifyType::ErrorMessage);
00122                             }
00123                             else
00124                             {
00125                                 Platform::String^ outputText = files->Size.ToString();
00126                                 outputText += (files->Size == 1) ? " file shared by " + userName + "\n\n"
00127                                                                  : " files shared by " + userName+ "\n\n";
00128                                 std::for_each(begin(files), end(files), [this, &outputText](StorageFile ^file)
00129                                 {
00130                                     outputText += file->Name + "\n";
00131                                 });
00132                                 rootPage->NotifyUser(outputText, NotifyType::StatusMessage);
00133                             }
00134                         });
00135                     }
00136                 });
00137             });
00138         }
00139         catch (Exception^ ex)
00140         {
00141             rootPage->NotifyUser(ex->Message + "\n", NotifyType::StatusMessage);
00142         }
00143     }
00144 }
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::CompassCPP::sealed Member List

This is the complete list of members for SDKSample::CompassCPP::sealed, including all inherited members.
compass | SDKSample::CompassCPP::sealed | [private]
desiredReportInterval | SDKSample::CompassCPP::sealed | [private]
dispatcher | SDKSample::CompassCPP::sealed | [private]
dispatcherTimer | SDKSample::CompassCPP::sealed | [private]
DisplayCurrentReading(Platform::Object^sender, Platform::Object^e) | SDKSample::CompassCPP::sealed | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::CompassCPP::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::CompassCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::CompassCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::CompassCPP::sealed | [protected, virtual]
ReadingChanged(Windows::Devices::Sensors::Compass^sender, Windows::Devices::Sensors::CompassReadingChangedEventArgs^e) | SDKSample::CompassCPP::sealed | [private]
readingToken | SDKSample::CompassCPP::sealed | [private]
rootPage | SDKSample::CompassCPP::sealed | [private]
Scenario1() | SDKSample::CompassCPP::sealed |
Scenario2() | SDKSample::CompassCPP::sealed |
ScenarioDisable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CompassCPP::sealed | [private]
ScenarioDisable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CompassCPP::sealed | [private]
ScenarioEnable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CompassCPP::sealed | [private]
ScenarioEnable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CompassCPP::sealed | [private]
VisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | SDKSample::CompassCPP::sealed | [private]
VisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | SDKSample::CompassCPP::sealed | [private]
visibilityToken | SDKSample::CompassCPP::sealed | [private]
Generated on Sat Nov 23 2024 16:09:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Tasks::sealed Member List

This is the complete list of members for Tasks::sealed, including all inherited members.
CancelRequested | Tasks::sealed | [private]
Deferral | Tasks::sealed | [private]
OnCanceled(IBackgroundTaskInstance^taskInstance, BackgroundTaskCancellationReason reason) | Tasks::sealed |
OnCanceled(IBackgroundTaskInstance^taskInstance, BackgroundTaskCancellationReason reason) | Tasks::sealed |
PeriodicTimer | Tasks::sealed | [private]
Progress | Tasks::sealed | [private]
Run(IBackgroundTaskInstance^taskInstance) | Tasks::sealed | [virtual]
Run(IBackgroundTaskInstance^taskInstance) | Tasks::sealed | [virtual]
SampleBackgroundTask() | Tasks::sealed |
ServicingComplete() | Tasks::sealed |
TaskInstance | Tasks::sealed | [private]
~SampleBackgroundTask() | Tasks::sealed | [private]
~ServicingComplete() | Tasks::sealed | [private]
Generated on Sat Nov 23 2024 16:09:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

ShareTarget::Common::LayoutAwarePage Member List

This is the complete list of members for ShareTarget::Common::LayoutAwarePage, including all inherited members.
__pad0__ | ShareTarget::Common::LayoutAwarePage |
_defaultViewModel | ShareTarget::Common::LayoutAwarePage | [private]
_layoutAwareControls | ShareTarget::Common::LayoutAwarePage | [private]
_useFilledStateForNarrowWindow | ShareTarget::Common::LayoutAwarePage | [private]
_windowSizeEventToken | ShareTarget::Common::LayoutAwarePage | [private]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | ShareTarget::Common::LayoutAwarePage | [virtual]
GoBack(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | ShareTarget::Common::LayoutAwarePage | [virtual]
InvalidateVisualState() | ShareTarget::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | ShareTarget::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | ShareTarget::Common::LayoutAwarePage |
WindowSizeChanged(Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | ShareTarget::Common::LayoutAwarePage | [private]
Generated on Sat Nov 23 2024 16:09:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

UiaCoreWindowProvider::ITriColorControlInternal Member List

This is the complete list of members for UiaCoreWindowProvider::ITriColorControlInternal, including all inherited members.
ControlRect([out, retval] Windows.Foundation.Rect *prc) | UiaCoreWindowProvider::ITriColorControlInternal
ControlValue([in] TriColorValue value) | UiaCoreWindowProvider::ITriColorControlInternal
ControlValue([out, retval] TriColorValue *pvalue) | UiaCoreWindowProvider::ITriColorControlInternal
GetAppWindowProvider([out, retval] IInspectable **provider) | UiaCoreWindowProvider::ITriColorControlInternal
GetTriColorControlProvider([out, retval] IInspectable **provider) | UiaCoreWindowProvider::ITriColorControlInternal
GetTriColorFragmentProvider([in] TriColorValue value,[out, retval] IInspectable **provider) | UiaCoreWindowProvider::ITriColorControlInternal
HasFocus([out, retval] VARIANT_BOOL *hasFocus) | UiaCoreWindowProvider::ITriColorControlInternal
RectFromValue([in] TriColorValue value,[out, retval] Windows.Foundation.Rect *prc) | UiaCoreWindowProvider::ITriColorControlInternal
ValueFromPoint([in] Windows.Foundation.Point pt,[out, retval] TriColorValue *value) | UiaCoreWindowProvider::ITriColorControlInternal
Generated on Sat Nov 23 2024 16:09:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite inline object/C++/pch.h Source File

  • DirectWrite inline object

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 <d3d11_1.h>
00012 #include <d2d1_1.h>
00013 #include <d2d1_1helper.h>
00014 #include <d2d1effects.h>
00015 #include <dwrite_1.h>
00016 #include <wincodec.h>
00017 #include <math.h>
00018 #include <agile.h>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Custom driver access/C++,JavaScript/DLL/support.h Source File

  • Custom driver access
  • C++,JavaScript
  • DLL

support.h

Go to the documentation of this file.
00001 #include <strsafe.h>
00002 #include <assert.h>
00003
00004 #pragma once
00005
00006 ///<summary>
00007 ///Printf to the debugger
00008 ///</summary>
00009 inline void DbgPrint(PCWSTR FormatString, ...) {
00010   WCHAR buffer[1024];
00011   static ULONG line = 0;
00012   va_list arglist;
00013   va_start(arglist, FormatString);
00014
00015   StringCbPrintf(buffer, sizeof(buffer), L"%03d:", line++);
00016   OutputDebugString(buffer);
00017
00018   StringCbVPrintf(buffer, sizeof(buffer), FormatString, arglist);
00019   OutputDebugString(buffer);
00020 }
00021
00022 namespace Samples {
00023     namespace Devices {
00024
00025         [uuid("999BAD24-9ACD-45BB-8669-2A2FC0288B04")]
00026         delegate void OnIoComplete(HRESULT Result, DWORD BytesReturned);
00027
00028         ///<summary>wrapper class for the result of an IOCTL</summary>
00029         struct DeviceControlResult {
00030             HRESULT Result;
00031             ULONG BytesTransferred;
00032
00033             DeviceControlResult() : Result(E_NOT_SET),
00034                                     BytesTransferred(0)
00035             {
00036                 return;
00037             }
00038
00039             DeviceControlResult(HRESULT Hr, DWORD Cb) : Result(Hr),
00040                                                         BytesTransferred(Cb)
00041             {
00042                 return;
00043             }
00044         };
00045
00046     ///<summary>
00047     ///Starts the requested IOCTL
00048     ///</summary>
00049     ///<returns>returns a task which will complete when the IOCTL completes</returns>
00050         inline
00051         concurrency::task<DeviceControlResult>
00052         StartIoctl(
00053             _In_ IDeviceIoControl* Device,
00054             _In_ ULONG DeviceControlCode,
00055             _In_reads_bytes_opt_(InputBufferCb) PUCHAR InputBuffer,
00056             _In_ ULONG InputBufferCb,
00057             _Out_writes_bytes_opt_(OutputBufferCb) PUCHAR OutputBuffer,
00058             _In_ ULONG OutputBufferCb,
00059             _Out_opt_ ULONG_PTR* CancelToken = NULL
00060             )
00061         {
00062             concurrency::task_completion_event<DeviceControlResult> tce;
00063             concurrency::task<DeviceControlResult> t(tce);
00064
00065             auto callback = ref new OnIoComplete(
00066                 [tce](HRESULT Hr, DWORD Cb) {
00067                     tce.set(DeviceControlResult(Hr, Cb));
00068                 }
00069             );
00070
00071             auto cb2 = (IDeviceRequestCompletionCallback*) callback;
00072
00073             HRESULT hr= Device->DeviceIoControlAsync(
00074                                     DeviceControlCode,
00075                                     InputBuffer,
00076                                     InputBufferCb,
00077                                     OutputBuffer,
00078                                     OutputBufferCb,
00079                                     cb2,
00080                                     CancelToken
00081                                     );
00082
00083             if (hr != S_OK) {
00084                 tce.set(DeviceControlResult(hr, 0));
00085             }
00086
00087             return t;
00088         }
00089     }
00090 }
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Credential locker/C++/common/suspensionmanager.cpp Source File

  • Credential locker
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:36 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2Dapp printing/C++/pch.cpp Source File

  • Direct2Dapp printing

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::NotificationBase Member List

This is the complete list of members for NotificationsExtensions::NotificationBase, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
GetContent() | NotificationsExtensions::NotificationBase | [pure virtual]
GetContent() | NotificationsExtensions::NotificationBase | [pure virtual]
GetContent() | NotificationsExtensions::NotificationBase | [pure virtual]
GetContent() | NotificationsExtensions::NotificationBase | [pure virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
m_AddImageQueryNullable | NotificationsExtensions::NotificationBase | [private]
m_BaseUri | NotificationsExtensions::NotificationBase | [private]
m_Images | NotificationsExtensions::NotificationBase | [private]
m_Lang | NotificationsExtensions::NotificationBase | [private]
m_StrictValidation | NotificationsExtensions::NotificationBase | [private]
m_TemplateName | NotificationsExtensions::NotificationBase | [private]
m_TextFields | NotificationsExtensions::NotificationBase | [private]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextFields | NotificationsExtensions::NotificationBase |
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:41 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XInput game controller/C++/SimpleController.cpp Source File

  • XInput game controller

SimpleController.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 "SimpleController.h"
00010 #include "DirectXSample.h"
00011
00012 namespace
00013 {
00014     const char16    APPLICATION_TITLE[] = L"XInput game controller sample";
00015
00016     const float     CLEAR_COLOR[4] = { 0.071f, 0.040f, 0.561f, 1.0f };
00017
00018     const char16    FONT_LOCAL[] = L"en-US";
00019     const char16    FONT_NAME[]  = L"Segoe UI";
00020     const float     FONT_SIZE_HEADER = 18.0f;
00021     const float     FONT_SIZE_TEXT   = 18.0f;
00022
00023     const float     INFORMATION_START_X = 32.0f;
00024     const float     INFORMATION_START_Y = 150.0f;
00025     const float     LINE_HEIGHT  = FONT_SIZE_HEADER * 1.5f;
00026
00027     const float     INPUT_LABEL_START = INFORMATION_START_X;
00028     const float     INPUT_DATA_START  = INFORMATION_START_X + 132.0f;
00029     const float     CAPS_LABEL_START  = INFORMATION_START_X + 300.0f;
00030     const float     CAPS_DATA_START   = INFORMATION_START_X + 400.0f;
00031
00032     const char16    MSG_NEED_CONTROLLER[]       = L"Please attach an Xbox 360 common controller device.";
00033     const uint64    XINPUT_ENUM_TIMEOUT_MS = 2000;  // 2 seconds
00034
00035     const char16    STATE_HEADER[]              = L"XInput State";
00036     const char16    LABEL_STATE_PACKET_NUMBER[] = L"Packet Number";
00037     const char16    LABEL_STATE_LEFT_TRIGGER[]  = L"Left Trigger";
00038     const char16    LABEL_STATE_RIGHT_TRIGGER[] = L"Right Trigger";
00039     const char16    LABEL_STATE_LEFT_THUMB_X[]  = L"Left Thumb X";
00040     const char16    LABEL_STATE_LEFT_THUMB_Y[]  = L"Left Thumb Y";
00041     const char16    LABEL_STATE_RIGHT_THUMB_X[] = L"Right Thumb X";
00042     const char16    LABEL_STATE_RIGHT_THUMB_Y[] = L"Right Thumb Y";
00043     const char16    LABEL_STATE_BUTTONS[]       = L"Buttons";
00044
00045     const char16    CAPS_HEADER[]               = L"XInput Capabilties";
00046     const char16    LABEL_CAPS_TYPE[]           = L"Type";
00047     const char16    LABEL_CAPS_SUBTYPE[]        = L"Subtype";
00048     const char16    LABEL_CAPS_FLAGS[]          = L"Flags";
00049     const char16    VALUE_CAPS_WIRED[]          = L"Wired";
00050     const char16    VALUE_CAPS_WIRELESS[]       = L"Wireless";
00051     const char16    VALUE_CAPS_VOICE_SUPPORT[]  = L"Voice Support";
00052 };
00053
00054 SimpleController::SimpleController() :
00055     m_isControllerConnected(false)
00056 {
00057     m_lastEnumTime = ::GetTickCount64();
00058 }
00059
00060 void SimpleController::CreateDeviceResources()
00061 {
00062     DirectXBase::CreateDeviceResources();
00063
00064     //
00065     // Create and initialize the default Sample graphics object
00066     //
00067     m_sampleOverlay = ref new SampleOverlay();
00068     m_sampleOverlay->Initialize(
00069         m_d2dDevice.Get(),
00070         m_d2dContext.Get(),
00071         m_wicFactory.Get(),
00072         m_dwriteFactory.Get(),
00073         ref new Platform::String(APPLICATION_TITLE)
00074         );
00075
00076     //
00077     // Setup the local graphics objects
00078     //
00079     DX::ThrowIfFailed(
00080         m_dwriteFactory->CreateTextFormat(
00081             FONT_NAME,
00082             nullptr,
00083             DWRITE_FONT_WEIGHT_SEMI_BOLD,
00084             DWRITE_FONT_STYLE_NORMAL,
00085             DWRITE_FONT_STRETCH_NORMAL,
00086             FONT_SIZE_HEADER,
00087             FONT_LOCAL,
00088             &m_headerTextFormat
00089             )
00090         );
00091     DX::ThrowIfFailed(
00092         m_dwriteFactory->CreateTextFormat(
00093             FONT_NAME,
00094             nullptr,
00095             DWRITE_FONT_WEIGHT_NORMAL,
00096             DWRITE_FONT_STYLE_NORMAL,
00097             DWRITE_FONT_STRETCH_NORMAL,
00098             FONT_SIZE_TEXT,
00099             FONT_LOCAL,
00100             &m_dataTextFormat
00101             )
00102         );
00103
00104     DX::ThrowIfFailed(
00105         m_headerTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)
00106         );
00107     DX::ThrowIfFailed(
00108         m_headerTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)
00109         );
00110     DX::ThrowIfFailed(
00111         m_dataTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)
00112         );
00113     DX::ThrowIfFailed(
00114         m_dataTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)
00115         );
00116
00117     DX::ThrowIfFailed(
00118         m_d2dContext->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &m_textBrush)
00119         );
00120 }
00121
00122 void SimpleController::CreateWindowSizeDependentResources()
00123 {
00124     DirectXBase::CreateWindowSizeDependentResources();
00125     m_sampleOverlay->UpdateForWindowSizeChange();
00126 }
00127
00128 void SimpleController::Render()
00129 {
00130     // Bind the render target
00131     m_d3dContext->OMSetRenderTargets(
00132         1,
00133         m_d3dRenderTargetView.GetAddressOf(),
00134         m_d3dDepthStencilView.Get());
00135
00136     // Clear the render target
00137     m_d3dContext->ClearRenderTargetView(m_d3dRenderTargetView.Get(), CLEAR_COLOR);
00138
00139     // Render the default sample header
00140     m_sampleOverlay->Render();
00141
00142     // Render the controller data
00143     RenderControllerInput();
00144 }
00145
00146 void SimpleController::FetchControllerInput()
00147 {
00148     if (!m_isControllerConnected)
00149     {
00150         //
00151         // Ennumerating for XInput devices takes 'time' on the order of milliseconds.
00152         // Any time a device is not currently known as connected (not yet called XInput, or calling
00153         // an XInput function after a failure) ennumeration happens.
00154         // An app should avoid repeatedly calling XInput functions if there are no known devices connected
00155         // as this can slow down application performance.
00156         // This sample takes the simple approach of not calling XInput functions after failure
00157         // until a specified timeout has passed.
00158         //
00159         uint64 currentTime = ::GetTickCount64();
00160         if (currentTime - m_lastEnumTime < XINPUT_ENUM_TIMEOUT_MS)
00161         {
00162             return;
00163         }
00164         m_lastEnumTime = currentTime;
00165
00166         // Check for controller connection by trying to get the capabilties
00167         uint32 capsResult = XInputGetCapabilities(0, XINPUT_FLAG_GAMEPAD, &m_xinputCaps);
00168         if (capsResult != ERROR_SUCCESS)
00169         {
00170             return;
00171         }
00172
00173         // Device is connected
00174         m_isControllerConnected = true;
00175     }
00176
00177     uint32 stateResult = XInputGetState(0, &m_xinputState);
00178     if (stateResult != ERROR_SUCCESS)
00179     {
00180         // Device is no longer connected
00181         m_isControllerConnected = false;
00182         m_lastEnumTime = ::GetTickCount64();
00183     }
00184 }
00185
00186 void SimpleController::RenderControllerInput()
00187 {
00188     D2D1_SIZE_F size = m_d2dContext->GetSize();
00189     D2D1_RECT_F pos = D2D1::RectF(INFORMATION_START_X, INFORMATION_START_Y, size.width, size.height);
00190
00191     m_d2dContext->BeginDraw();
00192
00193     if (!m_isControllerConnected)
00194     {
00195         //
00196         // Display message instructing user to connect a controller.
00197         //
00198         DrawText(MSG_NEED_CONTROLLER, pos);
00199     }
00200     else
00201     {
00202         //
00203         // Display State information
00204         //
00205
00206         // Labels
00207         DrawHeader(STATE_HEADER, pos);
00208         pos.top += LINE_HEIGHT;
00209         DrawText(LABEL_STATE_PACKET_NUMBER, pos);
00210         pos.top += LINE_HEIGHT;
00211         DrawText(LABEL_STATE_LEFT_TRIGGER, pos);
00212         pos.top += LINE_HEIGHT;
00213         DrawText(LABEL_STATE_RIGHT_TRIGGER, pos);
00214         pos.top += LINE_HEIGHT;
00215         DrawText(LABEL_STATE_LEFT_THUMB_X, pos);
00216         pos.top += LINE_HEIGHT;
00217         DrawText(LABEL_STATE_LEFT_THUMB_Y, pos);
00218         pos.top += LINE_HEIGHT;
00219         DrawText(LABEL_STATE_RIGHT_THUMB_X, pos);
00220         pos.top += LINE_HEIGHT;
00221         DrawText(LABEL_STATE_RIGHT_THUMB_Y, pos);
00222         pos.top += LINE_HEIGHT;
00223         DrawText(LABEL_STATE_BUTTONS, pos);
00224
00225         // Values
00226         pos.top = INFORMATION_START_Y + LINE_HEIGHT;
00227         pos.left = INPUT_DATA_START;
00228         DrawText(static_cast<uint32>(m_xinputState.dwPacketNumber), pos);
00229         pos.top += LINE_HEIGHT;
00230         DrawText(m_xinputState.Gamepad.bLeftTrigger, pos);
00231         pos.top += LINE_HEIGHT;
00232         DrawText(m_xinputState.Gamepad.bRightTrigger, pos);
00233         pos.top += LINE_HEIGHT;
00234         DrawText(m_xinputState.Gamepad.sThumbLX, pos);
00235         pos.top += LINE_HEIGHT;
00236         DrawText(m_xinputState.Gamepad.sThumbLY, pos);
00237         pos.top += LINE_HEIGHT;
00238         DrawText(m_xinputState.Gamepad.sThumbRX, pos);
00239         pos.top += LINE_HEIGHT;
00240         DrawText(m_xinputState.Gamepad.sThumbRY, pos);
00241         pos.top += LINE_HEIGHT;
00242         DrawButtonText(m_xinputState.Gamepad.wButtons, pos);
00243
00244         //
00245         // Display Capabilties
00246         //
00247
00248         // Labels
00249         pos.top = INFORMATION_START_Y;
00250         pos.left = CAPS_LABEL_START;
00251         DrawHeader(CAPS_HEADER, pos);
00252         pos.top += LINE_HEIGHT;
00253         DrawText(LABEL_CAPS_TYPE, pos);
00254         pos.top += LINE_HEIGHT;
00255         DrawText(LABEL_CAPS_SUBTYPE, pos);
00256         pos.top += LINE_HEIGHT;
00257         DrawText(LABEL_CAPS_FLAGS, pos);
00258
00259         // Values
00260         pos.top = INFORMATION_START_Y + LINE_HEIGHT;
00261         pos.left = CAPS_DATA_START;
00262         DrawText(m_xinputCaps.Type, pos);
00263         pos.top += LINE_HEIGHT;
00264         DrawText(m_xinputCaps.SubType, pos);
00265         pos.top += LINE_HEIGHT;
00266         if (m_xinputCaps.Flags & XINPUT_CAPS_WIRELESS)
00267         {
00268             DrawText(VALUE_CAPS_WIRELESS, pos);
00269         }
00270         else
00271         {
00272             DrawText(VALUE_CAPS_WIRED, pos);
00273         }
00274         if (m_xinputCaps.Flags & XINPUT_CAPS_VOICE_SUPPORTED)
00275         {
00276             pos.top += LINE_HEIGHT;
00277             DrawText(VALUE_CAPS_VOICE_SUPPORT, pos);
00278         }
00279     }
00280
00281     // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00282     // is lost. It will be handled during the next call to Present.
00283     HRESULT hr = m_d2dContext->EndDraw();
00284     if (hr != D2DERR_RECREATE_TARGET)
00285     {
00286         DX::ThrowIfFailed(hr);
00287     }
00288 }
00289
00290 void SimpleController::Update(float /*timeTotal*/, float /*timeDelta*/)
00291 {
00292     FetchControllerInput();
00293 }
00294
00295 void SimpleController::DrawHeader(const char16* text, const D2D1_RECT_F& loc)
00296 {
00297     m_d2dContext->DrawText(
00298         text,
00299         static_cast<UINT32>(::wcslen(text)),
00300         m_headerTextFormat.Get(),
00301         loc,
00302         m_textBrush.Get()
00303         );
00304 }
00305
00306
00307 void SimpleController::DrawText(const char16* text, const D2D1_RECT_F& loc)
00308 {
00309     m_d2dContext->DrawText(
00310         text,
00311         static_cast<UINT32>(::wcslen(text)),
00312         m_dataTextFormat.Get(),
00313         loc,
00314         m_textBrush.Get()
00315         );
00316 }
00317
00318 void SimpleController::DrawText(uint32 value, const D2D1_RECT_F& loc)
00319 {
00320     char16 text[16];
00321     ::_snwprintf_s(text, sizeof(text)/sizeof(char16), L"0x%08X", value);
00322     DrawText(text, loc);
00323 }
00324
00325 void SimpleController::DrawText(int16 value, const D2D1_RECT_F& loc)
00326 {
00327     char16 text[16];
00328     ::_snwprintf_s(text, sizeof(text)/sizeof(char16), L"%05d", value);
00329     DrawText(text, loc);
00330 }
00331
00332 void SimpleController::DrawText(uint8 value, const D2D1_RECT_F& loc)
00333 {
00334     char16 text[8];
00335     ::_snwprintf_s(text, sizeof(text)/sizeof(char16), L"0x%02X", value);
00336     DrawText(text, loc);
00337 }
00338
00339 void SimpleController::DrawButtonText(uint16 buttons, const D2D1_RECT_F& loc)
00340 {
00341     char16 text[64];
00342     size_t where = 0;
00343     if (buttons & XINPUT_GAMEPAD_A)
00344     {
00345         text[where++] = L'A';
00346     }
00347     if (buttons & XINPUT_GAMEPAD_B)
00348     {
00349         text[where++] = L'B';
00350     }
00351     if (buttons & XINPUT_GAMEPAD_X)
00352     {
00353         text[where++] = L'X';
00354     }
00355     if (buttons & XINPUT_GAMEPAD_Y)
00356     {
00357         text[where++] = L'Y';
00358     }
00359     if (where != 0)
00360     {
00361         text[where++] = L' ';
00362     }
00363
00364     size_t groupStart = where;
00365     if (buttons & XINPUT_GAMEPAD_DPAD_UP)
00366     {
00367         text[where++] = L'U';
00368     }
00369     if (buttons & XINPUT_GAMEPAD_DPAD_DOWN)
00370     {
00371         text[where++] = L'D';
00372     }
00373     if (buttons & XINPUT_GAMEPAD_DPAD_LEFT)
00374     {
00375         text[where++] = L'L';
00376     }
00377     if (buttons & XINPUT_GAMEPAD_DPAD_RIGHT)
00378     {
00379         text[where++] = L'R';
00380     }
00381     if (where != groupStart)
00382     {
00383         text[where++] = L' ';
00384     }
00385
00386     if (buttons & XINPUT_GAMEPAD_LEFT_THUMB)
00387     {
00388         text[where++] = L'L';
00389         text[where++] = L'T';
00390         text[where++] = L' ';
00391     }
00392     if (buttons & XINPUT_GAMEPAD_RIGHT_THUMB)
00393     {
00394         text[where++] = L'R';
00395         text[where++] = L'T';
00396         text[where++] = L' ';
00397     }
00398     if (buttons & XINPUT_GAMEPAD_LEFT_SHOULDER)
00399     {
00400         text[where++] = L'L';
00401         text[where++] = L'S';
00402         text[where++] = L' ';
00403     }
00404     if (buttons & XINPUT_GAMEPAD_RIGHT_SHOULDER)
00405     {
00406         text[where++] = L'R';
00407         text[where++] = L'S';
00408         text[where++] = L' ';
00409     }
00410     if (buttons & XINPUT_GAMEPAD_START)
00411     {
00412         text[where++] = L'S';
00413         text[where++] = L't';
00414         text[where++] = L'a';
00415         text[where++] = L'r';
00416         text[where++] = L't';
00417         text[where++] = L' ';
00418     }
00419     if (buttons & XINPUT_GAMEPAD_BACK)
00420     {
00421         text[where++] = L'B';
00422         text[where++] = L'a';
00423         text[where++] = L'c';
00424         text[where++] = L'k';
00425     }
00426     text[where] = L'\0';
00427
00428     DrawText(text, loc);
00429 }
Generated on Sat Nov 23 2024 16:08:28 for Win8-Examples by doxygen 1.7.1


Win8-Examples: App package information/C++/Scenario3.xaml.h Source File

  • App package information

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 // Scenario1.xaml.h
00013 // Declaration of the Scenario1 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario3.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace PackageSample
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 GetDependencies_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         };
00042     }
00043 }
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML user and custom controls/C++/Scenario3.xaml.h Source File

  • XAML user and custom controls

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 SDKSample
00023 {
00024     namespace UserAndCustomControls
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             void Go_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         void NavigateDPHelp(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         };
00042     }
00043 }
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Folder enumeration/C++/App.xaml.h Source File

  • Folder enumeration

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Audio Session (WASAPI)/C++/Scenario2.xaml.h Source File

  • Windows Audio Session (WASAPI)
  • C++

Scenario2.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.xaml.h
00013 // Declaration of the Scenario2 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario2.g.h"
00020 #include "MainPage.xaml.h"
00021 #include "WASAPIRenderer.h"
00022
00023 namespace SDKSample
00024 {
00025     namespace WASAPIAudio
00026     {
00027         public enum class ContentType
00028         {
00029             ContentTypeTone,
00030             ContentTypeFile
00031         };
00032
00033         [Windows::Foundation::Metadata::WebHostHidden]
00034         public ref class Scenario2 sealed
00035         {
00036
00037         public:
00038             Scenario2();
00039
00040         protected:
00041             // Template Support
00042             virtual void OnNavigatedTo( Windows::UI::Xaml::Navigation::NavigationEventArgs^ e ) override;
00043             virtual void OnNavigatedFrom( Windows::UI::Xaml::Navigation::NavigationEventArgs^ e ) override;
00044
00045         private:
00046             ~Scenario2();
00047
00048             // UI Events
00049             void btnPlay_Click( Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e );
00050             void btnPause_Click( Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e );
00051             void btnPlayPause_Click( Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e );
00052             void btnStop_Click( Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e );
00053             void btnFilePicker_Click( Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e );
00054             void radioTone_Checked( Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e );
00055             void radioFile_Checked( Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e );
00056             void sliderFrequency_ValueChanged( Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e );
00057             void sliderVolume_ValueChanged( Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e );
00058
00059             // UI Helpers
00060             void ShowStatusMessage( Platform::String^ str, NotifyType messageType );
00061             void UpdateContentProps( Platform::String^ str );
00062             void UpdateContentUI( Platform::Boolean disableAll );
00063             void UpdateMediaControlUI( DeviceState deviceState );
00064
00065             // Handlers
00066             void OnDeviceStateChange( Object^ sender, DeviceStateChangedEventArgs^ e );
00067             void OnPickFileAsync();
00068             void OnSetVolume( UINT32 volume );
00069
00070             void InitializeDevice();
00071             void StartDevice( Object^ sender, Object^ e );
00072             void StopDevice( Object^ sender, Object^ e );
00073             void PauseDevice( Object^ sender, Object^ e );
00074             void PlayPauseToggle( Object^ sender, Object^ e );
00075
00076         private:
00077             MainPage^                                       rootPage;
00078             Windows::UI::Core::CoreDispatcher^              m_CoreDispatcher;
00079             Windows::Foundation::EventRegistrationToken     m_deviceStateChangeToken;
00080             Windows::Foundation::EventRegistrationToken     m_MediaControlPlayToken;
00081             Windows::Foundation::EventRegistrationToken     m_MediaControlPauseToken;
00082             Windows::Foundation::EventRegistrationToken     m_MediaControlStopToken;
00083             Windows::Foundation::EventRegistrationToken     m_MediaControlPlayPauseToken;
00084
00085             Platform::Boolean          m_IsMFLoaded;
00086             IRandomAccessStream^       m_ContentStream;
00087             ContentType                m_ContentType;
00088             DeviceStateChangedEvent^   m_StateChangedEvent;
00089             ComPtr<WASAPIRenderer>     m_spRenderer;
00090         };
00091     }
00092 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XInput audio controller playback/C++/SampleOverlay.h Source File

  • XInput audio controller playback

SampleOverlay.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 "DirectXSample.h"
00011
00012 // This class is responsible for initializing and rendering the title overlay visible
00013 // at the top of the DirectX SDK samples.
00014 ref class SampleOverlay
00015 {
00016 internal:
00017     SampleOverlay();
00018
00019     void Initialize(
00020         _In_ ID2D1Device*         d2dDevice,
00021         _In_ ID2D1DeviceContext*  d2dContext,
00022         _In_ IWICImagingFactory*  wicFactory,
00023         _In_ IDWriteFactory*      dwriteFactory,
00024         _In_ Platform::String^    caption
00025         );
00026
00027     void ResetDirectXResources();
00028
00029     void UpdateForWindowSizeChange();
00030
00031     void Render();
00032
00033     float GetTitleHeightInDips();
00034
00035 private:
00036
00037     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00038     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00039     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00040     Microsoft::WRL::ComPtr<IDWriteFactory>          m_dwriteFactory;
00041     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_whiteBrush;
00042     Microsoft::WRL::ComPtr<ID2D1DrawingStateBlock>  m_stateBlock;
00043
00044     Microsoft::WRL::ComPtr<IWICImagingFactory>      m_wicFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Bitmap>             m_logoBitmap;
00046     Microsoft::WRL::ComPtr<IDWriteTextLayout>       m_textLayout;
00047
00048     UINT                                            m_idIncrement;
00049     bool                                            m_drawOverlay;
00050     Platform::String^                               m_sampleName;
00051     float                                           m_padding;
00052     float                                           m_textVerticalOffset;
00053     D2D1_SIZE_F                                     m_logoSize;
00054     float                                           m_overlayWidth;
00055 };
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/TargetTexture.h Source File

  • DirectX 3D shooting game

TargetTexture.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 // TargetTexture:
00011 // This is a helper class to procedurally generate textures for game
00012 // targets.  There are two versions of the textures, one when it is
00013 // hit and the other is when it is not.
00014 // The class creates the necessary resources to draw the texture into
00015 // an off screen resource at initialization time.
00016
00017 ref class TargetTexture
00018 {
00019 internal:
00020     TargetTexture(
00021         _In_ ID3D11Device1*      d3dDevice,
00022         _In_ ID2D1Factory1*      d2dFactory,
00023         _In_ IDWriteFactory1*    dwriteFactory,
00024         _In_ ID2D1DeviceContext* d2dContext
00025         );
00026
00027     void CreateTextureResourceView(
00028         _In_ Platform::String^ name,
00029         _Out_ ID3D11ShaderResourceView** textureResourceView
00030         );
00031     void CreateHitTextureResourceView(
00032         _In_ Platform::String^ name,
00033         _Out_ ID3D11ShaderResourceView** textureResourceView
00034         );
00035
00036 protected private:
00037     Microsoft::WRL::ComPtr<ID3D11Device1>           m_d3dDevice;
00038     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00039     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00040     Microsoft::WRL::ComPtr<IDWriteFactory1>         m_dwriteFactory;
00041
00042     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_redBrush;
00043     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_blueBrush;
00044     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_greenBrush;
00045     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_whiteBrush;
00046     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_blackBrush;
00047     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_yellowBrush;
00048     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_clearBrush;
00049
00050     Microsoft::WRL::ComPtr<ID2D1EllipseGeometry>    m_circleGeometry1;
00051     Microsoft::WRL::ComPtr<ID2D1EllipseGeometry>    m_circleGeometry2;
00052     Microsoft::WRL::ComPtr<ID2D1EllipseGeometry>    m_circleGeometry3;
00053     Microsoft::WRL::ComPtr<ID2D1EllipseGeometry>    m_circleGeometry4;
00054     Microsoft::WRL::ComPtr<ID2D1EllipseGeometry>    m_circleGeometry5;
00055
00056     Microsoft::WRL::ComPtr<IDWriteTextFormat>       m_textFormat;
00057 };
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows account authorization/C++/App.xaml.cpp Source File

  • Windows account authorization

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:28 for Win8-Examples by doxygen 1.7.1


Win8-Examples: App settings/C++/MainPage.xaml.cpp Source File

  • App settings

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/DelegateCommand.h Source File

  • Hilo C++
  • Hilo

DelegateCommand.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
00009 namespace Hilo
00010 {
00011     public delegate void ExecuteDelegate(Platform::Object^ parameter);
00012     public delegate bool CanExecuteDelegate(Platform::Object^ parameter);
00013
00014     // The DelegateCommand class implements Hilo commands. It is used by XAML button controls.
00015     [Windows::Foundation::Metadata::WebHostHidden]
00016     public ref class DelegateCommand sealed : public Windows::UI::Xaml::Input::ICommand
00017     {
00018     public:
00019         DelegateCommand(ExecuteDelegate^ execute, CanExecuteDelegate^ canExecute);
00020
00021         virtual event Windows::Foundation::EventHandler<Platform::Object^>^ CanExecuteChanged;
00022
00023         virtual void Execute(Platform::Object^ parameter);
00024
00025         virtual bool CanExecute(Platform::Object^ parameter);
00026
00027     private:
00028         ExecuteDelegate^ m_executeDelegate;
00029         CanExecuteDelegate^ m_canExecuteDelegate;
00030         bool m_canExecute;
00031     };
00032 }
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DXGI offer and reclaim resources/C++/OfferReclaimAPI.cpp Source File

  • DXGI offer and reclaim resources

OfferReclaimAPI.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 "OfferReclaimAPI.h"
00010 #include "BasicShapes.h"
00011 #include "BasicLoader.h"
00012
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::Foundation;
00015 using namespace Windows::UI::Core;
00016 using namespace Windows::ApplicationModel;
00017 using namespace Windows::ApplicationModel::Core;
00018 using namespace Windows::ApplicationModel::Activation;
00019
00020
00021 OfferReclaimAPI::OfferReclaimAPI()
00022 {
00023 }
00024
00025 void OfferReclaimAPI::CreateDeviceIndependentResources()
00026 {
00027     DirectXBase::CreateDeviceIndependentResources();
00028 }
00029
00030 void OfferReclaimAPI::CreateDeviceResources()
00031 {
00032     DirectXBase::CreateDeviceResources();
00033
00034     m_sampleOverlay = ref new SampleOverlay();
00035
00036     m_sampleOverlay->Initialize(
00037         m_d2dDevice.Get(),
00038         m_d2dContext.Get(),
00039         m_wicFactory.Get(),
00040         m_dwriteFactory.Get(),
00041         L"DXGI resource offer and reclaim sample"
00042         );
00043
00044     BasicLoader^ loader = ref new BasicLoader(m_d3dDevice.Get());
00045
00046     loader->LoadShader(
00047         L"SimpleVertexShader.cso",
00048         nullptr,
00049         0,
00050         &m_vertexShader,
00051         &m_inputLayout
00052         );
00053
00054     // Create the vertex and index buffers for drawing the cube.
00055
00056     BasicShapes^ shapes = ref new BasicShapes(m_d3dDevice.Get());
00057
00058     shapes->CreateCube(
00059         &m_vertexBuffer,
00060         &m_indexBuffer,
00061         nullptr,
00062         &m_indexCount
00063         );
00064
00065     // Create the constant buffer for updating model and camera data.
00066     CD3D11_BUFFER_DESC constantBufferDescription(sizeof(ConstantBuffer), D3D11_BIND_CONSTANT_BUFFER);
00067     DX::ThrowIfFailed(
00068         m_d3dDevice->CreateBuffer(
00069             &constantBufferDescription,
00070             nullptr,             // leave the buffer uninitialized
00071             &m_constantBuffer
00072             )
00073         );
00074
00075     loader->LoadShader(
00076         L"SimplePixelShader.cso",
00077         &m_pixelShader
00078         );
00079
00080     loader->LoadTexture(
00081         L"texture.dds",
00082         &m_texture,
00083         &m_textureSRV
00084         );
00085
00086     // Create the sampler.
00087     D3D11_SAMPLER_DESC samplerDescription;
00088     ZeroMemory(&samplerDescription, sizeof(D3D11_SAMPLER_DESC));
00089     samplerDescription.Filter = D3D11_FILTER_ANISOTROPIC;
00090     samplerDescription.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
00091     samplerDescription.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
00092     samplerDescription.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
00093     samplerDescription.MipLODBias = 0.0f;
00094     samplerDescription.MaxAnisotropy = m_featureLevel > D3D_FEATURE_LEVEL_9_1 ? 4 : 2;
00095     samplerDescription.ComparisonFunc = D3D11_COMPARISON_NEVER;
00096     samplerDescription.BorderColor[0] = 0.0f;
00097     samplerDescription.BorderColor[1] = 0.0f;
00098     samplerDescription.BorderColor[2] = 0.0f;
00099     samplerDescription.BorderColor[3] = 0.0f;
00100     // allow use of all mip levels
00101     samplerDescription.MinLOD = 0;
00102     samplerDescription.MaxLOD = D3D11_FLOAT32_MAX;
00103
00104     DX::ThrowIfFailed(
00105         m_d3dDevice->CreateSamplerState(
00106             &samplerDescription,
00107             &m_sampler)
00108         );
00109
00110     m_Camera = ref new BasicCamera();
00111
00112     // To test the Reclaim code, force the discard of the allocation by setting the flag - D3D11_DEBUG_FEATURE_ALWAYS_DISCARD_OFFERED_RESOURCE
00113     // Also, enable Debug Layers by passing in the D3D11_CREATE_DEVICE_DEBUG flag into "creationFlags" in the CreateDevice call (see DirectXBase.cpp)
00114 #ifdef _DEBUG
00115     ComPtr<ID3D11Debug> pDebug;
00116     DX::ThrowIfFailed(m_d3dDevice.As(&pDebug));
00117     pDebug->SetFeatureMask(D3D11_DEBUG_FEATURE_ALWAYS_DISCARD_OFFERED_RESOURCE);
00118 #endif
00119
00120 }
00121
00122 void OfferReclaimAPI::CreateWindowSizeDependentResources()
00123 {
00124     DirectXBase::CreateWindowSizeDependentResources();
00125
00126     // update the 3D projection matrix
00127     m_Camera->SetProjectionParameters(
00128         70.0f,                                                  // use a 70-degree vertical field of view
00129         m_renderTargetSize.Width /  m_renderTargetSize.Height,  // specify the aspect ratio of the window
00130         0.01f,                                                  // specify the nearest Z-distance at which to draw vertices
00131         100.0f                                                  // specify the farthest Z-distance at which to draw vertices
00132         );
00133
00134     // save the new projection matrix to the constant buffer data struct
00135     m_Camera->GetProjectionMatrix(&m_constantBufferData.projection);
00136
00137     m_sampleOverlay->UpdateForWindowSizeChange();
00138 }
00139
00140 void OfferReclaimAPI::Render()
00141 {
00142     UINT stride = sizeof(BasicVertex);
00143     UINT offset = 0;
00144
00145     // bind the render targets
00146     m_d3dContext->OMSetRenderTargets(
00147         1,
00148         m_d3dRenderTargetView.GetAddressOf(),
00149         m_d3dDepthStencilView.Get()
00150         );
00151
00152     // clear both the render target and depth stencil to default values
00153     const float ClearColor[4] = {0.071f, 0.040f, 0.561f, 1.0f};
00154
00155     m_d3dContext->ClearRenderTargetView(
00156         m_d3dRenderTargetView.Get(),
00157         ClearColor
00158         );
00159
00160     m_d3dContext->ClearDepthStencilView(
00161         m_d3dDepthStencilView.Get(),
00162         D3D11_CLEAR_DEPTH,
00163         1.0f,
00164         0
00165         );
00166
00167     m_d3dContext->IASetInputLayout(m_inputLayout.Get());
00168
00169     // set the vertex and index buffers, and specify the way they define geometry
00170     m_d3dContext->IASetVertexBuffers(
00171         0,                              // starting at the first vertex buffer slot
00172         1,                              // set one vertex buffer binding
00173         m_vertexBuffer.GetAddressOf(),
00174         &stride,                        // specify the size in bytes of a single vertex
00175         &offset                         // specify the base vertex in the buffer
00176         );
00177
00178     // set the index buffer
00179     m_d3dContext->IASetIndexBuffer(
00180         m_indexBuffer.Get(),
00181         DXGI_FORMAT_R16_UINT,   // unsigned short index format
00182         0                       // specify the base index in the buffer
00183         );
00184
00185     // specify the way the vertex and index buffers define geometry
00186     m_d3dContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
00187
00188     // set the vertex shader stage state
00189     m_d3dContext->VSSetShader(
00190         m_vertexShader.Get(),
00191         nullptr,                // don't use shader linkage
00192         0                       // don't use shader linkage
00193         );
00194
00195     m_d3dContext->VSSetConstantBuffers(
00196         0,                              // starting at the first constant buffer slot
00197         1,                              // set one constant buffer binding
00198         m_constantBuffer.GetAddressOf()
00199         );
00200
00201     // set the pixel shader stage state
00202     m_d3dContext->PSSetShader(
00203         m_pixelShader.Get(),
00204         nullptr,                // don't use shader linkage
00205         0                       // don't use shader linkage
00206         );
00207
00208     m_d3dContext->PSSetShaderResources(
00209         0,                          // starting at the first shader resource slot
00210         1,                          // set one shader resource binding
00211         m_textureSRV.GetAddressOf()
00212         );
00213
00214     m_d3dContext->PSSetSamplers(
00215         0,                          // starting at the first sampler slot
00216         1,                          // set one sampler binding
00217         m_sampler.GetAddressOf()
00218         );
00219
00220     // draw the cube
00221     m_d3dContext->DrawIndexed(
00222         m_indexCount,   // draw all created vertices
00223         0,              // starting with the first vertex
00224         0               // and the first index
00225         );
00226
00227     m_sampleOverlay->Render();
00228 }
00229
00230 void OfferReclaimAPI::Update(float TimeTotal, float TimeDelta)
00231 {
00232     // update the model matrix based on the time
00233     m_constantBufferData.model = rotationY(-TimeTotal * 60.0f);
00234
00235     // update the view matrix based on the camera position
00236     // note that for this sample, the camera position is fixed
00237     m_Camera->SetViewParameters(
00238         float3(0, 1.0f, 2.0f),
00239         float3(0, 0, 0),
00240         float3(0, 1, 0)
00241         );
00242
00243     m_Camera->GetViewMatrix(&m_constantBufferData.view);
00244
00245     // update the constant buffer with the new data
00246     m_d3dContext->UpdateSubresource(
00247         m_constantBuffer.Get(),
00248         0,
00249         nullptr,
00250         &m_constantBufferData,
00251         0,
00252         0
00253         );
00254 }
00255
00256 // Suspend handler
00257 void OfferReclaimAPI::OnSuspending()
00258 {
00259     ComPtr<IDXGIDevice2> pDXGIDevice;
00260     ComPtr<IDXGIResource> pDXGIResource;
00261
00262     DX::ThrowIfFailed(m_d3dDevice.As(&pDXGIDevice));
00263     DX::ThrowIfFailed(m_texture.As(&pDXGIResource));
00264
00265     // Call OfferResources on the resource
00266     DX::ThrowIfFailed(pDXGIDevice->OfferResources(1, pDXGIResource.GetAddressOf(), DXGI_OFFER_RESOURCE_PRIORITY_NORMAL));
00267 }
00268
00269 // Resume Handler
00270 void OfferReclaimAPI::OnResuming()
00271 {
00272     static BOOL swapTexture = 1;
00273     ComPtr<IDXGIDevice2> pDXGIDevice;
00274     DX::ThrowIfFailed(m_d3dDevice.As(&pDXGIDevice));
00275
00276     ComPtr<IDXGIResource> pDXGIResource;
00277     DX::ThrowIfFailed(m_texture.As(&pDXGIResource));
00278
00279     // Call ReclaimResources API on the resource
00280     BOOL discarded;
00281     DX::ThrowIfFailed(pDXGIDevice->ReclaimResources(1, pDXGIResource.GetAddressOf(), &discarded));
00282
00283     // Usage of ReclaimResources: check for BOOL discarded.
00284     // If discarded is 0, then it means that the texture resource is still around and we were able to reclaim it.
00285     // If discarded is 1, then we need to recreate the texture resource.
00286
00287     if (discarded)
00288     {
00289         // Regenerate the texture as it has been discarded.
00290         BasicLoader^ loader = ref new BasicLoader (m_d3dDevice.Get());
00291         // Swap the texture on every discard in resume.
00292         if (swapTexture)
00293         {
00294             loader->LoadTexture("texture2.dds", &m_texture, &m_textureSRV);
00295         }
00296         else
00297         {
00298             loader->LoadTexture("texture.dds", &m_texture, &m_textureSRV);
00299         }
00300         swapTexture = !swapTexture;
00301     }
00302 }
00303
Generated on Sat Nov 23 2024 16:08:15 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Real-time communication/C#,C++/LowLatency.xaml.cs Source File

  • Real-time communication
  • C#,C++

LowLatency.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.Threading;
00017 using System.Threading.Tasks;
00018 using Windows.Media.Capture;
00019 using Windows.Media.MediaProperties;
00020 using SimpleCommunication.Common;
00021 using Microsoft.Samples.SimpleCommunication;
00022
00023 namespace SimpleCommunication
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 LowLatency : SDKTemplate.Common.LayoutAwarePage
00029     {
00030         private enum State
00031         {
00032             Initializing,
00033             Waiting,
00034             Previewing,
00035             Streaming,
00036             End
00037         }
00038
00039         private enum LatencyMode
00040         {
00041             NormalLatency,
00042             LowLatency
00043         }
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         MainPage rootPage = MainPage.Current;
00048
00049         CaptureDevice device = null;
00050         State? currentState = null;
00051         State? previousState = null;
00052         VideoEncodingProperties previewEncodingProperties = null;
00053         LatencyMode? mode = null;
00054         LatencyMode defaultMode = LatencyMode.NormalLatency;
00055
00056         public LowLatency()
00057         {
00058             this.InitializeComponent();
00059
00060             rootPage.EnsureMediaExtensionManager();
00061
00062             mode = LatencyMode.NormalLatency;
00063             LatencyModeToggle.IsOn = (mode == LatencyMode.LowLatency);
00064             rootPage.NotifyUser("Initializing...Please wait.", NotifyType.StatusMessage);
00065         }
00066
00067         /// <summary>
00068         /// The media element visible in the local host client area
00069         /// </summary>
00070         private MediaElement LocalhostVideo
00071         {
00072             get
00073             {
00074                 return (mode == LatencyMode.NormalLatency) ? DefaultMediaElement : LowLatencyMediaElement;
00075             }
00076         }
00077
00078         /// <summary>
00079         /// Initializes the scenario
00080         /// </summary>
00081         /// <returns></returns>
00082         private async Task InitializeAsync(CancellationToken cancel = default(CancellationToken))
00083         {
00084             var streamFilteringCriteria = new
00085             {
00086                 //AspectRatio = 1.333333333333333,
00087                 HorizontalResolution = (uint)480,
00088                 SubType = "YUY2"
00089             };
00090             currentState = State.Initializing;
00091             device = new CaptureDevice();
00092
00093             CameraPreview.Visibility = Visibility.Collapsed;
00094             PreviewPoster.Visibility = Visibility.Visible;
00095             Preview.Content = "Start Preview";
00096             LoopbackClient.IsEnabled = false;
00097
00098             LatencyModeToggle.IsOn = (defaultMode == LatencyMode.LowLatency);
00099             LatencyModeToggle.IsEnabled = false;
00100
00101             await device.InitializeAsync();
00102             var setting = await device.SelectPreferredCameraStreamSettingAsync(MediaStreamType.VideoPreview, ((x) =>
00103             {
00104                 var previewStreamEncodingProperty = x as Windows.Media.MediaProperties.VideoEncodingProperties;
00105
00106                 return (previewStreamEncodingProperty.Width >= streamFilteringCriteria.HorizontalResolution &&
00107                     previewStreamEncodingProperty.Subtype == streamFilteringCriteria.SubType);
00108             }));
00109
00110             previewEncodingProperties = setting as VideoEncodingProperties;
00111
00112             PreviewSetupCompleted();
00113         }
00114
00115         private void PreviewSetupCompleted()
00116         {
00117             device.CaptureFailed += device_CaptureFailed;
00118             device.IncomingConnectionArrived += device_IncomingConnectionArrived;
00119             previousState = currentState;
00120             Preview.IsEnabled = true;
00121             rootPage.NotifyUser("Done. Tap or click 'Start Preview' button to start webcam preview", NotifyType.StatusMessage);
00122
00123             currentState = State.Waiting;
00124         }
00125
00126
00127         void device_IncomingConnectionArrived(object sender, IncomingConnectionEventArgs e)
00128         {
00129             e.Accept();
00130         }
00131
00132         void device_CaptureFailed(object sender, MediaCaptureFailedEventArgs e)
00133         {
00134             rootPage.NotifyUser(e.Message, NotifyType.ErrorMessage);
00135         }
00136
00137         async void Window_VisibilityChanged(object sender, Windows.UI.Core.VisibilityChangedEventArgs e)
00138         {
00139             if (!e.Visible)
00140             {
00141                 try
00142                 {
00143                     await CleanupAsync();
00144                 }
00145                 catch (Exception)
00146                 {
00147                 }
00148             }
00149             else
00150             {
00151                 try
00152                 {
00153                     await InitializeAsync();
00154                 }
00155                 catch (Exception err)
00156                 {
00157                     rootPage.NotifyUser("Camera initialization error: " + err.Message + "\n Try restarting the sample.", NotifyType.ErrorMessage);
00158                 }
00159             }
00160         }
00161
00162         /// <summary>
00163         /// Invoked when this page is about to be displayed in a Frame.
00164         /// </summary>
00165         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00166         /// property is typically used to configure the page.</param>
00167         protected async override void OnNavigatedTo(NavigationEventArgs e)
00168         {
00169             var cameraEnumTask = CaptureDevice.CheckForRecordingDeviceAsync();
00170
00171             var cameraFound = await cameraEnumTask;
00172
00173             if (cameraFound)
00174             {
00175                 try
00176                 {
00177                     await InitializeAsync();
00178
00179                     Window.Current.VisibilityChanged += Window_VisibilityChanged;
00180                 }
00181                 catch (Exception err)
00182                 {
00183                     rootPage.NotifyUser("Camera initialization error: " + err.Message + "\n Try restarting the sample.", NotifyType.ErrorMessage);
00184                 }
00185             }
00186             else
00187             {
00188                 rootPage.NotifyUser("A machine with a camera and a microphone is required to run this sample.", NotifyType.ErrorMessage);
00189             }
00190         }
00191
00192         protected async override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00193         {
00194             Window.Current.VisibilityChanged -= Window_VisibilityChanged;
00195             try
00196             {
00197                 await CleanupAsync();
00198             }
00199             catch (Exception)
00200             {
00201             }
00202             base.OnNavigatingFrom(e);
00203         }
00204
00205         /// <summary>
00206         /// This is the click handler for the 'Preview' button.  It starts or stops
00207         /// camera preview and streaming
00208         /// </summary>
00209         /// <param name="sender"></param>
00210         /// <param name="e"></param>
00211         private async void Preview_Click(object sender, RoutedEventArgs e)
00212         {
00213             Button b = sender as Button;
00214             if (b != null && device != null)
00215             {
00216                 previousState = currentState;
00217                 switch (currentState)
00218                 {
00219                     case State.Waiting:
00220                         await Waiting_PreviewButtonClicked();
00221                         break;
00222                     case State.Previewing:
00223                         await Previewing_PreviewButtonClicked();
00224                         break;
00225                     case State.Streaming:
00226                         await Streaming_PreviewButtonClicked();
00227                         break;
00228                     default:
00229                         break;
00230                 }
00231             }
00232         }
00233
00234         private async Task Previewing_PreviewButtonClicked()
00235         {
00236             Task stopPreviewTask = device.CaptureSource.StopPreviewAsync().AsTask();
00237
00238             CameraPreview.Visibility = Visibility.Collapsed;
00239             PreviewPoster.Visibility = Visibility.Visible;
00240             Preview.Content = "Start Preview";
00241             LoopbackClient.IsEnabled = false;
00242
00243             await stopPreviewTask;
00244             currentState = State.Waiting;
00245         }
00246
00247         private async Task Waiting_PreviewButtonClicked()
00248         {
00249             rootPage.NotifyUser("", NotifyType.StatusMessage);
00250             CameraPreview.Source = device.CaptureSource;
00251             await device.CaptureSource.StartPreviewAsync();
00252
00253             PreviewPoster.Visibility = Visibility.Collapsed;
00254             CameraPreview.Visibility = Visibility.Visible;
00255             Preview.Content = "Stop Preview";
00256             LoopbackClient.IsEnabled = true;
00257
00258             currentState = State.Previewing;
00259         }
00260
00261         private async Task Streaming_PreviewButtonClicked()
00262         {
00263             LocalhostVideo.Visibility = Visibility.Collapsed;
00264             LocalHostPoster.Visibility = Visibility.Visible;
00265
00266             LocalhostVideo.Stop();
00267             await device.StopRecordingAsync();
00268             LocalhostVideo.Source = null;
00269             await Previewing_PreviewButtonClicked();
00270
00271             mode = defaultMode;
00272             LatencyModeToggle.IsOn = (defaultMode == LatencyMode.LowLatency);
00273             LatencyModeToggle.IsEnabled = false;
00274         }
00275
00276         /// <summary>
00277         /// This is the click handler for the 'LoopbackClient' button.  It displays captured video
00278         /// recieved over the localhost network interface using a custom network media sink and media
00279         /// sources via a custom scheme
00280         /// </summary>
00281         /// <param name="sender">The LoopbackClient button</param>
00282         /// <param name="e">The button click routed event arguments</param>
00283         private async void LoopbackClient_Click(object sender, RoutedEventArgs e)
00284         {
00285             Button b = sender as Button;
00286             if (b != null)
00287             {
00288                 previousState = currentState;
00289                 await StartRecordingToCustomSink();
00290
00291                 if (currentState == State.Previewing)
00292                 {
00293                     LocalhostVideo.Source = new Uri("stsp://localhost");
00294                     LatencyModeToggle.IsEnabled = true;
00295                     LoopbackClient.IsEnabled = false;
00296                     LocalHostPoster.Visibility = Visibility.Collapsed;
00297                     LocalhostVideo.Visibility = Visibility.Visible;
00298
00299                     currentState = State.Streaming;
00300                 }
00301             }
00302         }
00303
00304         private async Task StartRecordingToCustomSink()
00305         {
00306             // Use the MP4 preset to an obtain H.264 video encoding profile
00307             var mep = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Vga);
00308             mep.Audio = null;
00309             mep.Container = null;
00310             if (previewEncodingProperties != null)
00311             {
00312                 mep.Video.Width = previewEncodingProperties.Width;
00313                 mep.Video.Height = previewEncodingProperties.Height;
00314             }
00315
00316             await device.StartRecordingAsync(mep);
00317         }
00318
00319         private async void LatencyModeToggle_Toggled(object sender, RoutedEventArgs e)
00320         {
00321             if (currentState == State.Streaming)
00322             {
00323                 var foregroundVideo = LocalhostVideo;
00324                 foregroundVideo.Stop();
00325
00326                 await device.StopRecordingAsync();
00327                 mode = (mode == LatencyMode.NormalLatency) ? LatencyMode.LowLatency : LatencyMode.NormalLatency;
00328                 await StartRecordingToCustomSink();
00329
00330                 foregroundVideo.Source = null;
00331                 LocalhostVideo.Source = new Uri("stsp://localhost");
00332                 foregroundVideo.Visibility = Visibility.Collapsed;
00333                 LocalhostVideo.Visibility = Visibility.Visible;
00334             }
00335         }
00336
00337         private async Task CleanupAsync()
00338         {
00339             if (currentState == State.Previewing || currentState == State.Streaming)
00340             {
00341                 await device.CaptureSource.StopPreviewAsync();
00342
00343                 if (currentState == State.Streaming)
00344                 {
00345                     LocalhostVideo.Stop();
00346
00347                     LocalhostVideo.Visibility = Visibility.Collapsed;
00348                     LocalHostPoster.Visibility = Visibility.Visible;
00349                 }
00350             }
00351
00352
00353             await device.CleanUpAsync();
00354             LocalhostVideo.Source = null;
00355         }
00356     }
00357 }
Generated on Sat Nov 23 2024 16:08:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DatagramSocketSample::sealed Member List

This is the complete list of members for DatagramSocketSample::sealed, including all inherited members.
__pad0__ | DatagramSocketSample::sealed |
autoSizeInputSectionWhenSnapped | DatagramSocketSample::sealed | [private]
CloseSockets_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | DatagramSocketSample::sealed | [private]
connected | DatagramSocketSample::sealed | [private]
ConnectSocket_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | DatagramSocketSample::sealed | [private]
EchoMessage(DatagramSocketMessageReceivedEventArgs^eventArguments) | DatagramSocketSample::sealed | [private]
Footer_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | DatagramSocketSample::sealed | [private]
GetWriter() | DatagramSocketSample::sealed |
HiddenFrame | DatagramSocketSample::sealed | [private]
hostName | DatagramSocketSample::sealed | [private]
InvalidateSize() | DatagramSocketSample::sealed | [private]
InvalidateViewState() | DatagramSocketSample::sealed | [private]
IsConnected() | DatagramSocketSample::sealed |
IsMatching(HostName^hostName, String^port) | DatagramSocketSample::sealed |
listener | DatagramSocketSample::sealed | [private]
ListenerContext(MainPage^rootPage, DatagramSocket^listener) | DatagramSocketSample::sealed |
LoadScenario(Platform::String^scenarioName) | DatagramSocketSample::sealed |
lock | DatagramSocketSample::sealed | [private]
MainPage() | DatagramSocketSample::sealed |
MainPage_SizeChanged(Object^sender, Windows::UI::Xaml::SizeChangedEventArgs^e) | DatagramSocketSample::sealed | [protected]
MainPageResized | DatagramSocketSample::sealed |
NotifyUser(Platform::String^strMessage, NotifyType type) | DatagramSocketSample::sealed |
NotifyUserFromAsyncThread(String^message, NotifyType type) | DatagramSocketSample::sealed | [private]
NotifyUserFromAsyncThread(String^message, NotifyType type) | DatagramSocketSample::sealed | [private]
OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^pArgs) override | DatagramSocketSample::sealed | [virtual]
OnMessage(DatagramSocket^socket, DatagramSocketMessageReceivedEventArgs^eventArguments) | DatagramSocketSample::sealed |
OnMessage(DatagramSocket^socket, DatagramSocketMessageReceivedEventArgs^eventArguments) | DatagramSocketSample::sealed |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | DatagramSocketSample::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | DatagramSocketSample::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | DatagramSocketSample::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | DatagramSocketSample::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | DatagramSocketSample::sealed | [protected, virtual]
OnSuspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^pArgs) | DatagramSocketSample::sealed | [virtual]
outputStream | DatagramSocketSample::sealed | [private]
PopulateScenarios() | DatagramSocketSample::sealed | [private]
port | DatagramSocketSample::sealed | [private]
rootFrame | DatagramSocketSample::sealed | [private]
rootPage | DatagramSocketSample::sealed | [private]
Scenario1() | DatagramSocketSample::sealed |
Scenario2() | DatagramSocketSample::sealed |
Scenario3() | DatagramSocketSample::sealed |
Scenario4() | DatagramSocketSample::sealed |
ScenarioList | DatagramSocketSample::sealed | [private]
ScenarioLoaded | DatagramSocketSample::sealed |
Scenarios_SelectionChanged(Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | DatagramSocketSample::sealed | [protected]
SendHello_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | DatagramSocketSample::sealed | [private]
SetConnected() | DatagramSocketSample::sealed |
SetFeatureName(Platform::String^strFeature) | DatagramSocketSample::sealed | [private]
socket | DatagramSocketSample::sealed | [private]
SocketContext(MainPage^rootPage, DatagramSocket^socket) | DatagramSocketSample::sealed |
StartListener_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | DatagramSocketSample::sealed | [private]
writer | DatagramSocketSample::sealed | [private]
~ListenerContext() | DatagramSocketSample::sealed | [private]
~MainPage() | DatagramSocketSample::sealed | [private]
~SocketContext() | DatagramSocketSample::sealed | [private]
Generated on Sat Nov 23 2024 16:09:37 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/ImageBrowserViewModel.h Source File

  • Hilo C++
  • Hilo

ImageBrowserViewModel.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
00009 #include "ViewModelBase.h"
00010
00011 namespace Hilo
00012 {
00013     interface class IPhoto;
00014     interface class IPhotoGroup;
00015     interface class IYearGroup;
00016     class concurrency::cancellation_token_source;
00017     class ExceptionPolicy;
00018     class PhotoCache;
00019     class Repository;
00020
00021     // See http://go.microsoft.com/fwlink/?LinkId=267276 for info on how view model classes interact
00022     // with view classes (pages) and model classes (the state and operations of business objects).
00023
00024     // The ImageBrowserViewModel class contains the presentation logic for the image browser page (ImageBrowserView.xaml).
00025     [Windows::UI::Xaml::Data::Bindable]
00026     [Windows::Foundation::Metadata::WebHostHidden]
00027     public ref class ImageBrowserViewModel sealed : public ViewModelBase
00028     {
00029     internal:
00030         ImageBrowserViewModel(std::shared_ptr<Repository> repository, std::shared_ptr<ExceptionPolicy> exceptionPolicy);
00031
00032         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00033         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00034
00035         IPhoto^ GetPhotoForYearAndMonth(unsigned int year, unsigned int month);
00036
00037     public:
00038         virtual ~ImageBrowserViewModel();
00039
00040         property Windows::Foundation::Collections::IObservableVector<IPhotoGroup^>^ MonthGroups
00041         {
00042             Windows::Foundation::Collections::IObservableVector<IPhotoGroup^>^ get();
00043         }
00044
00045         property Windows::Foundation::Collections::IObservableVector<IYearGroup^>^ YearGroups
00046         {
00047             Windows::Foundation::Collections::IObservableVector<IYearGroup^>^ get();
00048         }
00049
00050         property bool InProgress
00051         {
00052             bool get();
00053         }
00054
00055         property Windows::UI::Xaml::Input::ICommand^ GroupCommand
00056         {
00057             Windows::UI::Xaml::Input::ICommand^ get();
00058         }
00059
00060         property Windows::UI::Xaml::Input::ICommand^ CropImageCommand
00061         {
00062             Windows::UI::Xaml::Input::ICommand^ get();
00063         }
00064
00065         property Windows::UI::Xaml::Input::ICommand^ RotateImageCommand
00066         {
00067             Windows::UI::Xaml::Input::ICommand^ get();
00068         }
00069
00070         property Windows::UI::Xaml::Input::ICommand^ CartoonizeImageCommand
00071         {
00072             Windows::UI::Xaml::Input::ICommand^ get();
00073         }
00074
00075         // These are really IPhoto^ but XAML cannot convert any underlying
00076         // real object (e.g. Photo) back to IPhoto which results in strange
00077         // side effects (such as the AppBar not working).
00078         property Platform::Object^ SelectedItem
00079         {
00080             Platform::Object^ get();
00081             void set(Platform::Object^ value);
00082         }
00083
00084     private:
00085         enum class Mode {
00086             Default,        /* (0, 0, 0): no pending data changes, not updating, not visible */
00087             Active,         /* (0, 0, 1): no pending data changes, not updating, visible */
00088             Pending,        /* (1, 0, 0): pending data changes, not updating, not visible */
00089             Running,        /* (0, 1, 1): no pending data changes, updating, visible  */
00090             NotAllowed      /* error state */
00091         };
00092
00093         Platform::Collections::Vector<IPhotoGroup^>^ m_monthGroups;
00094         Platform::Collections::Vector<IYearGroup^>^ m_yearGroups;
00095         Windows::UI::Xaml::Input::ICommand^ m_groupCommand;
00096         Windows::UI::Xaml::Input::ICommand^ m_cropImageCommand;
00097         Windows::UI::Xaml::Input::ICommand^ m_rotateImageCommand;
00098         Windows::UI::Xaml::Input::ICommand^ m_cartoonizeImageCommand;
00099
00100         bool m_runningMonthQuery;
00101         bool m_runningYearQuery;
00102         int m_currentQueryId;
00103         Mode m_currentMode;
00104         ULONGLONG m_lastFileChangeTime;
00105         bool m_hasFileUpdateTask;
00106
00107         concurrency::cancellation_token_source m_cancellationTokenSource;
00108         std::shared_ptr<PhotoCache> m_photoCache;
00109         IPhoto^ m_photo;
00110         std::shared_ptr<Repository> m_repository;
00111
00112         void NavigateToGroup(Platform::Object^ parameter);
00113         void CropImage(Platform::Object^ parameter);
00114         void RotateImage(Platform::Object^ parameter);
00115         void CartoonizeImage(Platform::Object^ parameter);
00116         bool CanProcessImage(Object^ parameter);
00117         void OnDataChanged();
00118         void ObserveFileChange();
00119         void CancelMonthAndYearQueries();
00120         void StartMonthAndYearQueries();
00121         void StartMonthQuery(int queryId, concurrency::cancellation_token token);
00122         void StartYearQuery(int queryId, concurrency::cancellation_token token);
00123         void FinishMonthAndYearQueries();
00124     };
00125 }
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: SimpleOrientationSensor/C++/common/LayoutAwarePage.cpp Source File

  • SimpleOrientationSensor
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:32 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text editing/C++/Constants.cpp Source File

  • XAML text editing

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully qualified name for the class that implements the scenario" }
00021     { "Windows 8 text selection", "SDKSample.TextEditing.Scenario1" },
00022     { "Accessing text selection", "SDKSample.TextEditing.Scenario2" },
00023     { "Spell checking", "SDKSample.TextEditing.Scenario3" },
00024   { "Text prediction", "SDKSample.TextEditing.Scenario4" },
00025   { "Input scopes", "SDKSample.TextEditing.Scenario5" },
00026   { "RichEditBox and WinRT TOM", "SDKSample.TextEditing.Scenario6" },
00027   { "PasswordBox", "SDKSample.TextEditing.Scenario7" }
00028 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAudio2 audio stream effect/C++/BasicTimer.h Source File

  • XAudio2 audio stream effect

BasicTimer.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 timer class used to drive the render loop of the actively-animated
00011 // DirectX SDK samples. Uses the QueryPerformanceCounter function to retrieve
00012 // high-resolution timing information.
00013 ref class BasicTimer
00014 {
00015 private:
00016     LARGE_INTEGER m_frequency;
00017     LARGE_INTEGER m_currentTime;
00018     LARGE_INTEGER m_startTime;
00019     LARGE_INTEGER m_lastTime;
00020     float m_total;
00021     float m_delta;
00022
00023 internal:
00024     BasicTimer();
00025     void Reset();
00026     void Update();
00027     property float Total
00028     {
00029         float get();
00030     }
00031     property float Delta
00032     {
00033         float get();
00034     }
00035 };
Generated on Sat Nov 23 2024 16:08:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAudio2 audio file playback/C++/SampleOverlay.h Source File

  • XAudio2 audio file playback

SampleOverlay.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 "DirectXSample.h"
00011
00012 // This class is responsible for initializing and rendering the title overlay visible
00013 // at the top of the DirectX SDK samples.
00014 ref class SampleOverlay
00015 {
00016 internal:
00017     SampleOverlay();
00018
00019     void Initialize(
00020         _In_ ID2D1Device*         d2dDevice,
00021         _In_ ID2D1DeviceContext*  d2dContext,
00022         _In_ IWICImagingFactory*  wicFactory,
00023         _In_ IDWriteFactory*      dwriteFactory,
00024         _In_ Platform::String^    caption
00025         );
00026
00027     void ResetDirectXResources();
00028
00029     void UpdateForWindowSizeChange();
00030
00031     void Render();
00032
00033     float GetTitleHeightInDips();
00034
00035 private:
00036
00037     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00038     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00039     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00040     Microsoft::WRL::ComPtr<IDWriteFactory>          m_dwriteFactory;
00041     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_whiteBrush;
00042     Microsoft::WRL::ComPtr<ID2D1DrawingStateBlock>  m_stateBlock;
00043
00044     Microsoft::WRL::ComPtr<IWICImagingFactory>      m_wicFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Bitmap>             m_logoBitmap;
00046     Microsoft::WRL::ComPtr<IDWriteTextLayout>       m_textLayout;
00047
00048     UINT                                            m_idIncrement;
00049     bool                                            m_drawOverlay;
00050     Platform::String^                               m_sampleName;
00051     float                                           m_padding;
00052     float                                           m_textVerticalOffset;
00053     D2D1_SIZE_F                                     m_logoSize;
00054     float                                           m_overlayWidth;
00055 };
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/Simple3DGame.h Source File

  • XAML DirectX 3D shooting game

Simple3DGame.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 // Simple3DGame:
00011 // This is the main game class.  It controls game play logic and game state.
00012 // Some of the key object classes used by Simple3DGame are:
00013 //     MoveLookController - for handling all input to control player movement, aiming,
00014 //         and firing.
00015 //     GameRenderer - for handling all graphics presentation.
00016 //     Camera - for handling view projections.
00017 //     Audio - for handling sound output.
00018 // This class maintains several lists of objects:
00019 //     m_ammo <Sphere> - is the list of the balls used to throw at targets.  Simple3DGame
00020 //         cycles through the list in a LRU fashion each time a ball is thrown by the player.
00021 //     m_objects <GameObject> - is the list of all objects in the scene that participate in
00022 //         game physics.  This includes m_player <Sphere> to represent the player in the scene.
00023 //         The player object (m_player) is not visible in the scene so it is not rendered.
00024 //     m_renderObjects <GameObject> - is the list of all objects in the scene that may be
00025 //         rendered.  It includes both the m_ammo list, most of the m_objects list excluding m_player
00026 //         object and the objects representing the bounding world.
00027
00028 #include "GameConstants.h"
00029 #include "Audio.h"
00030 #include "Camera.h"
00031 #include "Level.h"
00032 #include "GameObject.h"
00033 #include "GameTimer.h"
00034 #include "MoveLookController.h"
00035 #include "PersistentState.h"
00036 #include "Sphere.h"
00037 #include "GameRenderer.h"
00038
00039 //--------------------------------------------------------------------------------------
00040
00041 enum class GameState
00042 {
00043     Waiting,
00044     Active,
00045     LevelComplete,
00046     TimeExpired,
00047     GameComplete,
00048 };
00049
00050 typedef struct
00051 {
00052     Platform::String^ tag;
00053     int totalHits;
00054     int totalShots;
00055     int levelCompleted;
00056 } HighScoreEntry;
00057
00058 typedef std::vector<HighScoreEntry> HighScoreEntries;
00059
00060 typedef struct
00061 {
00062     bool isTrial;
00063     bool autoFire;
00064     bool backgroundAvailable[GameConstants::MaxBackgroundTextures];
00065 } GameConfig;
00066
00067 //--------------------------------------------------------------------------------------
00068
00069 ref class GameRenderer;
00070
00071 ref class Simple3DGame
00072 {
00073 internal:
00074     Simple3DGame();
00075
00076     void Initialize(
00077         _In_ MoveLookController^ controller,
00078         _In_ GameRenderer^ renderer
00079         );
00080
00081     void LoadGame();
00082     concurrency::task<void> LoadLevelAsync();
00083     void FinalizeLoadLevel();
00084     void StartLevel();
00085     void PauseGame();
00086     void ContinueGame();
00087     GameState RunGame();
00088     void SetCurrentLevelToSavedState();
00089
00090     void OnSuspending();
00091     void OnResuming();
00092
00093     bool IsActivePlay()                         { return m_timer->Active(); }
00094     bool IsTrial()                              { return m_gameConfig.isTrial; }
00095     int LevelCompleted()                        { return m_currentLevel; };
00096     int TotalShots()                            { return m_totalShots; };
00097     int TotalHits()                             { return m_totalHits; };
00098     float BonusTime()                           { return m_levelBonusTime; };
00099     bool GameActive()                           { return m_gameActive; };
00100     bool LevelActive()                          { return m_levelActive; };
00101     HighScoreEntry HighScore()                  { return m_topScore; };
00102     Level^ CurrentLevel()                       { return m_level[m_currentLevel]; };
00103     float TimeRemaining()                       { return m_levelTimeRemaining; };
00104     Camera^ GameCamera()                        { return m_camera; };
00105     std::vector<GameObject^> RenderObjects()    { return m_renderObjects; };
00106
00107     void UpdateGameConfig(Windows::ApplicationModel::Store::LicenseInformation^ licenseInformation);
00108     void SetBackground(uint32 background);
00109     void CycleBackground();
00110
00111
00112 private:
00113     void LoadState();
00114     void SaveState();
00115     void SaveHighScore();
00116     void LoadHighScore();
00117     void InitializeAmmo();
00118     void UpdateDynamics();
00119     void InitializeGameConfig();
00120
00121     MoveLookController^                         m_controller;
00122     GameRenderer^                               m_renderer;
00123     Camera^                                     m_camera;
00124
00125     Audio^                                      m_audioController;
00126
00127     std::vector<Sphere^>                        m_ammo;
00128     uint32                                      m_ammoCount;
00129     uint32                                      m_ammoNext;
00130
00131     HighScoreEntry                              m_topScore;
00132     PersistentState^                            m_savedState;
00133
00134     GameTimer^                                  m_timer;
00135     bool                                        m_gameActive;
00136     bool                                        m_levelActive;
00137     int                                         m_totalHits;
00138     int                                         m_totalShots;
00139     float                                       m_levelDuration;
00140     float                                       m_levelBonusTime;
00141     float                                       m_levelTimeRemaining;
00142     std::vector<Level^>                         m_level;
00143     uint32                                      m_levelCount;
00144     uint32                                      m_currentLevel;
00145
00146     GameConfig                                  m_gameConfig;
00147     uint32                                      m_activeBackground;
00148
00149     Sphere^                                     m_player;
00150     std::vector<GameObject^>                    m_objects;           // List of all objects to be included in intersection calculations.
00151     std::vector<GameObject^>                    m_renderObjects;     // List of all objects to be rendered.
00152
00153     DirectX::XMFLOAT3                           m_minBound;
00154     DirectX::XMFLOAT3                           m_maxBound;
00155 };
00156
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-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 Sat Nov 23 2024 16:09:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File picker contracts/C++/App.xaml.cpp Source File

  • File picker contracts

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "App.xaml.h"
00018 #include "MainPage.xaml.h"
00019 #include "FileOpenPickerPage.xaml.h"
00020 #include "FileSavePickerPage.xaml.h"
00021 #include "CachedFileUpdaterPage.xaml.h"
00022 #include "Constants.h"
00023
00024 using namespace SDKSample;
00025 using namespace SDKSample::Common;
00026 using namespace SDKSample::FilePickerContracts;
00027 using namespace concurrency;
00028 using namespace Platform;
00029 using namespace Windows::ApplicationModel;
00030 using namespace Windows::ApplicationModel::Activation;
00031 using namespace Windows::Foundation::Collections;
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::Interop;
00036
00037 /// <summary>
00038 /// Initializes the singleton application object.  This is the first line of authored code
00039 /// executed, and as such is the logical equivalent of main() or WinMain().
00040 /// </summary>
00041 App::App()
00042 {
00043     InitializeComponent();
00044     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00045 }
00046
00047 /// <summary>
00048 /// Invoked when application execution is being suspended.  Application state is saved
00049 /// without knowing whether the application will be terminated or resumed with the contents
00050 /// of memory still intact.
00051 /// </summary>
00052 /// <param name="sender">The source of the suspend request.</param>
00053 /// <param name="e">Details about the suspend request.</param>
00054 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00055 {
00056     (void) sender;    // Unused parameter
00057
00058     auto deferral = e->SuspendingOperation->GetDeferral();
00059     SuspensionManager::SaveAsync().then([=]()
00060     {
00061         deferral->Complete();
00062     });
00063 }
00064
00065 /// <summary>
00066 /// Invoked when the application is launched normally by the end user.  Other entry points will
00067 /// be used when the application is launched to open a specific file, to display search results,
00068 /// and so forth.
00069 /// </summary>
00070 /// <param name="pArgs">Details about the launch request and process.</param>
00071 void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs)
00072 {
00073     EnsureMainPageActivated(pArgs);
00074 }
00075
00076 void App::EnsureMainPageActivated(Windows::ApplicationModel::Activation::IActivatedEventArgs^ pArgs)
00077 {
00078     // Do not repeat app initialization when already running, just ensure that
00079     // the window is active
00080     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00081     {
00082         Window::Current->Activate();
00083         return;
00084     }
00085
00086     // Create a Frame to act as the navigation context and associate it with
00087     // a SuspensionManager key
00088     auto rootFrame = ref new Frame();
00089     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00090
00091     auto prerequisite = task<void>([](){});
00092     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Terminated)
00093     {
00094         // Restore the saved session state only when appropriate, scheduling the
00095         // final launch steps after the restore is complete
00096         prerequisite = SuspensionManager::RestoreAsync();
00097     }
00098     prerequisite.then([=]()
00099     {
00100         // When the navigation stack isn't restored navigate to the first page,
00101         // configuring the new page by passing required information as a navigation
00102         // parameter
00103         if (rootFrame->Content == nullptr)
00104         {
00105             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00106             {
00107                 throw ref new FailureException("Failed to create initial page");
00108             }
00109         }
00110
00111         // Place the frame in the current Window and ensure that it is active
00112         Window::Current->Content = rootFrame;
00113         Window::Current->Activate();
00114     }, task_continuation_context::use_current());
00115 }
00116
00117 void App::OnFileOpenPickerActivated(FileOpenPickerActivatedEventArgs^ args)
00118 {
00119     auto fileOpenPickerPage = ref new FileOpenPickerPage();
00120     fileOpenPickerPage->Activate(args);
00121 }
00122
00123 void App::OnFileSavePickerActivated(FileSavePickerActivatedEventArgs^ args)
00124 {
00125     auto fileSavePickerPage = ref new FileSavePickerPage();
00126     fileSavePickerPage->Activate(args);
00127 }
00128
00129 void App::OnCachedFileUpdaterActivated(CachedFileUpdaterActivatedEventArgs^ args)
00130 {
00131     auto cachedFileUpdaterPage = ref new CachedFileUpdaterPage();
00132     cachedFileUpdaterPage->Activate(args);
00133 }
Generated on Sat Nov 23 2024 16:07:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/texconv/DirectXTexImage.cpp Source File

  • Direct3D resource loading
  • texconv

DirectXTexImage.cpp

Go to the documentation of this file.
00001 //-------------------------------------------------------------------------------------
00002 // DirectXTexImage.cpp
00003 //
00004 // DirectX Texture Library - Image container
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 #include "directxtexp.h"
00015
00016 namespace DirectX
00017 {
00018
00019 extern bool _CalculateMipLevels( _In_ size_t width, _In_ size_t height, _Inout_ size_t& mipLevels );
00020 extern bool _CalculateMipLevels3D( _In_ size_t width, _In_ size_t height, _In_ size_t depth, _Inout_ size_t& mipLevels );
00021
00022 //-------------------------------------------------------------------------------------
00023 // Determines number of image array entries and pixel size
00024 //-------------------------------------------------------------------------------------
00025 _Use_decl_annotations_
00026 void _DetermineImageArray( const TexMetadata& metadata, DWORD cpFlags,
00027                            size_t& nImages, size_t& pixelSize )
00028 {
00029     assert( metadata.width > 0 && metadata.height > 0 && metadata.depth > 0 );
00030     assert( metadata.arraySize > 0 );
00031     assert( metadata.mipLevels > 0 );
00032
00033     size_t _pixelSize = 0;
00034     size_t _nimages = 0;
00035
00036     switch( metadata.dimension )
00037     {
00038     case TEX_DIMENSION_TEXTURE1D:
00039     case TEX_DIMENSION_TEXTURE2D:
00040         for( size_t item = 0; item < metadata.arraySize; ++item )
00041         {
00042             size_t w = metadata.width;
00043             size_t h = metadata.height;
00044
00045             for( size_t level=0; level < metadata.mipLevels; ++level )
00046             {
00047                 size_t rowPitch, slicePitch;
00048                 ComputePitch( metadata.format, w, h, rowPitch, slicePitch, cpFlags );
00049
00050                 _pixelSize += slicePitch;
00051                 ++_nimages;
00052
00053                 if ( h > 1 )
00054                     h >>= 1;
00055
00056                 if ( w > 1 )
00057                     w >>= 1;
00058             }
00059         }
00060         break;
00061
00062     case TEX_DIMENSION_TEXTURE3D:
00063         {
00064             size_t w = metadata.width;
00065             size_t h = metadata.height;
00066             size_t d = metadata.depth;
00067
00068             for( size_t level=0; level < metadata.mipLevels; ++level )
00069             {
00070                 size_t rowPitch, slicePitch;
00071                 ComputePitch( metadata.format, w, h, rowPitch, slicePitch, cpFlags );
00072
00073                 for( size_t slice=0; slice < d; ++slice )
00074                 {
00075                     _pixelSize += slicePitch;
00076                     ++_nimages;
00077                 }
00078
00079                 if ( h > 1 )
00080                     h >>= 1;
00081
00082                 if ( w > 1 )
00083                     w >>= 1;
00084
00085                 if ( d > 1 )
00086                     d >>= 1;
00087             }
00088         }
00089         break;
00090
00091     default:
00092         assert( false );
00093         break;
00094     }
00095
00096     nImages = _nimages;
00097     pixelSize = _pixelSize;
00098 }
00099
00100
00101 //-------------------------------------------------------------------------------------
00102 // Fills in the image array entries
00103 //-------------------------------------------------------------------------------------
00104 _Use_decl_annotations_
00105 bool _SetupImageArray( uint8_t *pMemory, size_t pixelSize,
00106                        const TexMetadata& metadata, DWORD cpFlags,
00107                        Image* images, size_t nImages )
00108 {
00109     assert( pMemory );
00110     assert( pixelSize > 0 );
00111     assert( nImages > 0 );
00112
00113     if ( !images )
00114         return false;
00115
00116     size_t index = 0;
00117     uint8_t* pixels = pMemory;
00118     const uint8_t* pEndBits = pMemory + pixelSize;
00119
00120     switch( metadata.dimension )
00121     {
00122     case TEX_DIMENSION_TEXTURE1D:
00123     case TEX_DIMENSION_TEXTURE2D:
00124         if (metadata.arraySize == 0 || metadata.mipLevels == 0)
00125         {
00126             return false;
00127         }
00128
00129         for( size_t item = 0; item < metadata.arraySize; ++item )
00130         {
00131             size_t w = metadata.width;
00132             size_t h = metadata.height;
00133
00134             for( size_t level=0; level < metadata.mipLevels; ++level )
00135             {
00136                 if ( index >= nImages )
00137                 {
00138                     return false;
00139                 }
00140
00141                 size_t rowPitch, slicePitch;
00142                 ComputePitch( metadata.format, w, h, rowPitch, slicePitch, cpFlags );
00143
00144                 images[index].width = w;
00145                 images[index].height = h;
00146                 images[index].format = metadata.format;
00147                 images[index].rowPitch = rowPitch;
00148                 images[index].slicePitch = slicePitch;
00149                 images[index].pixels = pixels;
00150                 ++index;
00151
00152                 pixels += slicePitch;
00153                 if ( pixels > pEndBits )
00154                 {
00155                     return false;
00156                 }
00157
00158                 if ( h > 1 )
00159                     h >>= 1;
00160
00161                 if ( w > 1 )
00162                     w >>= 1;
00163             }
00164         }
00165         return true;
00166
00167     case TEX_DIMENSION_TEXTURE3D:
00168         {
00169             if (metadata.mipLevels == 0 || metadata.depth == 0)
00170             {
00171                 return false;
00172             }
00173
00174             size_t w = metadata.width;
00175             size_t h = metadata.height;
00176             size_t d = metadata.depth;
00177
00178             for( size_t level=0; level < metadata.mipLevels; ++level )
00179             {
00180                 size_t rowPitch, slicePitch;
00181                 ComputePitch( metadata.format, w, h, rowPitch, slicePitch, cpFlags );
00182
00183                 for( size_t slice=0; slice < d; ++slice )
00184                 {
00185                     if ( index >= nImages )
00186                     {
00187                         return false;
00188                     }
00189
00190                     // We use the same memory organization that Direct3D 11 needs for D3D11_SUBRESOURCE_DATA
00191                     // with all slices of a given miplevel being continuous in memory
00192                     images[index].width = w;
00193                     images[index].height = h;
00194                     images[index].format = metadata.format;
00195                     images[index].rowPitch = rowPitch;
00196                     images[index].slicePitch = slicePitch;
00197                     images[index].pixels = pixels;
00198                     ++index;
00199
00200                     pixels += slicePitch;
00201                     if ( pixels > pEndBits )
00202                     {
00203                         return false;
00204                     }
00205                 }
00206
00207                 if ( h > 1 )
00208                     h >>= 1;
00209
00210                 if ( w > 1 )
00211                     w >>= 1;
00212
00213                 if ( d > 1 )
00214                     d >>= 1;
00215             }
00216         }
00217         return true;
00218
00219     default:
00220         return false;
00221     }
00222 }
00223
00224
00225 //=====================================================================================
00226 // ScratchImage - Bitmap image container
00227 //=====================================================================================
00228
00229 //-------------------------------------------------------------------------------------
00230 // Methods
00231 //-------------------------------------------------------------------------------------
00232 _Use_decl_annotations_
00233 HRESULT ScratchImage::Initialize( const TexMetadata& mdata )
00234 {
00235     if ( !IsValid(mdata.format) || IsVideo(mdata.format) )
00236         return E_INVALIDARG;
00237
00238     size_t mipLevels = mdata.mipLevels;
00239
00240     switch( mdata.dimension )
00241     {
00242     case TEX_DIMENSION_TEXTURE1D:
00243         if ( !mdata.width || mdata.height != 1 || mdata.depth != 1 || !mdata.arraySize )
00244             return E_INVALIDARG;
00245
00246         if ( !_CalculateMipLevels(mdata.width,1,mipLevels) )
00247             return E_INVALIDARG;
00248         break;
00249
00250     case TEX_DIMENSION_TEXTURE2D:
00251         if ( !mdata.width || !mdata.height || mdata.depth != 1 || !mdata.arraySize )
00252             return E_INVALIDARG;
00253
00254         if ( mdata.miscFlags & TEX_MISC_TEXTURECUBE )
00255         {
00256             if ( (mdata.arraySize % 6) != 0 )
00257                 return E_INVALIDARG;
00258         }
00259
00260         if ( !_CalculateMipLevels(mdata.width,mdata.height,mipLevels) )
00261             return E_INVALIDARG;
00262         break;
00263
00264     case TEX_DIMENSION_TEXTURE3D:
00265         if ( !mdata.width || !mdata.height || !mdata.depth || mdata.arraySize != 1 )
00266             return E_INVALIDARG;
00267
00268         if ( !_CalculateMipLevels3D(mdata.width,mdata.height,mdata.depth,mipLevels) )
00269             return E_INVALIDARG;
00270         break;
00271
00272     default:
00273         return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
00274     }
00275
00276     Release();
00277
00278     _metadata.width = mdata.width;
00279     _metadata.height = mdata.height;
00280     _metadata.depth = mdata.depth;
00281     _metadata.arraySize = mdata.arraySize;
00282     _metadata.mipLevels = mipLevels;
00283     _metadata.miscFlags = mdata.miscFlags & TEX_MISC_TEXTURECUBE;
00284     _metadata.format = mdata.format;
00285     _metadata.dimension = mdata.dimension;
00286
00287     size_t pixelSize, nimages;
00288     _DetermineImageArray( _metadata, CP_FLAGS_NONE, nimages, pixelSize );
00289
00290     _image = new Image[ nimages ];
00291     if ( !_image )
00292         return E_OUTOFMEMORY;
00293
00294     _nimages = nimages;
00295     memset( _image, 0, sizeof(Image) * nimages );
00296
00297     _memory = reinterpret_cast<uint8_t*>( _aligned_malloc( pixelSize, 16 ) );
00298     if ( !_memory )
00299     {
00300         Release();
00301         return E_OUTOFMEMORY;
00302     }
00303     _size = pixelSize;
00304     if ( !_SetupImageArray( _memory, pixelSize, _metadata, CP_FLAGS_NONE, _image, nimages ) )
00305     {
00306         Release();
00307         return E_FAIL;
00308     }
00309
00310     return S_OK;
00311 }
00312
00313 _Use_decl_annotations_
00314 HRESULT ScratchImage::Initialize1D( DXGI_FORMAT fmt, size_t length, size_t arraySize, size_t mipLevels )
00315 {
00316     if ( !IsValid(fmt) || IsVideo(fmt) || !length || !arraySize )
00317         return E_INVALIDARG;
00318
00319     // 1D is a special case of the 2D case
00320     HRESULT hr = Initialize2D( fmt, length, 1, arraySize, mipLevels );
00321     if ( FAILED(hr) )
00322         return hr;
00323
00324     _metadata.dimension = TEX_DIMENSION_TEXTURE1D;
00325
00326     return S_OK;
00327 }
00328
00329 _Use_decl_annotations_
00330 HRESULT ScratchImage::Initialize2D( DXGI_FORMAT fmt, size_t width, size_t height, size_t arraySize, size_t mipLevels )
00331 {
00332     if ( !IsValid(fmt) || IsVideo(fmt) || !width || !height || !arraySize )
00333         return E_INVALIDARG;
00334
00335     if ( !_CalculateMipLevels(width,height,mipLevels) )
00336         return E_INVALIDARG;
00337
00338     Release();
00339
00340     _metadata.width = width;
00341     _metadata.height = height;
00342     _metadata.depth = 1;
00343     _metadata.arraySize = arraySize;
00344     _metadata.mipLevels = mipLevels;
00345     _metadata.miscFlags = 0;
00346     _metadata.format = fmt;
00347     _metadata.dimension = TEX_DIMENSION_TEXTURE2D;
00348
00349     size_t pixelSize, nimages;
00350     _DetermineImageArray( _metadata, CP_FLAGS_NONE, nimages, pixelSize );
00351
00352     _image = new Image[ nimages ];
00353     if ( !_image )
00354         return E_OUTOFMEMORY;
00355
00356     _nimages = nimages;
00357     memset( _image, 0, sizeof(Image) * nimages );
00358
00359     _memory = reinterpret_cast<uint8_t*>( _aligned_malloc( pixelSize, 16 ) );
00360     if ( !_memory )
00361     {
00362         Release();
00363         return E_OUTOFMEMORY;
00364     }
00365     _size = pixelSize;
00366     if ( !_SetupImageArray( _memory, pixelSize, _metadata, CP_FLAGS_NONE, _image, nimages ) )
00367     {
00368         Release();
00369         return E_FAIL;
00370     }
00371
00372     return S_OK;
00373 }
00374
00375 _Use_decl_annotations_
00376 HRESULT ScratchImage::Initialize3D( DXGI_FORMAT fmt, size_t width, size_t height, size_t depth, size_t mipLevels )
00377 {
00378     if ( !IsValid(fmt) || IsVideo(fmt) || !width || !height || !depth )
00379         return E_INVALIDARG;
00380
00381     if ( !_CalculateMipLevels3D(width,height,depth,mipLevels) )
00382         return E_INVALIDARG;
00383
00384     Release();
00385
00386     _metadata.width = width;
00387     _metadata.height = height;
00388     _metadata.depth = depth;
00389     _metadata.arraySize = 1;    // Direct3D 10.x/11 does not support arrays of 3D textures
00390     _metadata.mipLevels = mipLevels;
00391     _metadata.miscFlags = 0;
00392     _metadata.format = fmt;
00393     _metadata.dimension = TEX_DIMENSION_TEXTURE3D;
00394
00395     size_t pixelSize, nimages;
00396     _DetermineImageArray( _metadata, CP_FLAGS_NONE, nimages, pixelSize );
00397
00398     _image = new Image[ nimages ];
00399     if ( !_image )
00400     {
00401         Release();
00402         return E_OUTOFMEMORY;
00403     }
00404     _nimages = nimages;
00405     memset( _image, 0, sizeof(Image) * nimages );
00406
00407     _memory = reinterpret_cast<uint8_t*>( _aligned_malloc( pixelSize, 16 ) );
00408     if ( !_memory )
00409     {
00410         Release();
00411         return E_OUTOFMEMORY;
00412     }
00413     _size = pixelSize;
00414
00415     if ( !_SetupImageArray( _memory, pixelSize, _metadata, CP_FLAGS_NONE, _image, nimages ) )
00416     {
00417         Release();
00418         return E_FAIL;
00419     }
00420
00421     return S_OK;
00422 }
00423
00424 _Use_decl_annotations_
00425 HRESULT ScratchImage::InitializeCube( DXGI_FORMAT fmt, size_t width, size_t height, size_t nCubes, size_t mipLevels )
00426 {
00427     if ( !IsValid(fmt) || IsVideo(fmt)  || !width || !height || !nCubes )
00428         return E_INVALIDARG;
00429
00430     // A DirectX11 cubemap is just a 2D texture array that is a multiple of 6 for each cube
00431     HRESULT hr = Initialize2D( fmt, width, height, nCubes * 6, mipLevels );
00432     if ( FAILED(hr) )
00433         return hr;
00434
00435     _metadata.miscFlags |= TEX_MISC_TEXTURECUBE;
00436
00437     return S_OK;
00438 }
00439
00440 _Use_decl_annotations_
00441 HRESULT ScratchImage::InitializeFromImage( const Image& srcImage, bool allow1D )
00442 {
00443     HRESULT hr = ( srcImage.height > 1 || !allow1D )
00444                  ? Initialize2D( srcImage.format, srcImage.width, srcImage.height, 1, 1 )
00445                  : Initialize1D( srcImage.format, srcImage.width, 1, 1 );
00446
00447     if ( FAILED(hr) )
00448         return hr;
00449
00450     const uint8_t* sptr = reinterpret_cast<const uint8_t*>( srcImage.pixels );
00451     if ( !sptr )
00452         return E_POINTER;
00453
00454     uint8_t* dptr = reinterpret_cast<uint8_t*>( _image[0].pixels );
00455     if ( !dptr )
00456         return E_POINTER;
00457
00458     for( size_t y = 0; y < srcImage.height; ++y )
00459     {
00460         _CopyScanline( dptr, _image[0].rowPitch, sptr, srcImage.rowPitch, srcImage.format, TEXP_SCANLINE_NONE );
00461         sptr += srcImage.rowPitch;
00462         dptr += _image[0].rowPitch;
00463     }
00464
00465     return S_OK;
00466 }
00467
00468 _Use_decl_annotations_
00469 HRESULT ScratchImage::InitializeArrayFromImages( const Image* images, size_t nImages, bool allow1D )
00470 {
00471     if ( !images || !nImages )
00472         return E_INVALIDARG;
00473
00474     DXGI_FORMAT format = images[0].format;
00475     size_t width = images[0].width;
00476     size_t height = images[0].height;
00477
00478     for( size_t index=0; index < nImages; ++index )
00479     {
00480         if ( !images[index].pixels )
00481             return E_POINTER;
00482
00483         if ( images[index].format != format || images[index].width != width || images[index].height != height )
00484         {
00485             // All images must be the same format, width, and height
00486             return E_FAIL;
00487         }
00488     }
00489
00490     HRESULT hr = ( height > 1 || !allow1D )
00491                  ? Initialize2D( format, width, height, nImages, 1 )
00492                  : Initialize1D( format, width, nImages, 1 );
00493
00494     if ( FAILED(hr) )
00495         return hr;
00496
00497     for( size_t index=0; index < nImages; ++index )
00498     {
00499         const uint8_t* sptr = reinterpret_cast<const uint8_t*>( images[index].pixels );
00500         if ( !sptr )
00501             return E_POINTER;
00502
00503         assert( index < _nimages );
00504         uint8_t* dptr = reinterpret_cast<uint8_t*>( _image[index].pixels );
00505         if ( !dptr )
00506             return E_POINTER;
00507
00508         for( size_t y = 0; y < height; ++y )
00509         {
00510             _CopyScanline( dptr, _image[index].rowPitch, sptr, images[index].rowPitch, format, TEXP_SCANLINE_NONE );
00511             sptr += images[index].rowPitch;
00512             dptr += _image[index].rowPitch;
00513         }
00514     }
00515
00516     return S_OK;
00517 }
00518
00519 _Use_decl_annotations_
00520 HRESULT ScratchImage::InitializeCubeFromImages( const Image* images, size_t nImages )
00521 {
00522     if ( !images || !nImages )
00523         return E_INVALIDARG;
00524
00525     // A DirectX11 cubemap is just a 2D texture array that is a multiple of 6 for each cube
00526     if ( ( nImages % 6 ) != 0 )
00527         return E_INVALIDARG;
00528
00529     HRESULT hr = InitializeArrayFromImages( images, nImages, false );
00530     if ( FAILED(hr) )
00531         return hr;
00532
00533     _metadata.miscFlags |= TEX_MISC_TEXTURECUBE;
00534
00535     return S_OK;
00536 }
00537
00538 _Use_decl_annotations_
00539 HRESULT ScratchImage::Initialize3DFromImages( const Image* images, size_t depth )
00540 {
00541     if ( !images || !depth )
00542         return E_INVALIDARG;
00543
00544     DXGI_FORMAT format = images[0].format;
00545     size_t width = images[0].width;
00546     size_t height = images[0].height;
00547
00548     for( size_t slice=0; slice < depth; ++slice )
00549     {
00550         if ( !images[slice].pixels )
00551             return E_POINTER;
00552
00553         if ( images[slice].format != format || images[slice].width != width || images[slice].height != height )
00554         {
00555             // All images must be the same format, width, and height
00556             return E_FAIL;
00557         }
00558     }
00559
00560     HRESULT hr = Initialize3D( format, width, height, depth, 1 );
00561     if ( FAILED(hr) )
00562         return hr;
00563
00564     for( size_t slice=0; slice < depth; ++slice )
00565     {
00566         const uint8_t* sptr = reinterpret_cast<const uint8_t*>( images[slice].pixels );
00567         if ( !sptr )
00568             return E_POINTER;
00569
00570         assert( slice < _nimages );
00571         uint8_t* dptr = reinterpret_cast<uint8_t*>( _image[slice].pixels );
00572         if ( !dptr )
00573             return E_POINTER;
00574
00575         for( size_t y = 0; y < height; ++y )
00576         {
00577             _CopyScanline( dptr, _image[slice].rowPitch, sptr, images[slice].rowPitch, format, TEXP_SCANLINE_NONE );
00578             sptr += images[slice].rowPitch;
00579             dptr += _image[slice].rowPitch;
00580         }
00581     }
00582
00583     return S_OK;
00584 }
00585
00586 void ScratchImage::Release()
00587 {
00588     _nimages = 0;
00589     _size = 0;
00590
00591     if ( _image )
00592     {
00593         delete [] _image;
00594         _image = 0;
00595     }
00596
00597     if ( _memory )
00598     {
00599         _aligned_free( _memory );
00600         _memory = 0;
00601     }
00602
00603     memset(&_metadata, 0, sizeof(_metadata));
00604 }
00605
00606 _Use_decl_annotations_
00607 const Image* ScratchImage::GetImage(size_t mip, size_t item, size_t slice) const
00608 {
00609     if ( mip >= _metadata.mipLevels )
00610         return nullptr;
00611
00612     size_t index = 0;
00613
00614     switch( _metadata.dimension )
00615     {
00616     case TEX_DIMENSION_TEXTURE1D:
00617     case TEX_DIMENSION_TEXTURE2D:
00618         if ( slice > 0 )
00619             return nullptr;
00620
00621         if ( item >= _metadata.arraySize )
00622             return nullptr;
00623
00624         index = item*( _metadata.mipLevels ) + mip;
00625         break;
00626
00627     case TEX_DIMENSION_TEXTURE3D:
00628         if ( item > 0 )
00629         {
00630             // No support for arrays of volumes
00631             return nullptr;
00632         }
00633         else
00634         {
00635             size_t d = _metadata.depth;
00636
00637             for( size_t level = 0; level < mip; ++level )
00638             {
00639                 index += d;
00640                 if ( d > 1 )
00641                     d >>= 1;
00642             }
00643
00644             if ( slice >= d )
00645                 return nullptr;
00646
00647             index += slice;
00648         }
00649         break;
00650
00651     default:
00652         return nullptr;
00653     }
00654
00655     return &_image[index];
00656 }
00657
00658 }; // namespace
Generated on Sat Nov 23 2024 16:08:12 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML data binding/C++/Scenario6.xaml.cpp Source File

  • XAML data binding

Scenario6.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.xaml.cpp
00013 // Implementation of the Scenario6 class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario6.xaml.h"
00018 #include "Team.h"
00019
00020 using namespace SDKSample::DataBinding;
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Navigation;
00025
00026 Scenario6::Scenario6()
00027 {
00028   InitializeComponent();
00029   Scenario6Reset(nullptr,nullptr);
00030 }
00031
00032 void SDKSample::DataBinding::Scenario6::Scenario6Reset(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00033 {
00034   auto dataSource = ref new TeamDataSource();
00035   groupInfoCVS->Source = dataSource->ItemGroups;
00036 }
00037
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML data binding/C++/Team.h Source File

  • XAML data binding

Team.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 //
00009 // Team.h
00010 // Declaration of the Team class
00011 //
00012
00013 #pragma once
00014
00015 namespace SDKSample
00016 {
00017     namespace DataBinding
00018     {
00019       // This Data Source is used in Scenarios 4, 5 and 6.
00020       [Windows::UI::Xaml::Data::Bindable]
00021       [Windows::Foundation::Metadata::WebHostHidden]
00022       public ref class Team sealed
00023         : Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>
00024       {
00025       public:
00026         Team();
00027         property Platform::String^ Name
00028         {
00029           Platform::String^ get()
00030           {
00031             return _name;
00032           }
00033           void set(Platform::String^ value)
00034           {
00035             _name = value;
00036           }
00037         }
00038         property Platform::String^ City
00039         {
00040           Platform::String^ get()
00041           {
00042             return _city;
00043           }
00044           void set(Platform::String^ value)
00045           {
00046             _city = value;
00047           }
00048         }
00049         property Windows::UI::Xaml::Media::SolidColorBrush^ Color
00050         {
00051           Windows::UI::Xaml::Media::SolidColorBrush^ get()
00052           {
00053             return _color;
00054           }
00055           void set(Windows::UI::Xaml::Media::SolidColorBrush^ value)
00056           {
00057             _color = value;
00058           }
00059         }
00060
00061
00062         virtual void Clear()
00063         {
00064           _propBag->Clear();
00065         }
00066         virtual Windows::Foundation::Collections::IMapView<Platform::String^, Platform::Object^>^ GetView()
00067         {
00068           return _propBag->GetView();
00069         }
00070         virtual bool HasKey(Platform::String^ key)
00071         {
00072           return _propBag->HasKey(key);
00073         }
00074         virtual bool Insert(Platform::String^ key, Platform::Object^ value)
00075         {
00076           return _propBag->Insert(key, value);
00077         }
00078         virtual Object^ Lookup(Platform::String^ key)
00079         {
00080           return _propBag->Lookup(key);
00081         }
00082         virtual void Remove(Platform::String^ key)
00083         {
00084           return _propBag->Remove(key);
00085         }
00086         virtual property default::uint32 Size
00087         {
00088           default::uint32 get()
00089           {
00090             return _propBag->Size;
00091           }
00092         }
00093         virtual Windows::Foundation::Collections::IIterator<Windows::Foundation::Collections::IKeyValuePair<Platform::String^, Platform::Object^>^>^ First()
00094         {
00095           return _propBag->First();
00096         }
00097
00098       private:
00099         Platform::String^ _name;
00100         Platform::String^ _city;
00101         Windows::UI::Xaml::Media::SolidColorBrush^ _color;
00102         Windows::Foundation::Collections::PropertySet^ _propBag;
00103
00104       };
00105
00106       // This class is used to demonstrate grouping.
00107       [Windows::UI::Xaml::Data::Bindable] // in c++, adding this attribute to ref classes enables data binding for more info search for 'Bindable' on the page http://go.microsoft.com/fwlink/?LinkId=254639
00108       public ref class Teams sealed
00109         : Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>
00110       {
00111       public:
00112         Teams();
00113         property Windows::Foundation::Collections::IObservableVector<Platform::Object^>^ Items
00114         {
00115           Windows::Foundation::Collections::IObservableVector<Platform::Object^>^ get()
00116           {
00117             return _items;
00118           }
00119         }
00120
00121         virtual void Clear()
00122         {
00123           _propBag->Clear();
00124         }
00125         virtual Windows::Foundation::Collections::IMapView<Platform::String^, Platform::Object^>^ GetView()
00126         {
00127           return _propBag->GetView();
00128         }
00129         virtual bool HasKey(Platform::String^ key)
00130         {
00131           return _propBag->HasKey(key);
00132         }
00133         virtual bool Insert(Platform::String^ key, Platform::Object^ value)
00134         {
00135           return _propBag->Insert(key, value);
00136         }
00137         virtual Platform::Object^ Lookup(Platform::String^ key)
00138         {
00139           return _propBag->Lookup(key);
00140         }
00141         virtual void Remove(Platform::String^ key)
00142         {
00143           return _propBag->Remove(key);
00144         }
00145         virtual property default::uint32 Size
00146         {
00147           default::uint32 get()
00148           {
00149             return _propBag->Size;
00150           }
00151         }
00152         virtual Windows::Foundation::Collections::IIterator<Windows::Foundation::Collections::IKeyValuePair<Platform::String^, Platform::Object^>^>^ First()
00153         {
00154           return _propBag->First();
00155         }
00156
00157       private:
00158         Windows::Foundation::Collections::PropertySet^ _propBag;
00159         Platform::Collections::Vector<Platform::Object^>^ _items;
00160       };
00161
00162       /// <summary>
00163       /// Generic group data model.
00164       /// </summary>
00165       [Windows::UI::Xaml::Data::Bindable] // in c++, adding this attribute to ref classes enables data binding for more info search for 'Bindable' on the page http://go.microsoft.com/fwlink/?LinkId=254639
00166       public ref class TeamGroup sealed
00167       {
00168       public:
00169         TeamGroup(Platform::String^ name);
00170         property Platform::String^ Key
00171         {
00172           Platform::String^ get()
00173           {
00174             return _name;
00175           }
00176           void set(Platform::String^ value)
00177           {
00178             _name = value;
00179           }
00180         }
00181         property Windows::Foundation::Collections::IObservableVector<Platform::Object^>^ Items
00182         {
00183           Windows::Foundation::Collections::IObservableVector<Platform::Object^>^ get()
00184           {
00185             return _items;
00186           }
00187         }
00188       private:
00189         Platform::String^ _name;
00190         Platform::Collections::Vector<Platform::Object^>^ _items;
00191       };
00192
00193       /// <summary>
00194       /// Creates a collection of groups and items.
00195       /// </summary>
00196       [Windows::UI::Xaml::Data::Bindable] // in c++, adding this attribute to ref classes enables data binding for more info search for 'Bindable' on the page http://go.microsoft.com/fwlink/?LinkId=254639
00197       public ref class TeamDataSource sealed
00198       {
00199       public:
00200         TeamDataSource();
00201         property Windows::Foundation::Collections::IObservableVector<Platform::Object^>^ ItemGroups
00202         {
00203           Windows::Foundation::Collections::IObservableVector<Platform::Object^>^ get()
00204           {
00205             return _itemGroups;
00206           }
00207         }
00208       private:
00209         Platform::Collections::Vector<Platform::Object^>^ _itemGroups;
00210       };
00211
00212     }
00213 }
Generated on Sat Nov 23 2024 16:08:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Mobile broadband account provisioning/C++/App.xaml.h Source File

  • Mobile broadband account provisioning

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/CartoonizeImageView.xaml.h Source File

  • Hilo C++
  • Hilo

CartoonizeImageView.xaml.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
00009 #include "CartoonizeImageView.g.h"
00010
00011 namespace Hilo
00012 {
00013     // See http://go.microsoft.com/fwlink/?LinkId=267278 for info on how Hilo creates pages and navigates to pages.
00014
00015     // See http://go.microsoft.com/fwlink/?LinkId=267276 for info on how view classes interact
00016     // with corresponding view model classes that encapsulate the app’s state, actions, and operations.
00017
00018     // See http://go.microsoft.com/fwlink/?LinkId=267279 for info on how Hilo pages use XAML controls.
00019
00020     // The CartoonizeImageView class implements the cartoon effect page.
00021     [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class CartoonizeImageView sealed
00023     {
00024     public:
00025         CartoonizeImageView();
00026     };
00027 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Real-time communication/C++/pch.cpp Source File

  • Real-time communication

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text display/C++/Scenario1.xaml.h Source File

  • XAML text display

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 SDKSample
00023 {
00024     namespace TextDisplay
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 Scenario1 sealed
00031         {
00032         public:
00033             Scenario1();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040             void Other_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         };
00042     }
00043 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D HLSL fractal generator/C++/DirectXFractal.h Source File

  • Direct3D HLSL fractal generator

DirectXFractal.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 "DirectXBase.h"
00011 #include "SampleOverlay.h"
00012 #include "AutoThrottle.h"
00013
00014 namespace SampleSettings
00015 {
00016     static const int TargetIterations = 256;
00017     namespace Performance
00018     {
00019         static const float TargetFrameTime = 1.0f / 20.0f;
00020         static const int InitialIterationsPerFrame = 32;
00021         static const float InitialDownSampleRatio = 3.0f;
00022         static const float DownSampleRatioMax = 8.0f;
00023         static const float DownSampleRatioDeltaDecrease = 0.01f;
00024         static const float DownSampleRatioDeltaIncrease = 0.05f;
00025     }
00026     namespace Manipulation
00027     {
00028         static const double MinimumF8Scale = 1.0f;
00029         static const double MinimumF16Scale = 1.0e-2f;
00030         static const double MinimumF32Scale = 2.0e-5f;
00031         static const double MinimumF64Scale = 1.0e-13;
00032         static const double MaximumScale = 4.0;
00033         static const float MaximumTranslationMagnitude = 2.0f;
00034     }
00035     namespace DirectCompute
00036     {
00037         static const int ThreadGroupSizeX = 16;
00038         static const int ThreadGroupSizeY = 16;
00039     }
00040     namespace ThreePhase
00041     {
00042         static const int InitialIterations = 4;
00043         static const int StepIterations = 4;
00044         static const int FinalIterations = 4;
00045     }
00046 }
00047
00048 enum class FractalTechnique
00049 {
00050     ThreePhase,
00051     SinglePass,
00052     DirectCompute
00053 };
00054
00055 struct ViewTransform
00056 {
00057     double scale;
00058     double rotation;
00059     double translationX;
00060     double translationY;
00061 };
00062
00063 struct FractalVertex
00064 {
00065     float2 pos;
00066     float2 tex;
00067     float2 bounds;
00068 };
00069
00070 struct DrawRectCB
00071 {
00072     float4x4 boundsTransform;
00073     float2 texScale;
00074 };
00075
00076 struct ComputeCB
00077 {
00078     float2 originDtid00;
00079     float2 deltaPerDtidX;
00080     float2 deltaPerDtidY;
00081 };
00082
00083 struct ComputeDoubleCB
00084 {
00085     double2 originDtid00;
00086     double2 deltaPerDtidX;
00087     double2 deltaPerDtidY;
00088 };
00089
00090 struct FractalBufferElement
00091 {
00092     int iteration;
00093 };
00094
00095
00096 ref class DirectXFractal : public DirectXBase
00097 {
00098 internal:
00099     DirectXFractal();
00100
00101     virtual void HandleDeviceLost() override;
00102     virtual void CreateDeviceIndependentResources() override;
00103     virtual void CreateDeviceResources() override;
00104     virtual void CreateWindowSizeDependentResources() override;
00105     virtual void Render() override;
00106     void Update(float timeTotal, float timeDelta);
00107     void HandleViewManipulation(float dRotation, float dScale, float dX, float dY);
00108     void SaveInternalState(_In_ Windows::Foundation::Collections::IPropertySet^ state);
00109     void LoadInternalState(_In_ Windows::Foundation::Collections::IPropertySet^ state);
00110
00111 private:
00112     void SaveInternalValue(
00113         _In_ Windows::Foundation::Collections::IPropertySet^ state,
00114         _In_ Platform::String^ key,
00115         _In_ Platform::Object^ value
00116         );
00117     int RoundUpTo16(int value);
00118     void DetermineFractalTechnique();
00119
00120     SampleOverlay^                                    m_sampleOverlay;
00121     AutoThrottle^                                     m_movingThrottle;
00122     Microsoft::WRL::ComPtr<ID3D11InputLayout>         m_inputLayout;
00123     Microsoft::WRL::ComPtr<ID3D11VertexShader>        m_vertexShader;
00124     Microsoft::WRL::ComPtr<ID3D11PixelShader>         m_renderTexturePS;
00125     Microsoft::WRL::ComPtr<ID3D11Buffer>              m_vertexBuffer;
00126     Microsoft::WRL::ComPtr<ID3D11Buffer>              m_indexBuffer;
00127     Microsoft::WRL::ComPtr<ID3D11PixelShader>         m_singlePassPS;
00128     Microsoft::WRL::ComPtr<ID3D11PixelShader>         m_initialPS;
00129     Microsoft::WRL::ComPtr<ID3D11PixelShader>         m_stepPS;
00130     Microsoft::WRL::ComPtr<ID3D11PixelShader>         m_finalPS;
00131     Microsoft::WRL::ComPtr<ID3D11ComputeShader>       m_directComputeCS;
00132     Microsoft::WRL::ComPtr<ID3D11PixelShader>         m_renderBufferPS;
00133     Microsoft::WRL::ComPtr<ID3D11Buffer>              m_drawRectCB;
00134     Microsoft::WRL::ComPtr<ID3D11Buffer>              m_computeCB;
00135     Microsoft::WRL::ComPtr<ID3D11Buffer>              m_bufferInfoCB;
00136     Microsoft::WRL::ComPtr<ID3D11ShaderResourceView>  m_gradient;
00137     Microsoft::WRL::ComPtr<ID3D11SamplerState>        m_linearSampler;
00138     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>    m_tempRTV[2];
00139     Microsoft::WRL::ComPtr<ID3D11UnorderedAccessView> m_tempUAV;
00140     Microsoft::WRL::ComPtr<ID3D11ShaderResourceView>  m_tempSRV[2];
00141     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>    m_finalRTV;
00142     Microsoft::WRL::ComPtr<ID3D11ShaderResourceView>  m_finalSRV;
00143     Microsoft::WRL::ComPtr<ID3D11SamplerState>        m_pointSampler;
00144     ViewTransform                                     m_transform;
00145     int                                               m_indexCount;
00146     bool                                              m_fastGenerate;
00147     bool                                              m_complete;
00148     float                                             m_downSampleRatio;
00149     bool                                              m_useDoubles;
00150     bool                                              m_useUnormTextures;
00151     int                                               m_bufferWidth;
00152     int                                               m_bufferHeight;
00153     int                                               m_numIterationsPerFrame;
00154     int                                               m_completedIterations;
00155     FractalTechnique                                  m_technique;
00156 };
Generated on Sat Nov 23 2024 16:08:11 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CryptoWinRT/C++/common/LayoutAwarePage.h Source File

  • CryptoWinRT
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Scaling according to DPI/C++/common/suspensionmanager.cpp Source File

  • Scaling according to DPI
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:37 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/ExceptionPolicyFactory.h Source File

  • Hilo C++
  • Hilo

ExceptionPolicyFactory.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
00009 namespace Hilo
00010 {
00011     class ExceptionPolicy;
00012
00013     class ExceptionPolicyFactory
00014     {
00015     public:
00016         static std::shared_ptr<ExceptionPolicy> GetCurrentPolicy();
00017
00018         static std::shared_ptr<ExceptionPolicy> m_policy;
00019     };
00020 }
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media Play To/C++/Scenario2.xaml.cpp Source File

  • Media Play To

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 SDKSample::PlayTo;
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::UI::Xaml::Media::Imaging;
00025 using namespace Windows::Foundation;
00026 using namespace Windows::Storage;
00027 using namespace Windows::Storage::Streams;
00028 using namespace Windows::Storage::Pickers;
00029 using namespace Windows::Media::PlayTo;
00030 using namespace concurrency;
00031
00032 Scenario2::Scenario2()
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 Scenario2::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   dispatcher = Window::Current->Dispatcher;
00048
00049   playlistTimer = ref new DispatcherTimer();
00050   TimeSpan interval = { 10 * 10000000 };
00051   playlistTimer->Interval = interval;
00052   timerTickToken = playlistTimer->Tick += ref new EventHandler<Platform::Object^>(this, &Scenario2::playlistTimer_Tick);
00053
00054   playToManager = PlayToManager::GetForCurrentView();
00055   sourceRequestedToken = playToManager->SourceRequested += ref new TypedEventHandler<PlayToManager^, PlayToSourceRequestedEventArgs^>(this, &Scenario2::playToManager_SourceRequested);
00056   playListPlayNext();
00057 }
00058
00059 void Scenario2::playToManager_SourceRequested(Windows::Media::PlayTo::PlayToManager^ sender, Windows::Media::PlayTo::PlayToSourceRequestedEventArgs^ e)
00060 {
00061   auto deferral = e->SourceRequest->GetDeferral();
00062
00063   Windows::UI::Core::DispatchedHandler^ handler = ref new Windows::UI::Core::DispatchedHandler([=] (){
00064
00065     e->SourceRequest->SetSource(ImageSource->PlayToSource);
00066     deferral->Complete();
00067
00068   }, Platform::CallbackContext::Any);
00069
00070   auto action = dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, handler);
00071 }
00072
00073 void Scenario2::playlistTimer_Tick(Platform::Object^ sender, Platform::Object^ e)
00074 {
00075     if (Playlist != nullptr)
00076     {
00077         playListPlayNext();
00078     }
00079 }
00080
00081 void Scenario2::OnNavigatedFrom(NavigationEventArgs^ e)
00082 {
00083   playToManager->SourceRequested -= sourceRequestedToken;
00084   playlistTimer->Tick -= timerTickToken;
00085 }
00086
00087 void Scenario2::playSlideshow_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00088 {
00089     Button^ b = safe_cast<Button^>(sender);
00090     if (b != nullptr)
00091     {
00092     playlistTimer->Start();
00093         rootPage->NotifyUser("Playlist playing", NotifyType::StatusMessage);
00094     }
00095 }
00096
00097
00098 void Scenario2::pauseSlideshow_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00099 {
00100     Button^ b = safe_cast<Button^>(sender);
00101     if (b != nullptr)
00102     {
00103     playlistTimer->Stop();
00104         rootPage->NotifyUser("Playlist paused", NotifyType::StatusMessage);
00105     }
00106 }
00107
00108
00109 void Scenario2::previousItem_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00110 {
00111     Button^ b = safe_cast<Button^>(sender);
00112     if (b != nullptr)
00113     {
00114     Playlist->SelectedIndex = (Playlist->SelectedIndex - 1 >= 0) ? Playlist->SelectedIndex - 1 : Playlist->Items->Size - 1;
00115         rootPage->NotifyUser("Previous item selected in the list", NotifyType::StatusMessage);
00116     }
00117 }
00118
00119
00120 void Scenario2::nextItem_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00121 {
00122     Button^ b = safe_cast<Button^>(sender);
00123     if (b != nullptr)
00124     {
00125     playListPlayNext();
00126         rootPage->NotifyUser("Next item selected in the list", NotifyType::StatusMessage);
00127     }
00128 }
00129
00130 void Scenario2::playListPlayNext()
00131 {
00132     if (Playlist != nullptr)
00133     {
00134     Playlist->SelectedIndex = (Playlist->SelectedIndex + 1 < (int)Playlist->Items->Size) ? Playlist->SelectedIndex + 1 : 0;
00135     }
00136 }
00137
00138 void Scenario2::Playlist_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e)
00139 {
00140   if (Playlist != nullptr)
00141     {
00142     ListBoxItem^ selectedItem = dynamic_cast<ListBoxItem^>(Playlist->SelectedItem);
00143     ImageSource->Source = ref new BitmapImage(ref new Uri("ms-appx:///Assets/" + selectedItem->Content->ToString()));
00144     rootPage->NotifyUser(selectedItem->Content->ToString() + " selected from the list", NotifyType::StatusMessage);
00145     }
00146 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Connecting with WebSockets/C++/App.xaml.h Source File

  • Connecting with WebSockets

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Contact Picker app/C++/ContactPickerPage.xaml.cpp Source File

  • Contact Picker app

ContactPickerPage.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 // ContactPickerPage.xaml.cpp
00013 // Implementation of the ContactPickerPage class
00014 //
00015
00016 #include "pch.h"
00017 #include "ContactPickerPage.xaml.h"
00018 #include "MainPagePicker.xaml.h"
00019
00020 using namespace ContactPicker;
00021
00022 using namespace Platform;
00023 using namespace Windows::ApplicationModel::Contacts;
00024 using namespace Windows::ApplicationModel::Contacts::Provider;
00025 using namespace Windows::Foundation;
00026 using namespace Windows::UI::Xaml::Navigation;
00027 using namespace Windows::UI::Xaml::Controls;
00028
00029 ContactPickerPage::ContactPickerPage()
00030 {
00031     InitializeComponent();
00032     contactPickerUI = MainPagePicker::Current->contactPickerUI;
00033
00034     for each (SampleContact contact in contactSet)
00035     {
00036         ListBoxItem^ item = ref new ListBoxItem();
00037         item->Name = contact.Id;
00038         item->Content = contact.Name;
00039         item->Tag = contact;
00040         ContactList->Items->Append(item);
00041     }
00042 }
00043
00044 void ContactPickerPage::OnNavigatedTo(NavigationEventArgs^ e)
00045 {
00046     token = contactPickerUI->ContactRemoved += ref new TypedEventHandler<ContactPickerUI^, ContactRemovedEventArgs^>(this, &ContactPickerPage::OnContactRemoved, CallbackContext::Same);
00047 }
00048
00049 void ContactPickerPage::OnNavigatedFrom(NavigationEventArgs^ e)
00050 {
00051     contactPickerUI->ContactRemoved -= token;
00052 }
00053
00054 void ContactPickerPage::OnContactRemoved(ContactPickerUI^ sender, ContactRemovedEventArgs^ e)
00055 {
00056     for (unsigned int i = 0; i < ContactList->SelectedItems->Size; i++)
00057     {
00058         SampleContact contact = ResolveSampleContact(ContactList->SelectedItems->GetAt(i));
00059         if (e->Id == contact.Id)
00060         {
00061             ContactList->SelectedItems->RemoveAt(i);
00062             OutputText->Text += "\n" + contact.Name + " was removed from the basket";
00063             break;
00064         }
00065     }
00066 }
00067
00068 void ContactPickerPage::ContactList_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00069 {
00070     for each (Object^ added in e->AddedItems)
00071     {
00072         AddSampleContact(ResolveSampleContact(added));
00073     }
00074
00075     for each (Object^ removed in e->RemovedItems)
00076     {
00077         SampleContact contact = ResolveSampleContact(removed);
00078         if (contactPickerUI->ContainsContact(contact.Id))
00079         {
00080             contactPickerUI->RemoveContact(contact.Id);
00081             OutputText->Text = contact.Name + " was removed from the basket";
00082         }
00083     }
00084 }
00085
00086 void AppendValue(Contact^ contact, String^ value, ContactFieldType type, ContactFieldCategory category)
00087 {
00088     if (!value->IsEmpty())
00089     {
00090         contact->Fields->Append(ref new ContactField(value, type, category));
00091     }
00092 }
00093
00094 void ContactPickerPage::AddSampleContact(ContactPickerPage::SampleContact sampleContact)
00095 {
00096     Contact^ contact = ref new Contact();
00097     contact->Name = sampleContact.Name;
00098
00099     AppendValue(contact, sampleContact.HomeEmail, ContactFieldType::Email, ContactFieldCategory::Home);
00100     AppendValue(contact, sampleContact.WorkEmail, ContactFieldType::Email, ContactFieldCategory::Work);
00101
00102     AppendValue(contact, sampleContact.HomePhone, ContactFieldType::PhoneNumber, ContactFieldCategory::Home);
00103     AppendValue(contact, sampleContact.MobilePhone, ContactFieldType::PhoneNumber, ContactFieldCategory::Mobile);
00104     AppendValue(contact, sampleContact.WorkPhone, ContactFieldType::PhoneNumber, ContactFieldCategory::Work);
00105
00106     if (!sampleContact.Address->IsEmpty())
00107     {
00108         contact->Fields->Append(ref new ContactLocationField(sampleContact.Address, ContactFieldCategory::None,
00109             sampleContact.Street, sampleContact.City, sampleContact.State, "", sampleContact.ZipCode));
00110     }
00111
00112     switch (contactPickerUI->AddContact(sampleContact.Id, contact))
00113     {
00114         case AddContactResult::Added:
00115             // Notify the user that the contact was added
00116             OutputText->Text = sampleContact.Name + " was added to the basket";
00117             break;
00118         case AddContactResult::AlreadyAdded:
00119             // Notify the user that the contact is already added
00120             OutputText->Text = sampleContact.Name + " is already in the basket";
00121             break;
00122         case AddContactResult::Unavailable:
00123         default:
00124             // Notify the user that the basket is unavailable
00125             OutputText->Text = sampleContact.Name + " could not be added to the basket";
00126             break;
00127     }
00128 }
00129
00130 ContactPickerPage::SampleContact ContactPickerPage::ResolveSampleContact(Object^ listBoxItem)
00131 {
00132     return safe_cast<SampleContact>(safe_cast<ListBoxItem^>(listBoxItem)->Tag);
00133 }
00134
00135 // Sample set of contacts to pick from
00136 Array<ContactPickerPage::SampleContact>^ ContactPickerPage::contactSet = ref new Array<ContactPickerPage::SampleContact>
00137 {
00138     {
00139         /*Name*/ "David Jaffe",
00140         /*HomeEmail*/ "david@contoso.com",
00141         /*WorkEmail*/ "david@cpandl.com",
00142         /*HomePhone*/ "248-555-0150",
00143         /*WorkPhone*/ "",
00144         /*MobilePhone*/ "",
00145         /*Address*/ "3456 Broadway Ln, Los Angeles, CA",
00146         /*Street*/ "",
00147         /*City*/ "",
00148         /*State*/ "",
00149         /*ZipCode*/ "",
00150         /*Id*/ "761cb6fb-0270-451e-8725-bb575eeb24d5"
00151     },
00152
00153     {
00154         /*Name*/ "Kim Abercrombie",
00155         /*HomeEmail*/ "kim@contoso.com",
00156         /*WorkEmail*/ "kim@adatum.com",
00157         /*HomePhone*/ "444 555-0001",
00158         /*WorkPhone*/ "245 555-0123",
00159         /*MobilePhone*/ "921 555-0187",
00160         /*Address*/ "123 Main St, Redmond, WA 23456",
00161         /*Street*/ "123 Main St",
00162         /*City*/ "Redmond",
00163         /*State*/ "WA",
00164         /*ZipCode*/ "23456",
00165         /*Id*/ "49b0652e-8f39-48c5-853b-e5e94e6b8a11"
00166     },
00167
00168     {
00169         /*Name*/ "Jeff Phillips",
00170         /*HomeEmail*/ "jeff@contoso.com",
00171         /*WorkEmail*/ "jeff@fabrikam.com",
00172         /*HomePhone*/ "987-555-0199",
00173         /*WorkPhone*/ "",
00174         /*MobilePhone*/ "543-555-0111",
00175         /*Address*/ "456 2nd Ave, Dallas, TX 12345",
00176         /*Street*/ "456 2nd Ave",
00177         /*City*/ "Dallas",
00178         /*State*/ "TX",
00179         /*ZipCode*/ "12345",
00180         /*Id*/ "864abfb4-8998-4355-8236-8d69e47ec832"
00181     },
00182
00183     {
00184         /*Name*/ "Arlene Huff",
00185         /*HomeEmail*/ "arlene@contoso.com",
00186         /*WorkEmail*/ "",
00187         /*HomePhone*/ "",
00188         /*WorkPhone*/ "",
00189         /*MobilePhone*/ "234-555-0156",
00190         /*Address*/ "",
00191         /*Street*/ "",
00192         /*City*/ "",
00193         /*State*/ "",
00194         /*ZipCode*/ "",
00195         /*Id*/ "27347af8-0e92-45b8-b14c-dd70fcd3b4a6"
00196     },
00197
00198     {
00199         /*Name*/ "Miles Reid",
00200         /*HomeEmail*/ "miles@contoso.com",
00201         /*WorkEmail*/ "miles@proseware.com",
00202         /*HomePhone*/ "",
00203         /*WorkPhone*/ "",
00204         /*MobilePhone*/ "",
00205         /*Address*/ "678 Elm St, New York, New York 95111",
00206         /*Street*/ "678 Elm St",
00207         /*City*/ "New York",
00208         /*State*/ "New York",
00209         /*ZipCode*/ "95111",
00210         /*Id*/ "e3d24a99-0e29-41af-9add-18f5e3cfc518"
00211     }
00212 };
Generated on Sat Nov 23 2024 16:07:59 for Win8-Examples by doxygen 1.7.1


Win8-Examples: HomeGroup app/C++/pch.cpp Source File

  • HomeGroup app

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Toast notifications/C#,C++/ScenarioOutput4.xaml.h Source File

  • Toast notifications
  • C#,C++

ScenarioOutput4.xaml.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 //
00009 // Scenario1Output.xaml.h
00010 // Declaration of the Scenario1Output class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioOutput4.g.h"
00017 #include "MainPage.xaml.h"
00018
00019 namespace ToastsSampleCPP
00020 {
00021   [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class ScenarioOutput4 sealed
00023     {
00024     public:
00025         ScenarioOutput4();
00026
00027     protected:
00028         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030
00031     private:
00032         ~ScenarioOutput4();
00033
00034     MainPage^ rootPage;
00035         void rootPage_InputFrameLoaded(Object^ sender, Object^ e);
00036         Windows::Foundation::EventRegistrationToken _frameLoadedToken;
00037     };
00038 }
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Language font mapping/C++/pch.h Source File

  • Language font mapping

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 //
00009 // pch.h
00010 // Header for standard system include files.
00011 //
00012
00013 #pragma once
00014 #define USE_PPLTASKS
00015 #include "CppSamplesUtils.h"
00016 #include <ppltasks.h>
00017
00018 #include "LocalCache.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: EAS policies for mail clients/C++/App.xaml.h Source File

  • EAS policies for mail clients

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/PersistentState.cpp Source File

  • XAML DirectX 3D shooting game

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 Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML AppBar control/C++/Page3.xaml.cpp Source File

  • XAML AppBar control

Page3.xaml.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // Page3.xaml.cpp
00003 // Implementation of the Page3 class
00004 //
00005
00006 #include "pch.h"
00007 #include "Page3.xaml.h"
00008 #include "App.xaml.h"
00009
00010 using namespace AppBarControl;
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
00023 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00024 MainPage^ Page3::rootPage = nullptr;
00025
00026 Page3::Page3()
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 Page3::OnNavigatedTo(NavigationEventArgs^ e)
00037 {
00038   rootPage = (MainPage^)e->Parameter;
00039   BottomAppBar->IsOpen = true;
00040 }
00041
00042 void Page3::Back_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00043 {
00044   rootPage->Frame->GoBack();
00045 }
00046
00047 void Page3::RemoveSaveButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00048 {
00049   if (Save != nullptr)
00050   {
00051     unsigned int index;
00052     LeftPanel->Children->IndexOf(Save, &index);
00053     LeftPanel->Children->RemoveAt(index);
00054   }
00055 }
00056
00057 void Page3::AddFavoriteButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00058 {
00059   Button^ favButton = ref new Button();
00060   favButton->Style = safe_cast<Windows::UI::Xaml::Style^>(App::Current->Resources->Lookup("FavoriteAppBarButtonStyle"));
00061   LeftPanel->Children->InsertAt(2, favButton);
00062 }
Generated on Sat Nov 23 2024 16:08:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML images/C++/Constants.cpp Source File

  • XAML images

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully qualified name for the class that implements the scenario" }
00021     { "Displaying images", "SDKSample.Images.Scenario1" },
00022     { "Images from a file stream", "SDKSample.Images.Scenario2" },
00023     { "Displaying a NineGrid image", "SDKSample.Images.Scenario3" }
00024 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XInput game controller/C++/pch.h Source File

  • XInput game controller

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 <d3d11_1.h>
00012 #include <d2d1_1.h>
00013 #include <d2d1effects.h>
00014 #include <dwrite_1.h>
00015 #include <wincodec.h>
00016 #include <XInput.h>
00017 #include <stdio.h>
00018 #include <agile.h>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

IMft0Vtbl Member List

This is the complete list of members for IMft0Vtbl, including all inherited members.
HRESULT(STDMETHODCALLTYPE *QueryInterface)(__RPC__in IMft0 *This | IMft0Vtbl
HRESULT(STDMETHODCALLTYPE *UpdateDsp)(__RPC__in IMft0 *This | IMft0Vtbl
HRESULT(STDMETHODCALLTYPE *Enable)(__RPC__in IMft0 *This) | IMft0Vtbl
HRESULT(STDMETHODCALLTYPE *Disable)(__RPC__in IMft0 *This) | IMft0Vtbl
HRESULT(STDMETHODCALLTYPE *GetDspSetting)(__RPC__in IMft0 *This | IMft0Vtbl
HRESULT(STDMETHODCALLTYPE *QueryInterface)(__RPC__in IMft0 *This | IMft0Vtbl
HRESULT(STDMETHODCALLTYPE *UpdateDsp)(__RPC__in IMft0 *This | IMft0Vtbl
HRESULT(STDMETHODCALLTYPE *Enable)(__RPC__in IMft0 *This) | IMft0Vtbl
HRESULT(STDMETHODCALLTYPE *Disable)(__RPC__in IMft0 *This) | IMft0Vtbl
HRESULT(STDMETHODCALLTYPE *GetDspSetting)(__RPC__in IMft0 *This | IMft0Vtbl
pIsEnabled | IMft0Vtbl
ppvObject | IMft0Vtbl
puiPercentOfScreen | IMft0Vtbl
riid | IMft0Vtbl
uiPercentOfScreen | IMft0Vtbl
ULONG(STDMETHODCALLTYPE *AddRef)(__RPC__in IMft0 *This) | IMft0Vtbl
ULONG(STDMETHODCALLTYPE *Release)(__RPC__in IMft0 *This) | IMft0Vtbl
ULONG(STDMETHODCALLTYPE *AddRef)(__RPC__in IMft0 *This) | IMft0Vtbl
ULONG(STDMETHODCALLTYPE *Release)(__RPC__in IMft0 *This) | IMft0Vtbl
Generated on Sat Nov 23 2024 16:09:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

StereoSimpleD3D Member List

This is the complete list of members for StereoSimpleD3D, including all inherited members.
__pad0__ | StereoSimpleD3D |
CreateDeviceIndependentResources() override | StereoSimpleD3D | [virtual]
CreateDeviceResources() override | StereoSimpleD3D | [virtual]
CreateWindowSizeDependentResources() override | StereoSimpleD3D | [virtual]
GetStereoExaggeration() | StereoSimpleD3D |
m_brush | StereoSimpleD3D | [private]
m_constantBuffer | StereoSimpleD3D | [private]
m_constantBufferData | StereoSimpleD3D | [private]
m_farZ | StereoSimpleD3D | [private]
m_heightInInches | StereoSimpleD3D | [private]
m_hintMessage | StereoSimpleD3D | [private]
m_indexBuffer | StereoSimpleD3D | [private]
m_indexCount | StereoSimpleD3D | [private]
m_inputLayout | StereoSimpleD3D | [private]
m_nearZ | StereoSimpleD3D | [private]
m_pixelShader | StereoSimpleD3D | [private]
m_projAspect | StereoSimpleD3D | [private]
m_sampleOverlay | StereoSimpleD3D | [private]
m_sampler | StereoSimpleD3D | [private]
m_stereoExaggerationFactor | StereoSimpleD3D | [private]
m_textFormat | StereoSimpleD3D | [private]
m_textureShaderResourceView | StereoSimpleD3D | [private]
m_vertexBuffer | StereoSimpleD3D | [private]
m_vertexShader | StereoSimpleD3D | [private]
m_widthInInches | StereoSimpleD3D | [private]
m_worldScale | StereoSimpleD3D | [private]
Render() override | StereoSimpleD3D | [virtual]
RenderEye(_In_ unsigned int eyeIndex) | StereoSimpleD3D |
SetStereoExaggeration(_In_ float currentExaggeration) | StereoSimpleD3D |
Update(_In_ unsigned int eyeIndex, _In_ float timeTotal, _In_ float timeDelta) | StereoSimpleD3D |
Generated on Sat Nov 23 2024 16:09:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Geolocation/C++/backgroundtask/pch.h Source File

  • Geolocation
  • 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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017 #include <ppltasks.h>
00018 #include <agile.h>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application data/C++/DataChangedEvent.xaml.cpp Source File

  • Application data

DataChangedEvent.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 // DataChangedEvent.xaml.cpp
00013 // Implementation of the DataChangedEvent class
00014 //
00015
00016 #include "pch.h"
00017 #include "DataChangedEvent.xaml.h"
00018
00019 using namespace SDKSample::ApplicationDataSample;
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::UI::Core;
00027 using namespace Windows::Storage;
00028
00029 #define settingName "userName"
00030
00031 DataChangedEvent::DataChangedEvent()
00032 {
00033     InitializeComponent();
00034
00035     applicationData = ApplicationData::Current;
00036     applicationData->DataChanged += ref new TypedEventHandler<ApplicationData^, Object^>(this, &DataChangedEvent::DataChangedHandler);
00037
00038     DisplayOutput();
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 DataChangedEvent::OnNavigatedTo(NavigationEventArgs^ e)
00047 {
00048     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00049     // as NotifyUser()
00050     rootPage = MainPage::Current;
00051 }
00052
00053 void DataChangedEvent::SimulateRoaming_Click(Object^ sender, RoutedEventArgs^ e)
00054 {
00055     applicationData->RoamingSettings->Values->Insert(settingName, UserName->Text);
00056
00057     // Simulate roaming by intentionally signaling a data changed event.
00058     applicationData->SignalDataChanged();
00059 }
00060
00061 void DataChangedEvent::DataChangedHandler(Windows::Storage::ApplicationData^ appData, Object^)
00062 {
00063     // This event handler may be invoked on another thread, so use the Dispatcher to invoke the UI-related code on the UI thread.
00064     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler(
00065         [this]()
00066         {
00067             DisplayOutput();
00068         }));
00069 }
00070
00071 void DataChangedEvent::DisplayOutput()
00072 {
00073     String^ value = safe_cast<String^>(ApplicationData::Current->RoamingSettings->Values->Lookup(settingName));
00074     OutputTextBlock->Text = "Name: " + (value == nullptr ? "<empty>" : ("\"" + value + "\""));
00075 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text editing/C++/Scenario6.xaml.cpp Source File

  • XAML text editing

Scenario6.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.xaml.cpp
00013 // Implementation of the Scenario6 class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario6.xaml.h"
00018
00019 using namespace SDKSample::TextEditing;
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;
00026 using namespace Windows::UI::Xaml;
00027 using namespace Windows::UI::Text;
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 using namespace Windows::Storage;
00035 using namespace Windows::Storage::Streams ;
00036
00037 Scenario6::Scenario6()
00038 {
00039     InitializeComponent();
00040 }
00041
00042 void Scenario6::BoldButtonClick(Object^ sender, RoutedEventArgs^ e)
00043 {
00044     ITextSelection^ selectedText = editor->Document->Selection;
00045   if (selectedText != nullptr)
00046     {
00047         ITextCharacterFormat^ charFormatting = selectedText->CharacterFormat;
00048         charFormatting->Bold = FormatEffect::Toggle;
00049         selectedText->CharacterFormat = charFormatting;
00050     }
00051 }
00052
00053 void Scenario6::ItalicButtonClick(Object^ sender, RoutedEventArgs^ e)
00054 {
00055     ITextSelection^ selectedText = editor->Document->Selection;
00056     if (selectedText != nullptr)
00057     {
00058         ITextCharacterFormat^ charFormatting = selectedText->CharacterFormat;
00059         charFormatting->Italic = FormatEffect::Toggle;
00060         selectedText->CharacterFormat = charFormatting;
00061     }
00062 }
00063
00064 void Scenario6::FontColorButtonClick(Object^ sender, RoutedEventArgs^ e)
00065 {
00066     fontColorPopup->IsOpen = true;
00067     fontColorButton->Focus(Windows::UI::Xaml::FocusState::Keyboard);
00068 }
00069
00070 void Scenario6::FindBoxTextChanged(Object^ sender, TextChangedEventArgs^ e)
00071 {
00072     String^ textToFind = findBox->Text;
00073
00074   if (textToFind != "")
00075         FindAndHighlightText(textToFind);
00076 }
00077
00078 void Scenario6::FontColorButtonLostFocus(Object^ sender, RoutedEventArgs^ e)
00079 {
00080     fontColorPopup->IsOpen = false;
00081 }
00082
00083 void Scenario6::FindBoxLostFocus(Object^ sender, RoutedEventArgs^ e)
00084 {
00085     ClearAllHighlightedWords();
00086 }
00087
00088 void Scenario6::FindBoxGotFocus(Object^ sender, RoutedEventArgs^ e)
00089 {
00090     String^ textToFind = findBox->Text;
00091
00092   if (textToFind != "")
00093         FindAndHighlightText(textToFind);
00094 }
00095
00096 void Scenario6::ClearAllHighlightedWords()
00097 {
00098     ITextCharacterFormat^ charFormat;
00099     for (unsigned int i = 0; i < m_highlightedWords.size() ; i++)
00100     {
00101         charFormat = m_highlightedWords[i]->CharacterFormat;
00102         charFormat->BackgroundColor = Colors::Transparent;
00103         m_highlightedWords[i]->CharacterFormat = charFormat;
00104     }
00105
00106     m_highlightedWords.clear();
00107 }
00108
00109 void Scenario6::FindAndHighlightText(String^ textToFind)
00110 {
00111     ClearAllHighlightedWords();
00112
00113     ITextRange^ searchRange = editor->Document->GetRange(0, 1000000000);
00114   searchRange->Move(TextRangeUnit::Character,0) ;
00115
00116     bool textFound = true;
00117     do
00118     {
00119         if (searchRange->FindText(textToFind, 1000000000, FindOptions::None) < 1)
00120             textFound = false;
00121         else
00122         {
00123             m_highlightedWords.push_back(searchRange->GetClone());
00124
00125             ITextCharacterFormat^ charFormatting = searchRange->CharacterFormat;
00126             charFormatting->BackgroundColor = Colors::Yellow;
00127             searchRange->CharacterFormat = charFormatting;
00128         }
00129     } while (textFound);
00130 }
00131
00132 void Scenario6::ColorButtonClick(Object^ sender, RoutedEventArgs^ e)
00133 {
00134   Button^ clickedColor = dynamic_cast<Button^>(sender);
00135
00136     ITextCharacterFormat^ charFormatting = editor->Document->Selection-> CharacterFormat;
00137     if(clickedColor->Name == "black")
00138     charFormatting->ForegroundColor = Colors::Black;
00139   else
00140     if(clickedColor->Name == "gray")
00141       charFormatting->ForegroundColor = Colors::Gray;
00142     else
00143       if(clickedColor->Name == "darkgreen")
00144         charFormatting->ForegroundColor = Colors::DarkGreen;
00145       else
00146         if(clickedColor->Name == "green")
00147           charFormatting->ForegroundColor = Colors::Green;
00148         else
00149           if(clickedColor->Name == "blue")
00150             charFormatting->ForegroundColor = Colors::Blue;
00151
00152     editor->Document->Selection->CharacterFormat = charFormatting;
00153
00154     editor->Focus(Windows::UI::Xaml::FocusState::Keyboard);
00155     fontColorPopup->IsOpen = false;
00156 }
00157
00158 void Scenario6::LoadContentAsync()
00159 {
00160   IAsyncOperation<StorageFile^>^ getFileResult = Windows::ApplicationModel::Package::Current->InstalledLocation->GetFileAsync("lorem.rtf");
00161   StorageFile^ file = getFileResult->GetResults() ;
00162
00163   IAsyncOperation<IRandomAccessStream^>^ openFileResults = file->OpenAsync(FileAccessMode::Read) ;
00164   IRandomAccessStream^ randAccStream = openFileResults->GetResults() ;
00165
00166     editor->Document->LoadFromStream(TextSetOptions::FormatRtf, randAccStream);
00167 }
00168
00169 /// <summary>
00170 /// Invoked when this page is about to be displayed in a Frame.
00171 /// </summary>
00172 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00173 /// property is typically used to configure the page.</param>
00174 void Scenario6::OnNavigatedTo(NavigationEventArgs^ e)
00175 {
00176     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00177     // as NotifyUser()
00178     rootPage = MainPage::Current;
00179 }
00180
00181 void SDKSample::TextEditing::Scenario6::Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00182 {
00183     Button^ b = safe_cast<Button^>(sender);
00184     if (b != nullptr)
00185     {
00186         rootPage->NotifyUser("You clicked the " + b->Name + " button", NotifyType::StatusMessage);
00187     }
00188 }
00189
00190 void SDKSample::TextEditing::Scenario6::Other_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00191 {
00192     Button^ b = safe_cast<Button^>(sender);
00193     if (b != nullptr)
00194     {
00195         rootPage->NotifyUser("You clicked the " + b->Name + " button", NotifyType::StatusMessage);
00196     }
00197 }
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D bump mapping/C++/BasicTimer.cpp Source File

  • Direct3D bump mapping

BasicTimer.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 "BasicTimer.h"
00010
00011 BasicTimer::BasicTimer()
00012 {
00013     if (!QueryPerformanceFrequency(&m_frequency))
00014     {
00015         throw ref new Platform::FailureException();
00016     }
00017     Reset();
00018 }
00019
00020 void BasicTimer::Reset()
00021 {
00022     Update();
00023     m_startTime = m_currentTime;
00024     m_total = 0.0f;
00025     m_delta = 1.0f / 60.0f;
00026 }
00027
00028 void BasicTimer::Update()
00029 {
00030     if (!QueryPerformanceCounter(&m_currentTime))
00031     {
00032         throw ref new Platform::FailureException();
00033     }
00034
00035     m_total = static_cast<float>(
00036         static_cast<double>(m_currentTime.QuadPart-m_startTime.QuadPart) /
00037         static_cast<double>(m_frequency.QuadPart)
00038         );
00039
00040     if (m_lastTime.QuadPart == m_startTime.QuadPart)
00041     {
00042         // If the timer was just reset, report a time delta equivalent to 60Hz frame time.
00043         m_delta = 1.0f / 60.0f;
00044     }
00045     else
00046     {
00047         m_delta = static_cast<float>(
00048             static_cast<double>(m_currentTime.QuadPart-m_lastTime.QuadPart) /
00049             static_cast<double>(m_frequency.QuadPart)
00050             );
00051     }
00052
00053     m_lastTime = m_currentTime;
00054 }
00055
00056 float BasicTimer::Total::get()
00057 {
00058     return m_total;
00059 }
00060
00061 float BasicTimer::Delta::get()
00062 {
00063     return m_delta;
00064 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: SMS background task/C++/SmsBackgroundTask/pch.h Source File

  • SMS background task
  • SmsBackgroundTask

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
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML FlipView control/C++/pch.h Source File

  • XAML FlipView control

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/GameHud.cpp Source File

  • XAML DirectX 3D shooting game

GameHud.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 "GameHud.h"
00010 #include "GameConstants.h"
00011
00012 using namespace Microsoft::WRL;
00013 using namespace Windows::UI::Core;
00014 using namespace Windows::ApplicationModel;
00015 using namespace Windows::Foundation;
00016 using namespace Windows::Storage;
00017 using namespace Windows::UI::ViewManagement;
00018 using namespace Windows::Graphics::Display;
00019 using namespace D2D1;
00020
00021 //----------------------------------------------------------------------
00022
00023 GameHud::GameHud(
00024     _In_ Platform::String^ titleHeader,
00025     _In_ Platform::String^ titleBody,
00026     _In_ Platform::String^ titleLicenseInfo
00027     )
00028 {
00029     m_titleHeader = titleHeader;
00030     m_titleBody = titleBody;
00031     m_titleLicenseInfo = titleLicenseInfo;
00032
00033     m_showTitle = true;
00034     m_titleBodyVerticalOffset = GameConstants::Margin;
00035     m_logoSize = D2D1::SizeF(0.0f, 0.0f);
00036 }
00037
00038 //----------------------------------------------------------------------
00039
00040 void GameHud::CreateDeviceIndependentResources(
00041     _In_ IDWriteFactory* dwriteFactory,
00042     _In_ IWICImagingFactory* wicFactory
00043     )
00044 {
00045     m_dwriteFactory = dwriteFactory;
00046     m_wicFactory = wicFactory;
00047
00048     DX::ThrowIfFailed(
00049         m_dwriteFactory->CreateTextFormat(
00050             L"Segoe UI",
00051             nullptr,
00052             DWRITE_FONT_WEIGHT_LIGHT,
00053             DWRITE_FONT_STYLE_NORMAL,
00054             DWRITE_FONT_STRETCH_NORMAL,
00055             GameConstants::HudBodyPointSize,
00056             L"en-us",
00057             &m_textFormatBody
00058             )
00059         );
00060     DX::ThrowIfFailed(
00061         m_dwriteFactory->CreateTextFormat(
00062             L"Segoe UI Symbol",
00063             nullptr,
00064             DWRITE_FONT_WEIGHT_LIGHT,
00065             DWRITE_FONT_STYLE_NORMAL,
00066             DWRITE_FONT_STRETCH_NORMAL,
00067             GameConstants::HudBodyPointSize,
00068             L"en-us",
00069             &m_textFormatBodySymbol
00070             )
00071         );
00072     DX::ThrowIfFailed(
00073         m_dwriteFactory->CreateTextFormat(
00074             L"Segoe UI Light",
00075             nullptr,
00076             DWRITE_FONT_WEIGHT_LIGHT,
00077             DWRITE_FONT_STYLE_NORMAL,
00078             DWRITE_FONT_STRETCH_NORMAL,
00079             GameConstants::HudTitleHeaderPointSize,
00080             L"en-us",
00081             &m_textFormatTitleHeader
00082             )
00083         );
00084     DX::ThrowIfFailed(
00085         m_dwriteFactory->CreateTextFormat(
00086             L"Segoe UI Light",
00087             nullptr,
00088             DWRITE_FONT_WEIGHT_LIGHT,
00089             DWRITE_FONT_STYLE_NORMAL,
00090             DWRITE_FONT_STRETCH_NORMAL,
00091             GameConstants::HudTitleBodyPointSize,
00092             L"en-us",
00093             &m_textFormatTitleBody
00094             )
00095         );
00096     DX::ThrowIfFailed(
00097         m_dwriteFactory->CreateTextFormat(
00098             L"Segoe UI Bold",
00099             nullptr,
00100             DWRITE_FONT_WEIGHT_BOLD,
00101             DWRITE_FONT_STYLE_NORMAL,
00102             DWRITE_FONT_STRETCH_NORMAL,
00103             GameConstants::HudLicensePointSize,
00104             L"en-us",
00105             &m_textFormatTitleLicense
00106             )
00107         );
00108
00109     DX::ThrowIfFailed(m_textFormatBody->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING));
00110     DX::ThrowIfFailed(m_textFormatBody->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR));
00111     DX::ThrowIfFailed(m_textFormatBodySymbol->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING));
00112     DX::ThrowIfFailed(m_textFormatBodySymbol->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR));
00113     DX::ThrowIfFailed(m_textFormatTitleHeader->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING));
00114     DX::ThrowIfFailed(m_textFormatTitleHeader->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR));
00115     DX::ThrowIfFailed(m_textFormatTitleBody->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING));
00116     DX::ThrowIfFailed(m_textFormatTitleBody->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR));
00117     DX::ThrowIfFailed(m_textFormatTitleLicense->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING));
00118     DX::ThrowIfFailed(m_textFormatTitleLicense->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR));
00119 }
00120
00121 //----------------------------------------------------------------------
00122
00123 void GameHud::CreateDeviceResources(_In_ ID2D1DeviceContext* d2dContext)
00124 {
00125     auto location = Package::Current->InstalledLocation;
00126     Platform::String^ path = Platform::String::Concat(location->Path, "\\");
00127     path = Platform::String::Concat(path, "windows-sdk.png");
00128
00129     ComPtr<IWICBitmapDecoder> wicBitmapDecoder;
00130     DX::ThrowIfFailed(
00131         m_wicFactory->CreateDecoderFromFilename(
00132             path->Data(),
00133             nullptr,
00134             GENERIC_READ,
00135             WICDecodeMetadataCacheOnDemand,
00136             &wicBitmapDecoder
00137             )
00138         );
00139
00140     ComPtr<IWICBitmapFrameDecode> wicBitmapFrame;
00141     DX::ThrowIfFailed(
00142         wicBitmapDecoder->GetFrame(0, &wicBitmapFrame)
00143         );
00144
00145     ComPtr<IWICFormatConverter> wicFormatConverter;
00146     DX::ThrowIfFailed(
00147         m_wicFactory->CreateFormatConverter(&wicFormatConverter)
00148         );
00149
00150     DX::ThrowIfFailed(
00151         wicFormatConverter->Initialize(
00152             wicBitmapFrame.Get(),
00153             GUID_WICPixelFormat32bppPBGRA,
00154             WICBitmapDitherTypeNone,
00155             nullptr,
00156             0.0,
00157             WICBitmapPaletteTypeCustom  // The BGRA format has no palette so this value is ignored.
00158             )
00159         );
00160
00161     double dpiX = 96.0f;
00162     double dpiY = 96.0f;
00163     DX::ThrowIfFailed(
00164         wicFormatConverter->GetResolution(&dpiX, &dpiY)
00165         );
00166
00167     // Create D2D Resources
00168     DX::ThrowIfFailed(
00169         d2dContext->CreateBitmapFromWicBitmap(
00170             wicFormatConverter.Get(),
00171             BitmapProperties(
00172                 PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00173                 static_cast<float>(dpiX),
00174                 static_cast<float>(dpiY)
00175                 ),
00176             &m_logoBitmap
00177             )
00178         );
00179
00180     m_logoSize = m_logoBitmap->GetSize();
00181
00182     DX::ThrowIfFailed(
00183         d2dContext->CreateSolidColorBrush(
00184             D2D1::ColorF(D2D1::ColorF::White),
00185             &m_textBrush
00186             )
00187         );
00188     DX::ThrowIfFailed(
00189         d2dContext->CreateSolidColorBrush(
00190             D2D1::ColorF(0xaaaaaa, 1.0f),
00191             &m_textBrushGrey
00192             )
00193         );
00194 }
00195
00196 //----------------------------------------------------------------------
00197
00198 void GameHud::UpdateForWindowSizeChange(_In_ Windows::Foundation::Rect windowBounds)
00199 {
00200     m_maxTitleSize.width = windowBounds.Width - GameConstants::HudSafeWidth;
00201     m_maxTitleSize.height = windowBounds.Height;
00202
00203     float headerWidth = m_maxTitleSize.width - (m_logoSize.width + 2 * GameConstants::Margin);
00204
00205     if (headerWidth > 0)
00206     {
00207         // Only resize the text layout for the Title area when there is enough space.
00208         m_showTitle = true;
00209
00210         DX::ThrowIfFailed(
00211             m_dwriteFactory->CreateTextLayout(
00212                 m_titleHeader->Data(),
00213                 m_titleHeader->Length(),
00214                 m_textFormatTitleHeader.Get(),
00215                 headerWidth,
00216                 m_maxTitleSize.height,
00217                 &m_titleHeaderLayout
00218                 )
00219             );
00220
00221         DWRITE_TEXT_METRICS metrics = {0};
00222         DX::ThrowIfFailed(
00223             m_titleHeaderLayout->GetMetrics(&metrics)
00224             );
00225
00226         // Compute the vertical size of the laid out Header and logo.  This could change
00227         // based on the window size and the layout of the text.  In some cases the text
00228         // may wrap.
00229         m_titleBodyVerticalOffset = max(m_logoSize.height + GameConstants::Margin * 2, metrics.height + 2 * GameConstants::Margin);
00230
00231         DX::ThrowIfFailed(
00232             m_dwriteFactory->CreateTextLayout(
00233                 m_titleBody->Data(),
00234                 m_titleBody->Length(),
00235                 m_textFormatTitleBody.Get(),
00236                 m_maxTitleSize.width,
00237                 m_maxTitleSize.height - m_titleBodyVerticalOffset,
00238                 &m_titleBodyLayout
00239                 )
00240             );
00241
00242         DX::ThrowIfFailed(
00243             m_titleBodyLayout->GetMetrics(&metrics)
00244             );
00245
00246         m_titleLicenseVerticalOffset = m_titleBodyVerticalOffset + metrics.height + GameConstants::Margin;
00247
00248         DX::ThrowIfFailed(
00249             m_dwriteFactory->CreateTextLayout(
00250                 m_titleLicenseInfo->Data(),
00251                 m_titleLicenseInfo->Length(),
00252                 m_textFormatTitleLicense.Get(),
00253                 m_maxTitleSize.width,
00254                 m_maxTitleSize.height - m_titleLicenseVerticalOffset,
00255                 &m_titleLicenseInfoLayout
00256                 )
00257             );
00258     }
00259     else
00260     {
00261         // Not enough horizontal space for the titles so just turn it off.
00262         m_showTitle = false;
00263     }
00264 }
00265
00266 //----------------------------------------------------------------------
00267
00268 void GameHud::SetLicenseInfo(_In_ Platform::String^ licenseInfo)
00269 {
00270     m_titleLicenseInfo = licenseInfo;
00271
00272     DX::ThrowIfFailed(
00273         m_dwriteFactory->CreateTextLayout(
00274             m_titleLicenseInfo->Data(),
00275             m_titleLicenseInfo->Length(),
00276             m_textFormatTitleLicense.Get(),
00277             m_maxTitleSize.width,
00278             m_maxTitleSize.height - m_titleLicenseVerticalOffset,
00279             &m_titleLicenseInfoLayout
00280             )
00281         );
00282 }
00283
00284 //----------------------------------------------------------------------
00285
00286 void GameHud::Render(
00287     _In_ Simple3DGame^ game,
00288     _In_ ID2D1DeviceContext* d2dContext,
00289     _In_ Windows::Foundation::Rect windowBounds
00290     )
00291 {
00292     if (m_showTitle)
00293     {
00294         d2dContext->DrawBitmap(
00295             m_logoBitmap.Get(),
00296             D2D1::RectF(
00297                 GameConstants::Margin,
00298                 GameConstants::Margin,
00299                 m_logoSize.width + GameConstants::Margin,
00300                 m_logoSize.height + GameConstants::Margin
00301                 )
00302             );
00303         d2dContext->DrawTextLayout(
00304             Point2F(m_logoSize.width + 2.0f * GameConstants::Margin, GameConstants::Margin),
00305             m_titleHeaderLayout.Get(),
00306             m_textBrush.Get()
00307             );
00308         d2dContext->DrawTextLayout(
00309             Point2F(GameConstants::Margin, m_titleBodyVerticalOffset),
00310             m_titleBodyLayout.Get(),
00311             m_textBrush.Get()
00312             );
00313         d2dContext->DrawTextLayout(
00314             Point2F(GameConstants::Margin, m_titleLicenseVerticalOffset),
00315             m_titleLicenseInfoLayout.Get(),
00316             m_textBrush.Get()
00317             );
00318     }
00319
00320     if (game != nullptr)
00321     {
00322         // This section is only used after the game state has been initialized.
00323         static const int bufferLength = 256;
00324         static char16 wsbuffer[bufferLength];
00325         int length = swprintf_s(
00326             wsbuffer,
00327             bufferLength,
00328             L"Hits:\t%10d\nShots:\t%10d\nTime:\t%8.1f",
00329             game->TotalHits(),
00330             game->TotalShots(),
00331             game->TimeRemaining()
00332             );
00333
00334         d2dContext->DrawText(
00335             wsbuffer,
00336             length,
00337             m_textFormatBody.Get(),
00338             D2D1::RectF(
00339                 windowBounds.Width - GameConstants::HudRightOffset,
00340                 GameConstants::HudTopOffset,
00341                 windowBounds.Width,
00342                 GameConstants::HudTopOffset + (GameConstants::HudBodyPointSize + GameConstants::Margin) * 3
00343                 ),
00344             m_textBrush.Get()
00345             );
00346
00347         // Using the unicode characters starting at 0x2780 ( ➀ ) for the consecutive levels of the game.
00348         // For completed levels start with 0x278A ( ➊ ) (This is 0x2780 + 10).
00349         uint32 levelCharacter[6];
00350         for (uint32 i = 0; i < 6; i++)
00351         {
00352             levelCharacter[i] = 0x2780 + i + ((static_cast<uint32>(game->LevelCompleted()) == i) ? 10 : 0);
00353         }
00354
00355         if (game->IsTrial())
00356         {
00357             length = swprintf_s(
00358                 wsbuffer,
00359                 bufferLength,
00360                 L"%lc %lc",
00361                 levelCharacter[0],
00362                 levelCharacter[1]
00363                 );
00364             d2dContext->DrawText(
00365                 wsbuffer,
00366                 length,
00367                 m_textFormatBodySymbol.Get(),
00368                 D2D1::RectF(
00369                     windowBounds.Width - GameConstants::HudRightOffset,
00370                     GameConstants::HudTopOffset + (GameConstants::HudBodyPointSize + GameConstants::Margin) * 3 + GameConstants::Margin,
00371                     windowBounds.Width,
00372                     GameConstants::HudTopOffset + (GameConstants::HudBodyPointSize+ GameConstants::Margin) * 4
00373                     ),
00374                 m_textBrush.Get()
00375                 );
00376
00377             length = swprintf_s(
00378                 wsbuffer,
00379                 bufferLength,
00380                 L"%lc %lc %lc %lc",
00381                 levelCharacter[2],
00382                 levelCharacter[3],
00383                 levelCharacter[4],
00384                 levelCharacter[5]
00385                 );
00386
00387             d2dContext->DrawText(
00388                 wsbuffer,
00389                 length,
00390                 m_textFormatBodySymbol.Get(),
00391                 D2D1::RectF(
00392                     windowBounds.Width - GameConstants::HudRightOffset + 52.0f,
00393                     GameConstants::HudTopOffset + (GameConstants::HudBodyPointSize + GameConstants::Margin) * 3 + GameConstants::Margin,
00394                     windowBounds.Width,
00395                     GameConstants::HudTopOffset + (GameConstants::HudBodyPointSize+ GameConstants::Margin) * 4
00396                     ),
00397                 m_textBrushGrey.Get()
00398                 );
00399         }
00400         else
00401         {
00402             length = swprintf_s(
00403                 wsbuffer,
00404                 bufferLength,
00405                 L"%lc %lc %lc %lc %lc %lc",
00406                 levelCharacter[0],
00407                 levelCharacter[1],
00408                 levelCharacter[2],
00409                 levelCharacter[3],
00410                 levelCharacter[4],
00411                 levelCharacter[5]
00412                 );
00413             d2dContext->DrawText(
00414                 wsbuffer,
00415                 length,
00416                 m_textFormatBodySymbol.Get(),
00417                 D2D1::RectF(
00418                     windowBounds.Width - GameConstants::HudRightOffset,
00419                     GameConstants::HudTopOffset + (GameConstants::HudBodyPointSize + GameConstants::Margin) * 3 + GameConstants::Margin,
00420                     windowBounds.Width,
00421                     GameConstants::HudTopOffset + (GameConstants::HudBodyPointSize+ GameConstants::Margin) * 4
00422                     ),
00423                 m_textBrush.Get()
00424                 );
00425         }
00426
00427         if (game->IsActivePlay())
00428         {
00429             // Draw a rectangle for the touch input for the move control.
00430             d2dContext->DrawRectangle(
00431                 D2D1::RectF(
00432                     0.0f,
00433                     windowBounds.Height - GameConstants::TouchRectangleSize,
00434                     GameConstants::TouchRectangleSize,
00435                     windowBounds.Height
00436                     ),
00437                 m_textBrush.Get()
00438                 );
00439             // Draw a rectangle for the touch input for the fire control.
00440             d2dContext->DrawRectangle(
00441                 D2D1::RectF(
00442                     windowBounds.Width - GameConstants::TouchRectangleSize,
00443                     windowBounds.Height - GameConstants::TouchRectangleSize,
00444                     windowBounds.Width,
00445                     windowBounds.Height
00446                     ),
00447                 m_textBrush.Get()
00448                 );
00449
00450             // Draw the cross hairs
00451             d2dContext->DrawLine(
00452                 D2D1::Point2F(windowBounds.Width / 2.0f - GameConstants::CrossHairHalfSize, windowBounds.Height / 2.0f),
00453                 D2D1::Point2F(windowBounds.Width / 2.0f + GameConstants::CrossHairHalfSize, windowBounds.Height / 2.0f),
00454                 m_textBrush.Get(),
00455                 3.0f
00456                 );
00457             d2dContext->DrawLine(
00458                 D2D1::Point2F(windowBounds.Width / 2.0f, windowBounds.Height / 2.0f - GameConstants::CrossHairHalfSize),
00459                 D2D1::Point2F(windowBounds.Width / 2.0f, windowBounds.Height / 2.0f + GameConstants::CrossHairHalfSize),
00460                 m_textBrush.Get(),
00461                 3.0f
00462                 );
00463         }
00464     }
00465 }
00466
00467 //----------------------------------------------------------------------
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CryptoWinRT/C++/Constants.cpp Source File

  • CryptoWinRT

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
00021     { "CryptographicBuffer", "SDKSample.CryptoWinRT.Scenario1" },
00022     { "Hash Algorithms", "SDKSample.CryptoWinRT.Scenario2" },
00023     { "Hmac Algorithms", "SDKSample.CryptoWinRT.Scenario3" },
00024     { "Key Derivation", "SDKSample.CryptoWinRT.Scenario4" },
00025     { "Cipher Algorithms", "SDKSample.CryptoWinRT.Scenario5" },
00026     { "Authenticated Encryption Algorithms", "SDKSample.CryptoWinRT.Scenario6" },
00027     { "Encrypt and Decrypt", "SDKSample.CryptoWinRT.Scenario7" },
00028     { "Sign and Verify Signature", "SDKSample.CryptoWinRT.Scenario8" },
00029     { "Asynchronous Data Protection", "SDKSample.CryptoWinRT.Scenario9" },
00030     { "Asynchronous Data Protection with Streams", "SDKSample.CryptoWinRT.Scenario10" }
00031 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Animation metrics/C++/common/LayoutAwarePage.cpp Source File

  • Animation metrics
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:30 for Win8-Examples by doxygen 1.7.1


Win8-Examples: App tiles and badges/C#,C++/SendTextTile.xaml.cpp Source File

  • App tiles and badges
  • C#,C++

SendTextTile.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 // SendTextTile.xaml.cpp
00013 // Implementation of the SendTextTile class
00014 //
00015
00016 #include "pch.h"
00017 #include "SendTextTile.xaml.h"
00018
00019 using namespace SDKSample::Tiles;
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::UI::Notifications;
00025 using namespace NotificationsExtensions::TileContent;
00026
00027 SendTextTile::SendTextTile()
00028 {
00029   InitializeComponent();
00030 }
00031
00032 void SendTextTile::OnNavigatedTo(NavigationEventArgs^ e)
00033 {
00034   rootPage = MainPage::Current;
00035 }
00036
00037 void SendTextTile::UpdateTileWithText_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00038 {
00039   // Note: This sample contains an additional project, NotificationsExtensions.
00040   // NotificationsExtensions exposes an object model for creating notifications, but you can also
00041   // modify the strings directly. See UpdateTileWithTextWithStringManipulation_Click for an example
00042
00043   // create the wide template
00044   auto tileContent = TileContentFactory::CreateTileWideText03();
00045   tileContent->TextHeadingWrap->Text = "Hello World! My very own tile notification";
00046
00047   // Users can resize tiles to square or wide.
00048   // Apps can choose to include only square assets (meaning the app's tile can never be wide), or
00049   // include both wide and square assets (the user can resize the tile to square or wide).
00050   // Apps cannot include only wide assets.
00051
00052   // Apps that support being wide should include square tile notifications since users
00053   // determine the size of the tile.
00054
00055   // create the square template and attach it to the wide template
00056   auto squareContent = TileContentFactory::CreateTileSquareText04();
00057   squareContent->TextBodyWrap->Text = "Hello World! My very own tile notification";
00058   tileContent->SquareContent = squareContent;
00059
00060   // Send the notification to the app's application tile
00061   TileUpdateManager::CreateTileUpdaterForApplication()->Update(tileContent->CreateNotification());
00062
00063   OutputTextBlock->Text = tileContent->GetContent();
00064 }
00065
00066 void SendTextTile::UpdateTileWithTextWithStringManipulation_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00067 {
00068   // create a string with the tile template xml
00069   auto tileXmlString = "<tile>"
00070     + "<visual>"
00071     + "<binding template='TileWideText03'>"
00072     + "<text id='1'>Hello World! My very own tile notification</text>"
00073     + "</binding>"
00074     + "<binding template='TileSquareText04'>"
00075     + "<text id='1'>Hello World! My very own tile notification</text>"
00076     + "</binding>"
00077     + "</visual>"
00078     + "</tile>";
00079
00080   // create a DOM
00081   auto tileDOM = ref new Windows::Data::Xml::Dom::XmlDocument();
00082
00083   // load the xml string into the DOM, catching any invalid xml characters
00084   tileDOM->LoadXml(tileXmlString);
00085
00086   // create a tile notification
00087   auto tile = ref new TileNotification(tileDOM);
00088
00089   // Send the notification to the app's application tile
00090   TileUpdateManager::CreateTileUpdaterForApplication()->Update(tile);
00091
00092   OutputTextBlock->Text = tileDOM->GetXml();
00093 }
00094
00095 void SendTextTile::ClearTile_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00096 {
00097   // A TileUpdater is also used to clear the tile
00098   TileUpdateManager::CreateTileUpdaterForApplication()->Clear();
00099   OutputTextBlock->Text = "Tile cleared";
00100 }
Generated on Sat Nov 23 2024 16:07:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Secondary tiles/C#,C++/App.xaml.h Source File

  • Secondary tiles
  • C#,C++

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SecondaryTiles
00023 {
00024     ref class App sealed
00025     {
00026     public:
00027         App();
00028         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00029         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00030
00031     private:
00032         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00033     };
00034 }
00035
00036
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playback Manager Companion/C++/common/suspensionmanager.cpp Source File

  • Playback Manager Companion
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:37 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application data/C++/MainPage.xaml.cpp Source File

  • Application data

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Thread pool/C++/PeriodicTimerScenario.xaml.h Source File

  • Thread pool

PeriodicTimerScenario.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 // PeriodicTimerScenario.xaml.h
00013 // Declaration of the PeriodicTimerScenario class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Constants.h"
00020 #include "PeriodicTimerScenario.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKSample
00024 {
00025     namespace ThreadPool
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 PeriodicTimerScenario sealed
00032         {
00033         public:
00034             PeriodicTimerScenario();
00035             void UpdateUI(ThreadPool::Status status);
00036
00037         protected:
00038             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00039             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00040         private:
00041             MainPage^ rootPage;
00042             void CreatePeriodicTimer(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00043             void CancelPeriodicTimer(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00044         };
00045     }
00046 }
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

BackgroundTask::sealed Member List

This is the complete list of members for BackgroundTask::sealed, including all inherited members.
geopositionTaskTokenSource | BackgroundTask::sealed | [private]
LocationBackgroundTask() | BackgroundTask::sealed |
OnCanceled(Windows::ApplicationModel::Background::IBackgroundTaskInstance^taskInstance, Windows::ApplicationModel::Background::BackgroundTaskCancellationReason reason) | BackgroundTask::sealed | [private]
Run(Windows::ApplicationModel::Background::IBackgroundTaskInstance^taskInstance) | BackgroundTask::sealed | [virtual]
~LocationBackgroundTask() | BackgroundTask::sealed | [private]
Generated on Sat Nov 23 2024 16:09:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/pch.cpp Source File

  • Media extensions

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 //
00009 // pch.cpp
00010 // Include the standard header and generate the precompiled header.
00011 //
00012
00013 #include "pch.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CryptoWinRT/C++/Scenario5.xaml.cpp Source File

  • CryptoWinRT

Scenario5.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 // Scenario5.xaml.cpp
00013 // Implementation of the Scenario5 class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario5.xaml.h"
00018
00019 using namespace SDKSample::CryptoWinRT;
00020
00021 using namespace Platform;
00022 using namespace Windows::Security::Cryptography;
00023 using namespace Windows::Security::Cryptography::Core;
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 Scenario5::Scenario5()
00030 {
00031     InitializeComponent();
00032     AlgorithmNames->SelectedIndex = 0;
00033     KeySizes->SelectedIndex = 0;
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 Scenario5::OnNavigatedTo(NavigationEventArgs^ e)
00042 {
00043     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00044     // as NotifyUser()
00045     rootPage = MainPage::Current;
00046 }
00047
00048 void SDKSample::CryptoWinRT::Scenario5::RunSample_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00049 {
00050     IBuffer^ encrypted;
00051     IBuffer^ decrypted;
00052     IBuffer^ buffer;
00053     IBuffer^ iv = nullptr;
00054     String^ blockCookie = "1234567812345678"; // 16 bytes
00055     String^ algName = AlgorithmNames->SelectionBoxItem->ToString();
00056     int keySize;
00057     bool cbc = false;
00058
00059     Scenario5Text->Text = "";
00060
00061     switch (AlgorithmNames->SelectedIndex)
00062     {
00063     case 0:
00064     case 2:
00065     case 4:
00066     case 6:
00067     case 8:
00068     case 10:
00069         cbc = true;
00070         break;
00071     }
00072
00073     switch (KeySizes->SelectedIndex)
00074     {
00075     case 0:
00076         keySize = 64;
00077         break;
00078     case 1:
00079         keySize = 128;
00080         break;
00081     case 2:
00082         keySize = 192;
00083         break;
00084     case 3:
00085         keySize = 256;
00086         break;
00087     case 4:
00088         keySize = 512;
00089         break;
00090     default:
00091         Scenario5Text->Text += "An invalid key size was selected";
00092         return;
00093     }
00094
00095     // Open the algorithm provider for the algorithm specified on input.
00096     SymmetricKeyAlgorithmProvider^ Algorithm = SymmetricKeyAlgorithmProvider::OpenAlgorithm(algName);
00097     Scenario5Text->Text += "*** Sample Cipher Encryption\n";
00098     Scenario5Text->Text += "    Algorithm Name: " + Algorithm->AlgorithmName + "\n";
00099     Scenario5Text->Text += "    Key Size: " + keySize + "\n";
00100     Scenario5Text->Text += "    Block length: " + Algorithm->BlockLength + "\n";
00101
00102     // Generate a symmetric key.
00103     IBuffer^ keymaterial = CryptographicBuffer::GenerateRandom((keySize + 7) / 8);
00104     CryptographicKey^ key;
00105
00106     try
00107     {
00108         key = Algorithm->CreateSymmetricKey(keymaterial);
00109     }
00110     catch(InvalidArgumentException^ e)
00111     {
00112         Scenario5Text->Text += "Exception: " + e->Message + "\n";
00113         Scenario5Text->Text += "Invalid Algorithm / Key Size pairing.";
00114         return;
00115     }
00116
00117     // CBC mode needs Initialization vector, here just random data.
00118     // IV property will be set on "Encrypted".
00119     if (cbc)
00120         iv = CryptographicBuffer::GenerateRandom(Algorithm->BlockLength);
00121
00122     // Set the data to encrypt.
00123     buffer = CryptographicBuffer::ConvertStringToBinary(blockCookie, BinaryStringEncoding::Utf8);
00124
00125     // Encrypt and create an authenticated tag.
00126     encrypted = CryptographicEngine::Encrypt(key, buffer, iv);
00127
00128     Scenario5Text->Text += "    Plain text: " + buffer->Length + " bytes, Encrypted: " + encrypted->Length + " bytes\n";
00129
00130     // Create another instance of the key from the same material.
00131     CryptographicKey^ key2 = Algorithm->CreateSymmetricKey(keymaterial);
00132
00133     if (key->KeySize != key2->KeySize)
00134     {
00135         Scenario5Text->Text += "CreateSymmetricKey failed!  The imported key's size did not match the original's!";
00136         return;
00137     }
00138
00139     // Decrypt and verify the authenticated tag.
00140     decrypted = CryptographicEngine::Decrypt(key2, encrypted, iv);
00141
00142     if (!CryptographicBuffer::Compare(decrypted, buffer))
00143     {
00144         Scenario5Text->Text += "Decrypted does not match original!";
00145         return;
00146     }
00147 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Network information/C++/ConnectionProfileList.xaml.cpp Source File

  • Network information

ConnectionProfileList.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 // ConnectionProfileList.xaml.cpp
00012 // Implementation of the ConnectionProfileList class
00013
00014 #include "pch.h"
00015 #include "ConnectionProfileList.xaml.h"
00016
00017 using namespace SDKSample::NetworkInformationApi;
00018
00019 using namespace Windows::UI::Xaml;
00020 using namespace Windows::UI::Xaml::Controls;
00021 using namespace Windows::UI::Xaml::Navigation;
00022
00023 ConnectionProfileList::ConnectionProfileList()
00024 {
00025     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 void ConnectionProfileList::OnNavigatedTo(NavigationEventArgs^ e)
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     rootPage = MainPage::Current;
00038 }
00039
00040 // Get Connection Cost based suggestions
00041 String^ ConnectionProfileList::GetCostBasedSuggestions(ConnectionCost^ connectionCost)
00042 {
00043     String^ strRet = "";
00044
00045     strRet = L"Cost Based Suggestions: \n";
00046     if (connectionCost->Roaming)
00047     {
00048         strRet += L"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";
00049     }
00050     else if (connectionCost->NetworkCostType == NetworkCostType::Variable)
00051     {
00052         strRet += L"Connection cost is variable, and the connection is charged based on usage, so application can implement the Conservative behavior\n";
00053     }
00054     else if (connectionCost->NetworkCostType == NetworkCostType::Fixed)
00055     {
00056         if (connectionCost->OverDataLimit || connectionCost->ApproachingDataLimit)
00057         {
00058             strRet += L"Connection has exceeded the usage cap limit or is approaching the datalimit, and the application can implement High Cost behavior in this scenario\n";
00059         }
00060         else
00061         {
00062             strRet += L"Application can implemement the Conservative behavior\n";
00063         }
00064     }
00065     else
00066     {
00067         strRet += L"Application can implement the Standard behavior\n";
00068     }
00069
00070     return strRet;
00071 }
00072
00073 // Get Connection Cost information
00074 String^ ConnectionProfileList::GetConnectionCostInfo(ConnectionCost^ connectionCost)
00075 {
00076     String^ strRet = "";
00077
00078     if (connectionCost == nullptr)
00079     {
00080         return strRet;
00081     }
00082
00083     strRet = L"Connection Cost Information: \n";
00084     strRet += L"====================\n";
00085     switch(connectionCost->NetworkCostType)
00086     {
00087         case NetworkCostType::Unrestricted:
00088             strRet += L"Cost: Unrestricted\n";
00089             break;
00090         case NetworkCostType::Fixed:
00091             strRet += L"Cost: Fixed\n";
00092             break;
00093         case NetworkCostType::Variable:
00094             strRet += L"Cost: Variable\n";
00095             break;
00096         case NetworkCostType::Unknown:
00097             strRet += L"Cost: Unknown\n";
00098             break;
00099         default:
00100             strRet += L"Cost: Error\n";
00101             break;
00102     }
00103
00104     if (connectionCost->Roaming)
00105     {
00106         strRet += L"Roaming    : Yes\n";
00107     }
00108     else
00109     {
00110         strRet += L"Roaming    : No\n";
00111     }
00112
00113     if (connectionCost->OverDataLimit)
00114     {
00115         strRet += L"OverDataLimit    : Yes\n";
00116     }
00117     else
00118     {
00119         strRet += L"OverDataLimit    : No\n";
00120     }
00121
00122     if (connectionCost->ApproachingDataLimit)
00123     {
00124         strRet += L"ApproachingDataLimit    : Yes\n";
00125     }
00126     else
00127     {
00128         strRet += L"ApproachingDataLimit    : No\n";
00129     }
00130
00131     // Get cost based suggestions
00132     strRet += GetCostBasedSuggestions(connectionCost);
00133     return strRet;
00134 }
00135
00136 // Get Dataplan Status Information
00137 String^ ConnectionProfileList::GetDataPlanStatusInfo(DataPlanStatus^ dataPlan)
00138 {
00139     String ^strRet = "";
00140
00141     if (dataPlan == nullptr)
00142     {
00143         return strRet;
00144     }
00145
00146     strRet = L"Dataplan Status Information: \n";
00147     strRet += L"====================\n";
00148
00149     if (dataPlan->DataPlanUsage != nullptr)
00150     {
00151         auto lastSyncTime = dataPlan->DataPlanUsage->LastSyncTime;
00152         ULARGE_INTEGER lst;
00153         lst.QuadPart = lastSyncTime.UniversalTime;
00154         FILETIME ftLastSyncTime;
00155         SYSTEMTIME stLastSyncTime;
00156
00157         //get FILETIME from lastSyncTime, convert FILETIME to SYSTEMTIME and display
00158         ftLastSyncTime.dwLowDateTime = lst.LowPart;
00159         ftLastSyncTime.dwHighDateTime = lst.HighPart;
00160         FileTimeToSystemTime(&ftLastSyncTime, &stLastSyncTime);
00161         strRet += L"Usage In Megabytes : " + dataPlan->DataPlanUsage->MegabytesUsed.ToString() + "\n";
00162         strRet += L"LastSyncTime: " + stLastSyncTime.wMonth.ToString() + "/" + stLastSyncTime.wDay.ToString() + "/" + stLastSyncTime.wYear.ToString() + " " + stLastSyncTime.wHour.ToString() + ":" + stLastSyncTime.wMinute.ToString() + ":"+ stLastSyncTime.wSecond.ToString() + "\n";
00163     }
00164     else
00165     {
00166         strRet += L"DataPlan Usage : Not Defined\n";
00167     }
00168
00169     if (dataPlan->InboundBitsPerSecond != nullptr)
00170     {
00171         auto inboundBandwidth = dataPlan->InboundBitsPerSecond->Value;
00172         strRet += L"InboundBitsPerSecond : " + inboundBandwidth.ToString() + "\n";
00173     }
00174     else
00175     {
00176         strRet += L"InboundBitsPerSecond : Not Defined\n";
00177     }
00178
00179     if (dataPlan->OutboundBitsPerSecond != nullptr)
00180     {
00181         auto outboundBandwidth = dataPlan->OutboundBitsPerSecond->Value;
00182         strRet += L"OutboundBitsPerSecond : " + outboundBandwidth.ToString() + "\n";
00183     }
00184     else
00185     {
00186         strRet += L"OutboundBitsPerSecond : Not Defined\n";
00187     }
00188
00189     if (dataPlan->DataLimitInMegabytes != nullptr)
00190     {
00191         auto dataLimit = dataPlan->DataLimitInMegabytes->Value;
00192         strRet += L"DataLimitInMegabytes : " + dataLimit.ToString() + "\n";
00193     }
00194     else
00195     {
00196         strRet += L"DataLimitInMegabytes : Not Defined\n";
00197     }
00198
00199     if (dataPlan->NextBillingCycle != nullptr)
00200     {
00201         auto nextBillingCycle = dataPlan->NextBillingCycle->Value;
00202         ULARGE_INTEGER nbc;
00203         nbc.QuadPart = nextBillingCycle.UniversalTime;
00204         FILETIME ftNextBillingCycle;
00205         SYSTEMTIME stNextBillingCycle;
00206
00207         //get FILETIME from NextBillingCycle, convert to FILETIME to SYSTEMTIME and display
00208         ftNextBillingCycle.dwLowDateTime = nbc.LowPart;
00209         ftNextBillingCycle.dwHighDateTime = nbc.HighPart;
00210         FileTimeToSystemTime(&ftNextBillingCycle, &stNextBillingCycle);
00211         strRet += L"NextBillingCycle: " + stNextBillingCycle.wMonth.ToString() + "/" + stNextBillingCycle.wDay.ToString() + "/" + stNextBillingCycle.wYear.ToString() + " " + stNextBillingCycle.wHour.ToString() + ":" + stNextBillingCycle.wMinute.ToString() + ":" + stNextBillingCycle.wSecond.ToString() + "\n";
00212     }
00213     else
00214     {
00215         strRet += L"NextBillingCycle : Not Defined\n";
00216     }
00217
00218     if (dataPlan->MaxTransferSizeInMegabytes != nullptr)
00219     {
00220         auto transferSize = dataPlan->MaxTransferSizeInMegabytes->Value;
00221         strRet += L"MaxTransferSizeInMegabytes : " + transferSize.ToString() + "\n";
00222     }
00223     else
00224     {
00225         strRet += L"MaxTransferSizeInMegabytes : Not Defined\n";
00226     }
00227
00228     return strRet;
00229 }
00230
00231
00232 // Get Network Security Settings information
00233 String^ ConnectionProfileList::GetNetworkSecuritySettingsInfo(NetworkSecuritySettings^ netSecuritySettings)
00234 {
00235     String^ networkSecurity = "";
00236     networkSecurity += L"Network Security Settings: \n";
00237     networkSecurity += L"====================\n";
00238
00239     if (netSecuritySettings == nullptr)
00240     {
00241         networkSecurity += L"Network Security Settings not available\n";
00242         return networkSecurity;
00243     }
00244
00245     //NetworkAuthenticationType
00246     switch (netSecuritySettings->NetworkAuthenticationType)
00247     {
00248         case NetworkAuthenticationType::None:
00249             networkSecurity += L"NetworkAuthenticationType: None";
00250             break;
00251         case NetworkAuthenticationType::Unknown:
00252             networkSecurity += L"NetworkAuthenticationType: Unknown";
00253             break;
00254         case NetworkAuthenticationType::Open80211:
00255             networkSecurity += L"NetworkAuthenticationType: Open80211";
00256             break;
00257         case NetworkAuthenticationType::SharedKey80211:
00258             networkSecurity += L"NetworkAuthenticationType: SharedKey80211";
00259             break;
00260         case NetworkAuthenticationType::Wpa:
00261             networkSecurity += L"NetworkAuthenticationType: Wpa";
00262             break;
00263         case NetworkAuthenticationType::WpaPsk:
00264             networkSecurity += L"NetworkAuthenticationType: WpaPsk";
00265             break;
00266         case NetworkAuthenticationType::WpaNone:
00267             networkSecurity += L"NetworkAuthenticationType: WpaNone";
00268             break;
00269         case NetworkAuthenticationType::Rsna:
00270             networkSecurity += L"NetworkAuthenticationType: Rsna";
00271             break;
00272         case NetworkAuthenticationType::RsnaPsk:
00273             networkSecurity += L"NetworkAuthenticationType: RsnaPsk";
00274             break;
00275         default:
00276             networkSecurity += L"NetworkAuthenticationType: Error";
00277             break;
00278     }
00279     networkSecurity += L"\n";
00280
00281     //NetworkEncryptionType
00282     switch (netSecuritySettings->NetworkEncryptionType)
00283     {
00284         case NetworkEncryptionType::None:
00285             networkSecurity += L"NetworkEncryptionType: None";
00286             break;
00287         case NetworkEncryptionType::Unknown:
00288             networkSecurity += L"NetworkEncryptionType: Unknown";
00289             break;
00290         case NetworkEncryptionType::Wep:
00291             networkSecurity += L"NetworkEncryptionType: Wep";
00292             break;
00293         case NetworkEncryptionType::Wep40:
00294             networkSecurity += L"NetworkEncryptionType: Wep40";
00295             break;
00296         case NetworkEncryptionType::Wep104:
00297             networkSecurity += L"NetworkEncryptionType: Wep104";
00298             break;
00299         case NetworkEncryptionType::Tkip:
00300             networkSecurity += L"NetworkEncryptionType: Tkip";
00301             break;
00302         case NetworkEncryptionType::Ccmp:
00303             networkSecurity += L"NetworkEncryptionType: Ccmp";
00304             break;
00305         case NetworkEncryptionType::WpaUseGroup:
00306             networkSecurity += L"NetworkEncryptionType: WpaUseGroup";
00307             break;
00308         case NetworkEncryptionType::RsnUseGroup:
00309             networkSecurity += L"NetworkEncryptionType: RsnUseGroup";
00310             break;
00311         default:
00312             networkSecurity += L"NetworkEncryptionType: Error";
00313             break;
00314     }
00315     networkSecurity += L"\n";
00316     return networkSecurity;
00317 }
00318
00319
00320
00321 // Get Connection Profile Information
00322 String^ ConnectionProfileList::GetConnectionProfile(ConnectionProfile^ connectionProfile)
00323 {
00324     String^ strProfileInfo = "";
00325
00326     switch (connectionProfile->GetNetworkConnectivityLevel())
00327     {
00328         case NetworkConnectivityLevel::None:
00329             strProfileInfo += "Connectivity Level : None\n";
00330             break;
00331         case NetworkConnectivityLevel::LocalAccess:
00332             strProfileInfo += "Connectivity Level : Local Access\n";
00333             break;
00334         case NetworkConnectivityLevel::ConstrainedInternetAccess:
00335             strProfileInfo += "Connectivity Level : Constrained Internet Access\n";
00336             break;
00337         case NetworkConnectivityLevel::InternetAccess:
00338             strProfileInfo += "Connectivity Level : Internet Access\n";
00339             break;
00340     }
00341
00342     // Get Connection Cost information
00343     ConnectionCost^ connectionCost = connectionProfile->GetConnectionCost();
00344     strProfileInfo += GetConnectionCostInfo(connectionCost);
00345
00346     // Get Dataplan Status information
00347     DataPlanStatus^ dataPlan = connectionProfile->GetDataPlanStatus();
00348     strProfileInfo += GetDataPlanStatusInfo(dataPlan);
00349
00350     // Get Network Security Settings
00351     NetworkSecuritySettings^ netSecuritySettings = connectionProfile->NetworkSecuritySettings;
00352     strProfileInfo += GetNetworkSecuritySettingsInfo(netSecuritySettings);
00353
00354     return strProfileInfo;
00355 }
00356
00357 // Display Connection Profile List
00358 void SDKSample::NetworkInformationApi::ConnectionProfileList::ConnectionProfileList_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00359 {
00360     try
00361     {
00362         connectionProfileInfo = "";
00363         auto connectionProfiles = NetworkInformation::GetConnectionProfiles();
00364         rootPage->NotifyUser("", NotifyType::StatusMessage);
00365
00366         std::for_each(begin(connectionProfiles), end(connectionProfiles), [this](ConnectionProfile^ connectionProfile)
00367         {
00368             if (connectionProfile != nullptr)
00369             {
00370                 // Display Connection Profile information for each of the profiles
00371                 connectionProfileInfo += L"Profile Name : " + connectionProfile->ProfileName + L"\n" + GetConnectionProfile(connectionProfile);
00372                 connectionProfileInfo += L"--------------------------------------------------------------------\n";
00373             }
00374         });
00375         rootPage->NotifyUser(connectionProfileInfo, NotifyType::StatusMessage);
00376     }
00377
00378     catch (Exception^ ex)
00379     {
00380         rootPage->NotifyUser("An unexpected exception occured: " + ex->Message, NotifyType::ErrorMessage);
00381     }
00382 }
00383
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: User domain name/C++/GetDomainName.xaml.h Source File

  • User domain name

GetDomainName.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 // GetDomainName.xaml.h
00013 // Declaration of the GetDomainName class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "GetDomainName.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace UserDomainName
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 GetDomainName sealed
00031         {
00032         public:
00033             GetDomainName();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void GetDNSDomain_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Device capabilities/C++/pch.cpp Source File

  • Input Device capabilities

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Association launching/C++/LaunchUriInput.xaml.h Source File

  • Association launching

LaunchUriInput.xaml.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 // LaunchUriInput.xaml.h
00009 // Declaration of the LaunchUriInput class.
00010 //
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "LaunchUriInput.g.h"
00016 #include "MainPage.xaml.h"
00017
00018 using namespace Windows::UI::Xaml;
00019
00020 namespace AssociationLaunching
00021 {
00022   [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class LaunchUriInput sealed
00024     {
00025     public:
00026         LaunchUriInput();
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         MainPage^ rootPage;
00034
00035         void LaunchUriButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00036         void LaunchUriWithWarningButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00037         void LaunchUriOpenWithButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038         ~LaunchUriInput();
00039
00040         static Windows::Foundation::Point GetOpenWithPosition(Windows::UI::Xaml::FrameworkElement^ element);
00041         static Platform::String^ uriToLaunch;
00042     };
00043 }
Generated on Sat Nov 23 2024 16:07:57 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML accessibility/C++/Constants.cpp Source File

  • XAML accessibility

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully qualified name for the class that implements the scenario" }
00021     { "Creating an accessible form", "SDKSample.Accessibility.Scenario1" },
00022     { "Tab sequence", "SDKSample.Accessibility.Scenario2" },
00023     { "Override AutomationPeers", "SDKSample.Accessibility.Scenario3" },
00024   { "Databound ListView", "SDKSample.Accessibility.Scenario4" }
00025 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Scaling according to DPI/C++/Scenario1.xaml.h Source File

  • Scaling according to DPI

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 SDKSample
00023 {
00024     namespace Scaling
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 Scenario1 sealed
00031         {
00032         public:
00033             Scenario1();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037
00038         private:
00039             static const int DEFAULT_LOGICALPPI = 96;
00040             static const int PERCENT = 100;
00041
00042             Windows::UI::Xaml::Media::Imaging::BitmapImage^ image100;
00043             Windows::UI::Xaml::Media::Imaging::BitmapImage^ image140;
00044             Windows::UI::Xaml::Media::Imaging::BitmapImage^ image180;
00045
00046             Platform::String^ GetMinDPI();
00047             Platform::String^ GetMinResolution();
00048             void SetManualLoadImage();
00049             void ResetOutput();
00050             void DisplayProperties_LogicalDpiChanged(Platform::Object^ sender);
00051         };
00052     }
00053 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML personality animations/C++/App.xaml.h Source File

  • XAML personality animations

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D command list/C++/DirectXBase.cpp Source File

  • Direct2D command list

DirectXBase.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 "DirectXBase.h"
00010
00011 using namespace Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::Graphics::Display;
00015 using namespace D2D1;
00016
00017 // Constructor.
00018 DirectXBase::DirectXBase() :
00019     m_windowSizeChangeInProgress(false),
00020     m_dpi(-1.0f)
00021 {
00022 }
00023
00024 // Initialize the DirectX resources required to run.
00025 void DirectXBase::Initialize(CoreWindow^ window, float dpi)
00026 {
00027     m_window = window;
00028
00029     CreateDeviceIndependentResources();
00030     CreateDeviceResources();
00031     SetDpi(dpi);
00032 }
00033
00034 // Recreate all device resources and set them back to the current state.
00035 void DirectXBase::HandleDeviceLost()
00036 {
00037     // Reset these member variables to ensure that SetDpi recreates all resources.
00038     float dpi = m_dpi;
00039     m_dpi = -1.0f;
00040     m_windowBounds.Width = 0;
00041     m_windowBounds.Height = 0;
00042     m_swapChain = nullptr;
00043
00044     CreateDeviceResources();
00045     SetDpi(dpi);
00046 }
00047
00048 // These are the resources required independent of the device.
00049 void DirectXBase::CreateDeviceIndependentResources()
00050 {
00051     D2D1_FACTORY_OPTIONS options;
00052     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00053
00054 #if defined(_DEBUG)
00055     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00056     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00057 #endif
00058
00059     DX::ThrowIfFailed(
00060         D2D1CreateFactory(
00061             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00062             __uuidof(ID2D1Factory1),
00063             &options,
00064             &m_d2dFactory
00065             )
00066         );
00067
00068     DX::ThrowIfFailed(
00069         DWriteCreateFactory(
00070             DWRITE_FACTORY_TYPE_SHARED,
00071             __uuidof(IDWriteFactory),
00072             &m_dwriteFactory
00073             )
00074         );
00075
00076     DX::ThrowIfFailed(
00077         CoCreateInstance(
00078             CLSID_WICImagingFactory,
00079             nullptr,
00080             CLSCTX_INPROC_SERVER,
00081             IID_PPV_ARGS(&m_wicFactory)
00082             )
00083         );
00084 }
00085
00086 // These are the resources that depend on the device.
00087 void DirectXBase::CreateDeviceResources()
00088 {
00089     // This flag adds support for surfaces with a different color channel ordering
00090     // than the API default. It is required for compatibility with Direct2D.
00091     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00092     ComPtr<IDXGIDevice> dxgiDevice;
00093
00094 #if defined(_DEBUG)
00095     // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00096     creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00097 #endif
00098
00099     // This array defines the set of DirectX hardware feature levels this app will support.
00100     // Note the ordering should be preserved.
00101     // Don't forget to declare your application's minimum required feature level in its
00102     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00103     D3D_FEATURE_LEVEL featureLevels[] =
00104     {
00105         D3D_FEATURE_LEVEL_11_1,
00106         D3D_FEATURE_LEVEL_11_0,
00107         D3D_FEATURE_LEVEL_10_1,
00108         D3D_FEATURE_LEVEL_10_0,
00109         D3D_FEATURE_LEVEL_9_3,
00110         D3D_FEATURE_LEVEL_9_2,
00111         D3D_FEATURE_LEVEL_9_1
00112     };
00113
00114     // Create the Direct3D 11 API device object and a corresponding context.
00115     ComPtr<ID3D11Device> device;
00116     ComPtr<ID3D11DeviceContext> context;
00117     DX::ThrowIfFailed(
00118         D3D11CreateDevice(
00119             nullptr,                    // Specify nullptr to use the default adapter.
00120             D3D_DRIVER_TYPE_HARDWARE,
00121             0,
00122             creationFlags,              // Set debug and Direct2D compatibility flags.
00123             featureLevels,              // List of feature levels this app can support.
00124             ARRAYSIZE(featureLevels),
00125             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Metro style apps.
00126             &device,                    // Returns the Direct3D device created.
00127             &m_featureLevel,            // Returns feature level of device created.
00128             &context                    // Returns the device immediate context.
00129             )
00130         );
00131
00132     // Get the Direct3D 11.1 API device and context interfaces.
00133     DX::ThrowIfFailed(
00134         device.As(&m_d3dDevice)
00135         );
00136
00137     DX::ThrowIfFailed(
00138         context.As(&m_d3dContext)
00139         );
00140
00141     // Get the underlying DXGI device of the Direct3D device.
00142     DX::ThrowIfFailed(
00143         m_d3dDevice.As(&dxgiDevice)
00144         );
00145
00146     // Create the Direct2D device object and a corresponding context.
00147     DX::ThrowIfFailed(
00148         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00149         );
00150
00151     DX::ThrowIfFailed(
00152         m_d2dDevice->CreateDeviceContext(
00153             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00154             &m_d2dContext
00155             )
00156         );
00157 }
00158
00159 // Helps track the DPI in the helper class.
00160 // This is called in the dpiChanged event handler in the view class.
00161 void DirectXBase::SetDpi(float dpi)
00162 {
00163     if (dpi != m_dpi)
00164     {
00165         // Save the DPI of this display in our class.
00166         m_dpi = dpi;
00167
00168         // Update Direct2D's stored DPI.
00169         m_d2dContext->SetDpi(m_dpi, m_dpi);
00170
00171         // Often a DPI change implies a window size change. In some cases Windows will issue
00172         // both a size changed event and a DPI changed event. In this case, the resulting bounds
00173         // will not change, and the window resize code will only be executed once.
00174         UpdateForWindowSizeChange();
00175     }
00176 }
00177
00178 // This routine is called in the event handler for the view SizeChanged event.
00179 void DirectXBase::UpdateForWindowSizeChange()
00180 {
00181     // Only handle window size changed if there is no pending DPI change.
00182     if (m_dpi != DisplayProperties::LogicalDpi)
00183     {
00184         return;
00185     }
00186
00187     if (m_window->Bounds.Width  != m_windowBounds.Width ||
00188         m_window->Bounds.Height != m_windowBounds.Height)
00189     {
00190         m_d2dContext->SetTarget(nullptr);
00191         m_d2dTargetBitmap = nullptr;
00192         m_d3dRenderTargetView = nullptr;
00193         m_d3dDepthStencilView = nullptr;
00194         m_windowSizeChangeInProgress = true;
00195         CreateWindowSizeDependentResources();
00196     }
00197 }
00198
00199 // Allocate all memory resources that change on a window SizeChanged event.
00200 void DirectXBase::CreateWindowSizeDependentResources()
00201 {
00202     // Store the window bounds so the next time we get a SizeChanged event we can
00203     // avoid rebuilding everything if the size is identical.
00204     m_windowBounds = m_window->Bounds;
00205
00206     if (m_swapChain != nullptr)
00207     {
00208         // If the swap chain already exists, resize it.
00209         HRESULT hr = m_swapChain->ResizeBuffers(2, 0, 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0);
00210
00211         if (hr == DXGI_ERROR_DEVICE_REMOVED)
00212         {
00213             // If the device was removed for any reason, a new device and swapchain will need to be created.
00214             HandleDeviceLost();
00215
00216             // Everything is set up now. Do not continue execution of this method.
00217             return;
00218         }
00219         else
00220         {
00221             DX::ThrowIfFailed(hr);
00222         }
00223     }
00224     else
00225     {
00226         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00227         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00228         swapChainDesc.Width = 0;                                     // Use automatic sizing.
00229         swapChainDesc.Height = 0;
00230         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;           // This is the most common swap chain format.
00231         swapChainDesc.Stereo = false;
00232         swapChainDesc.SampleDesc.Count = 1;                          // Don't use multi-sampling.
00233         swapChainDesc.SampleDesc.Quality = 0;
00234         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00235         swapChainDesc.BufferCount = 2;                               // Use double-buffering to minimize latency.
00236         swapChainDesc.Scaling = DXGI_SCALING_NONE;
00237         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Metro style apps must use this SwapEffect.
00238         swapChainDesc.Flags = 0;
00239
00240         ComPtr<IDXGIDevice1> dxgiDevice;
00241         DX::ThrowIfFailed(
00242             m_d3dDevice.As(&dxgiDevice)
00243             );
00244
00245         ComPtr<IDXGIAdapter> dxgiAdapter;
00246         DX::ThrowIfFailed(
00247             dxgiDevice->GetAdapter(&dxgiAdapter)
00248             );
00249
00250         ComPtr<IDXGIFactory2> dxgiFactory;
00251         DX::ThrowIfFailed(
00252             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00253             );
00254
00255         CoreWindow^ window = m_window.Get();
00256         DX::ThrowIfFailed(
00257             dxgiFactory->CreateSwapChainForCoreWindow(
00258                 m_d3dDevice.Get(),
00259                 reinterpret_cast<IUnknown*>(window),
00260                 &swapChainDesc,
00261                 nullptr,
00262                 &m_swapChain
00263                 )
00264             );
00265
00266         // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
00267         // ensures that the application will only render after each VSync, minimizing power consumption.
00268         DX::ThrowIfFailed(
00269             dxgiDevice->SetMaximumFrameLatency(1)
00270             );
00271     }
00272
00273     // Create a Direct3D render target view of the swap chain back buffer.
00274     ComPtr<ID3D11Texture2D> backBuffer;
00275     DX::ThrowIfFailed(
00276         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00277         );
00278
00279     DX::ThrowIfFailed(
00280         m_d3dDevice->CreateRenderTargetView(
00281             backBuffer.Get(),
00282             nullptr,
00283             &m_d3dRenderTargetView
00284             )
00285         );
00286
00287     // Cache the rendertarget dimensions in our helper class for convenient use.
00288     D3D11_TEXTURE2D_DESC backBufferDesc = {0};
00289     backBuffer->GetDesc(&backBufferDesc);
00290     m_renderTargetSize.Width  = static_cast<float>(backBufferDesc.Width);
00291     m_renderTargetSize.Height = static_cast<float>(backBufferDesc.Height);
00292
00293     // Create a depth stencil view for use with 3D rendering if needed.
00294     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00295         DXGI_FORMAT_D24_UNORM_S8_UINT,
00296         backBufferDesc.Width,
00297         backBufferDesc.Height,
00298         1,
00299         1,
00300         D3D11_BIND_DEPTH_STENCIL
00301         );
00302
00303     ComPtr<ID3D11Texture2D> depthStencil;
00304     DX::ThrowIfFailed(
00305         m_d3dDevice->CreateTexture2D(
00306             &depthStencilDesc,
00307             nullptr,
00308             &depthStencil
00309             )
00310         );
00311
00312     auto viewDesc = CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D);
00313     DX::ThrowIfFailed(
00314         m_d3dDevice->CreateDepthStencilView(
00315             depthStencil.Get(),
00316             &viewDesc,
00317             &m_d3dDepthStencilView
00318             )
00319         );
00320
00321     // Set the 3D rendering viewport to target the entire window.
00322     CD3D11_VIEWPORT viewport(
00323         0.0f,
00324         0.0f,
00325         static_cast<float>(backBufferDesc.Width),
00326         static_cast<float>(backBufferDesc.Height)
00327         );
00328
00329     m_d3dContext->RSSetViewports(1, &viewport);
00330
00331     // Create a Direct2D target bitmap associated with the
00332     // swap chain back buffer and set it as the current target.
00333     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00334         BitmapProperties1(
00335             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00336             PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00337             m_dpi,
00338             m_dpi
00339             );
00340
00341     ComPtr<IDXGISurface> dxgiBackBuffer;
00342     DX::ThrowIfFailed(
00343         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00344         );
00345
00346     DX::ThrowIfFailed(
00347         m_d2dContext->CreateBitmapFromDxgiSurface(
00348             dxgiBackBuffer.Get(),
00349             &bitmapProperties,
00350             &m_d2dTargetBitmap
00351             )
00352         );
00353
00354     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00355
00356     // Grayscale text anti-aliasing is recommended for all Metro style apps.
00357     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00358 }
00359
00360 // Method to deliver the final image to the display.
00361 void DirectXBase::Present()
00362 {
00363     // The application may optionally specify "dirty" or "scroll" rects to improve efficiency
00364     // in certain scenarios.  In this sample, however, we do not utilize those features.
00365     DXGI_PRESENT_PARAMETERS parameters = {0};
00366     parameters.DirtyRectsCount = 0;
00367     parameters.pDirtyRects = nullptr;
00368     parameters.pScrollRect = nullptr;
00369     parameters.pScrollOffset = nullptr;
00370
00371     // The first argument instructs DXGI to block until VSync, putting the application
00372     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00373     // frames that will never be displayed to the screen.
00374     HRESULT hr = m_swapChain->Present1(1, 0, &parameters);
00375
00376     // Discard the contents of the render target.
00377     // This is a valid operation only when the existing contents will be entirely
00378     // overwritten. If dirty or scroll rects are used, this call should be removed.
00379     m_d3dContext->DiscardView(m_d3dRenderTargetView.Get());
00380
00381     // Discard the contents of the depth stencil.
00382     m_d3dContext->DiscardView(m_d3dDepthStencilView.Get());
00383
00384     // If the device was removed either by a disconnect or a driver upgrade, we
00385     // must recreate all device resources.
00386     if (hr == DXGI_ERROR_DEVICE_REMOVED)
00387     {
00388         HandleDeviceLost();
00389     }
00390     else
00391     {
00392         DX::ThrowIfFailed(hr);
00393     }
00394
00395     if (m_windowSizeChangeInProgress)
00396     {
00397         // A window size change has been initiated and the app has just completed presenting
00398         // the first frame with the new size. Notify the resize manager so we can short
00399         // circuit any resize animation and prevent unnecessary delays.
00400         CoreWindowResizeManager::GetForCurrentView()->NotifyLayoutCompleted();
00401         m_windowSizeChangeInProgress = false;
00402     }
00403 }
00404
00405 void DirectXBase::ValidateDevice()
00406 {
00407     // The D3D Device is no longer valid if the default adapter changes or if
00408     // the device has been removed.
00409
00410     // First, get the information for the adapter related to the current device.
00411
00412     ComPtr<IDXGIDevice1> dxgiDevice;
00413     ComPtr<IDXGIAdapter> deviceAdapter;
00414     DXGI_ADAPTER_DESC deviceDesc;
00415     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00416     DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter));
00417     DX::ThrowIfFailed(deviceAdapter->GetDesc(&deviceDesc));
00418
00419     // Next, get the information for the default adapter.
00420
00421     ComPtr<IDXGIFactory2> dxgiFactory;
00422     ComPtr<IDXGIAdapter1> currentAdapter;
00423     DXGI_ADAPTER_DESC currentDesc;
00424     DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)));
00425     DX::ThrowIfFailed(dxgiFactory->EnumAdapters1(0, &currentAdapter));
00426     DX::ThrowIfFailed(currentAdapter->GetDesc(&currentDesc));
00427
00428     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00429     // a new D3D device must be created.
00430
00431     if ((deviceDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart) ||
00432         (deviceDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart) ||
00433         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00434     {
00435         // Release references to resources related to the old device.
00436         dxgiDevice = nullptr;
00437         deviceAdapter = nullptr;
00438
00439         // Create a new device and swap chain.
00440         HandleDeviceLost();
00441     }
00442 }
Generated on Sat Nov 23 2024 16:08:02 for Win8-Examples by doxygen 1.7.1


Win8-Examples: USSD message management/C++/MainPage.xaml.h Source File

  • USSD message management

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Search contract/C++/Scenario1.xaml.cpp Source File

  • Search contract

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::SearchContract;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 Scenario1::Scenario1()
00026 {
00027     // Code for participating in the Search contract and handling the user's search queries can be found
00028     // in App::OnWindowCreated.  Code must be placed there so that it can receive user queries at any time.
00029     // You also need to add the Search declaration in the package.appxmanifest to support the Search contract.
00030
00031     InitializeComponent();
00032 }
00033
00034 void Scenario1::OnNavigatedTo(NavigationEventArgs^ e)
00035 {
00036     MainPage::Current->NotifyUser("Use the search pane to submit a query", NotifyType::StatusMessage);
00037 }
Generated on Sat Nov 23 2024 16:07:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Edge gesture invocation/C++/ScenarioInput2.xaml.h Source File

  • Edge gesture invocation

ScenarioInput2.xaml.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 // ScenarioInput2.xaml.h
00009 // Declaration of the ScenarioInput2 class.
00010 //
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "ScenarioInput2.g.h"
00016 #include "MainPage.xaml.h"
00017
00018 namespace EdgeGestureSample
00019 {
00020   [Windows::Foundation::Metadata::WebHostHidden]
00021     public ref class ScenarioInput2 sealed
00022     {
00023     public:
00024         ScenarioInput2();
00025
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
00030     private:
00031         MainPage^ rootPage;
00032         TextBlock^ outputText;
00033         ListBox^ RightClickRegion;
00034         Windows::Foundation::EventRegistrationToken RightClickEventToken;
00035         Windows::Foundation::EventRegistrationToken RightClickRegionEventToken;
00036         Windows::Foundation::EventRegistrationToken EdgeGestureStartingEventToken;
00037         Windows::Foundation::EventRegistrationToken EdgeGestureCompletedEventToken;
00038         Windows::Foundation::EventRegistrationToken EdgeGestureCanceledEventToken;
00039
00040         void rootPage_OutputFrameLoaded(Object^ sender, Object^ e);
00041
00042         void OnStarting(EdgeGesture^ sender, EdgeGestureEventArgs^ e);
00043         void OnCompleted(EdgeGesture^ sender, EdgeGestureEventArgs^ e);
00044         void OnCanceled(EdgeGesture^ sender, EdgeGestureEventArgs^ e);
00045         void OnContextMenu(Object^ sender, RightTappedRoutedEventArgs^ e);
00046         void RightClickOverride(Object^ sender, RightTappedRoutedEventArgs^ e);
00047         void InitializeEdgeGestureHandlers();
00048         ~ScenarioInput2();
00049
00050         Windows::Foundation::EventRegistrationToken _layoutHandlerToken;
00051         Windows::Foundation::EventRegistrationToken _frameLoadedToken;
00052     };
00053 }
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::GyrometerCPP::sealed Member List

This is the complete list of members for SDKSample::GyrometerCPP::sealed, including all inherited members.
desiredReportInterval | SDKSample::GyrometerCPP::sealed | [private]
dispatcher | SDKSample::GyrometerCPP::sealed | [private]
dispatcherTimer | SDKSample::GyrometerCPP::sealed | [private]
DisplayCurrentReading(Platform::Object^sender, Platform::Object^e) | SDKSample::GyrometerCPP::sealed | [private]
gyrometer | SDKSample::GyrometerCPP::sealed | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::GyrometerCPP::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::GyrometerCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::GyrometerCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::GyrometerCPP::sealed | [protected, virtual]
ReadingChanged(Windows::Devices::Sensors::Gyrometer^sender, Windows::Devices::Sensors::GyrometerReadingChangedEventArgs^e) | SDKSample::GyrometerCPP::sealed | [private]
readingToken | SDKSample::GyrometerCPP::sealed | [private]
rootPage | SDKSample::GyrometerCPP::sealed | [private]
Scenario1() | SDKSample::GyrometerCPP::sealed |
Scenario2() | SDKSample::GyrometerCPP::sealed |
ScenarioDisable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::GyrometerCPP::sealed | [private]
ScenarioDisable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::GyrometerCPP::sealed | [private]
ScenarioEnable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::GyrometerCPP::sealed | [private]
ScenarioEnable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::GyrometerCPP::sealed | [private]
VisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | SDKSample::GyrometerCPP::sealed | [private]
VisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | SDKSample::GyrometerCPP::sealed | [private]
visibilityToken | SDKSample::GyrometerCPP::sealed | [private]
Generated on Sat Nov 23 2024 16:09:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media Server client/C++/MainPage.xaml.h Source File

  • Media Server client

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:46 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/ScenarioInput3.xaml.h Source File

  • Media extensions

ScenarioInput3.xaml.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 //
00009 // Scenario3Input.xaml.h
00010 // Declaration of the Scenario3Input class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioInput3.g.h"
00017 #include "MainPage.g.h"
00018
00019 namespace MediaExtensionsCPP
00020 {
00021     [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class ScenarioInput3 sealed
00023     {
00024     public:
00025         ScenarioInput3();
00026
00027     protected:
00028         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030
00031     private:
00032         ~ScenarioInput3();
00033         MainPage^ rootPage;
00034         Windows::UI::Xaml::Controls::MediaElement^ outputVideo;
00035         Windows::UI::Xaml::Controls::MediaElement^ outputVideoStabilized;
00036
00037         void rootPage_OutputFrameLoaded(Object^ sender, Object^ e);
00038         void Open_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039         void Stop_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         Windows::Foundation::EventRegistrationToken _frameLoadedToken;
00041     };
00042 }
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: IXmlReader and IXmlWriter XML data readwrite/C++/App.xaml.h Source File

  • IXmlReader and IXmlWriter XML data readwrite

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML scrolling, panning, and zooming/C++/Constants.h Source File

  • XAML scrolling, panning, and zooming

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"XAML ScrollViewer SDK Sample");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Mobile broadband account provisioning/C++/MainPage.xaml.cpp Source File

  • Mobile broadband account provisioning

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:43 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Credential locker/C++/MainPage.xaml.h Source File

  • Credential locker

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

D2DInterpolationModes Member List

This is the complete list of members for D2DInterpolationModes, including all inherited members.
__pad0__ | D2DInterpolationModes |
AddMenuItem(Windows::UI::Popups::PopupMenu^popupMenu, Platform::String^caption) | D2DInterpolationModes | [private]
Clamp(float v, float low, float high) | D2DInterpolationModes | [inline, private]
CreateDeviceResources() override | D2DInterpolationModes | [virtual]
CreateWindowSizeDependentResources() override | D2DInterpolationModes | [virtual]
HandleManipulationUpdated(Windows::Foundation::Point position, Windows::Foundation::Point positionDelta, float zoomDelta) | D2DInterpolationModes | [private]
HandlePointerPressed(Windows::UI::Input::PointerPoint^point) | D2DInterpolationModes | [private]
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | D2DInterpolationModes | [virtual]
Load(_In_ Platform::String^entryPoint) | D2DInterpolationModes | [virtual]
m_2DAffineTransformEffectLeft | D2DInterpolationModes | [private]
m_2DAffineTransformEffectRight | D2DInterpolationModes | [private]
m_bitmapSourceEffect | D2DInterpolationModes | [private]
m_gestureRecognizer | D2DInterpolationModes | [private]
m_imageRotate | D2DInterpolationModes | [private]
m_imageSize | D2DInterpolationModes | [private]
m_imageSizeDips | D2DInterpolationModes | [private]
m_isSnapped | D2DInterpolationModes | [private]
m_isWindowClosed | D2DInterpolationModes | [private]
m_isWindowVisible | D2DInterpolationModes | [private]
m_modeTextFormat | D2DInterpolationModes | [private]
m_modeTextLeft | D2DInterpolationModes | [private]
m_modeTextRight | D2DInterpolationModes | [private]
m_renderDuration | D2DInterpolationModes | [private]
m_renderTimeFormat | D2DInterpolationModes | [private]
m_renderTimer | D2DInterpolationModes | [private]
m_sampleOverlay | D2DInterpolationModes | [private]
m_selectedEffect | D2DInterpolationModes | [private]
m_totalZoom | D2DInterpolationModes | [private]
m_viewPosition | D2DInterpolationModes | [private]
m_whiteBrush | D2DInterpolationModes | [private]
MenuItemSelected(Windows::UI::Popups::IUICommand^command) | D2DInterpolationModes |
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | D2DInterpolationModes | [private]
OnDisplayContentsInvalidated(_In_ Platform::Object^sender) | D2DInterpolationModes | [private]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | D2DInterpolationModes | [private]
OnManipulationUpdated(_In_ Windows::UI::Input::GestureRecognizer^recognizer, _In_ Windows::UI::Input::ManipulationUpdatedEventArgs^args) | D2DInterpolationModes | [private]
OnPointerMoved(_In_ Windows::UI::Core::CoreWindow^window, _In_ Windows::UI::Core::PointerEventArgs^args) | D2DInterpolationModes | [private]
OnPointerPressed(_In_ Windows::UI::Core::CoreWindow^window, _In_ Windows::UI::Core::PointerEventArgs^args) | D2DInterpolationModes | [private]
OnPointerReleased(_In_ Windows::UI::Core::CoreWindow^window, _In_ Windows::UI::Core::PointerEventArgs^args) | D2DInterpolationModes | [private]
OnPointerWheelChanged(_In_ Windows::UI::Core::CoreWindow^window, _In_ Windows::UI::Core::PointerEventArgs^args) | D2DInterpolationModes | [private]
OnResuming(_In_ Platform::Object^sender, _In_ Platform::Object^args) | D2DInterpolationModes | [private]
OnSuspending(_In_ Platform::Object^sender, _In_ Windows::ApplicationModel::SuspendingEventArgs^args) | D2DInterpolationModes | [private]
OnVisibilityChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::VisibilityChangedEventArgs^args) | D2DInterpolationModes | [private]
OnWindowClosed(_In_ Windows::UI::Core::CoreWindow^window, _In_ Windows::UI::Core::CoreWindowEventArgs^args) | D2DInterpolationModes | [private]
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | D2DInterpolationModes | [private]
Render() override | D2DInterpolationModes | [virtual]
Run() | D2DInterpolationModes | [virtual]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | D2DInterpolationModes | [virtual]
Uninitialize() | D2DInterpolationModes | [virtual]
UpdateEffectMatrices() | D2DInterpolationModes |
Generated on Sat Nov 23 2024 16:09:10 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML Popup/C++/Scenario1.xaml.cpp Source File

  • XAML Popup

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::XAMLPopup;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 Scenario1::Scenario1()
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 Scenario1::OnNavigatedTo(NavigationEventArgs^ e)
00036 {
00037     rootPage = MainPage::Current;
00038 }
00039
00040 // Handles the Click event on the Button within the simple Popup control and simply opens it.
00041 void SDKSample::XAMLPopup::Scenario1::ShowPopupOffsetClicked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00042 {
00043     // open the Popup if it isn't open already
00044   if (!StandardPopup->IsOpen) { StandardPopup->IsOpen = true; }
00045 }
00046
00047 // Handles the Click event on the Button within the simple Popup control and simply closes it.
00048 void SDKSample::XAMLPopup::Scenario1::ClosePopupClicked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00049 {
00050     // open the Popup if it isn't open already
00051   if (StandardPopup->IsOpen) { StandardPopup->IsOpen = false; }
00052 }
Generated on Sat Nov 23 2024 16:07:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

ConstantBufferNeverChanges Member List

This is the complete list of members for ConstantBufferNeverChanges, including all inherited members.
lightColor | ConstantBufferNeverChanges
lightPosition | ConstantBufferNeverChanges
Generated on Sat Nov 23 2024 16:09:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D custom image effects/C++/VertexShader/DirectXBase.cpp Source File

  • Direct2D custom image effects
  • VertexShader

DirectXBase.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 "DirectXBase.h"
00010
00011 using namespace Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::Graphics::Display;
00015 using namespace D2D1;
00016
00017 // Constructor.
00018 DirectXBase::DirectXBase() :
00019     m_windowSizeChangeInProgress(false),
00020     m_dpi(-1.0f)
00021 {
00022 }
00023
00024 // Initialize the DirectX resources required to run.
00025 void DirectXBase::Initialize(CoreWindow^ window, float dpi)
00026 {
00027     m_window = window;
00028
00029     CreateDeviceIndependentResources();
00030     CreateDeviceResources();
00031     SetDpi(dpi);
00032 }
00033
00034 // Recreate all device resources and set them back to the current state.
00035 void DirectXBase::HandleDeviceLost()
00036 {
00037     // Reset these member variables to ensure that SetDpi recreates all resources.
00038     float dpi = m_dpi;
00039     m_dpi = -1.0f;
00040     m_windowBounds.Width = 0;
00041     m_windowBounds.Height = 0;
00042     m_swapChain = nullptr;
00043
00044     CreateDeviceResources();
00045     SetDpi(dpi);
00046 }
00047
00048 // These are the resources required independent of the device.
00049 void DirectXBase::CreateDeviceIndependentResources()
00050 {
00051     D2D1_FACTORY_OPTIONS options;
00052     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00053
00054 #if defined(_DEBUG)
00055     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00056     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00057 #endif
00058
00059     DX::ThrowIfFailed(
00060         D2D1CreateFactory(
00061             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00062             __uuidof(ID2D1Factory1),
00063             &options,
00064             &m_d2dFactory
00065             )
00066         );
00067
00068     DX::ThrowIfFailed(
00069         DWriteCreateFactory(
00070             DWRITE_FACTORY_TYPE_SHARED,
00071             __uuidof(IDWriteFactory),
00072             &m_dwriteFactory
00073             )
00074         );
00075
00076     DX::ThrowIfFailed(
00077         CoCreateInstance(
00078             CLSID_WICImagingFactory,
00079             nullptr,
00080             CLSCTX_INPROC_SERVER,
00081             IID_PPV_ARGS(&m_wicFactory)
00082             )
00083         );
00084 }
00085
00086 // These are the resources that depend on the device.
00087 void DirectXBase::CreateDeviceResources()
00088 {
00089     // This flag adds support for surfaces with a different color channel ordering
00090     // than the API default. It is required for compatibility with Direct2D.
00091     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00092     ComPtr<IDXGIDevice> dxgiDevice;
00093
00094 #if defined(_DEBUG)
00095     // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00096     creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00097 #endif
00098
00099     // This array defines the set of DirectX hardware feature levels this app will support.
00100     // Note the ordering should be preserved.
00101     // Don't forget to declare your application's minimum required feature level in its
00102     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00103     D3D_FEATURE_LEVEL featureLevels[] =
00104     {
00105         D3D_FEATURE_LEVEL_11_1,
00106         D3D_FEATURE_LEVEL_11_0,
00107         D3D_FEATURE_LEVEL_10_1,
00108         D3D_FEATURE_LEVEL_10_0,
00109         D3D_FEATURE_LEVEL_9_3,
00110         D3D_FEATURE_LEVEL_9_2,
00111         D3D_FEATURE_LEVEL_9_1
00112     };
00113
00114     // Create the Direct3D 11 API device object and a corresponding context.
00115     ComPtr<ID3D11Device> device;
00116     ComPtr<ID3D11DeviceContext> context;
00117     DX::ThrowIfFailed(
00118         D3D11CreateDevice(
00119             nullptr,                    // Specify nullptr to use the default adapter.
00120             D3D_DRIVER_TYPE_HARDWARE,
00121             0,
00122             creationFlags,              // Set debug and Direct2D compatibility flags.
00123             featureLevels,              // List of feature levels this app can support.
00124             ARRAYSIZE(featureLevels),
00125             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Metro style apps.
00126             &device,                    // Returns the Direct3D device created.
00127             &m_featureLevel,            // Returns feature level of device created.
00128             &context                    // Returns the device immediate context.
00129             )
00130         );
00131
00132     // Get the Direct3D 11.1 API device and context interfaces.
00133     DX::ThrowIfFailed(
00134         device.As(&m_d3dDevice)
00135         );
00136
00137     DX::ThrowIfFailed(
00138         context.As(&m_d3dContext)
00139         );
00140
00141     // Get the underlying DXGI device of the Direct3D device.
00142     DX::ThrowIfFailed(
00143         m_d3dDevice.As(&dxgiDevice)
00144         );
00145
00146     // Create the Direct2D device object and a corresponding context.
00147     DX::ThrowIfFailed(
00148         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00149         );
00150
00151     DX::ThrowIfFailed(
00152         m_d2dDevice->CreateDeviceContext(
00153             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00154             &m_d2dContext
00155             )
00156         );
00157 }
00158
00159 // Helps track the DPI in the helper class.
00160 // This is called in the dpiChanged event handler in the view class.
00161 void DirectXBase::SetDpi(float dpi)
00162 {
00163     if (dpi != m_dpi)
00164     {
00165         // Save the DPI of this display in our class.
00166         m_dpi = dpi;
00167
00168         // Update Direct2D's stored DPI.
00169         m_d2dContext->SetDpi(m_dpi, m_dpi);
00170
00171         // Often a DPI change implies a window size change. In some cases Windows will issue
00172         // both a size changed event and a DPI changed event. In this case, the resulting bounds
00173         // will not change, and the window resize code will only be executed once.
00174         UpdateForWindowSizeChange();
00175     }
00176 }
00177
00178 // This routine is called in the event handler for the view SizeChanged event.
00179 void DirectXBase::UpdateForWindowSizeChange()
00180 {
00181     // Only handle window size changed if there is no pending DPI change.
00182     if (m_dpi != DisplayProperties::LogicalDpi)
00183     {
00184         return;
00185     }
00186
00187     if (m_window->Bounds.Width  != m_windowBounds.Width ||
00188         m_window->Bounds.Height != m_windowBounds.Height)
00189     {
00190         m_d2dContext->SetTarget(nullptr);
00191         m_d2dTargetBitmap = nullptr;
00192         m_d3dRenderTargetView = nullptr;
00193         m_d3dDepthStencilView = nullptr;
00194         m_windowSizeChangeInProgress = true;
00195         CreateWindowSizeDependentResources();
00196     }
00197 }
00198
00199 // Allocate all memory resources that change on a window SizeChanged event.
00200 void DirectXBase::CreateWindowSizeDependentResources()
00201 {
00202     // Store the window bounds so the next time we get a SizeChanged event we can
00203     // avoid rebuilding everything if the size is identical.
00204     m_windowBounds = m_window->Bounds;
00205
00206     if (m_swapChain != nullptr)
00207     {
00208         // If the swap chain already exists, resize it.
00209         HRESULT hr = m_swapChain->ResizeBuffers(2, 0, 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0);
00210
00211         if (hr == DXGI_ERROR_DEVICE_REMOVED)
00212         {
00213             // If the device was removed for any reason, a new device and swapchain will need to be created.
00214             HandleDeviceLost();
00215
00216             // Everything is set up now. Do not continue execution of this method.
00217             return;
00218         }
00219         else
00220         {
00221             DX::ThrowIfFailed(hr);
00222         }
00223     }
00224     else
00225     {
00226         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00227         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00228         swapChainDesc.Width = 0;                                     // Use automatic sizing.
00229         swapChainDesc.Height = 0;
00230         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;           // This is the most common swap chain format.
00231         swapChainDesc.Stereo = false;
00232         swapChainDesc.SampleDesc.Count = 1;                          // Don't use multi-sampling.
00233         swapChainDesc.SampleDesc.Quality = 0;
00234         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00235         swapChainDesc.BufferCount = 2;                               // Use double-buffering to minimize latency.
00236         swapChainDesc.Scaling = DXGI_SCALING_NONE;
00237         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Metro style apps must use this SwapEffect.
00238         swapChainDesc.Flags = 0;
00239
00240         ComPtr<IDXGIDevice1> dxgiDevice;
00241         DX::ThrowIfFailed(
00242             m_d3dDevice.As(&dxgiDevice)
00243             );
00244
00245         ComPtr<IDXGIAdapter> dxgiAdapter;
00246         DX::ThrowIfFailed(
00247             dxgiDevice->GetAdapter(&dxgiAdapter)
00248             );
00249
00250         ComPtr<IDXGIFactory2> dxgiFactory;
00251         DX::ThrowIfFailed(
00252             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00253             );
00254
00255         CoreWindow^ window = m_window.Get();
00256         DX::ThrowIfFailed(
00257             dxgiFactory->CreateSwapChainForCoreWindow(
00258                 m_d3dDevice.Get(),
00259                 reinterpret_cast<IUnknown*>(window),
00260                 &swapChainDesc,
00261                 nullptr,
00262                 &m_swapChain
00263                 )
00264             );
00265
00266         // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
00267         // ensures that the application will only render after each VSync, minimizing power consumption.
00268         DX::ThrowIfFailed(
00269             dxgiDevice->SetMaximumFrameLatency(1)
00270             );
00271     }
00272
00273     // Create a Direct3D render target view of the swap chain back buffer.
00274     ComPtr<ID3D11Texture2D> backBuffer;
00275     DX::ThrowIfFailed(
00276         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00277         );
00278
00279     DX::ThrowIfFailed(
00280         m_d3dDevice->CreateRenderTargetView(
00281             backBuffer.Get(),
00282             nullptr,
00283             &m_d3dRenderTargetView
00284             )
00285         );
00286
00287     // Cache the rendertarget dimensions in our helper class for convenient use.
00288     D3D11_TEXTURE2D_DESC backBufferDesc = {0};
00289     backBuffer->GetDesc(&backBufferDesc);
00290     m_renderTargetSize.Width  = static_cast<float>(backBufferDesc.Width);
00291     m_renderTargetSize.Height = static_cast<float>(backBufferDesc.Height);
00292
00293     // Create a depth stencil view for use with 3D rendering if needed.
00294     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00295         DXGI_FORMAT_D24_UNORM_S8_UINT,
00296         backBufferDesc.Width,
00297         backBufferDesc.Height,
00298         1,
00299         1,
00300         D3D11_BIND_DEPTH_STENCIL
00301         );
00302
00303     ComPtr<ID3D11Texture2D> depthStencil;
00304     DX::ThrowIfFailed(
00305         m_d3dDevice->CreateTexture2D(
00306             &depthStencilDesc,
00307             nullptr,
00308             &depthStencil
00309             )
00310         );
00311
00312     auto viewDesc = CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D);
00313     DX::ThrowIfFailed(
00314         m_d3dDevice->CreateDepthStencilView(
00315             depthStencil.Get(),
00316             &viewDesc,
00317             &m_d3dDepthStencilView
00318             )
00319         );
00320
00321     // Set the 3D rendering viewport to target the entire window.
00322     CD3D11_VIEWPORT viewport(
00323         0.0f,
00324         0.0f,
00325         static_cast<float>(backBufferDesc.Width),
00326         static_cast<float>(backBufferDesc.Height)
00327         );
00328
00329     m_d3dContext->RSSetViewports(1, &viewport);
00330
00331     // Create a Direct2D target bitmap associated with the
00332     // swap chain back buffer and set it as the current target.
00333     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00334         BitmapProperties1(
00335             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00336             PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00337             m_dpi,
00338             m_dpi
00339             );
00340
00341     ComPtr<IDXGISurface> dxgiBackBuffer;
00342     DX::ThrowIfFailed(
00343         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00344         );
00345
00346     DX::ThrowIfFailed(
00347         m_d2dContext->CreateBitmapFromDxgiSurface(
00348             dxgiBackBuffer.Get(),
00349             &bitmapProperties,
00350             &m_d2dTargetBitmap
00351             )
00352         );
00353
00354     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00355
00356     // Grayscale text anti-aliasing is recommended for all Metro style apps.
00357     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00358 }
00359
00360 // Method to deliver the final image to the display.
00361 void DirectXBase::Present()
00362 {
00363     // The application may optionally specify "dirty" or "scroll" rects to improve efficiency
00364     // in certain scenarios.  In this sample, however, we do not utilize those features.
00365     DXGI_PRESENT_PARAMETERS parameters = {0};
00366     parameters.DirtyRectsCount = 0;
00367     parameters.pDirtyRects = nullptr;
00368     parameters.pScrollRect = nullptr;
00369     parameters.pScrollOffset = nullptr;
00370
00371     // The first argument instructs DXGI to block until VSync, putting the application
00372     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00373     // frames that will never be displayed to the screen.
00374     HRESULT hr = m_swapChain->Present1(1, 0, &parameters);
00375
00376     // Discard the contents of the render target.
00377     // This is a valid operation only when the existing contents will be entirely
00378     // overwritten. If dirty or scroll rects are used, this call should be removed.
00379     m_d3dContext->DiscardView(m_d3dRenderTargetView.Get());
00380
00381     // Discard the contents of the depth stencil.
00382     m_d3dContext->DiscardView(m_d3dDepthStencilView.Get());
00383
00384     // If the device was removed either by a disconnect or a driver upgrade, we
00385     // must recreate all device resources.
00386     if (hr == DXGI_ERROR_DEVICE_REMOVED)
00387     {
00388         HandleDeviceLost();
00389     }
00390     else
00391     {
00392         DX::ThrowIfFailed(hr);
00393     }
00394
00395     if (m_windowSizeChangeInProgress)
00396     {
00397         // A window size change has been initiated and the app has just completed presenting
00398         // the first frame with the new size. Notify the resize manager so we can short
00399         // circuit any resize animation and prevent unnecessary delays.
00400         CoreWindowResizeManager::GetForCurrentView()->NotifyLayoutCompleted();
00401         m_windowSizeChangeInProgress = false;
00402     }
00403 }
00404
00405 void DirectXBase::ValidateDevice()
00406 {
00407     // The D3D Device is no longer valid if the default adapter changes or if
00408     // the device has been removed.
00409
00410     // First, get the information for the adapter related to the current device.
00411
00412     ComPtr<IDXGIDevice1> dxgiDevice;
00413     ComPtr<IDXGIAdapter> deviceAdapter;
00414     DXGI_ADAPTER_DESC deviceDesc;
00415     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00416     DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter));
00417     DX::ThrowIfFailed(deviceAdapter->GetDesc(&deviceDesc));
00418
00419     // Next, get the information for the default adapter.
00420
00421     ComPtr<IDXGIFactory2> dxgiFactory;
00422     ComPtr<IDXGIAdapter1> currentAdapter;
00423     DXGI_ADAPTER_DESC currentDesc;
00424     DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)));
00425     DX::ThrowIfFailed(dxgiFactory->EnumAdapters1(0, &currentAdapter));
00426     DX::ThrowIfFailed(currentAdapter->GetDesc(&currentDesc));
00427
00428     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00429     // a new D3D device must be created.
00430
00431     if ((deviceDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart) ||
00432         (deviceDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart) ||
00433         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00434     {
00435         // Release references to resources related to the old device.
00436         dxgiDevice = nullptr;
00437         deviceAdapter = nullptr;
00438
00439         // Create a new device and swap chain.
00440         HandleDeviceLost();
00441     }
00442 }
Generated on Sat Nov 23 2024 16:08:02 for Win8-Examples by doxygen 1.7.1


Win8-Examples: UI contrast and settings/C++/UI.xaml.cpp Source File

  • UI contrast and settings

UI.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 // UI.xaml.cpp
00013 // Implementation of the UI class
00014 //
00015
00016 #include "pch.h"
00017 #include "UI.xaml.h"
00018
00019 using namespace SDKSample::HighContrast;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 using namespace Windows::UI::ViewManagement;
00026
00027
00028 UI::UI()
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 UI::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 SDKSample::HighContrast::UI::UIGetSettings_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00046 {
00047     Button^ b = safe_cast<Button^>(sender);
00048     if (b != nullptr)
00049     {
00050     UISettings^ pUserSettings = ref new UISettings();
00051     Platform::String^ Buffer;
00052         Windows::UI::Color Color;
00053
00054         Buffer =  "Hand Preference " + (pUserSettings->HandPreference == HandPreference::RightHanded ? "right" : "left") + "\n";
00055         Buffer += "Cursor Size "  + pUserSettings->CursorSize.Width.ToString() + " x " + pUserSettings->CursorSize.Height.ToString() + "\n";
00056         Buffer += "Scrollbar Size "  + pUserSettings->ScrollBarSize.Width.ToString() + " x " + pUserSettings->ScrollBarSize.Height.ToString() + "\n";
00057         Buffer += "Scrollbar Arrow Size "   + pUserSettings->ScrollBarArrowSize.Width.ToString() + " x " + pUserSettings->ScrollBarArrowSize.Height.ToString() + "\n";
00058         Buffer += "Scrollbar Thumb Box Size " + pUserSettings->ScrollBarThumbBoxSize.Width.ToString() + " x " + pUserSettings->ScrollBarThumbBoxSize.Height.ToString() + "\n";
00059         Buffer += "Message Duration "  + pUserSettings->MessageDuration.ToString() + "\n";
00060         Buffer += "Animations Enabled "  + (pUserSettings->AnimationsEnabled ? "true" : "false") + "\n";
00061         Buffer += "Caret Browsing Enabled "  + (pUserSettings->CaretBrowsingEnabled ? "true" : "false") + "\n";
00062         Buffer += "Caret Blink Rate "  + pUserSettings->CaretBlinkRate.ToString() + "\n";
00063         Buffer += "Caret Width " + pUserSettings->CaretWidth.ToString() + "\n";
00064         Buffer += "Double Click Time " + pUserSettings->DoubleClickTime.ToString() + "\n";
00065         Buffer += "Mouse Hover Time " + pUserSettings->MouseHoverTime.ToString() + "\n";
00066
00067         Buffer += "System Colors: \n";
00068
00069         Color = pUserSettings->UIElementColor(UIElementType::ActiveCaption);
00070         Buffer += "Active Caption: " + Color.R.ToString() + ", " + Color.G.ToString() + ", " + Color.B.ToString() + "\n";
00071         Color = pUserSettings->UIElementColor(UIElementType::Background);
00072         Buffer += "Background: " + Color.R.ToString() + ", " + Color.G.ToString() + ", " + Color.B.ToString() + "\n";
00073         Color = pUserSettings->UIElementColor(UIElementType::ButtonFace);
00074         Buffer += "Button Face: " + Color.R.ToString() + ", " + Color.G.ToString() + ", " + Color.B.ToString() + "\n";
00075         Color = pUserSettings->UIElementColor(UIElementType::ButtonText);
00076         Buffer += "Button Text: " + Color.R.ToString() + ", " + Color.G.ToString() + ", " + Color.B.ToString() + "\n";
00077         Color = pUserSettings->UIElementColor(UIElementType::CaptionText);
00078         Buffer += "Caption Text: " + Color.R.ToString() + ", " + Color.G.ToString() + ", " + Color.B.ToString() + "\n";
00079         Color = pUserSettings->UIElementColor(UIElementType::GrayText);
00080         Buffer += "Gray Text: " + Color.R.ToString() + ", " + Color.G.ToString() + ", " + Color.B.ToString() + "\n";
00081         Color = pUserSettings->UIElementColor(UIElementType::Highlight);
00082         Buffer += "Highlight: " + Color.R.ToString() + ", " + Color.G.ToString() + ", " + Color.B.ToString() + "\n";
00083         Color = pUserSettings->UIElementColor(UIElementType::HighlightText);
00084         Buffer += "Highlight Text: " + Color.R.ToString() + ", " + Color.G.ToString() + ", " + Color.B.ToString() + "\n";
00085         Color = pUserSettings->UIElementColor(UIElementType::Hotlight);
00086         Buffer += "Hotlight: " + Color.R.ToString() + ", " + Color.G.ToString() + ", " + Color.B.ToString() + "\n";
00087         Color = pUserSettings->UIElementColor(UIElementType::InactiveCaption);
00088         Buffer += "Inactive Caption: " + Color.R.ToString() + ", " + Color.G.ToString() + ", " + Color.B.ToString() + "\n";
00089         Color = pUserSettings->UIElementColor(UIElementType::InactiveCaptionText);
00090         Buffer += "Inactive Caption Text: " + Color.R.ToString() + ", " + Color.G.ToString() + ", " + Color.B.ToString() + "\n";
00091         Color = pUserSettings->UIElementColor(UIElementType::Window);
00092         Buffer += "Window: " + Color.R.ToString() + ", " + Color.G.ToString() + ", " + Color.B.ToString() + "\n";
00093         Color = pUserSettings->UIElementColor(UIElementType::WindowText);
00094         Buffer += "Window Text: " + Color.R.ToString() + ", " + Color.G.ToString() + ", " + Color.B.ToString() + "\n";
00095
00096     UIOutputTextBlock->Text = Buffer;
00097     }
00098 }
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XInput audio controller playback/C++/SampleOverlay.cpp Source File

  • XInput audio controller playback

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 Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::UI::ViewManagement;
00015 using namespace Windows::Graphics::Display;
00016 using namespace D2D1;
00017
00018 SampleOverlay::SampleOverlay() :
00019     m_drawOverlay(true)
00020 {
00021 }
00022
00023 void SampleOverlay::Initialize(
00024     _In_ ID2D1Device*         d2dDevice,
00025     _In_ ID2D1DeviceContext*  d2dContext,
00026     _In_ IWICImagingFactory*  wicFactory,
00027     _In_ IDWriteFactory*      dwriteFactory,
00028     _In_ Platform::String^    caption
00029     )
00030 {
00031     m_wicFactory = wicFactory;
00032     m_dwriteFactory = dwriteFactory;
00033     m_sampleName = caption;
00034     m_d2dDevice = d2dDevice;
00035     m_d2dContext = d2dContext;
00036     m_padding = 3.0f;
00037     m_textVerticalOffset = 5.0f;
00038     m_logoSize = D2D1::SizeF(0.0f, 0.0f);
00039     m_overlayWidth = 0.0f;
00040
00041     ComPtr<ID2D1Factory> factory;
00042     d2dDevice->GetFactory(&factory);
00043
00044     DX::ThrowIfFailed(
00045         factory.As(&m_d2dFactory)
00046         );
00047
00048     ResetDirectXResources();
00049 }
00050
00051 void SampleOverlay::ResetDirectXResources()
00052 {
00053     DX::ThrowIfFailed(
00054         m_d2dContext->CreateSolidColorBrush(ColorF(ColorF::White), &m_whiteBrush)
00055         );
00056
00057     ComPtr<IWICBitmapDecoder> wicBitmapDecoder;
00058     DX::ThrowIfFailed(
00059         m_wicFactory->CreateDecoderFromFilename(
00060             L"windowsbig-sdk.png",
00061             nullptr,
00062             GENERIC_READ,
00063             WICDecodeMetadataCacheOnDemand,
00064             &wicBitmapDecoder
00065             )
00066         );
00067
00068     ComPtr<IWICBitmapFrameDecode> wicBitmapFrame;
00069     DX::ThrowIfFailed(
00070         wicBitmapDecoder->GetFrame(0, &wicBitmapFrame)
00071         );
00072
00073     ComPtr<IWICFormatConverter> wicFormatConverter;
00074     DX::ThrowIfFailed(
00075         m_wicFactory->CreateFormatConverter(&wicFormatConverter)
00076         );
00077
00078     DX::ThrowIfFailed(
00079         wicFormatConverter->Initialize(
00080             wicBitmapFrame.Get(),
00081             GUID_WICPixelFormat32bppPBGRA,
00082             WICBitmapDitherTypeNone,
00083             nullptr,
00084             0.0,
00085             WICBitmapPaletteTypeCustom  // the BGRA format has no palette so this value is ignored
00086             )
00087         );
00088
00089     double dpiX = 96.0f;
00090     double dpiY = 96.0f;
00091     DX::ThrowIfFailed(
00092         wicFormatConverter->GetResolution(&dpiX, &dpiY)
00093         );
00094
00095     DX::ThrowIfFailed(
00096         m_d2dContext->CreateBitmapFromWicBitmap(
00097             wicFormatConverter.Get(),
00098             BitmapProperties(
00099                 PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00100                 static_cast<float>(dpiX),
00101                 static_cast<float>(dpiY)
00102                 ),
00103             &m_logoBitmap
00104             )
00105         );
00106
00107     m_logoSize = m_logoBitmap->GetSize();
00108
00109     ComPtr<IDWriteTextFormat> nameTextFormat;
00110     DX::ThrowIfFailed(
00111         m_dwriteFactory->CreateTextFormat(
00112             L"Segoe UI",
00113             nullptr,
00114             DWRITE_FONT_WEIGHT_LIGHT,
00115             DWRITE_FONT_STYLE_NORMAL,
00116             DWRITE_FONT_STRETCH_NORMAL,
00117             36.0f,
00118             L"en-US",
00119             &nameTextFormat
00120             )
00121         );
00122
00123     DX::ThrowIfFailed(
00124         nameTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)
00125         );
00126
00127     DX::ThrowIfFailed(
00128         nameTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)
00129         );
00130
00131     DX::ThrowIfFailed(
00132         m_dwriteFactory->CreateTextLayout(
00133             m_sampleName->Data(),
00134             m_sampleName->Length(),
00135             nameTextFormat.Get(),
00136             4096.0f,
00137             4096.0f,
00138             &m_textLayout
00139             )
00140         );
00141
00142     DWRITE_TEXT_METRICS metrics = {0};
00143     DX::ThrowIfFailed(
00144         m_textLayout->GetMetrics(&metrics)
00145         );
00146
00147     m_overlayWidth = m_padding * 3.0f + m_logoSize.width + metrics.width;
00148
00149     DX::ThrowIfFailed(
00150         m_d2dFactory->CreateDrawingStateBlock(&m_stateBlock)
00151         );
00152
00153     UpdateForWindowSizeChange();
00154 }
00155
00156 void SampleOverlay::UpdateForWindowSizeChange()
00157 {
00158     if (CoreWindow::GetForCurrentThread()->Bounds.Width < m_overlayWidth)
00159     {
00160         m_drawOverlay = false;
00161     }
00162     else
00163     {
00164         m_drawOverlay = true;
00165     }
00166 }
00167
00168 void SampleOverlay::Render()
00169 {
00170     if (m_drawOverlay)
00171     {
00172         m_d2dContext->SaveDrawingState(m_stateBlock.Get());
00173
00174         m_d2dContext->BeginDraw();
00175         m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00176         m_d2dContext->DrawBitmap(
00177             m_logoBitmap.Get(),
00178             D2D1::RectF(m_padding, 0.0f, m_logoSize.width + m_padding, m_logoSize.height)
00179             );
00180
00181         m_d2dContext->DrawTextLayout(
00182             Point2F(m_logoSize.width + 2.0f * m_padding, m_textVerticalOffset),
00183             m_textLayout.Get(),
00184             m_whiteBrush.Get()
00185             );
00186
00187         // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00188         // is lost. It will be handled during the next call to Present.
00189         HRESULT hr = m_d2dContext->EndDraw();
00190         if (hr != D2DERR_RECREATE_TARGET)
00191         {
00192             DX::ThrowIfFailed(hr);
00193         }
00194
00195         m_d2dContext->RestoreDrawingState(m_stateBlock.Get());
00196     }
00197 }
00198
00199 float SampleOverlay::GetTitleHeightInDips()
00200 {
00201     return m_logoSize.height;
00202 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/DirectXApp.cpp Source File

  • DirectX 3D shooting game

DirectXApp.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 "DirectXApp.h"
00010
00011 using namespace concurrency;
00012 using namespace DirectX;
00013 using namespace Windows::ApplicationModel;
00014 using namespace Windows::ApplicationModel::Activation;
00015 using namespace Windows::ApplicationModel::Core;
00016 using namespace Windows::Foundation;
00017 using namespace Windows::Graphics::Display;
00018 using namespace Windows::UI::Core;
00019 using namespace Windows::UI::Input;
00020 using namespace Windows::UI::ViewManagement;
00021
00022
00023 DirectXApp::DirectXApp() :
00024     m_windowClosed(false),
00025     m_haveFocus(false),
00026     m_gameInfoOverlayCommand(GameInfoOverlayCommand::None),
00027     m_visible(true),
00028     m_loadingCount(0),
00029     m_updateState(UpdateEngineState::WaitingForResources)
00030 {
00031 }
00032
00033 //--------------------------------------------------------------------------------------
00034
00035 void DirectXApp::Initialize(
00036     _In_ CoreApplicationView^ applicationView
00037     )
00038 {
00039     applicationView->Activated +=
00040         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &DirectXApp::OnActivated);
00041
00042     CoreApplication::Suspending +=
00043         ref new EventHandler<SuspendingEventArgs^>(this, &DirectXApp::OnSuspending);
00044
00045     CoreApplication::Resuming +=
00046         ref new EventHandler<Platform::Object^>(this, &DirectXApp::OnResuming);
00047
00048     m_controller = ref new MoveLookController();
00049     m_renderer = ref new GameRenderer();
00050     m_game = ref new Simple3DGame();
00051 }
00052
00053 //--------------------------------------------------------------------------------------
00054
00055 void DirectXApp::SetWindow(
00056     _In_ CoreWindow^ window
00057     )
00058 {
00059     window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
00060
00061     PointerVisualizationSettings^ visualizationSettings = PointerVisualizationSettings::GetForCurrentView();
00062     visualizationSettings->IsContactFeedbackEnabled = false;
00063     visualizationSettings->IsBarrelButtonFeedbackEnabled = false;
00064
00065     window->SizeChanged +=
00066         ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &DirectXApp::OnWindowSizeChanged);
00067
00068     window->Closed +=
00069         ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &DirectXApp::OnWindowClosed);
00070
00071     window->VisibilityChanged +=
00072         ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &DirectXApp::OnVisibilityChanged);
00073
00074     DisplayProperties::LogicalDpiChanged +=
00075         ref new DisplayPropertiesEventHandler(this, &DirectXApp::OnLogicalDpiChanged);
00076
00077     DisplayProperties::DisplayContentsInvalidated +=
00078         ref new DisplayPropertiesEventHandler(this, &DirectXApp::OnDisplayContentsInvalidated);
00079
00080     m_controller->Initialize(window);
00081
00082     m_controller->SetMoveRect(
00083         XMFLOAT2(0.0f, window->Bounds.Height - GameConstants::TouchRectangleSize),
00084         XMFLOAT2(GameConstants::TouchRectangleSize, window->Bounds.Height)
00085         );
00086     m_controller->SetFireRect(
00087         XMFLOAT2(window->Bounds.Width - GameConstants::TouchRectangleSize, window->Bounds.Height - GameConstants::TouchRectangleSize),
00088         XMFLOAT2(window->Bounds.Width, window->Bounds.Height)
00089         );
00090
00091     m_renderer->Initialize(window, DisplayProperties::LogicalDpi);
00092     m_renderer->DeviceLost += ref new D3DDeviceEventHandler(this, &DirectXApp::OnDeviceLost);
00093     m_renderer->DeviceReset += ref new D3DDeviceEventHandler(this, &DirectXApp::OnDeviceReset);
00094
00095     SetGameInfoOverlay(GameInfoOverlayState::Loading);
00096     ShowGameInfoOverlay();
00097 }
00098
00099 //--------------------------------------------------------------------------------------
00100
00101 void DirectXApp::Load(
00102     _In_ Platform::String^ /* entryPoint */
00103     )
00104 {
00105     create_task([this]()
00106     {
00107         // Asynchronously initialize the game class and load the renderer device resources.
00108         // By doing all this asynchronously, the game gets to its main loop more quickly
00109         // and in parallel all the necessary resources are loaded on other threads.
00110         m_game->Initialize(m_controller, m_renderer);
00111
00112         return m_renderer->CreateGameDeviceResourcesAsync(m_game);
00113
00114     }).then([this]()
00115     {
00116         // The finalize code needs to run in the same thread context
00117         // as the m_renderer object was created because the D3D device context
00118         // can ONLY be accessed on a single thread.
00119         m_renderer->FinalizeCreateGameDeviceResources();
00120
00121         InitializeGameState();
00122
00123         if (m_updateState == UpdateEngineState::WaitingForResources)
00124         {
00125             // In the middle of a game so spin up the async task to load the level.
00126             create_task([this]()
00127             {
00128                 return m_game->LoadLevelAsync();
00129
00130             }).then([this]()
00131             {
00132                 // The m_game object may need to deal with D3D device context work so
00133                 // again the finalize code needs to run in the same thread
00134                 // context as the m_renderer object was created because the D3D
00135                 // device context can ONLY be accessed on a single thread.
00136                 m_game->FinalizeLoadLevel();
00137                 m_game->SetCurrentLevelToSavedState();
00138                 m_updateState = UpdateEngineState::ResourcesLoaded;
00139
00140             }, task_continuation_context::use_current());
00141         }
00142     }, task_continuation_context::use_current());
00143 }
00144
00145 //--------------------------------------------------------------------------------------
00146
00147 void DirectXApp::Run()
00148 {
00149     while (!m_windowClosed)
00150     {
00151         if (m_visible)
00152         {
00153             switch (m_updateState)
00154             {
00155             case UpdateEngineState::Deactivated:
00156             case UpdateEngineState::Snapped:
00157                 if (!m_renderNeeded)
00158                 {
00159                     // The App is not currently the active window, so just wait for events.
00160                     CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
00161                     break;
00162                 }
00163                 // otherwise fall through and do normal processing to get the rendering handled.
00164             default:
00165                 CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
00166                 Update();
00167                 m_renderer->Render();
00168                 m_renderNeeded = false;
00169             }
00170         }
00171         else
00172         {
00173             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
00174         }
00175     }
00176     m_game->OnSuspending();  // exiting due to window close.  Make sure to save state.
00177 }
00178
00179 //--------------------------------------------------------------------------------------
00180
00181 void DirectXApp::Uninitialize()
00182 {
00183 }
00184
00185 //--------------------------------------------------------------------------------------
00186
00187 void DirectXApp::OnWindowSizeChanged(
00188     _In_ CoreWindow^ window,
00189     _In_ WindowSizeChangedEventArgs^ /* args */
00190     )
00191 {
00192     UpdateViewState();
00193     m_renderer->UpdateForWindowSizeChange();
00194
00195     // The location of the Control regions may have changed with the size change so update the controller.
00196     m_controller->SetMoveRect(
00197         XMFLOAT2(0.0f, window->Bounds.Height - GameConstants::TouchRectangleSize),
00198         XMFLOAT2(GameConstants::TouchRectangleSize, window->Bounds.Height)
00199         );
00200     m_controller->SetFireRect(
00201         XMFLOAT2(window->Bounds.Width - GameConstants::TouchRectangleSize, window->Bounds.Height - GameConstants::TouchRectangleSize),
00202         XMFLOAT2(window->Bounds.Width, window->Bounds.Height)
00203         );
00204
00205     if (m_updateState == UpdateEngineState::WaitingForPress)
00206     {
00207         // A side effect of m_renderer->UpdateForWindowSizeChange() is that the GameInfoOverlay rectangle may have
00208         // changed as a result of layout, so make sure the WaitForPress rectangle is set to the new size.
00209         m_controller->WaitForPress(m_renderer->GameInfoOverlayUpperLeft(), m_renderer->GameInfoOverlayLowerRight());
00210     }
00211 }
00212
00213 //--------------------------------------------------------------------------------------
00214
00215 void DirectXApp::OnWindowClosed(
00216     _In_ CoreWindow^ /* sender */,
00217     _In_ CoreWindowEventArgs^ /* args */
00218     )
00219 {
00220     m_windowClosed = true;
00221 }
00222
00223 //--------------------------------------------------------------------------------------
00224
00225 void DirectXApp::OnLogicalDpiChanged(
00226     _In_ Platform::Object^ /* sender */
00227     )
00228 {
00229     m_renderer->SetDpi(DisplayProperties::LogicalDpi);
00230
00231     // The GameInfoOverlay may have been recreated as a result of DPI changes so
00232     // regenerate the data.
00233     SetGameInfoOverlay(m_gameInfoOverlayState);
00234     SetAction(m_gameInfoOverlayCommand);
00235 }
00236
00237 //--------------------------------------------------------------------------------------
00238
00239 void DirectXApp::OnDisplayContentsInvalidated(
00240     _In_ Platform::Object^ /* sender */
00241     )
00242 {
00243     m_renderNeeded = true;
00244 }
00245
00246 //--------------------------------------------------------------------------------------
00247
00248 void DirectXApp::OnActivated(
00249     _In_ CoreApplicationView^ /* applicationView */,
00250     _In_ IActivatedEventArgs^ /* args */
00251     )
00252 {
00253     CoreWindow::GetForCurrentThread()->Activated +=
00254         ref new TypedEventHandler<CoreWindow^, WindowActivatedEventArgs^>(this, &DirectXApp::OnWindowActivationChanged);
00255     CoreWindow::GetForCurrentThread()->Activate();
00256 }
00257
00258 //--------------------------------------------------------------------------------------
00259
00260 void DirectXApp::OnVisibilityChanged(
00261     _In_ CoreWindow^ /* sender */,
00262     _In_ VisibilityChangedEventArgs^ args
00263     )
00264 {
00265     m_visible = args->Visible;
00266 }
00267
00268 //--------------------------------------------------------------------------------------
00269
00270 void DirectXApp::InitializeGameState()
00271 {
00272     // Set up the initial state machine for handling Game playing state
00273     if (m_game->GameActive() && m_game->LevelActive())
00274     {
00275         // The last time the game terminated it was in the middle
00276         // of a level.
00277         // We are waiting for the user to continue the game.
00278         m_updateState = UpdateEngineState::WaitingForResources;
00279         m_pressResult = PressResultState::ContinueLevel;
00280         SetGameInfoOverlay(GameInfoOverlayState::Pause);
00281         SetAction(GameInfoOverlayCommand::PleaseWait);
00282     }
00283     else if (!m_game->GameActive() && (m_game->HighScore().totalHits > 0))
00284     {
00285         // The last time the game terminated the game had been completed.
00286         // Show the high score.
00287         // We are waiting for the user to acknowledge the high score and start a new game.
00288         // The level resources for the first level will be loaded later.
00289         m_updateState = UpdateEngineState::WaitingForPress;
00290         m_pressResult = PressResultState::LoadGame;
00291         SetGameInfoOverlay(GameInfoOverlayState::GameStats);
00292         m_controller->WaitForPress(m_renderer->GameInfoOverlayUpperLeft(), m_renderer->GameInfoOverlayLowerRight());
00293         SetAction(GameInfoOverlayCommand::TapToContinue);
00294     }
00295     else
00296     {
00297         // This is either the first time the game has run or
00298         // the last time the game terminated the level was completed.
00299         // We are waiting for the user to begin the next level.
00300         m_updateState = UpdateEngineState::WaitingForResources;
00301         m_pressResult = PressResultState::PlayLevel;
00302         SetGameInfoOverlay(GameInfoOverlayState::LevelStart);
00303         SetAction(GameInfoOverlayCommand::PleaseWait);
00304     }
00305     ShowGameInfoOverlay();
00306 }
00307
00308 //--------------------------------------------------------------------------------------
00309
00310 void DirectXApp::Update()
00311 {
00312     static uint32 loadCount = 0;
00313
00314     m_controller->Update();
00315
00316     switch (m_updateState)
00317     {
00318     case UpdateEngineState::WaitingForResources:
00319         // Waiting for initial load.  Display an update once per 60 updates.
00320         loadCount++;
00321         if ((loadCount % 60) == 0)
00322         {
00323             m_loadingCount++;
00324             SetGameInfoOverlay(m_gameInfoOverlayState);
00325         }
00326         break;
00327
00328     case UpdateEngineState::ResourcesLoaded:
00329         switch (m_pressResult)
00330         {
00331         case PressResultState::LoadGame:
00332             SetGameInfoOverlay(GameInfoOverlayState::GameStats);
00333             break;
00334
00335         case PressResultState::PlayLevel:
00336             SetGameInfoOverlay(GameInfoOverlayState::LevelStart);
00337             break;
00338
00339         case PressResultState::ContinueLevel:
00340             SetGameInfoOverlay(GameInfoOverlayState::Pause);
00341             break;
00342         }
00343         m_updateState = UpdateEngineState::WaitingForPress;
00344         SetAction(GameInfoOverlayCommand::TapToContinue);
00345         m_controller->WaitForPress(m_renderer->GameInfoOverlayUpperLeft(), m_renderer->GameInfoOverlayLowerRight());
00346         ShowGameInfoOverlay();
00347         m_renderNeeded = true;
00348         break;
00349
00350     case UpdateEngineState::WaitingForPress:
00351         if (m_controller->IsPressComplete())
00352         {
00353             switch (m_pressResult)
00354             {
00355             case PressResultState::LoadGame:
00356                 m_updateState = UpdateEngineState::WaitingForResources;
00357                 m_pressResult = PressResultState::PlayLevel;
00358                 m_controller->Active(false);
00359                 m_game->LoadGame();
00360                 SetAction(GameInfoOverlayCommand::PleaseWait);
00361                 SetGameInfoOverlay(GameInfoOverlayState::LevelStart);
00362                 ShowGameInfoOverlay();
00363
00364                 m_game->LoadLevelAsync().then([this]()
00365                 {
00366                     m_game->FinalizeLoadLevel();
00367                     m_updateState = UpdateEngineState::ResourcesLoaded;
00368
00369                 }, task_continuation_context::use_current());
00370                 break;
00371
00372             case PressResultState::PlayLevel:
00373                 m_updateState = UpdateEngineState::Dynamics;
00374                 HideGameInfoOverlay();
00375                 m_controller->Active(true);
00376                 m_game->StartLevel();
00377                 break;
00378
00379             case PressResultState::ContinueLevel:
00380                 m_updateState = UpdateEngineState::Dynamics;
00381                 HideGameInfoOverlay();
00382                 m_controller->Active(true);
00383                 m_game->ContinueGame();
00384                 break;
00385             }
00386         }
00387         break;
00388
00389     case UpdateEngineState::Dynamics:
00390         if (m_controller->IsPauseRequested())
00391         {
00392             m_game->PauseGame();
00393             SetGameInfoOverlay(GameInfoOverlayState::Pause);
00394             SetAction(GameInfoOverlayCommand::TapToContinue);
00395             m_updateState = UpdateEngineState::WaitingForPress;
00396             m_pressResult = PressResultState::ContinueLevel;
00397             ShowGameInfoOverlay();
00398         }
00399         else
00400         {
00401             GameState runState = m_game->RunGame();
00402             switch (runState)
00403             {
00404             case GameState::TimeExpired:
00405                 SetAction(GameInfoOverlayCommand::TapToContinue);
00406                 SetGameInfoOverlay(GameInfoOverlayState::GameOverExpired);
00407                 ShowGameInfoOverlay();
00408                 m_updateState = UpdateEngineState::WaitingForPress;
00409                 m_pressResult = PressResultState::LoadGame;
00410                 break;
00411
00412             case GameState::LevelComplete:
00413                 SetAction(GameInfoOverlayCommand::PleaseWait);
00414                 SetGameInfoOverlay(GameInfoOverlayState::LevelStart);
00415                 ShowGameInfoOverlay();
00416                 m_updateState = UpdateEngineState::WaitingForResources;
00417                 m_pressResult = PressResultState::PlayLevel;
00418
00419                 m_game->LoadLevelAsync().then([this]()
00420                 {
00421                     m_game->FinalizeLoadLevel();
00422                     m_updateState = UpdateEngineState::ResourcesLoaded;
00423
00424                 }, task_continuation_context::use_current());
00425                 break;
00426
00427             case GameState::GameComplete:
00428                 SetAction(GameInfoOverlayCommand::TapToContinue);
00429                 SetGameInfoOverlay(GameInfoOverlayState::GameOverCompleted);
00430                 ShowGameInfoOverlay();
00431                 m_updateState  = UpdateEngineState::WaitingForPress;
00432                 m_pressResult = PressResultState::LoadGame;
00433                 break;
00434             }
00435         }
00436
00437         if (m_updateState == UpdateEngineState::WaitingForPress)
00438         {
00439             // Transitioning state, so enable waiting for the press event
00440             m_controller->WaitForPress(m_renderer->GameInfoOverlayUpperLeft(), m_renderer->GameInfoOverlayLowerRight());
00441         }
00442         if (m_updateState == UpdateEngineState::WaitingForResources)
00443         {
00444             // Transitioning state, so shut down the input controller until resources are loaded
00445             m_controller->Active(false);
00446         }
00447         break;
00448     }
00449 }
00450
00451 //--------------------------------------------------------------------------------------
00452
00453 void DirectXApp::OnWindowActivationChanged(
00454     _In_ Windows::UI::Core::CoreWindow^ /* sender */,
00455     _In_ Windows::UI::Core::WindowActivatedEventArgs^ args
00456     )
00457 {
00458     if (args->WindowActivationState == CoreWindowActivationState::Deactivated)
00459     {
00460         m_haveFocus = false;
00461
00462         switch (m_updateState)
00463         {
00464         case UpdateEngineState::Dynamics:
00465             // From Dynamic mode, when coming out of Deactivated rather than going directly back into game play
00466             // go to the paused state waiting for user input to continue
00467             m_updateStateNext = UpdateEngineState::WaitingForPress;
00468             m_pressResult = PressResultState::ContinueLevel;
00469             SetGameInfoOverlay(GameInfoOverlayState::Pause);
00470             ShowGameInfoOverlay();
00471             m_game->PauseGame();
00472             m_updateState = UpdateEngineState::Deactivated;
00473             SetAction(GameInfoOverlayCommand::None);
00474             m_renderNeeded = true;
00475             break;
00476
00477         case UpdateEngineState::WaitingForResources:
00478         case UpdateEngineState::WaitingForPress:
00479             m_updateStateNext = m_updateState;
00480             m_updateState = UpdateEngineState::Deactivated;
00481             SetAction(GameInfoOverlayCommand::None);
00482             ShowGameInfoOverlay();
00483             m_renderNeeded = true;
00484             break;
00485         }
00486         // Don't have focus so shutdown input processing
00487         m_controller->Active(false);
00488     }
00489     else if (args->WindowActivationState == CoreWindowActivationState::CodeActivated
00490         || args->WindowActivationState == CoreWindowActivationState::PointerActivated)
00491     {
00492         m_haveFocus = true;
00493
00494         if (m_updateState == UpdateEngineState::Deactivated)
00495         {
00496             m_updateState = m_updateStateNext;
00497
00498             if (m_updateState == UpdateEngineState::WaitingForPress)
00499             {
00500                 SetAction(GameInfoOverlayCommand::TapToContinue);
00501                 m_controller->WaitForPress(m_renderer->GameInfoOverlayUpperLeft(), m_renderer->GameInfoOverlayLowerRight());
00502             }
00503             else if (m_updateStateNext == UpdateEngineState::WaitingForResources)
00504             {
00505                 SetAction(GameInfoOverlayCommand::PleaseWait);
00506             }
00507         }
00508     }
00509 }
00510
00511 //--------------------------------------------------------------------------------------
00512
00513 void DirectXApp::OnSuspending(
00514     _In_ Platform::Object^ /* sender */,
00515     _In_ SuspendingEventArgs^ args
00516     )
00517 {
00518     // Save application state.
00519     switch (m_updateState)
00520     {
00521     case UpdateEngineState::Dynamics:
00522         // Game is in the active game play state, Stop Game Timer and Pause play and save state
00523         SetAction(GameInfoOverlayCommand::None);
00524         SetGameInfoOverlay(GameInfoOverlayState::Pause);
00525         m_updateStateNext = UpdateEngineState::WaitingForPress;
00526         m_pressResult = PressResultState::ContinueLevel;
00527         m_game->PauseGame();
00528         break;
00529
00530     case UpdateEngineState::WaitingForResources:
00531     case UpdateEngineState::WaitingForPress:
00532         m_updateStateNext = m_updateState;
00533         break;
00534
00535     default:
00536         // any other state don't save as next state as they are trancient states and have already set m_updateStateNext
00537         break;
00538     }
00539     m_updateState = UpdateEngineState::Suspended;
00540
00541     m_controller->Active(false);
00542     m_game->OnSuspending();
00543 }
00544
00545 //--------------------------------------------------------------------------------------
00546
00547 void DirectXApp::OnResuming(
00548     _In_ Platform::Object^ /* sender */,
00549     _In_ Platform::Object^ /* args */
00550     )
00551 {
00552     if (m_haveFocus)
00553     {
00554         m_updateState = m_updateStateNext;
00555     }
00556     else
00557     {
00558         m_updateState = UpdateEngineState::Deactivated;
00559     }
00560
00561     if (m_updateState == UpdateEngineState::WaitingForPress)
00562     {
00563         SetAction(GameInfoOverlayCommand::TapToContinue);
00564         m_controller->WaitForPress(m_renderer->GameInfoOverlayUpperLeft(), m_renderer->GameInfoOverlayLowerRight());
00565     }
00566     m_game->OnResuming();
00567     ShowGameInfoOverlay();
00568     m_renderNeeded = true;
00569 }
00570
00571 //--------------------------------------------------------------------------------------
00572
00573 void DirectXApp::OnDeviceLost()
00574 {
00575     if (m_updateState == UpdateEngineState::Dynamics)
00576     {
00577         // Game is in the active game play state, Stop Game Timer and Pause play and save state
00578         m_game->PauseGame();
00579     }
00580     m_renderNeeded = false;
00581 }
00582 //--------------------------------------------------------------------------------------
00583
00584 void DirectXApp::OnDeviceReset()
00585 {
00586
00587     SetAction(GameInfoOverlayCommand::PleaseWait);
00588     SetGameInfoOverlay(GameInfoOverlayState::Loading);
00589     m_updateState = UpdateEngineState::WaitingForResources;
00590     m_renderNeeded = true;
00591
00592     create_task([this]()
00593     {
00594         return m_renderer->CreateGameDeviceResourcesAsync(m_game);
00595
00596     }).then([this]()
00597     {
00598         // The finalize code needs to run in the same thread context
00599         // as the m_renderer object was created because the D3D device context
00600         // can ONLY be accessed on a single thread.
00601         m_renderer->FinalizeCreateGameDeviceResources();
00602
00603         // Reset the main state machine based on the current game state now
00604         // that the device resources have been restored.
00605         InitializeGameState();
00606
00607         if (m_updateState == UpdateEngineState::WaitingForResources)
00608         {
00609             // In the middle of a game so spin up the async task to load the level.
00610             return m_game->LoadLevelAsync().then([this]()
00611             {
00612                 // The m_game object may need to deal with D3D device context work so
00613                 // again the finalize code needs to run in the same thread
00614                 // context as the m_renderer object was created because the D3D
00615                 // device context can ONLY be accessed on a single thread.
00616                 m_game->FinalizeLoadLevel();
00617                 m_game->SetCurrentLevelToSavedState();
00618                 m_updateState = UpdateEngineState::ResourcesLoaded;
00619
00620             }, task_continuation_context::use_current());
00621         }
00622         else
00623         {
00624             // The game is not in the middle of a level so there aren't any level
00625             // resources to load.  Creating a no-op task so that in both cases
00626             // the same continuation logic is used.
00627             return create_task([]()
00628             {
00629             });
00630         }
00631
00632     }, task_continuation_context::use_current()).then([this]()
00633     {
00634         // Since Device lost is an unexpected event, the app visual state
00635         // may be snapped or not have focus.  Put the state machine
00636         // into the correct state to reflect these cases.
00637         if (ApplicationView::Value == ApplicationViewState::Snapped)
00638         {
00639             m_updateStateNext = m_updateState;
00640             m_updateState = UpdateEngineState::Snapped;
00641             m_controller->Active(false);
00642             HideGameInfoOverlay();
00643             SetSnapped();
00644             m_renderNeeded = true;
00645         }
00646         else if (!m_haveFocus)
00647         {
00648             m_updateStateNext = m_updateState;
00649             m_updateState = UpdateEngineState::Deactivated;
00650             m_controller->Active(false);
00651             SetAction(GameInfoOverlayCommand::None);
00652             m_renderNeeded = true;
00653         }
00654     }, task_continuation_context::use_current());
00655 }
00656
00657 //--------------------------------------------------------------------------------------
00658
00659 void DirectXApp::UpdateViewState()
00660 {
00661     m_renderNeeded = true;
00662
00663     if (ApplicationView::Value == ApplicationViewState::Snapped)
00664     {
00665         switch (m_updateState)
00666         {
00667         case UpdateEngineState::Dynamics:
00668             // From Dynamic mode, when coming out of SNAPPED layout rather than going directly back into game play
00669             // go to the paused state waiting for user input to continue
00670             m_updateStateNext = UpdateEngineState::WaitingForPress;
00671             m_pressResult = PressResultState::ContinueLevel;
00672             SetGameInfoOverlay(GameInfoOverlayState::Pause);
00673             SetAction(GameInfoOverlayCommand::TapToContinue);
00674             m_game->PauseGame();
00675             break;
00676
00677         case UpdateEngineState::WaitingForResources:
00678         case UpdateEngineState::WaitingForPress:
00679             // Avoid corrupting the m_updateStateNext on a transition from Snapped -> Snapped.
00680             // Otherwise just cache the current state and return to it when leaving SNAPPED layout
00681
00682             m_updateStateNext = m_updateState;
00683             break;
00684
00685         default:
00686             break;
00687         }
00688
00689         m_updateState = UpdateEngineState::Snapped;
00690         m_controller->Active(false);
00691         HideGameInfoOverlay();
00692         SetSnapped();
00693     }
00694     else if (ApplicationView::Value == ApplicationViewState::Filled ||
00695         ApplicationView::Value == ApplicationViewState::FullScreenLandscape ||
00696         ApplicationView::Value == ApplicationViewState::FullScreenPortrait)
00697     {
00698         if (m_updateState == UpdateEngineState::Snapped)
00699         {
00700             HideSnapped();
00701             ShowGameInfoOverlay();
00702             m_renderNeeded = true;
00703
00704             if (m_haveFocus)
00705             {
00706                 if (m_updateStateNext == UpdateEngineState::WaitingForPress)
00707                 {
00708                     SetAction(GameInfoOverlayCommand::TapToContinue);
00709                 }
00710                 else if (m_updateStateNext == UpdateEngineState::WaitingForResources)
00711                 {
00712                     SetAction(GameInfoOverlayCommand::PleaseWait);
00713                 }
00714
00715                 m_updateState = m_updateStateNext;
00716             }
00717             else
00718             {
00719                 m_updateState = UpdateEngineState::Deactivated;
00720                 SetAction(GameInfoOverlayCommand::None);
00721             }
00722         }
00723         else if (m_updateState == UpdateEngineState::Dynamics)
00724         {
00725             // In Dynamic mode, when a resize event happens, go to the paused state waiting for user input to continue.
00726             m_pressResult = PressResultState::ContinueLevel;
00727             SetGameInfoOverlay(GameInfoOverlayState::Pause);
00728             m_game->PauseGame();
00729             if (m_haveFocus)
00730             {
00731                 m_updateState = UpdateEngineState::WaitingForPress;
00732                 SetAction(GameInfoOverlayCommand::TapToContinue);
00733             }
00734             else
00735             {
00736                 m_updateState = UpdateEngineState::Deactivated;
00737                 SetAction(GameInfoOverlayCommand::None);
00738             }
00739             ShowGameInfoOverlay();
00740             m_renderNeeded = true;
00741         }
00742     }
00743 }
00744
00745 //--------------------------------------------------------------------------------------
00746
00747 void DirectXApp::SetGameInfoOverlay(GameInfoOverlayState state)
00748 {
00749     m_gameInfoOverlayState = state;
00750     switch (state)
00751     {
00752     case GameInfoOverlayState::Loading:
00753         m_renderer->InfoOverlay()->SetGameLoading(m_loadingCount);
00754         break;
00755
00756     case GameInfoOverlayState::GameStats:
00757         m_renderer->InfoOverlay()->SetGameStats(
00758             m_game->HighScore().levelCompleted + 1,
00759             m_game->HighScore().totalHits,
00760             m_game->HighScore().totalShots
00761             );
00762         break;
00763
00764     case GameInfoOverlayState::LevelStart:
00765         m_renderer->InfoOverlay()->SetLevelStart(
00766             m_game->LevelCompleted() + 1,
00767             m_game->CurrentLevel()->Objective(),
00768             m_game->CurrentLevel()->TimeLimit(),
00769             m_game->BonusTime()
00770             );
00771         break;
00772
00773     case GameInfoOverlayState::GameOverCompleted:
00774         m_renderer->InfoOverlay()->SetGameOver(
00775             true,
00776             m_game->LevelCompleted() + 1,
00777             m_game->TotalHits(),
00778             m_game->TotalShots(),
00779             m_game->HighScore().totalHits
00780             );
00781         break;
00782
00783     case GameInfoOverlayState::GameOverExpired:
00784         m_renderer->InfoOverlay()->SetGameOver(
00785             false,
00786             m_game->LevelCompleted(),
00787             m_game->TotalHits(),
00788             m_game->TotalShots(),
00789             m_game->HighScore().totalHits
00790             );
00791         break;
00792
00793     case GameInfoOverlayState::Pause:
00794         m_renderer->InfoOverlay()->SetPause();
00795         break;
00796     }
00797 }
00798
00799 //--------------------------------------------------------------------------------------
00800
00801 void DirectXApp::SetAction (GameInfoOverlayCommand command)
00802 {
00803     m_gameInfoOverlayCommand = command;
00804     m_renderer->InfoOverlay()->SetAction(command);
00805 }
00806
00807 //--------------------------------------------------------------------------------------
00808
00809 void DirectXApp::ShowGameInfoOverlay()
00810 {
00811     m_renderer->InfoOverlay()->ShowGameInfoOverlay();
00812 }
00813
00814 //--------------------------------------------------------------------------------------
00815
00816 void DirectXApp::HideGameInfoOverlay()
00817 {
00818     m_renderer->InfoOverlay()->HideGameInfoOverlay();
00819 }
00820
00821 //--------------------------------------------------------------------------------------
00822
00823 void DirectXApp::SetSnapped()
00824 {
00825     m_renderer->InfoOverlay()->SetPause();
00826     m_renderer->InfoOverlay()->ShowGameInfoOverlay();
00827 }
00828
00829 //--------------------------------------------------------------------------------------
00830
00831 void DirectXApp::HideSnapped()
00832 {
00833     m_renderer->InfoOverlay()->HideGameInfoOverlay();
00834     SetGameInfoOverlay(m_gameInfoOverlayState);
00835 }
00836
00837 //--------------------------------------------------------------------------------------
00838
00839 IFrameworkView^ DirectXAppSource::CreateView()
00840 {
00841     return ref new DirectXApp();
00842 }
00843
00844 //--------------------------------------------------------------------------------------
00845
00846 [Platform::MTAThread]
00847 int main(Platform::Array<Platform::String^>^)
00848 {
00849     auto directXAppSource = ref new DirectXAppSource();
00850     CoreApplication::Run(directXAppSource);
00851     return 0;
00852 }
00853
00854 //--------------------------------------------------------------------------------------
00855
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite custom text renderer/C++/CustomTextRenderer.cpp Source File

  • DirectWrite custom text renderer

CustomTextRenderer.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 #include "CustomTextRenderer.h"
00009
00010 ////  CustomTextRenderer::CustomTextRenderer
00011 ////
00012 ////  The constructor stores the Direct2D factory, the render
00013 ////  target, and the outline and fill brushes used for drawing the
00014 ////  glyphs, underlines, and strikethroughs.
00015
00016 CustomTextRenderer::CustomTextRenderer(
00017     Microsoft::WRL::ComPtr<ID2D1Factory> D2DFactory,
00018     Microsoft::WRL::ComPtr<ID2D1DeviceContext> D2DDeviceContext,
00019     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> outlineBrush,
00020     Microsoft::WRL::ComPtr<ID2D1BitmapBrush> fillBrush
00021     ) :
00022     refCount(0),
00023     D2DFactory(D2DFactory),
00024     D2DDeviceContext(D2DDeviceContext),
00025     outlineBrush(outlineBrush),
00026     fillBrush(fillBrush)
00027 {
00028 }
00029
00030 ////  CustomTextRenderer::DrawGlyphRun
00031 ////
00032 ////  Gets GlyphRun outlines via IDWriteFontFace::GetGlyphRunOutline
00033 ////  and then draws and fills them using Direct2D path geometries
00034
00035 IFACEMETHODIMP CustomTextRenderer::DrawGlyphRun(
00036     _In_opt_ void* clientDrawingContext,
00037     FLOAT baselineOriginX,
00038     FLOAT baselineOriginY,
00039     DWRITE_MEASURING_MODE measuringMode,
00040     _In_ DWRITE_GLYPH_RUN const* glyphRun,
00041     _In_ DWRITE_GLYPH_RUN_DESCRIPTION const* glyphRunDescription,
00042     IUnknown* clientDrawingEffect
00043     )
00044 {
00045     HRESULT hr = S_OK;
00046
00047     // Create the path geometry.
00048     Microsoft::WRL::ComPtr<ID2D1PathGeometry> pathGeometry;
00049     hr = D2DFactory->CreatePathGeometry(&pathGeometry);
00050
00051     // Write to the path geometry using the geometry sink.
00052     Microsoft::WRL::ComPtr<ID2D1GeometrySink> sink;
00053     if (SUCCEEDED(hr))
00054     {
00055         hr = pathGeometry->Open(&sink);
00056     }
00057
00058     // Get the glyph run outline geometries back from DirectWrite and place them within the
00059     // geometry sink.
00060     if (SUCCEEDED(hr))
00061     {
00062         hr = glyphRun->fontFace->GetGlyphRunOutline(
00063             glyphRun->fontEmSize,
00064             glyphRun->glyphIndices,
00065             glyphRun->glyphAdvances,
00066             glyphRun->glyphOffsets,
00067             glyphRun->glyphCount,
00068             glyphRun->isSideways,
00069             glyphRun->bidiLevel%2,
00070             sink.Get()
00071             );
00072     }
00073
00074     // Close the geometry sink
00075     if (SUCCEEDED(hr))
00076     {
00077         hr = sink.Get()->Close();
00078     }
00079
00080     // Initialize a matrix to translate the origin of the glyph run.
00081     D2D1::Matrix3x2F const matrix = D2D1::Matrix3x2F(
00082         1.0f, 0.0f,
00083         0.0f, 1.0f,
00084         baselineOriginX, baselineOriginY
00085         );
00086
00087     // Create the transformed geometry
00088     Microsoft::WRL::ComPtr<ID2D1TransformedGeometry> transformedGeometry;
00089     if (SUCCEEDED(hr))
00090     {
00091         hr = D2DFactory.Get()->CreateTransformedGeometry(
00092             pathGeometry.Get(),
00093             &matrix,
00094             &transformedGeometry
00095             );
00096     }
00097
00098     // Draw the outline of the glyph run
00099     D2DDeviceContext->DrawGeometry(
00100         transformedGeometry.Get(),
00101         outlineBrush.Get()
00102         );
00103
00104     // Fill in the glyph run
00105     D2DDeviceContext->FillGeometry(
00106         transformedGeometry.Get(),
00107         fillBrush.Get()
00108         );
00109
00110     return hr;
00111 }
00112
00113 ////  CustomTextRenderer::DrawUnderline
00114 ////
00115 ////  Draws underlines below the text using a Direct2D recatangle
00116 ////  geometry
00117
00118 IFACEMETHODIMP CustomTextRenderer::DrawUnderline(
00119     _In_opt_ void* clientDrawingContext,
00120     FLOAT baselineOriginX,
00121     FLOAT baselineOriginY,
00122     _In_ DWRITE_UNDERLINE const* underline,
00123     IUnknown* clientDrawingEffect
00124     )
00125 {
00126     HRESULT hr;
00127
00128     D2D1_RECT_F rect = D2D1::RectF(
00129         0,
00130         underline->offset,
00131         underline->width,
00132         underline->offset + underline->thickness
00133         );
00134
00135     Microsoft::WRL::ComPtr<ID2D1RectangleGeometry> rectangleGeometry;
00136     hr = D2DFactory.Get()->CreateRectangleGeometry(
00137         &rect,
00138         &rectangleGeometry
00139         );
00140
00141     // Initialize a matrix to translate the origin of the underline
00142     D2D1::Matrix3x2F const matrix = D2D1::Matrix3x2F(
00143         1.0f, 0.0f,
00144         0.0f, 1.0f,
00145         baselineOriginX, baselineOriginY
00146         );
00147
00148     Microsoft::WRL::ComPtr<ID2D1TransformedGeometry> transformedGeometry;
00149     if (SUCCEEDED(hr))
00150     {
00151         hr = D2DFactory.Get()->CreateTransformedGeometry(
00152             rectangleGeometry.Get(),
00153             &matrix,
00154             &transformedGeometry
00155             );
00156     }
00157
00158     // Draw the outline of the rectangle
00159     D2DDeviceContext.Get()->DrawGeometry(
00160         transformedGeometry.Get(),
00161         outlineBrush.Get()
00162         );
00163
00164     // Fill in the rectangle
00165     D2DDeviceContext.Get()->FillGeometry(
00166         transformedGeometry.Get(),
00167         fillBrush.Get()
00168         );
00169
00170     return S_OK;
00171 }
00172
00173 ////  CustomTextRenderer::DrawStrikethrough
00174 ////
00175 ////  Draws strikethroughs below the text using a Direct2D
00176 ////  recatangle geometry
00177 ////
00178
00179 IFACEMETHODIMP CustomTextRenderer::DrawStrikethrough(
00180     _In_opt_ void* clientDrawingContext,
00181     FLOAT baselineOriginX,
00182     FLOAT baselineOriginY,
00183     _In_ DWRITE_STRIKETHROUGH const* strikethrough,
00184     IUnknown* clientDrawingEffect
00185     )
00186 {
00187     HRESULT hr;
00188
00189     D2D1_RECT_F rect = D2D1::RectF(
00190         0,
00191         strikethrough->offset,
00192         strikethrough->width,
00193         strikethrough->offset + strikethrough->thickness
00194         );
00195
00196     Microsoft::WRL::ComPtr<ID2D1RectangleGeometry> rectangleGeometry;
00197     hr = D2DFactory.Get()->CreateRectangleGeometry(
00198         &rect,
00199         &rectangleGeometry
00200         );
00201
00202     // Initialize a matrix to translate the origin of the strikethrough
00203     D2D1::Matrix3x2F const matrix = D2D1::Matrix3x2F(
00204         1.0f, 0.0f,
00205         0.0f, 1.0f,
00206         baselineOriginX, baselineOriginY
00207         );
00208
00209     Microsoft::WRL::ComPtr<ID2D1TransformedGeometry> transformedGeometry;
00210     if (SUCCEEDED(hr))
00211     {
00212         hr = D2DFactory.Get()->CreateTransformedGeometry(
00213             rectangleGeometry.Get(),
00214             &matrix,
00215             &transformedGeometry
00216             );
00217     }
00218
00219     // Draw the outline of the rectangle
00220     D2DDeviceContext.Get()->DrawGeometry(
00221         transformedGeometry.Get(),
00222         outlineBrush.Get()
00223         );
00224
00225     // Fill in the rectangle
00226     D2DDeviceContext.Get()->FillGeometry(
00227         transformedGeometry.Get(),
00228         fillBrush.Get()
00229         );
00230
00231     return S_OK;
00232 }
00233
00234 ////  CustomTextRenderer::DrawInlineObject
00235 ////
00236 ////  This function is not implemented for the purposes of this
00237 ////  sample.
00238
00239 IFACEMETHODIMP CustomTextRenderer::DrawInlineObject(
00240     _In_opt_ void* clientDrawingContext,
00241     FLOAT originX,
00242     FLOAT originY,
00243     IDWriteInlineObject* inlineObject,
00244     BOOL isSideways,
00245     BOOL isRightToLeft,
00246     IUnknown* clientDrawingEffect
00247     )
00248 {
00249     // Not implemented
00250     return E_NOTIMPL;
00251 }
00252
00253 ////  CustomTextRenderer::AddRef
00254 ////
00255 ////  Increments the ref count
00256
00257 IFACEMETHODIMP_(unsigned long) CustomTextRenderer::AddRef()
00258 {
00259     return InterlockedIncrement(&refCount);
00260 }
00261
00262 ////  CustomTextRenderer::Release
00263 ////
00264 ////  Decrements the ref count and deletes the instance if the ref
00265 ////  count becomes 0
00266
00267 IFACEMETHODIMP_(unsigned long) CustomTextRenderer::Release()
00268 {
00269     unsigned long newCount = InterlockedDecrement(&refCount);
00270     if (newCount == 0)
00271     {
00272         delete this;
00273         return 0;
00274     }
00275
00276     return newCount;
00277 }
00278
00279 ////  CustomTextRenderer::IsPixelSnappingDisabled
00280 ////
00281 ////  Determines whether pixel snapping is disabled. The recommended
00282 ////  default is FALSE, unless doing animation that requires
00283 ////  subpixel vertical placement.
00284
00285 IFACEMETHODIMP CustomTextRenderer::IsPixelSnappingDisabled(
00286     _In_opt_ void* clientDrawingContext,
00287     _Out_ BOOL* isDisabled
00288     )
00289 {
00290     *isDisabled = FALSE;
00291     return S_OK;
00292 }
00293
00294 ////  CustomTextRenderer::GetCurrentTransform
00295 ////
00296 ////  Returns the current transform applied to the render target..
00297
00298 IFACEMETHODIMP CustomTextRenderer::GetCurrentTransform(
00299     _In_opt_ void* clientDrawingContext,
00300     _Out_ DWRITE_MATRIX* transform
00301     )
00302 {
00303     // forward the render target's transform
00304     D2DDeviceContext->GetTransform(reinterpret_cast<D2D1_MATRIX_3X2_F*>(transform));
00305     return S_OK;
00306 }
00307
00308 ////  CustomTextRenderer::GetPixelsPerDip
00309 ////
00310 ////  This returns the number of pixels per DIP.
00311 ////
00312
00313 IFACEMETHODIMP CustomTextRenderer::GetPixelsPerDip(
00314     _In_opt_ void* clientDrawingContext,
00315     _Out_ FLOAT* pixelsPerDip
00316     )
00317 {
00318     float x, yUnused;
00319
00320     D2DDeviceContext.Get()->GetDpi(&x, &yUnused);
00321     *pixelsPerDip = x / 96;
00322
00323     return S_OK;
00324 }
00325
00326 ////  CustomTextRenderer::QueryInterface
00327 ////
00328 ////  Query interface implementation
00329
00330 IFACEMETHODIMP CustomTextRenderer::QueryInterface(
00331     IID const& riid,
00332     void** ppvObject
00333     )
00334 {
00335     if (__uuidof(IDWriteTextRenderer) == riid)
00336     {
00337         *ppvObject = this;
00338     }
00339     else if (__uuidof(IDWritePixelSnapping) == riid)
00340     {
00341         *ppvObject = this;
00342     }
00343     else if (__uuidof(IUnknown) == riid)
00344     {
00345         *ppvObject = this;
00346     }
00347     else
00348     {
00349         *ppvObject = nullptr;
00350         return E_FAIL;
00351     }
00352
00353     this->AddRef();
00354
00355     return S_OK;
00356 }
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

BackgroundTasks::sealed Member List

This is the complete list of members for BackgroundTasks::sealed, including all inherited members.
Run(Windows::ApplicationModel::Background::IBackgroundTaskInstance^taskInstance) BackgroundTasks::sealed [virtual]
Generated on Sat Nov 23 2024 16:09:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Real-time communication/C++/Constants.h Source File

  • Real-time communication

Constants.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 namespace SimpleCommunication
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME {
00027             Platform::String^ get() {  return ref new Platform::String(L"Simple Communication"); }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios {
00031             Platform::Array<Scenario>^ get()
00032             {
00033                 return scenariosInner;
00034             }
00035         }
00036     private:
00037         static Platform::Array<Scenario>^ scenariosInner;
00038     };
00039
00040
00041 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Store device app for camera/C++/Constants.h Source File

  • Windows Store device app for camera

Constants.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 namespace DeviceAppForWebcam
00016 {
00017     partial ref class MainPage
00018     {
00019     public:
00020         static property Platform::String^ FEATURE_NAME
00021         {
00022             Platform::String^ get()
00023             {
00024                 return ref new Platform::String(L"Windows Store device app for webcam sample");
00025             }
00026         }
00027     };
00028
00029
00030 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/MediaExtensions/Invert/VideoBufferLock.h Source File

  • Media extensions
  • MediaExtensions
  • Invert

VideoBufferLock.h

Go to the documentation of this file.
00001 #pragma once
00002 #include <mfapi.h>
00003 #include <mftransform.h>
00004 #include <mfidl.h>
00005 #include <assert.h>
00006 #include <wrl\client.h>
00007
00008 using namespace Microsoft::WRL;
00009
00010 class VideoBufferLock
00011 {
00012 public:
00013     VideoBufferLock() : _bLockedBuffer(FALSE), _bLocked2D(FALSE), _bLocked2D2(FALSE), _pData(NULL), _lPitch(0) {}
00014
00015     HRESULT Lock(__in IMFMediaBuffer *pBuffer, __in MF2DBuffer_LockFlags flags, __in UINT uiMinSize, __in LONG lDefaultStride)
00016     {
00017         HRESULT hr = S_OK;
00018         DWORD dwBufferCount = 0;
00019         DWORD maxSize = 0;
00020         BYTE *pbBufferStart = NULL;
00021         DWORD dwBufferLength = 0;
00022
00023         assert(pBuffer);
00024
00025         // if the lock is already locked, assert
00026         assert(!(_bLocked2D || _bLocked2D2 || _bLockedBuffer));
00027         _pInputBuffer = pBuffer;
00028
00029         hr = _pInputBuffer.As(&_pInputBuffer2D2);
00030         if (SUCCEEDED(hr))
00031         {
00032             hr = _pInputBuffer2D2->Lock2DSize( flags, &_pData, &_lPitch, &pbBufferStart, &dwBufferLength );
00033             if (SUCCEEDED(hr))
00034             {
00035                 if (dwBufferLength < uiMinSize || abs(_lPitch) < abs(lDefaultStride))
00036                 {
00037                     _pInputBuffer2D2->Unlock2D();
00038                     hr = MF_E_BUFFERTOOSMALL;
00039                     goto done;
00040                 }
00041                 _bLocked2D2 = TRUE;
00042             }
00043         }
00044
00045         if(!_bLocked2D2)
00046         {
00047             hr = _pInputBuffer.As(&_pInputBuffer2D);
00048             if (SUCCEEDED(hr))
00049             {
00050                 hr = _pInputBuffer2D->Lock2D(&_pData, &_lPitch);
00051                 if (SUCCEEDED(hr))
00052                 {
00053                     if (abs(_lPitch) < abs(lDefaultStride))
00054                     {
00055                         _pInputBuffer2D->Unlock2D();
00056                         hr = MF_E_BUFFERTOOSMALL;
00057                         goto done;
00058                     }
00059                     _bLocked2D = TRUE;
00060                 }
00061             }
00062         }
00063
00064         if (!(_bLocked2D2 || _bLocked2D))
00065         {
00066             hr = _pInputBuffer->Lock(&_pData, &maxSize, NULL);
00067
00068             if (SUCCEEDED(hr))
00069             {
00070                 if (maxSize < uiMinSize)
00071                 {
00072                     _pInputBuffer->Unlock();
00073                     hr = MF_E_BUFFERTOOSMALL;
00074                     goto done;
00075                 }
00076
00077                 _bLockedBuffer = TRUE;
00078                 _lPitch = lDefaultStride;
00079             }
00080         }
00081
00082     done:
00083         return hr;
00084     }
00085
00086     ~VideoBufferLock() { Unlock(); }
00087
00088     HRESULT Unlock()
00089     {
00090         HRESULT hr = S_OK;
00091
00092         if(_bLockedBuffer && _pInputBuffer)
00093         {
00094             hr = _pInputBuffer->Unlock();
00095             _bLockedBuffer = FALSE;
00096             _pInputBuffer = nullptr;
00097         }
00098         if(_bLocked2D && _pInputBuffer2D)
00099         {
00100             hr = _pInputBuffer2D->Unlock2D();
00101             _bLocked2D = FALSE;
00102             _pInputBuffer2D = nullptr;
00103         }
00104         if(_bLocked2D2 && _pInputBuffer2D2)
00105         {
00106             hr = _pInputBuffer2D2->Unlock2D();
00107             _bLocked2D2 = FALSE;
00108             _pInputBuffer2D2 = nullptr;
00109         }
00110         return hr;
00111     }
00112
00113     BYTE *GetData(){ return _pData; }
00114     LONG GetStride(){ return _lPitch; }
00115
00116 private:
00117     ComPtr<IMFMediaBuffer> _pInputBuffer;
00118     BOOL _bLockedBuffer;
00119
00120     ComPtr<IMF2DBuffer> _pInputBuffer2D;
00121     BOOL _bLocked2D;
00122
00123     ComPtr<IMF2DBuffer2> _pInputBuffer2D2;
00124     BOOL _bLocked2D2;
00125
00126     BYTE *_pData;
00127     LONG _lPitch;
00128 };
Generated on Sat Nov 23 2024 16:08:21 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::SDKTemplate::sealed Member List

This is the complete list of members for SDKSample::SDKTemplate::sealed, including all inherited members.
AddCallback_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::SDKTemplate::sealed | [private]
AddURIIfValid(Windows::Foundation::Collections::IVector< Windows::Foundation::Uri^>^vectorToReceive, Platform::String^polledUrl) | SDKSample::SDKTemplate::sealed | [private]
CloseChannel_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::SDKTemplate::sealed | [private]
GetRegisteredTask() | SDKSample::SDKTemplate::sealed | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::SDKTemplate::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::SDKTemplate::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::SDKTemplate::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::SDKTemplate::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::SDKTemplate::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::SDKTemplate::sealed | [protected, virtual]
OnPushNotificationReceived(Windows::Networking::PushNotifications::PushNotificationChannel^sender, Windows::Networking::PushNotifications::PushNotificationReceivedEventArgs^e) | SDKSample::SDKTemplate::sealed | [private]
OpenChannel_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::SDKTemplate::sealed | [private]
pushReceivedToken | SDKSample::SDKTemplate::sealed | [private]
RegisterTaskButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::SDKTemplate::sealed | [private]
RemoveCallback_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::SDKTemplate::sealed | [private]
RenewChannelsButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::SDKTemplate::sealed | [private]
rootPage | SDKSample::SDKTemplate::sealed | [private]
Scenario1() | SDKSample::SDKTemplate::sealed |
Scenario2() | SDKSample::SDKTemplate::sealed |
Scenario3() | SDKSample::SDKTemplate::sealed |
Scenario4() | SDKSample::SDKTemplate::sealed |
Scenario5() | SDKSample::SDKTemplate::sealed |
StartBadgePolling_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::SDKTemplate::sealed | [private]
StartTilePolling_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::SDKTemplate::sealed | [private]
StopBadgePolling_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::SDKTemplate::sealed | [private]
StopTilePolling_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::SDKTemplate::sealed | [private]
UnregisterTaskButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::SDKTemplate::sealed | [private]
UpdateListener(bool add) | SDKSample::SDKTemplate::sealed | [private]
Generated on Sat Nov 23 2024 16:09:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media capture using capture device/C++/Constants.cpp Source File

  • Media capture using capture device

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
00021     { "Video preview, record and take pictures", "SDKSample.MediaCapture.BasicCapture" },
00022     { "Enumerate cameras and add a video effect", "SDKSample.MediaCapture.AdvancedCapture" },
00023     { "Audio Capture", "SDKSample.MediaCapture.AudioCapture" }
00024 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML animation library/C++/Scenario3.xaml.cpp Source File

  • XAML animation library

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 SDKSample::Animation;
00020
00021 using namespace Platform;
00022 using namespace Windows::Foundation;
00023 using namespace Windows::UI;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Media;
00026 using namespace Windows::UI::Xaml::Media::Animation;
00027 using namespace Windows::UI::Xaml::Shapes;
00028 using namespace Windows::UI::Xaml::Controls;
00029 using namespace Windows::UI::Xaml::Navigation;
00030 using namespace Windows::UI::ViewManagement;
00031
00032 Scenario3::Scenario3()
00033 {
00034     InitializeComponent();
00035 }
00036
00037 // Invoked when this page is about to be displayed in a Frame.
00038 void Scenario3::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   // Set the initaial combo box values
00045   Scenario3EasingModeSelector->SelectedIndex = 0;
00046   Scenario3FunctionSelector->SelectedIndex = 0;
00047 }
00048
00049 void Scenario3::Scenario3EasingFunctionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e)
00050 {
00051   // Stop the storyboard
00052   Scenario3Storyboard->Stop();
00053
00054   EasingFunctionBase^ easingFunction = nullptr;
00055
00056   // Select an easing function based on the user's selection
00057   auto selectedFunctionItem = (ComboBoxItem^) Scenario3FunctionSelector->SelectedItem;
00058
00059   if (selectedFunctionItem != nullptr)
00060   {
00061
00062     auto selectedFunction = selectedFunctionItem->Content->ToString();
00063
00064           if(selectedFunction == "BounceEase")
00065       {
00066               easingFunction = ref new BounceEase();
00067       }
00068       else if(selectedFunction == "CircleEase")
00069       {
00070               easingFunction = ref new CircleEase();
00071       }
00072       else if(selectedFunction == "ExponentialEase")
00073       {
00074               easingFunction = ref new ExponentialEase();
00075       }
00076       else if(selectedFunction == "PowerEase")
00077       {
00078               easingFunction = ref new PowerEase();
00079       }
00080       else {}
00081   }
00082
00083   // If no valid easing function was specified, let the storyboard stay stopped and do not continue
00084   if (easingFunction == nullptr)
00085     return;
00086
00087   auto selectedEasingModeItem = (ComboBoxItem^) Scenario3EasingModeSelector->SelectedItem;
00088
00089   // Select an easing mode based on the user's selection, defaulting to EaseIn if no selection was given
00090   if (selectedEasingModeItem != nullptr)
00091   {
00092      auto easingMode = selectedEasingModeItem->Content->ToString();
00093
00094           if(easingMode == "EaseOut")
00095       {
00096               easingFunction->EasingMode = EasingMode::EaseOut;
00097       }
00098       if(easingMode == "EaseIn")
00099       {
00100               easingFunction->EasingMode = EasingMode::EaseIn;
00101       }
00102       if(easingMode == "EaseInOut")
00103       {
00104               easingFunction->EasingMode = EasingMode::EaseInOut;
00105       }
00106   }
00107
00108   // Plot a graph of the easing function
00109   PlotEasingFunctionGraph(easingFunction, 0.005);
00110
00111   // Set the easing functions
00112   RectanglePositionAnimation->EasingFunction = easingFunction;
00113   GraphPositionMarkerXAnimation->EasingFunction = easingFunction;
00114   GraphPositionMarkerYAnimation->EasingFunction = easingFunction;
00115
00116   // Start the storyboard
00117   Scenario3Storyboard->Begin();
00118 }
00119
00120
00121 // Plot an easing function graph
00122 void Scenario3::PlotEasingFunctionGraph(EasingFunctionBase^ easingFunction, double samplingInterval)
00123 {
00124     UISettings^ UserSettings = ref new UISettings();
00125   // Clear the element
00126   Graph->Children->Clear();
00127
00128   // Initialize path
00129   auto path = ref new Path();
00130   auto pathGeometry = ref new PathGeometry();
00131   auto pathFigure = ref new PathFigure();
00132
00133   // Set starting point
00134   Point  startPoint;
00135   startPoint.X = 0;
00136   startPoint.Y = 0;
00137   pathFigure->StartPoint = startPoint;
00138
00139   auto pathSegmentCollection = ref new PathSegmentCollection();
00140
00141   // Note that an easing function is just like a regular function that operates on doubles.
00142   // Here we plot the range of the easing function's output on the y-axis of a graph.
00143   for (double i = 0; i < 1; i += samplingInterval)
00144   {
00145       auto x = i * GraphContainer->Width;
00146       auto y = easingFunction->Ease(i) * GraphContainer->Height;
00147
00148       auto segment = ref new LineSegment();
00149     Point p;
00150     p.X = (float)x;
00151     p.Y = (float)y;
00152       segment->Point = p;
00153       pathSegmentCollection->Append(segment);
00154   }
00155
00156   // Define the path parameters
00157   pathFigure->Segments = pathSegmentCollection;
00158   pathGeometry->Figures->Append(pathFigure);
00159   path->Data = pathGeometry;
00160   path->Stroke = ref new SolidColorBrush(UserSettings->UIElementColor(UIElementType::ButtonText));
00161   path->StrokeThickness = 1;
00162
00163   // Append the path to the Canvas
00164   Graph->Children->Append(path);
00165 }
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX marble maze game/C++/MarbleMaze.h Source File

  • DirectX marble maze game

MarbleMaze.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 "DirectXBase.h"
00011 #include "BasicMath.h"
00012 #include "Camera.h"
00013 #include "SampleOverlay.h"
00014 #include "Primitives.h"
00015 #include "Collision.h"
00016 #include "Physics.h"
00017 #include "SDKMesh.h"
00018 #include "UserInterface.h"
00019 #include "Audio.h"
00020 #include "PersistentState.h"
00021 #include "LoadScreen.h"
00022
00023 // Describes the constant buffer that draws the meshes.
00024 struct ConstantBuffer
00025 {
00026     float4x4 model;
00027     float4x4 view;
00028     float4x4 projection;
00029
00030     float3 marblePosition;
00031     float marbleRadius;
00032     float lightStrength;
00033 };
00034
00035 enum class GameState
00036 {
00037     Initial,
00038     MainMenu,
00039     HighScoreDisplay,
00040     PreGameCountdown,
00041     InGameActive,
00042     InGamePaused,
00043     PostGameResults,
00044 };
00045
00046 enum class CheckpointState
00047 {
00048     None, // No checkpoint hit.
00049     Save, // A save-game checkpoint was hit.
00050     Goal, // The end of game "goal" point was hit.
00051 };
00052
00053 ref class MarbleMaze : public DirectXBase
00054 {
00055 internal:
00056     MarbleMaze();
00057
00058     virtual void CreateDeviceResources() override;
00059     virtual void CreateWindowSizeDependentResources() override;
00060     virtual void Render() override;
00061     virtual void Initialize(Windows::UI::Core::CoreWindow^ window, float dpi) override;
00062     virtual void HandleDeviceLost() override;
00063
00064     void LoadDeferredResources(bool delay, bool deviceOnly);
00065
00066     void Update(float timeTotal, float timeDelta);
00067     void AddTouch(int id, Windows::Foundation::Point point);
00068     void UpdateTouch(int id, Windows::Foundation::Point point);
00069     void RemoveTouch(int id);
00070     void KeyDown(Windows::System::VirtualKey key);
00071     void KeyUp(Windows::System::VirtualKey key);
00072     void OnSuspending();
00073     void OnResuming();
00074     void OnFocusChange(bool active);
00075     void OnViewChange(Windows::UI::ViewManagement::ApplicationViewState state);
00076
00077 private:
00078     SampleOverlay^                                      m_sampleOverlay;
00079     LoadScreen^                                         m_loadScreen;
00080
00081     Microsoft::WRL::ComPtr<ID3D11InputLayout>           m_inputLayout;
00082     Microsoft::WRL::ComPtr<ID3D11VertexShader>          m_vertexShader;
00083     Microsoft::WRL::ComPtr<ID3D11PixelShader>           m_pixelShader;
00084     Microsoft::WRL::ComPtr<ID3D11SamplerState>          m_sampler;
00085     Microsoft::WRL::ComPtr<ID3D11Buffer>                m_constantBuffer;
00086     Microsoft::WRL::ComPtr<ID3D11BlendState>            m_blendState;
00087     Windows::UI::ViewManagement::ApplicationViewState   m_viewState;
00088     Windows::Devices::Sensors::Accelerometer^           m_accelerometer;
00089
00090     Camera^         m_camera;
00091     ConstantBuffer  m_mazeConstantBufferData;
00092     SDKMesh         m_mazeMesh;
00093     ConstantBuffer  m_marbleConstantBufferData;
00094     SDKMesh         m_marbleMesh;
00095     unsigned int    m_vertexStride;
00096     float           m_lightStrength;
00097     float           m_targetLightStrength;
00098     Collision       m_collision;
00099     Physics         m_physics;
00100     Audio           m_audio;
00101     GameState       m_gameState;
00102     bool            m_resetCamera;
00103     bool            m_resetMarbleRotation;
00104     typedef std::vector<XMFLOAT3> Checkpoints;
00105     Checkpoints     m_checkpoints;
00106     size_t          m_currentCheckpoint;
00107     TextButton      m_startGameButton;
00108     TextButton      m_highScoreButton;
00109     HighScoreTable  m_highScoreTable;
00110     CountdownTimer  m_preGameCountdownTimer;
00111     StopwatchTimer  m_inGameStopwatchTimer;
00112     TextElement     m_checkpointText;
00113     TextButton      m_pausedText;
00114     TextElement     m_resultsText;
00115     HighScoreEntry  m_newHighScore;
00116     typedef std::map<int, XMFLOAT2> TouchMap;
00117     TouchMap        m_touches;
00118     typedef std::queue<D2D1_POINT_2F> PointQueue;
00119     PointQueue      m_pointQueue;
00120     bool            m_pauseKeyActive;
00121     bool            m_pauseKeyPressed;
00122     bool            m_homeKeyActive;
00123     bool            m_homeKeyPressed;
00124     bool            m_windowActive;
00125     bool            m_deferredResourcesReady;
00126     PersistentState^ m_persistentState;
00127
00128     HRESULT ExtractTrianglesFromMesh(
00129         SDKMesh &mesh,
00130         const char *meshName,
00131         std::vector<Triangle> &triangles
00132         );
00133
00134     void ResetCheckpoints();
00135     CheckpointState UpdateCheckpoints();
00136
00137     void SetGameState(GameState nextState);
00138     void SaveState();
00139     void LoadState();
00140 };
00141
Generated on Sat Nov 23 2024 16:08:15 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Language font mapping/C++/CppSamplesUtils.h Source File

  • Language font mapping

CppSamplesUtils.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 <string>
00014 #include <sstream>
00015 #include <algorithm>
00016 #include <collection.h>
00017 #include <ppltasks.h>
00018
00019 namespace CppSamplesUtils
00020 {
00021     namespace Details
00022     {
00023         static Windows::Foundation::Collections::PropertySet^ sessionState = nullptr;
00024         static Platform::String^ sessionStateFileName = ref new Platform::String(L"_cppSessionState.xml");
00025
00026         concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file);
00027         concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file);
00028     }
00029
00030     class SuspensionManager
00031     {
00032     public:
00033         static Windows::Foundation::Collections::PropertySet^ SessionState()
00034         {
00035             using namespace Windows::Foundation::Collections;
00036             using namespace Details;
00037
00038             if (sessionState == nullptr)
00039             {
00040                 sessionState = ref new PropertySet();
00041             }
00042             return sessionState;
00043         }
00044
00045         static concurrency::task<void> StartRestoreTask()
00046         {
00047             using namespace Windows::Foundation;
00048             using namespace Windows::Storage;
00049             using namespace Windows::Storage::Streams;
00050             using namespace Details;
00051
00052             auto state = SessionState();
00053             state->Clear();
00054
00055             concurrency::task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFileName));
00056             return getFileTask.then([=](StorageFile^ file)
00057             {
00058                 return DeserializeSessionState(file);
00059             });
00060         }
00061
00062         static concurrency::task<void> StartSaveTask()
00063         {
00064             using namespace Windows::Foundation;
00065             using namespace Windows::Storage;
00066             using namespace Windows::Storage::Streams;
00067             using namespace Details;
00068
00069             concurrency::task<StorageFile^> createFileTask(ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFileName, CreationCollisionOption::ReplaceExisting));
00070             return createFileTask.then([=](StorageFile^ file)
00071             {
00072                 return SerializeSessionState(file);
00073             });
00074         }
00075     };
00076
00077     namespace Details
00078     {
00079         template <class T>
00080         inline Platform::String^ ToString(T value)
00081         {
00082             std::wstringstream wss;
00083             wss << value;
00084             return ref new Platform::String(wss.str().c_str());
00085         }
00086
00087         template <class T>
00088         inline T FromStringTo(Platform::String^ str)
00089         {
00090             std::wistringstream wiss(str->Data());
00091             T value = 0;
00092             wiss >> value;
00093             return value;
00094         }
00095
00096         template <class T>
00097         inline T FromHexStringTo(Platform::String^ str)
00098         {
00099             std::wistringstream wiss(str->Data());
00100             T value = 0;
00101             wiss >> std::hex >> value;
00102             return value;
00103         }
00104
00105         template <>
00106         inline Platform::Guid FromStringTo<Platform::Guid>(Platform::String^ str)
00107         {
00108             using namespace Platform;
00109
00110             if (str->Length() != 38)
00111             {
00112                 throw ref new InvalidArgumentException;
00113             }
00114             std::wstring ws(str->Data());
00115             if (ws[0] != L'{' || ws[37] != L'}' || ws[9] != L'-' || ws[14] != L'-' || ws[19] != L'-' || ws[24] != L'-')
00116             {
00117                 throw ref new InvalidArgumentException;
00118             }
00119             ws[0] = ws[37] = ws[9] = ws[14] = ws[19] =ws[24] = L' ';
00120             std::wistringstream wiss(ws);
00121             unsigned int a = 0;
00122             unsigned short b = 0;
00123             unsigned short c = 0;
00124             unsigned short d = 0;
00125             unsigned long long e = 0;
00126             static_assert(sizeof(d) == sizeof(char) * 2, "sizeof(d) == sizeof(char) * 2");
00127             static_assert(sizeof(e) == sizeof(char) * 8, "sizeof(e) == sizeof(char) * 8");
00128             wiss >> std::hex >> a >> b >> c >> d >> e;
00129             unsigned char *ad = (unsigned char*)(&d);
00130             unsigned char *ae = (unsigned char*)(&e);
00131             return Platform::Guid(a, b, c, ad[1], ad[0], ae[5], ae[4], ae[3], ae[2], ae[1], ae[0]);
00132         }
00133
00134         inline Platform::Object^ ConvertStringToObject(Windows::Foundation::PropertyType type, Platform::String^ str)
00135         {
00136             using namespace Platform;
00137             using namespace Windows::Foundation;
00138
00139             if (type == PropertyType::String)
00140             {
00141                 return PropertyValue::CreateString(str);
00142             }
00143
00144             switch (type)
00145             {
00146             case PropertyType::UInt8:
00147                 return PropertyValue::CreateUInt8((unsigned char)FromStringTo<unsigned short>(str));
00148             case PropertyType::UInt16:
00149                 return PropertyValue::CreateUInt16(FromStringTo<unsigned short>(str));
00150             case PropertyType::UInt32:
00151                 return PropertyValue::CreateUInt32(FromStringTo<unsigned int>(str));
00152             case PropertyType::UInt64:
00153                 return PropertyValue::CreateUInt64(FromStringTo<unsigned long long>(str));
00154             case PropertyType::Int16:
00155                 return PropertyValue::CreateInt16(FromStringTo<short>(str));
00156             case PropertyType::Int32:
00157                 return PropertyValue::CreateInt32(FromStringTo<int>(str));
00158             case PropertyType::Int64:
00159                 return PropertyValue::CreateInt64(FromStringTo<long long>(str));
00160             case PropertyType::Single:
00161                 return PropertyValue::CreateSingle(FromStringTo<float>(str));
00162             case PropertyType::Double:
00163                 return PropertyValue::CreateDouble(FromStringTo<double>(str));
00164             case PropertyType::Boolean:
00165                 return PropertyValue::CreateBoolean(FromStringTo<bool>(str));
00166             case PropertyType::Char16:
00167                 return PropertyValue::CreateChar16(str->Data()[0]);
00168             case PropertyType::Guid:
00169                 return PropertyValue::CreateGuid(FromStringTo<Guid>(str));
00170             default:
00171                 throw ref new Platform::InvalidCastException;
00172             }
00173         }
00174
00175         inline Platform::String^ ConvertPropertyValueToString(Windows::Foundation::IPropertyValue^ pv)
00176         {
00177             using namespace Platform;
00178             using namespace Windows::Foundation;
00179
00180             String^ valueString;
00181
00182             switch (pv->Type)
00183             {
00184             case PropertyType::String:
00185                 valueString = pv->GetString();
00186                 break;
00187
00188             case PropertyType::UInt8:
00189             case PropertyType::UInt16:
00190             case PropertyType::UInt32:
00191             case PropertyType::UInt64:
00192                 valueString = ToString(pv->GetUInt64());
00193                 break;
00194
00195             case PropertyType::Int16:
00196             case PropertyType::Int32:
00197             case PropertyType::Int64:
00198                 valueString = ToString(pv->GetInt64());
00199                 break;
00200
00201             case PropertyType::Single:
00202                 valueString = ToString(pv->GetSingle());
00203                 break;
00204
00205             case PropertyType::Double:
00206                 valueString = ToString(pv->GetDouble());
00207                 break;
00208
00209             case PropertyType::Boolean:
00210                 valueString = ToString(pv->GetBoolean());
00211                 break;
00212
00213             case PropertyType::Char16:
00214                 wchar_t buffer[2];
00215                 buffer[0] = pv->GetChar16();
00216                 buffer[1] = 0;
00217                 valueString = ref new String(buffer);
00218                 break;
00219
00220             case PropertyType::Guid:
00221                 valueString = pv->GetGuid().ToString();
00222                 break;
00223
00224             default:
00225                 throw ref new InvalidCastException;
00226             }
00227
00228             return valueString;
00229         }
00230
00231         inline Windows::Data::Xml::Dom::XmlElement^ CreateXmlElementFromObject(Windows::Data::Xml::Dom::XmlDocument^ doc, Platform::String^ name, Platform::Object^ value)
00232         {
00233             using namespace Platform;
00234             using namespace Windows::Foundation;
00235             using namespace Windows::Data::Xml::Dom;
00236
00237             XmlElement^ element = doc->CreateElement("item");
00238             element->SetAttribute("name", name);
00239
00240             IPropertyValue^ pv = (IPropertyValue^)value;
00241             element->SetAttribute("type", ToString((int)pv->Type));
00242             element->SetAttribute("value", ConvertPropertyValueToString(pv));
00243
00244             return element;
00245         }
00246
00247         inline concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file)
00248         {
00249             using namespace Windows::Data::Xml::Dom;
00250             using namespace Windows::Foundation;
00251             namespace WFC = Windows::Foundation::Collections;
00252             typedef Windows::Foundation::Collections::IKeyValuePair<Platform::String^, Platform::Object^> KVPair;
00253
00254             XmlDocument^ doc = ref new XmlDocument;
00255             doc->AppendChild(doc->CreateElement("items"));
00256             auto sessionState = SuspensionManager::SessionState();
00257
00258             std::for_each(WFC::begin(sessionState), WFC::end(sessionState), [doc](KVPair^ item)
00259             {
00260                 doc->DocumentElement->AppendChild(CreateXmlElementFromObject(doc, item->Key, item->Value));
00261             });
00262
00263             return concurrency::task<void>(doc->SaveToFileAsync(file));
00264         }
00265
00266         inline Windows::Foundation::PropertyType PropertyTypeFromString(Platform::String^ str)
00267         {
00268             int value = FromStringTo<int>(str);
00269             return (Windows::Foundation::PropertyType)value;
00270         }
00271
00272         inline concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file)
00273         {
00274             using namespace Platform;
00275             using namespace Windows::Foundation;
00276             using namespace Windows::Data::Xml::Dom;
00277             namespace WFC = Windows::Foundation::Collections;
00278
00279             concurrency::task<XmlDocument^> loadFileTask(XmlDocument::LoadFromFileAsync(file));
00280             return loadFileTask.then([=](concurrency::task<XmlDocument^> docTask)
00281             {
00282                 try
00283                 {
00284                     auto doc = docTask.get();
00285                     auto items = doc->SelectNodes("/items/item");
00286                     auto sessionState = SuspensionManager::SessionState();
00287
00288                     std::for_each(WFC::begin(items), WFC::end(items), [sessionState](IXmlNode^ node)
00289                     {
00290                         auto element = (IXmlElement^)node;
00291                         String^ name = element->GetAttribute("name");
00292                         String^ value = element->GetAttribute("value");
00293                         PropertyType type = PropertyTypeFromString(element->GetAttribute("type"));
00294
00295                         Object^ valueObject = ConvertStringToObject(type, value);
00296                         sessionState->Insert(name, valueObject);
00297                     });
00298
00299                 }
00300                 catch (Platform::Exception^)
00301                 {
00302                     // Restoring is best effort
00303                 }
00304             });
00305         }
00306     } // namespace Details
00307 } // namespace CppSamplesUtils
Generated on Sat Nov 23 2024 16:07:53 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML animation library/C++/common/LayoutAwarePage.h Source File

  • XAML animation library
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML ListView and GridView essentials/C++/MainPage.xaml.h Source File

  • XAML ListView and GridView essentials

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Compass sensor/C++/Scenario2.xaml.h Source File

  • Compass sensor

Scenario2.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.xaml.h
00013 // Declaration of the Scenario2 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario2.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace CompassCPP
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 sealed
00031         {
00032         public:
00033             Scenario2();
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             MainPage^ rootPage;
00041             Windows::UI::Core::CoreDispatcher^ dispatcher;
00042             Windows::Devices::Sensors::Compass^ compass;
00043             Windows::Foundation::EventRegistrationToken visibilityToken;
00044             uint32 desiredReportInterval;
00045             Windows::UI::Xaml::DispatcherTimer^ dispatcherTimer;
00046
00047             void VisibilityChanged(Platform::Object^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ e);
00048             void DisplayCurrentReading(Platform::Object^ sender, Platform::Object^ e);
00049             void ScenarioEnable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00050             void ScenarioDisable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00051         };
00052     }
00053 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Page Member List

This is the complete list of members for Page, including all inherited members.
__pad0__ | Element |
AcceptChildNode(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^childXmlNode) override | Page | [virtual]
AddChild(_In_ Element^element) | Element |
AddSibling(_In_ Element^element) | Element |
BindResource(_In_ Element^rootElement) | Element | [virtual]
Create(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^xmlNode) | Element | [static]
Draw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
GetFirstChild() | Element | [inline]
GetName() | Element | [inline]
GetNextSibling() | Element | [inline]
GetOpacity() | Element | [inline, virtual]
GetParent() | Element | [inline]
GetSize() | Element | [inline]
Initialize(_In_ Document^document, _In_ Windows::Data::Xml::Dom::XmlElement^xmlElement) | Element | [virtual]
Measure(_In_ Document^document, D2D1_SIZE_F const &parentSize, _Out_ D2D1_RECT_F *bounds) | Element | [virtual]
PrepareToDraw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
ReleaseParent() | Element | [virtual]
Generated on Sat Nov 23 2024 16:09:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File picker/C++/Constants.cpp Source File

  • File picker

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 using namespace Platform;
00018 using namespace Windows::UI::ViewManagement;
00019 using namespace Windows::UI::Xaml::Controls;
00020
00021 Array<Scenario>^ MainPage::scenariosInner = ref new Array<Scenario>
00022 {
00023     { "Pick a single photo",   "SDKSample.FilePicker.Scenario1" },
00024     { "Pick multiple files",   "SDKSample.FilePicker.Scenario2" },
00025     { "Pick a folder",         "SDKSample.FilePicker.Scenario3" },
00026     { "Save a file",           "SDKSample.FilePicker.Scenario4" },
00027     { "Open a cached file",    "SDKSample.FilePicker.Scenario5" },
00028     { "Update a cached file",  "SDKSample.FilePicker.Scenario6" },
00029 };
00030
00031 bool MainPage::EnsureUnsnapped()
00032 {
00033     // FilePicker APIs will not work if the application is in a snapped state.
00034     // If an app wants to show a FilePicker while snapped, it must attempt to unsnap first
00035     bool unsnapped = ((ApplicationView::Value != ApplicationViewState::Snapped) || ApplicationView::TryUnsnap());
00036     if (!unsnapped)
00037     {
00038         NotifyUser("Cannot unsnap the sample application", NotifyType::StatusMessage);
00039     }
00040
00041     return unsnapped;
00042 }
00043
00044 void MainPage::ResetScenarioOutput(TextBlock^ output)
00045 {
00046     // clear Error/Status
00047     NotifyUser("", NotifyType::ErrorMessage);
00048     NotifyUser("", NotifyType::StatusMessage);
00049     // clear scenario output
00050     output->Text = "";
00051 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DirectX::D3DX_BC6H::EncodeParams Member List

This is the complete list of members for DirectX::D3DX_BC6H::EncodeParams, including all inherited members.
aHDRPixels | DirectX::D3DX_BC6H::EncodeParams |
aIPixels | DirectX::D3DX_BC6H::EncodeParams |
aUnqEndPts | DirectX::D3DX_BC6H::EncodeParams |
bSigned | DirectX::D3DX_BC6H::EncodeParams |
EncodeParams(const HDRColorA *const aOriginal, bool bSignedFormat) | DirectX::D3DX_BC6H::EncodeParams | [inline]
fBestErr | DirectX::D3DX_BC6H::EncodeParams |
uMode | DirectX::D3DX_BC6H::EncodeParams |
uShape | DirectX::D3DX_BC6H::EncodeParams |
Generated on Sat Nov 23 2024 16:09:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML animation library/C++/Constants.h Source File

  • XAML animation library

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"Animation Library sample");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Bing Maps Trip Optimizer/C++,JavaScript/cpp/AntSystem.cpp Source File

  • Bing Maps Trip Optimizer
  • C++,JavaScript
  • cpp

AntSystem.cpp

Go to the documentation of this file.
00001 //-----------------------------------------------------------------------
00002 //
00003 //  Copyright (C) Microsoft Corporation.  All rights reserved.
00004 //
00005 //
00006 // THIS CODE AND INFORMATION ARE PROVIDED AS-IS WITHOUT WARRANTY OF ANY
00007 // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
00008 // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00009 // PARTICULAR PURPOSE.
00010 //-----------------------------------------------------------------------
00011 #include "pch.h"
00012 #include "AntSystem.h"
00013 #include <assert.h>
00014
00015 using namespace concurrency;
00016 using namespace std;
00017
00018 namespace AntSystem
00019 {
00020     // Searches the given range for an Edge object that contains the provided
00021     // Node pointers. This function returns nullptr if no such Edge exists.
00022     template <typename IterType>
00023     typename IterType::value_type FindEdge(
00024         IterType firstEdge,
00025         IterType lastEdge,
00026         const shared_ptr<Node> pointA,
00027         const shared_ptr<Node> pointB)
00028     {
00029         typedef IterType::value_type EdgeType;
00030         auto result = find_if(firstEdge, lastEdge, [&pointA, &pointB](EdgeType edge)
00031         {
00032             return (edge->PointA == pointA && edge->PointB == pointB) ||
00033                 (edge->PointA == pointB && edge->PointB == pointA);
00034         });
00035         return result != lastEdge ? (*result) : nullptr;
00036     }
00037
00038     // Computes the length of the provided route.
00039     double ComputeLengthOfRoute(
00040         const vector<shared_ptr<Node>>& nodes,    // node collection
00041         const vector<size_t>& indices,            // indices into node collection
00042         const vector<shared_ptr<Edge>>& edges)    // edge collection
00043     {
00044         double length = 0.0;
00045
00046         auto index_start = begin(indices);
00047         auto index_end = index_start + 1;
00048
00049         while (index_end != end(indices))
00050         {
00051             length += FindEdge(begin(edges), end(edges),
00052                 nodes[*index_start], nodes[*index_end])->TravelDistance;
00053
00054             index_start++;
00055             index_end++;
00056         }
00057         return length;
00058     }
00059
00060     // Computes a heuristic shortest tour among the provided collection
00061     // of nodes.
00062     double ComputeHeuristicShortestDistance(
00063         const vector<shared_ptr<Node>>& nodes,
00064         const vector<shared_ptr<Edge>>& edges)
00065     {
00066         // Hold index of each node that we visit during the tour.
00067         vector<size_t> heuristicBestRoute;
00068
00069         //
00070         // Use the nearest neighbor algorithm to compute the shortest tour.
00071         // http://en.wikipedia.org/wiki/Nearest_neighbour_algorithm
00072         //
00073
00074         size_t S = 0;
00075         size_t C = 0;
00076         size_t V = 0;
00077
00078         list<size_t> visited;
00079         visited.push_back(C);
00080
00081         heuristicBestRoute.push_back(C);
00082
00083         while (visited.size() < nodes.size())
00084         {
00085             double closestDistance = -1.0;
00086
00087             for (size_t i = 0; i < nodes.size(); ++i)
00088             {
00089                 if (find(begin(visited), end(visited), i) == end(visited))
00090                 {
00091                     double c = FindEdge(begin(edges), end(edges), nodes[C], nodes[i])->TravelDistance;
00092                     if (closestDistance < 0 || c < closestDistance)
00093                     {
00094                         closestDistance = c;
00095                         V = i;
00096                     }
00097                 }
00098             }
00099             C = V;
00100             heuristicBestRoute.push_back(C);
00101             visited.push_back(V);
00102         }
00103         heuristicBestRoute.push_back(S);
00104
00105         // Return the length of the tour.
00106         return ComputeLengthOfRoute(nodes, heuristicBestRoute, edges);
00107     }
00108
00109     // Represents a single ant within an ant colony.
00110     class Ant
00111     {
00112     public:
00113         explicit Ant(
00114             const vector<shared_ptr<Node>>& nodes,
00115             vector<shared_ptr<Edge>>& edges,
00116             const size_t initialNodeIndex,
00117             double heuristicShortestDistance,
00118             double alpha,
00119             double beta)
00120             : m_nodes(nodes)
00121             , m_edges(edges)
00122             , m_initialNodeIndex(initialNodeIndex)
00123             , m_lengthOfPath(0)
00124             , m_heuristicShortestDistance(heuristicShortestDistance)
00125             , m_alpha(alpha)
00126             , m_beta(beta)
00127         {
00128         }
00129
00130         // Computes a single tour of the graph.
00131         void Explore();
00132
00133         // Retrieves the tour and its length.
00134         void GetTour(vector<size_t>& tour, double& tourLength) const
00135         {
00136             tour = m_route;
00137             tourLength = m_lengthOfPath;
00138         }
00139
00140         // Tours the computed route and drops pheromone on each edge.
00141         void Backtrack();
00142
00143     private:
00144
00145         // Moves the ant to the next node in the graph.
00146         size_t MoveNext(size_t currentNodeIndex);
00147
00148         // Shared collection of nodes that comprise the graph.
00149         const vector<shared_ptr<Node>>& m_nodes;
00150
00151         // Shared collection of edges that connect each pair of nodes.
00152         vector<shared_ptr<Edge>>& m_edges;
00153
00154         // The start and end point of each tour.
00155         const size_t m_initialNodeIndex;
00156
00157         // The current route.
00158         vector<size_t> m_route;
00159
00160         // The length of the current route.
00161         double m_lengthOfPath;
00162
00163         // The estimated shortest route.
00164         double m_heuristicShortestDistance;
00165
00166         // Controls the influence of pheromone when choosing the next node.
00167         double m_alpha;
00168
00169         // Controls the influence of distance when choosing the next node.
00170         double m_beta;
00171
00172         // Disable assignment operator.
00173         Ant const & operator=(Ant const&);
00174     };
00175
00176     // Moves the ant to the next node in the graph.
00177     size_t Ant::MoveNext(size_t currentNodeIndex)
00178     {
00179         size_t candidate = static_cast<size_t>(-1);
00180
00181         // Compute the total edge pheromone contribution (denominator of formula).
00182         double totalEdgeContribution = 0.0;
00183         for (size_t i = 0; i < m_nodes.size(); ++i)
00184         {
00185             if (currentNodeIndex == i || find(begin(m_route), end(m_route), i) != end(m_route))
00186                 continue;
00187             auto edge = FindEdge(begin(m_edges), end(m_edges), m_nodes[currentNodeIndex], m_nodes[i]);
00188             totalEdgeContribution += (pow(edge->Pheromone, m_alpha) * pow((1.0 / edge->TravelDistance), m_beta));
00189         }
00190
00191         // Select next node.
00192         double bestProbability = 0.0;
00193         for (size_t i = 0; i < m_nodes.size(); ++i)
00194         {
00195             if (i == currentNodeIndex)
00196                 continue;
00197
00198             // If we did not yet visit this node...
00199             if (find(begin(m_route), end(m_route), i) == end(m_route))
00200             {
00201                 // Get the edge that connects the current node to the candidate node.
00202                 const auto edge = FindEdge(begin(m_edges), end(m_edges),
00203                     m_nodes[currentNodeIndex], m_nodes[i]);
00204
00205                 //
00206                 // Choose this node if it is the best fit so far.
00207
00208                 double top = (pow(edge->Pheromone, m_alpha) * pow((1.0 / edge->TravelDistance), m_beta));
00209                 double p = top / totalEdgeContribution;
00210
00211                 if (p >= bestProbability)
00212                 {
00213                     bestProbability = p;
00214                     candidate = i;
00215                 }
00216             }
00217         }
00218
00219         return candidate;
00220     }
00221
00222     // Computes a single tour of the graph.
00223     void Ant::Explore()
00224     {
00225         // Clear previous route.
00226         m_route.clear();
00227
00228         // Begin at start node.
00229         m_route.push_back(m_initialNodeIndex);
00230
00231         // Tour the graph.
00232         size_t currentNodeIndex = m_initialNodeIndex;
00233         while (m_route.size() < m_nodes.size())
00234         {
00235             currentNodeIndex = MoveNext(currentNodeIndex);
00236             assert(currentNodeIndex != static_cast<size_t>(-1));
00237             m_route.push_back(currentNodeIndex);
00238         }
00239
00240         // End at start node.
00241         m_route.push_back(m_initialNodeIndex);
00242
00243         // Compute length of path.
00244         m_lengthOfPath = ComputeLengthOfRoute(m_nodes, m_route, m_edges);
00245     }
00246
00247     // Tours the computed route and drops pheromone on each edge.
00248     void Ant::Backtrack()
00249     {
00250         // The amount of pheromone is inversely proportional to the
00251         // length of the current tour.
00252         // This means that shorter tours receive a greater amount
00253         // of pheromone.
00254         const double amount = m_heuristicShortestDistance / m_lengthOfPath;
00255
00256         auto last = end(m_route) - 1;
00257         for (auto iter = begin(m_route); iter != last; ++iter)
00258         {
00259             auto next = iter + 1;
00260
00261             //
00262             // Drop pheromone on edge.
00263
00264             auto edge = FindEdge(begin(m_edges), end(m_edges),
00265                 m_nodes[*iter], m_nodes[*next]);
00266
00267             edge->Pheromone += amount;
00268         }
00269     }
00270
00271     // Optimizes the route among the given nodes for the shortest travel distance.
00272     // This method returns indicies to the provided Node collection.
00273     vector<size_t> OptimizeRoute(
00274         vector<shared_ptr<Node>>& nodes,
00275         vector<shared_ptr<Edge>>& edges,
00276         double alpha, double beta, double rho,
00277         unsigned int iterations,
00278         cancellation_token cancellationToken,
00279         function<void(unsigned int)>* progressCallback,
00280         bool parallel)
00281     {
00282         // Compute the estimated shortest tour through the graph.
00283         double Q = ComputeHeuristicShortestDistance(nodes, edges);
00284
00285         //
00286         // Place a small amount of pheromone on each edge.
00287
00288         // The initial amount of pheromone is inversely proportional to the
00289         // number of locations.
00290         const double initialPheromone = 1.0 / nodes.size();
00291         for_each(begin(edges), end(edges), [initialPheromone](shared_ptr<AntSystem::Edge> edge)
00292         {
00293             edge->Pheromone = initialPheromone;
00294         });
00295
00296         //
00297         // Place an ant on each node.
00298         vector<Ant> ants;
00299
00300         for (size_t index = 0; index < nodes.size(); ++index)
00301         {
00302             ants.push_back(Ant(nodes, edges, index, Q, alpha, beta));
00303         }
00304
00305         // Perform the simulation several times.
00306         auto startTime = GetTickCount64();
00307         for (unsigned int i = 0; i < iterations; ++i)
00308         {
00309             // Occasionally check for cancellation.
00310             auto time = GetTickCount64();
00311             if (time - startTime > 100)
00312             {
00313                 if (cancellationToken.is_canceled())
00314                 {
00315                     // Return the empty collection.
00316                     return vector<size_t>();
00317                 }
00318                 startTime = time;
00319             }
00320
00321             // Send progress.
00322             if (progressCallback != nullptr)
00323             {
00324                 (*progressCallback)(i);
00325             }
00326
00327             //
00328             // Allow each ant to perform a tour of the graph.
00329             // Note that this operation can be performed in parallel because each ant acts independently.
00330             // This step contains no shared data or dependent computations.
00331             if (parallel)
00332             {
00333                 parallel_for_each(begin(ants), end(ants), [&](Ant& blitz)
00334                 {
00335                     blitz.Explore();
00336                 });
00337             }
00338             else
00339             {
00340                 for_each(begin(ants), end(ants), [&](Ant& blitz)
00341                 {
00342                     blitz.Explore();
00343                 });
00344             }
00345
00346             //
00347             // Evaporate pheromone.
00348             for_each(begin(edges), end(edges), [rho](shared_ptr<Edge> edge)
00349             {
00350                 edge->Pheromone *= (1.0 - rho);
00351             });
00352
00353             //
00354             // Allow each ant to backtrack through the graph and drop pheromone on
00355             // each edge.
00356             //
00357             // Note that this operation is NOT performed in parallel because
00358             // the ants update the pherone value of each edge.
00359             // Because the backtrack operation is not relatively lengthy, the
00360             // overhead that is required to synchronize access to the edges would
00361             // likely outweigh any benefits of parallel processing.
00362             for_each(begin(ants), end(ants), [&](Ant& blitz)
00363             {
00364                 blitz.Backtrack();
00365             });
00366         }
00367
00368         // Determine the best route.
00369         double bestCost = 0.0;
00370         vector<size_t> bestTour;
00371         for_each(begin(ants), end(ants), [&bestCost, &bestTour, &nodes, &edges](Ant& ant)
00372         {
00373             vector<size_t> tour;
00374             double tourLength;
00375             ant.GetTour(tour, tourLength);
00376
00377             if (bestTour.empty() || tourLength < bestCost)
00378             {
00379                 bestTour = tour;
00380                 bestCost = tourLength;
00381             }
00382         });
00383         return bestTour;
00384     }
00385 }
Generated on Sat Nov 23 2024 16:07:58 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D tutorial/C++/Lesson5.Components/BasicReaderWriter.h Source File

  • Direct3D tutorial
  • Lesson5.Components

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     Platform::String^ m_locationPath;
00019
00020 internal:
00021     BasicReaderWriter();
00022     BasicReaderWriter(
00023         _In_ Windows::Storage::StorageFolder^ folder
00024         );
00025
00026     Platform::Array<byte>^ ReadData(
00027         _In_ Platform::String^ filename
00028         );
00029
00030     concurrency::task<Platform::Array<byte>^> ReadDataAsync(
00031         _In_ Platform::String^ filename
00032         );
00033
00034     uint32 WriteData(
00035         _In_ Platform::String^ filename,
00036         _In_ const Platform::Array<byte>^ fileData
00037         );
00038
00039     concurrency::task<void> WriteDataAsync(
00040         _In_ Platform::String^ filename,
00041         _In_ const Platform::Array<byte>^ fileData
00042         );
00043 };
Generated on Sat Nov 23 2024 16:08:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/Simple3DGame.h Source File

  • DirectX 3D shooting game

Simple3DGame.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 // Simple3DGame:
00011 // This is the main game class.  It controls game play logic and game state.
00012 // Some of the key object classes used by Simple3DGame are:
00013 //     MoveLookController - for handling all input to control player movement, aiming,
00014 //         and firing.
00015 //     GameRenderer - for handling all graphics presentation.
00016 //     Camera - for handling view projections.
00017 //     Audio - for handling sound output.
00018 // This class maintains several lists of objects:
00019 //     m_ammo <Sphere> - is the list of the balls used to throw at targets.  Simple3DGame
00020 //         cycles through the list in a LRU fashion each time a ball is thrown by the player.
00021 //     m_objects <GameObject> - is the list of all objects in the scene that participate in
00022 //         game physics.  This includes m_player <Sphere> to represent the player in the scene.
00023 //         The player object (m_player) is not visible in the scene so it is not rendered.
00024 //     m_renderObjects <GameObject> - is the list of all objects in the scene that may be
00025 //         rendered.  It includes both the m_ammo list, most of the m_objects list excluding m_player
00026 //         object and the objects representing the bounding world.
00027
00028 #include "GameConstants.h"
00029 #include "Audio.h"
00030 #include "Camera.h"
00031 #include "Level.h"
00032 #include "GameObject.h"
00033 #include "GameTimer.h"
00034 #include "MoveLookController.h"
00035 #include "PersistentState.h"
00036 #include "Sphere.h"
00037 #include "GameRenderer.h"
00038
00039 //--------------------------------------------------------------------------------------
00040
00041 enum class GameState
00042 {
00043     Waiting,
00044     Active,
00045     LevelComplete,
00046     TimeExpired,
00047     GameComplete,
00048 };
00049
00050 typedef struct
00051 {
00052     Platform::String^ tag;
00053     int totalHits;
00054     int totalShots;
00055     int levelCompleted;
00056 } HighScoreEntry;
00057
00058 typedef std::vector<HighScoreEntry> HighScoreEntries;
00059
00060 //--------------------------------------------------------------------------------------
00061
00062 ref class GameRenderer;
00063
00064 ref class Simple3DGame
00065 {
00066 internal:
00067     Simple3DGame();
00068
00069     void Initialize(
00070         _In_ MoveLookController^ controller,
00071         _In_ GameRenderer^ renderer
00072         );
00073
00074     void LoadGame();
00075     concurrency::task<void> LoadLevelAsync();
00076     void FinalizeLoadLevel();
00077     void StartLevel();
00078     void PauseGame();
00079     void ContinueGame();
00080     GameState RunGame();
00081     void SetCurrentLevelToSavedState();
00082
00083     void OnSuspending();
00084     void OnResuming();
00085
00086     bool IsActivePlay()                         { return m_timer->Active(); }
00087     int LevelCompleted()                        { return m_currentLevel; };
00088     int TotalShots()                            { return m_totalShots; };
00089     int TotalHits()                             { return m_totalHits; };
00090     float BonusTime()                           { return m_levelBonusTime; };
00091     bool GameActive()                           { return m_gameActive; };
00092     bool LevelActive()                          { return m_levelActive; };
00093     HighScoreEntry HighScore()                  { return m_topScore; };
00094     Level^ CurrentLevel()                       { return m_level[m_currentLevel]; };
00095     float TimeRemaining()                       { return m_levelTimeRemaining; };
00096     Camera^ GameCamera()                        { return m_camera; };
00097     std::vector<GameObject^> RenderObjects()    { return m_renderObjects; };
00098
00099 private:
00100     void LoadState();
00101     void SaveState();
00102     void SaveHighScore();
00103     void LoadHighScore();
00104     void InitializeAmmo();
00105     void UpdateDynamics();
00106
00107     MoveLookController^                         m_controller;
00108     GameRenderer^                               m_renderer;
00109     Camera^                                     m_camera;
00110
00111     Audio^                                      m_audioController;
00112
00113     std::vector<Sphere^>                        m_ammo;
00114     uint32                                      m_ammoCount;
00115     uint32                                      m_ammoNext;
00116
00117     HighScoreEntry                              m_topScore;
00118     PersistentState^                            m_savedState;
00119
00120     GameTimer^                                  m_timer;
00121     bool                                        m_gameActive;
00122     bool                                        m_levelActive;
00123     int                                         m_totalHits;
00124     int                                         m_totalShots;
00125     float                                       m_levelDuration;
00126     float                                       m_levelBonusTime;
00127     float                                       m_levelTimeRemaining;
00128     std::vector<Level^>                         m_level;
00129     uint32                                      m_levelCount;
00130     uint32                                      m_currentLevel;
00131
00132     Sphere^                                     m_player;
00133     std::vector<GameObject^>                    m_objects;           // List of all objects to be included in intersection calculations.
00134     std::vector<GameObject^>                    m_renderObjects;     // List of all objects to be rendered.
00135
00136     DirectX::XMFLOAT3                           m_minBound;
00137     DirectX::XMFLOAT3                           m_maxBound;
00138 };
00139
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML high contrast style/C++/Scenario1.xaml.h Source File

  • XAML high contrast style

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 SDKSample
00023 {
00024   namespace HighContrast
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::WebHostHiddenAttribute]
00030      public ref class Scenario1 sealed
00031     {
00032     public:
00033       Scenario1();
00034
00035     protected:
00036       virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037     private:
00038       MainPage^ rootPage;
00039       void Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040       void Other_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041     };
00042   }
00043 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Device auto rotation preferences/C++/pch.cpp Source File

  • Device auto rotation preferences

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Sharing content target app/C++/sample-utils/CppSamplesUtils.h Source File

  • Sharing content target app
  • sample-utils

CppSamplesUtils.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 <string>
00014 #include <sstream>
00015 #include <algorithm>
00016 #include <collection.h>
00017 #include <ppltasks.h>
00018
00019 namespace CppSamplesUtils
00020 {
00021     namespace Details
00022     {
00023         static Windows::Foundation::Collections::PropertySet^ sessionState = nullptr;
00024         static Platform::String^ sessionStateFileName = ref new Platform::String(L"_cppSessionState.xml");
00025
00026         concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file);
00027         concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file);
00028     }
00029
00030     class SuspensionManager
00031     {
00032     public:
00033         static Windows::Foundation::Collections::PropertySet^ SessionState()
00034         {
00035             using namespace Windows::Foundation::Collections;
00036             using namespace Details;
00037
00038             if (sessionState == nullptr)
00039             {
00040                 sessionState = ref new PropertySet();
00041             }
00042             return sessionState;
00043         }
00044
00045         static concurrency::task<void> StartRestoreTask()
00046         {
00047             using namespace Windows::Foundation;
00048             using namespace Windows::Storage;
00049             using namespace Windows::Storage::Streams;
00050             using namespace Details;
00051
00052             auto state = SessionState();
00053             state->Clear();
00054
00055             concurrency::task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFileName));
00056             return getFileTask.then([=](StorageFile^ file)
00057             {
00058                 return DeserializeSessionState(file);
00059             });
00060         }
00061
00062         static concurrency::task<void> StartSaveTask()
00063         {
00064             using namespace Windows::Foundation;
00065             using namespace Windows::Storage;
00066             using namespace Windows::Storage::Streams;
00067             using namespace Details;
00068
00069             concurrency::task<StorageFile^> createFileTask(ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFileName, CreationCollisionOption::ReplaceExisting));
00070             return createFileTask.then([=](StorageFile^ file)
00071             {
00072                 return SerializeSessionState(file);
00073             });
00074         }
00075     };
00076
00077     namespace Details
00078     {
00079         template <class T>
00080         inline Platform::String^ ToString(T value)
00081         {
00082             std::wstringstream wss;
00083             wss << value;
00084             return ref new Platform::String(wss.str().c_str());
00085         }
00086
00087         template <class T>
00088         inline T FromStringTo(Platform::String^ str)
00089         {
00090             std::wistringstream wiss(str->Data());
00091             T value = 0;
00092             wiss >> value;
00093             return value;
00094         }
00095
00096         template <class T>
00097         inline T FromHexStringTo(Platform::String^ str)
00098         {
00099             std::wistringstream wiss(str->Data());
00100             T value = 0;
00101             wiss >> std::hex >> value;
00102             return value;
00103         }
00104
00105         template <>
00106         inline Platform::Guid FromStringTo<Platform::Guid>(Platform::String^ str)
00107         {
00108             using namespace Platform;
00109
00110             if (str->Length() != 38)
00111             {
00112                 throw ref new InvalidArgumentException;
00113             }
00114             std::wstring ws(str->Data());
00115             if (ws[0] != L'{' || ws[37] != L'}' || ws[9] != L'-' || ws[14] != L'-' || ws[19] != L'-' || ws[24] != L'-')
00116             {
00117                 throw ref new InvalidArgumentException;
00118             }
00119             ws[0] = ws[37] = ws[9] = ws[14] = ws[19] =ws[24] = L' ';
00120             std::wistringstream wiss(ws);
00121             unsigned int a = 0;
00122             unsigned short b = 0;
00123             unsigned short c = 0;
00124             unsigned short d = 0;
00125             unsigned long long e = 0;
00126             static_assert(sizeof(d) == sizeof(char) * 2, "sizeof(d) == sizeof(char) * 2");
00127             static_assert(sizeof(e) == sizeof(char) * 8, "sizeof(e) == sizeof(char) * 8");
00128             wiss >> std::hex >> a >> b >> c >> d >> e;
00129             unsigned char *ad = (unsigned char*)(&d);
00130             unsigned char *ae = (unsigned char*)(&e);
00131             return Platform::Guid(a, b, c, ad[1], ad[0], ae[5], ae[4], ae[3], ae[2], ae[1], ae[0]);
00132         }
00133
00134         inline Platform::Object^ ConvertStringToObject(Windows::Foundation::PropertyType type, Platform::String^ str)
00135         {
00136             using namespace Platform;
00137             using namespace Windows::Foundation;
00138
00139             if (type == PropertyType::String)
00140             {
00141                 return PropertyValue::CreateString(str);
00142             }
00143
00144             switch (type)
00145             {
00146             case PropertyType::UInt8:
00147                 return PropertyValue::CreateUInt8((unsigned char)FromStringTo<unsigned short>(str));
00148             case PropertyType::UInt16:
00149                 return PropertyValue::CreateUInt16(FromStringTo<unsigned short>(str));
00150             case PropertyType::UInt32:
00151                 return PropertyValue::CreateUInt32(FromStringTo<unsigned int>(str));
00152             case PropertyType::UInt64:
00153                 return PropertyValue::CreateUInt64(FromStringTo<unsigned long long>(str));
00154             case PropertyType::Int16:
00155                 return PropertyValue::CreateInt16(FromStringTo<short>(str));
00156             case PropertyType::Int32:
00157                 return PropertyValue::CreateInt32(FromStringTo<int>(str));
00158             case PropertyType::Int64:
00159                 return PropertyValue::CreateInt64(FromStringTo<long long>(str));
00160             case PropertyType::Single:
00161                 return PropertyValue::CreateSingle(FromStringTo<float>(str));
00162             case PropertyType::Double:
00163                 return PropertyValue::CreateDouble(FromStringTo<double>(str));
00164             case PropertyType::Boolean:
00165                 return PropertyValue::CreateBoolean(FromStringTo<bool>(str));
00166             case PropertyType::Char16:
00167                 return PropertyValue::CreateChar16(str->Data()[0]);
00168             case PropertyType::Guid:
00169                 return PropertyValue::CreateGuid(FromStringTo<Guid>(str));
00170             default:
00171                 throw ref new Platform::InvalidCastException;
00172             }
00173         }
00174
00175         inline Platform::String^ ConvertPropertyValueToString(Windows::Foundation::IPropertyValue^ pv)
00176         {
00177             using namespace Platform;
00178             using namespace Windows::Foundation;
00179
00180             String^ valueString;
00181
00182             switch (pv->Type)
00183             {
00184             case PropertyType::String:
00185                 valueString = pv->GetString();
00186                 break;
00187
00188             case PropertyType::UInt8:
00189             case PropertyType::UInt16:
00190             case PropertyType::UInt32:
00191             case PropertyType::UInt64:
00192                 valueString = ToString(pv->GetUInt64());
00193                 break;
00194
00195             case PropertyType::Int16:
00196             case PropertyType::Int32:
00197             case PropertyType::Int64:
00198                 valueString = ToString(pv->GetInt64());
00199                 break;
00200
00201             case PropertyType::Single:
00202                 valueString = ToString(pv->GetSingle());
00203                 break;
00204
00205             case PropertyType::Double:
00206                 valueString = ToString(pv->GetDouble());
00207                 break;
00208
00209             case PropertyType::Boolean:
00210                 valueString = ToString(pv->GetBoolean());
00211                 break;
00212
00213             case PropertyType::Char16:
00214                 wchar_t buffer[2];
00215                 buffer[0] = pv->GetChar16();
00216                 buffer[1] = 0;
00217                 valueString = ref new String(buffer);
00218                 break;
00219
00220             case PropertyType::Guid:
00221                 valueString = pv->GetGuid().ToString();
00222                 break;
00223
00224             default:
00225                 throw ref new InvalidCastException;
00226             }
00227
00228             return valueString;
00229         }
00230
00231         inline Windows::Data::Xml::Dom::XmlElement^ CreateXmlElementFromObject(Windows::Data::Xml::Dom::XmlDocument^ doc, Platform::String^ name, Platform::Object^ value)
00232         {
00233             using namespace Platform;
00234             using namespace Windows::Foundation;
00235             using namespace Windows::Data::Xml::Dom;
00236
00237             XmlElement^ element = doc->CreateElement("item");
00238             element->SetAttribute("name", name);
00239
00240             IPropertyValue^ pv = (IPropertyValue^)value;
00241             element->SetAttribute("type", ToString((int)pv->Type));
00242             element->SetAttribute("value", ConvertPropertyValueToString(pv));
00243
00244             return element;
00245         }
00246
00247         inline concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file)
00248         {
00249             using namespace Windows::Data::Xml::Dom;
00250             using namespace Windows::Foundation;
00251             namespace WFC = Windows::Foundation::Collections;
00252             typedef Windows::Foundation::Collections::IKeyValuePair<Platform::String^, Platform::Object^> KVPair;
00253
00254             XmlDocument^ doc = ref new XmlDocument;
00255             doc->AppendChild(doc->CreateElement("items"));
00256             auto sessionState = SuspensionManager::SessionState();
00257
00258             std::for_each(WFC::begin(sessionState), WFC::end(sessionState), [doc](KVPair^ item)
00259             {
00260                 doc->DocumentElement->AppendChild(CreateXmlElementFromObject(doc, item->Key, item->Value));
00261             });
00262
00263             return concurrency::task<void>(doc->SaveToFileAsync(file));
00264         }
00265
00266         inline Windows::Foundation::PropertyType PropertyTypeFromString(Platform::String^ str)
00267         {
00268             int value = FromStringTo<int>(str);
00269             return (Windows::Foundation::PropertyType)value;
00270         }
00271
00272         inline concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file)
00273         {
00274             using namespace Platform;
00275             using namespace Windows::Foundation;
00276             using namespace Windows::Data::Xml::Dom;
00277             namespace WFC = Windows::Foundation::Collections;
00278
00279             concurrency::task<XmlDocument^> loadFileTask(XmlDocument::LoadFromFileAsync(file));
00280             return loadFileTask.then([=](concurrency::task<XmlDocument^> docTask)
00281             {
00282                 try
00283                 {
00284                     auto doc = docTask.get();
00285                     auto items = doc->SelectNodes("/items/item");
00286                     auto sessionState = SuspensionManager::SessionState();
00287
00288                     std::for_each(WFC::begin(items), WFC::end(items), [sessionState](IXmlNode^ node)
00289                     {
00290                         auto element = (IXmlElement^)node;
00291                         String^ name = element->GetAttribute("name");
00292                         String^ value = element->GetAttribute("value");
00293                         PropertyType type = PropertyTypeFromString(element->GetAttribute("type"));
00294
00295                         Object^ valueObject = ConvertStringToObject(type, value);
00296                         sessionState->Insert(name, valueObject);
00297                     });
00298
00299                 }
00300                 catch (Platform::Exception^)
00301                 {
00302                     // Restoring is best effort
00303                 }
00304             });
00305         }
00306     } // namespace Details
00307 } // namespace CppSamplesUtils
Generated on Sat Nov 23 2024 16:07:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/texconv/DirectXTexP.h Source File

  • Direct3D resource loading
  • texconv

DirectXTexP.h

Go to the documentation of this file.
00001 //-------------------------------------------------------------------------------------
00002 // DirectXTexp.h
00003 //
00004 // DirectX Texture Library - Private header
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 #if defined(_MSC_VER) && (_MSC_VER > 1000)
00015 #pragma once
00016 #endif
00017
00018 #define NOMINMAX
00019 #include <windows.h>
00020 #include <directxmath.h>
00021 #include <directxpackedvector.h>
00022 #include <assert.h>
00023
00024 #include <malloc.h>
00025 #include <memory>
00026
00027 #include <vector>
00028
00029 #include <stdlib.h>
00030 #include <search.h>
00031
00032 #include <ole2.h>
00033
00034 #pragma warning(push)
00035 #pragma warning(disable : 4005)
00036 #include <wincodec.h>
00037 #pragma warning(pop)
00038
00039 #include "directxtex.h"
00040
00041 #include "scoped.h"
00042
00043 struct IWICImagingFactory;
00044
00045 #define TEX_FILTER_MASK 0xF00000
00046
00047 namespace DirectX
00048 {
00049     //---------------------------------------------------------------------------------
00050     // WIC helper functions
00051     DXGI_FORMAT _WICToDXGI( _In_ const GUID& guid );
00052     bool _DXGIToWIC( _In_ DXGI_FORMAT format, _Out_ GUID& guid );
00053
00054     size_t _WICBitsPerPixel( _In_ REFGUID targetGuid );
00055
00056     IWICImagingFactory* _GetWIC();
00057
00058     inline WICBitmapDitherType _GetWICDither( _In_ DWORD flags )
00059     {
00060         static_assert( TEX_FILTER_DITHER == 0x10000, "TEX_FILTER_DITHER* flag values don't match mask" );
00061
00062         static_assert( TEX_FILTER_DITHER == WIC_FLAGS_DITHER, "TEX_FILTER_DITHER* should match WIC_FLAGS_DITHER*" );
00063         static_assert( TEX_FILTER_DITHER_DIFFUSION == WIC_FLAGS_DITHER_DIFFUSION, "TEX_FILTER_DITHER* should match WIC_FLAGS_DITHER*" );
00064
00065         switch( flags & 0xF0000 )
00066         {
00067         case TEX_FILTER_DITHER:
00068             return WICBitmapDitherTypeOrdered4x4;
00069
00070         case TEX_FILTER_DITHER_DIFFUSION:
00071             return WICBitmapDitherTypeErrorDiffusion;
00072
00073         default:
00074             return WICBitmapDitherTypeNone;
00075         }
00076     }
00077
00078     inline WICBitmapInterpolationMode _GetWICInterp( _In_ DWORD flags )
00079     {
00080         static_assert( TEX_FILTER_POINT == 0x100000, "TEX_FILTER_ flag values don't match TEX_FILTER_MASK" );
00081
00082         static_assert( TEX_FILTER_POINT == WIC_FLAGS_FILTER_POINT, "TEX_FILTER_* flags should match WIC_FLAGS_FILTER_*" );
00083         static_assert( TEX_FILTER_LINEAR == WIC_FLAGS_FILTER_LINEAR, "TEX_FILTER_* flags should match WIC_FLAGS_FILTER_*"  );
00084         static_assert( TEX_FILTER_CUBIC == WIC_FLAGS_FILTER_CUBIC, "TEX_FILTER_* flags should match WIC_FLAGS_FILTER_*"  );
00085         static_assert( TEX_FILTER_FANT == WIC_FLAGS_FILTER_FANT, "TEX_FILTER_* flags should match WIC_FLAGS_FILTER_*"  );
00086
00087         switch( flags & TEX_FILTER_MASK )
00088         {
00089         case TEX_FILTER_POINT:
00090             return WICBitmapInterpolationModeNearestNeighbor;
00091
00092         case TEX_FILTER_LINEAR:
00093             return WICBitmapInterpolationModeLinear;
00094
00095         case TEX_FILTER_CUBIC:
00096             return WICBitmapInterpolationModeCubic;
00097
00098         case TEX_FILTER_FANT:
00099         default:
00100             return WICBitmapInterpolationModeFant;
00101         }
00102     }
00103
00104     //---------------------------------------------------------------------------------
00105     // Image helper functions
00106     void _DetermineImageArray( _In_ const TexMetadata& metadata, _In_ DWORD cpFlags,
00107                                _Out_ size_t& nImages, _Out_ size_t& pixelSize );
00108
00109     _Success_(return != false)
00110     bool _SetupImageArray( _In_reads_bytes_(pixelSize) uint8_t *pMemory, _In_ size_t pixelSize,
00111                            _In_ const TexMetadata& metadata, _In_ DWORD cpFlags,
00112                            _Out_writes_(nImages) Image* images, _In_ size_t nImages );
00113
00114     //---------------------------------------------------------------------------------
00115     // Conversion helper functions
00116
00117     enum TEXP_SCANLINE_FLAGS
00118     {
00119         TEXP_SCANLINE_NONE          = 0,
00120         TEXP_SCANLINE_SETALPHA      = 0x1,  // Set alpha channel to known opaque value
00121         TEXP_SCANLINE_LEGACY        = 0x2,  // Enables specific legacy format conversion cases
00122     };
00123
00124     enum CONVERT_FLAGS
00125     {
00126         CONVF_FLOAT     = 0x1,
00127         CONVF_UNORM     = 0x2,
00128         CONVF_UINT      = 0x4,
00129         CONVF_SNORM     = 0x8,
00130         CONVF_SINT      = 0x10,
00131         CONVF_DEPTH     = 0x20,
00132         CONVF_STENCIL   = 0x40,
00133         CONVF_SHAREDEXP = 0x80,
00134         CONVF_BGR       = 0x100,
00135         CONVF_X2        = 0x200,
00136         CONVF_PACKED    = 0x400,
00137         CONVF_BC        = 0x800,
00138         CONVF_R         = 0x10000,
00139         CONVF_G         = 0x20000,
00140         CONVF_B         = 0x40000,
00141         CONVF_A         = 0x80000,
00142         CONVF_RGB_MASK  = 0x70000,
00143         CONVF_RGBA_MASK = 0xF0000,
00144     };
00145
00146     DWORD _GetConvertFlags( _In_ DXGI_FORMAT format );
00147
00148     void _CopyScanline( _When_(pDestination == pSource, _Inout_updates_bytes_(outSize))
00149                         _When_(pDestination != pSource, _Out_writes_bytes_(outSize))
00150                         LPVOID pDestination, _In_ size_t outSize,
00151                         _In_reads_bytes_(inSize) LPCVOID pSource, _In_ size_t inSize,
00152                         _In_ DXGI_FORMAT format, _In_ DWORD flags );
00153
00154     void _SwizzleScanline( _When_(pDestination == pSource, _In_)
00155                            _When_(pDestination != pSource, _Out_writes_bytes_(outSize))
00156                            LPVOID pDestination, _In_ size_t outSize,
00157                            _In_reads_bytes_(inSize) LPCVOID pSource, _In_ size_t inSize,
00158                            _In_ DXGI_FORMAT format, _In_ DWORD flags );
00159
00160     _Success_(return != false)
00161     bool _ExpandScanline( _Out_writes_bytes_(outSize) LPVOID pDestination, _In_ size_t outSize,
00162                           _In_ DXGI_FORMAT outFormat,
00163                           _In_reads_bytes_(inSize) LPCVOID pSource, _In_ size_t inSize,
00164                           _In_ DXGI_FORMAT inFormat, _In_ DWORD flags );
00165
00166     _Success_(return != false)
00167     bool _LoadScanline( _Out_writes_(count) XMVECTOR* pDestination, _In_ size_t count,
00168                         _In_reads_bytes_(size) LPCVOID pSource, _In_ size_t size, _In_ DXGI_FORMAT format );
00169
00170     _Success_(return != false)
00171     bool _StoreScanline( LPVOID pDestination, _In_ size_t size, _In_ DXGI_FORMAT format,
00172                          _In_reads_(count) const XMVECTOR* pSource, _In_ size_t count );
00173
00174     HRESULT _ConvertToR32G32B32A32( _In_ const Image& srcImage, _Inout_ ScratchImage& image );
00175
00176     HRESULT _ConvertFromR32G32B32A32( _In_ const Image& srcImage, _In_ const Image& destImage );
00177     HRESULT _ConvertFromR32G32B32A32( _In_ const Image& srcImage, _In_ DXGI_FORMAT format, _Inout_ ScratchImage& image );
00178     HRESULT _ConvertFromR32G32B32A32( _In_reads_(nimages) const Image* srcImages, _In_ size_t nimages, _In_ const TexMetadata& metadata,
00179                                       _In_ DXGI_FORMAT format, _Out_ ScratchImage& result );
00180
00181     void _ConvertScanline( _Inout_updates_all_(count) XMVECTOR* pBuffer, _In_ size_t count,
00182                            _In_ DXGI_FORMAT outFormat, _In_ DXGI_FORMAT inFormat, _In_ DWORD flags );
00183
00184     //---------------------------------------------------------------------------------
00185     // DDS helper functions
00186     HRESULT _EncodeDDSHeader( _In_ const TexMetadata& metadata, DWORD flags,
00187                               _Out_writes_bytes_to_opt_(maxsize, required) LPVOID pDestination, _In_ size_t maxsize, _Out_ size_t& required );
00188
00189 }; // namespace
Generated on Sat Nov 23 2024 16:08:12 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Thread pool/C++/App.xaml.cpp Source File

  • Thread pool

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:28 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Bluetooth call control/C++/App.xaml.h Source File

  • Bluetooth call control

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D animated text/C++/DirectXBase.cpp Source File

  • Direct2D animated text

DirectXBase.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 "DirectXBase.h"
00010
00011 using namespace Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::Graphics::Display;
00015 using namespace D2D1;
00016
00017 // Constructor.
00018 DirectXBase::DirectXBase() :
00019     m_windowSizeChangeInProgress(false),
00020     m_dpi(-1.0f)
00021 {
00022 }
00023
00024 // Initialize the DirectX resources required to run.
00025 void DirectXBase::Initialize(CoreWindow^ window, float dpi)
00026 {
00027     m_window = window;
00028
00029     CreateDeviceIndependentResources();
00030     CreateDeviceResources();
00031     SetDpi(dpi);
00032 }
00033
00034 // Recreate all device resources and set them back to the current state.
00035 void DirectXBase::HandleDeviceLost()
00036 {
00037     // Reset these member variables to ensure that SetDpi recreates all resources.
00038     float dpi = m_dpi;
00039     m_dpi = -1.0f;
00040     m_windowBounds.Width = 0;
00041     m_windowBounds.Height = 0;
00042     m_swapChain = nullptr;
00043
00044     CreateDeviceResources();
00045     SetDpi(dpi);
00046 }
00047
00048 // These are the resources required independent of the device.
00049 void DirectXBase::CreateDeviceIndependentResources()
00050 {
00051     D2D1_FACTORY_OPTIONS options;
00052     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00053
00054 #if defined(_DEBUG)
00055     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00056     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00057 #endif
00058
00059     DX::ThrowIfFailed(
00060         D2D1CreateFactory(
00061             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00062             __uuidof(ID2D1Factory1),
00063             &options,
00064             &m_d2dFactory
00065             )
00066         );
00067
00068     DX::ThrowIfFailed(
00069         DWriteCreateFactory(
00070             DWRITE_FACTORY_TYPE_SHARED,
00071             __uuidof(IDWriteFactory),
00072             &m_dwriteFactory
00073             )
00074         );
00075
00076     DX::ThrowIfFailed(
00077         CoCreateInstance(
00078             CLSID_WICImagingFactory,
00079             nullptr,
00080             CLSCTX_INPROC_SERVER,
00081             IID_PPV_ARGS(&m_wicFactory)
00082             )
00083         );
00084 }
00085
00086 // These are the resources that depend on the device.
00087 void DirectXBase::CreateDeviceResources()
00088 {
00089     // This flag adds support for surfaces with a different color channel ordering
00090     // than the API default. It is required for compatibility with Direct2D.
00091     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00092     ComPtr<IDXGIDevice> dxgiDevice;
00093
00094 #if defined(_DEBUG)
00095     // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00096     creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00097 #endif
00098
00099     // This array defines the set of DirectX hardware feature levels this app will support.
00100     // Note the ordering should be preserved.
00101     // Don't forget to declare your application's minimum required feature level in its
00102     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00103     D3D_FEATURE_LEVEL featureLevels[] =
00104     {
00105         D3D_FEATURE_LEVEL_11_1,
00106         D3D_FEATURE_LEVEL_11_0,
00107         D3D_FEATURE_LEVEL_10_1,
00108         D3D_FEATURE_LEVEL_10_0,
00109         D3D_FEATURE_LEVEL_9_3,
00110         D3D_FEATURE_LEVEL_9_2,
00111         D3D_FEATURE_LEVEL_9_1
00112     };
00113
00114     // Create the Direct3D 11 API device object and a corresponding context.
00115     ComPtr<ID3D11Device> device;
00116     ComPtr<ID3D11DeviceContext> context;
00117     DX::ThrowIfFailed(
00118         D3D11CreateDevice(
00119             nullptr,                    // Specify nullptr to use the default adapter.
00120             D3D_DRIVER_TYPE_HARDWARE,
00121             0,
00122             creationFlags,              // Set debug and Direct2D compatibility flags.
00123             featureLevels,              // List of feature levels this app can support.
00124             ARRAYSIZE(featureLevels),
00125             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Metro style apps.
00126             &device,                    // Returns the Direct3D device created.
00127             &m_featureLevel,            // Returns feature level of device created.
00128             &context                    // Returns the device immediate context.
00129             )
00130         );
00131
00132     // Get the Direct3D 11.1 API device and context interfaces.
00133     DX::ThrowIfFailed(
00134         device.As(&m_d3dDevice)
00135         );
00136
00137     DX::ThrowIfFailed(
00138         context.As(&m_d3dContext)
00139         );
00140
00141     // Get the underlying DXGI device of the Direct3D device.
00142     DX::ThrowIfFailed(
00143         m_d3dDevice.As(&dxgiDevice)
00144         );
00145
00146     // Create the Direct2D device object and a corresponding context.
00147     DX::ThrowIfFailed(
00148         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00149         );
00150
00151     DX::ThrowIfFailed(
00152         m_d2dDevice->CreateDeviceContext(
00153             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00154             &m_d2dContext
00155             )
00156         );
00157 }
00158
00159 // Helps track the DPI in the helper class.
00160 // This is called in the dpiChanged event handler in the view class.
00161 void DirectXBase::SetDpi(float dpi)
00162 {
00163     if (dpi != m_dpi)
00164     {
00165         // Save the DPI of this display in our class.
00166         m_dpi = dpi;
00167
00168         // Update Direct2D's stored DPI.
00169         m_d2dContext->SetDpi(m_dpi, m_dpi);
00170
00171         // Often a DPI change implies a window size change. In some cases Windows will issue
00172         // both a size changed event and a DPI changed event. In this case, the resulting bounds
00173         // will not change, and the window resize code will only be executed once.
00174         UpdateForWindowSizeChange();
00175     }
00176 }
00177
00178 // This routine is called in the event handler for the view SizeChanged event.
00179 void DirectXBase::UpdateForWindowSizeChange()
00180 {
00181     // Only handle window size changed if there is no pending DPI change.
00182     if (m_dpi != DisplayProperties::LogicalDpi)
00183     {
00184         return;
00185     }
00186
00187     if (m_window->Bounds.Width  != m_windowBounds.Width ||
00188         m_window->Bounds.Height != m_windowBounds.Height)
00189     {
00190         m_d2dContext->SetTarget(nullptr);
00191         m_d2dTargetBitmap = nullptr;
00192         m_d3dRenderTargetView = nullptr;
00193         m_d3dDepthStencilView = nullptr;
00194         m_windowSizeChangeInProgress = true;
00195         CreateWindowSizeDependentResources();
00196     }
00197 }
00198
00199 // Allocate all memory resources that change on a window SizeChanged event.
00200 void DirectXBase::CreateWindowSizeDependentResources()
00201 {
00202     // Store the window bounds so the next time we get a SizeChanged event we can
00203     // avoid rebuilding everything if the size is identical.
00204     m_windowBounds = m_window->Bounds;
00205
00206     if (m_swapChain != nullptr)
00207     {
00208         // If the swap chain already exists, resize it.
00209         HRESULT hr = m_swapChain->ResizeBuffers(2, 0, 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0);
00210
00211         if (hr == DXGI_ERROR_DEVICE_REMOVED)
00212         {
00213             // If the device was removed for any reason, a new device and swapchain will need to be created.
00214             HandleDeviceLost();
00215
00216             // Everything is set up now. Do not continue execution of this method.
00217             return;
00218         }
00219         else
00220         {
00221             DX::ThrowIfFailed(hr);
00222         }
00223     }
00224     else
00225     {
00226         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00227         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00228         swapChainDesc.Width = 0;                                     // Use automatic sizing.
00229         swapChainDesc.Height = 0;
00230         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;           // This is the most common swap chain format.
00231         swapChainDesc.Stereo = false;
00232         swapChainDesc.SampleDesc.Count = 1;                          // Don't use multi-sampling.
00233         swapChainDesc.SampleDesc.Quality = 0;
00234         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00235         swapChainDesc.BufferCount = 2;                               // Use double-buffering to minimize latency.
00236         swapChainDesc.Scaling = DXGI_SCALING_NONE;
00237         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Metro style apps must use this SwapEffect.
00238         swapChainDesc.Flags = 0;
00239
00240         ComPtr<IDXGIDevice1> dxgiDevice;
00241         DX::ThrowIfFailed(
00242             m_d3dDevice.As(&dxgiDevice)
00243             );
00244
00245         ComPtr<IDXGIAdapter> dxgiAdapter;
00246         DX::ThrowIfFailed(
00247             dxgiDevice->GetAdapter(&dxgiAdapter)
00248             );
00249
00250         ComPtr<IDXGIFactory2> dxgiFactory;
00251         DX::ThrowIfFailed(
00252             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00253             );
00254
00255         CoreWindow^ window = m_window.Get();
00256         DX::ThrowIfFailed(
00257             dxgiFactory->CreateSwapChainForCoreWindow(
00258                 m_d3dDevice.Get(),
00259                 reinterpret_cast<IUnknown*>(window),
00260                 &swapChainDesc,
00261                 nullptr,
00262                 &m_swapChain
00263                 )
00264             );
00265
00266         // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
00267         // ensures that the application will only render after each VSync, minimizing power consumption.
00268         DX::ThrowIfFailed(
00269             dxgiDevice->SetMaximumFrameLatency(1)
00270             );
00271     }
00272
00273     // Create a Direct3D render target view of the swap chain back buffer.
00274     ComPtr<ID3D11Texture2D> backBuffer;
00275     DX::ThrowIfFailed(
00276         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00277         );
00278
00279     DX::ThrowIfFailed(
00280         m_d3dDevice->CreateRenderTargetView(
00281             backBuffer.Get(),
00282             nullptr,
00283             &m_d3dRenderTargetView
00284             )
00285         );
00286
00287     // Cache the rendertarget dimensions in our helper class for convenient use.
00288     D3D11_TEXTURE2D_DESC backBufferDesc = {0};
00289     backBuffer->GetDesc(&backBufferDesc);
00290     m_renderTargetSize.Width  = static_cast<float>(backBufferDesc.Width);
00291     m_renderTargetSize.Height = static_cast<float>(backBufferDesc.Height);
00292
00293     // Create a depth stencil view for use with 3D rendering if needed.
00294     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00295         DXGI_FORMAT_D24_UNORM_S8_UINT,
00296         backBufferDesc.Width,
00297         backBufferDesc.Height,
00298         1,
00299         1,
00300         D3D11_BIND_DEPTH_STENCIL
00301         );
00302
00303     ComPtr<ID3D11Texture2D> depthStencil;
00304     DX::ThrowIfFailed(
00305         m_d3dDevice->CreateTexture2D(
00306             &depthStencilDesc,
00307             nullptr,
00308             &depthStencil
00309             )
00310         );
00311
00312     auto viewDesc = CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D);
00313     DX::ThrowIfFailed(
00314         m_d3dDevice->CreateDepthStencilView(
00315             depthStencil.Get(),
00316             &viewDesc,
00317             &m_d3dDepthStencilView
00318             )
00319         );
00320
00321     // Set the 3D rendering viewport to target the entire window.
00322     CD3D11_VIEWPORT viewport(
00323         0.0f,
00324         0.0f,
00325         static_cast<float>(backBufferDesc.Width),
00326         static_cast<float>(backBufferDesc.Height)
00327         );
00328
00329     m_d3dContext->RSSetViewports(1, &viewport);
00330
00331     // Create a Direct2D target bitmap associated with the
00332     // swap chain back buffer and set it as the current target.
00333     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00334         BitmapProperties1(
00335             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00336             PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00337             m_dpi,
00338             m_dpi
00339             );
00340
00341     ComPtr<IDXGISurface> dxgiBackBuffer;
00342     DX::ThrowIfFailed(
00343         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00344         );
00345
00346     DX::ThrowIfFailed(
00347         m_d2dContext->CreateBitmapFromDxgiSurface(
00348             dxgiBackBuffer.Get(),
00349             &bitmapProperties,
00350             &m_d2dTargetBitmap
00351             )
00352         );
00353
00354     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00355
00356     // Grayscale text anti-aliasing is recommended for all Metro style apps.
00357     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00358 }
00359
00360 // Method to deliver the final image to the display.
00361 void DirectXBase::Present()
00362 {
00363     // The application may optionally specify "dirty" or "scroll" rects to improve efficiency
00364     // in certain scenarios.  In this sample, however, we do not utilize those features.
00365     DXGI_PRESENT_PARAMETERS parameters = {0};
00366     parameters.DirtyRectsCount = 0;
00367     parameters.pDirtyRects = nullptr;
00368     parameters.pScrollRect = nullptr;
00369     parameters.pScrollOffset = nullptr;
00370
00371     // The first argument instructs DXGI to block until VSync, putting the application
00372     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00373     // frames that will never be displayed to the screen.
00374     HRESULT hr = m_swapChain->Present1(1, 0, &parameters);
00375
00376     // Discard the contents of the render target.
00377     // This is a valid operation only when the existing contents will be entirely
00378     // overwritten. If dirty or scroll rects are used, this call should be removed.
00379     m_d3dContext->DiscardView(m_d3dRenderTargetView.Get());
00380
00381     // Discard the contents of the depth stencil.
00382     m_d3dContext->DiscardView(m_d3dDepthStencilView.Get());
00383
00384     // If the device was removed either by a disconnect or a driver upgrade, we
00385     // must recreate all device resources.
00386     if (hr == DXGI_ERROR_DEVICE_REMOVED)
00387     {
00388         HandleDeviceLost();
00389     }
00390     else
00391     {
00392         DX::ThrowIfFailed(hr);
00393     }
00394
00395     if (m_windowSizeChangeInProgress)
00396     {
00397         // A window size change has been initiated and the app has just completed presenting
00398         // the first frame with the new size. Notify the resize manager so we can short
00399         // circuit any resize animation and prevent unnecessary delays.
00400         CoreWindowResizeManager::GetForCurrentView()->NotifyLayoutCompleted();
00401         m_windowSizeChangeInProgress = false;
00402     }
00403 }
00404
00405 void DirectXBase::ValidateDevice()
00406 {
00407     // The D3D Device is no longer valid if the default adapter changes or if
00408     // the device has been removed.
00409
00410     // First, get the information for the adapter related to the current device.
00411
00412     ComPtr<IDXGIDevice1> dxgiDevice;
00413     ComPtr<IDXGIAdapter> deviceAdapter;
00414     DXGI_ADAPTER_DESC deviceDesc;
00415     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00416     DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter));
00417     DX::ThrowIfFailed(deviceAdapter->GetDesc(&deviceDesc));
00418
00419     // Next, get the information for the default adapter.
00420
00421     ComPtr<IDXGIFactory2> dxgiFactory;
00422     ComPtr<IDXGIAdapter1> currentAdapter;
00423     DXGI_ADAPTER_DESC currentDesc;
00424     DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)));
00425     DX::ThrowIfFailed(dxgiFactory->EnumAdapters1(0, &currentAdapter));
00426     DX::ThrowIfFailed(currentAdapter->GetDesc(&currentDesc));
00427
00428     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00429     // a new D3D device must be created.
00430
00431     if ((deviceDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart) ||
00432         (deviceDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart) ||
00433         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00434     {
00435         // Release references to resources related to the old device.
00436         dxgiDevice = nullptr;
00437         deviceAdapter = nullptr;
00438
00439         // Create a new device and swap chain.
00440         HandleDeviceLost();
00441     }
00442 }
Generated on Sat Nov 23 2024 16:08:02 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Trial app and in-app purchase/C++/AppListingUri.xaml.cpp Source File

  • Trial app and in-app purchase

AppListingUri.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 // AppListingUri.xaml.cpp
00013 // Implementation of the AppListingUri class
00014 //
00015
00016 #include "pch.h"
00017 #include "AppListingUri.xaml.h"
00018
00019 using namespace SDKSample::StoreSample;
00020
00021 using namespace concurrency;
00022 using namespace Windows::ApplicationModel;
00023 using namespace Windows::ApplicationModel::Store;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Globalization;
00026 using namespace Windows::Storage;
00027 using namespace Windows::UI::Xaml;
00028 using namespace Windows::UI::Xaml::Controls;
00029 using namespace Windows::UI::Xaml::Navigation;
00030
00031 AppListingUri::AppListingUri()
00032 {
00033     InitializeComponent();
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 AppListingUri::OnNavigatedTo(NavigationEventArgs^ e)
00042 {
00043     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00044     // as NotifyUser()
00045     rootPage = MainPage::Current;
00046     LoadAppListingUriProxyFile();
00047 }
00048 void AppListingUri::OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^ e)
00049 {
00050     CurrentAppSimulator::LicenseInformation->LicenseChanged -= eventRegistrationToken;
00051 }
00052
00053 void AppListingUri::LoadAppListingUriProxyFile()
00054 {
00055     create_task(Package::Current->InstalledLocation->GetFolderAsync("data")).then([this](StorageFolder^ proxyDataFolder)
00056     {
00057         create_task(proxyDataFolder->GetFileAsync("app-listing-uri.xml")).then([this](StorageFile^ proxyFile)
00058         {
00059             eventRegistrationToken = (CurrentAppSimulator::LicenseInformation->LicenseChanged += ref new LicenseChangedEventHandler(this, &AppListingUri::AppListingUriRefreshScenario));
00060             create_task(CurrentAppSimulator::ReloadSimulatorAsync(proxyFile)).then([this]()
00061             {
00062             });
00063         });
00064     });
00065 }
00066
00067 void AppListingUri::AppListingUriRefreshScenario()
00068 {
00069 }
00070
00071 void AppListingUri::DisplayLink_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00072 {
00073     rootPage->NotifyUser(CurrentAppSimulator::LinkUri->AbsoluteUri, NotifyType::StatusMessage);
00074 }
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: HttpClient/C++/Constants.h Source File

  • HttpClient

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"HttpClient");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041
00042         bool TryGetUri(Platform::String^ uriString, Windows::Foundation::Uri^* uri)
00043         {
00044             // Create a Uri instance and catch exceptions related to invalid input. This method returns 'true'
00045             // if the Uri instance was successfully created and 'false' otherwise.
00046             try
00047             {
00048                 *uri = ref new Windows::Foundation::Uri(Helpers::Trim(uriString));
00049                 return true;
00050             }
00051             catch (Platform::NullReferenceException^ exception)
00052             {
00053                 NotifyUser("Error: URI must not be null or empty.", NotifyType::ErrorMessage);
00054             }
00055             catch (Platform::InvalidArgumentException^ exception)
00056             {
00057                 NotifyUser("Error: Invalid URI", NotifyType::ErrorMessage);
00058             }
00059
00060             return false;
00061         }
00062
00063     private:
00064         static Platform::Array<Scenario>^ scenariosInner;
00065     };
00066
00067     class Helpers
00068     {
00069     public:
00070         static void ScenarioStarted(Windows::UI::Xaml::Controls::Button^ startButton, Windows::UI::Xaml::Controls::Button^ cancelButton)
00071         {
00072             startButton->IsEnabled = false;
00073             cancelButton->IsEnabled = true;
00074         }
00075
00076         static void ScenarioCompleted(Windows::UI::Xaml::Controls::Button^ startButton, Windows::UI::Xaml::Controls::Button^ cancelButton)
00077         {
00078             startButton->IsEnabled = true;
00079             cancelButton->IsEnabled = false;
00080         }
00081
00082         static Platform::String^ Trim(Platform::String^ s)
00083         {
00084             const char16* first = s->Begin();
00085             const char16* last = s->End();
00086
00087             while (first != last && iswspace(*first))
00088             {
00089                 ++first;
00090             }
00091
00092             while (first != last && iswspace(last[-1]))
00093             {
00094                 --last;
00095             }
00096
00097             return ref new Platform::String(first, (int)(last - first));
00098         }
00099
00100         static void ReplaceAll(std::wstring& value, _In_z_ const char16* from, _In_z_ const char16* to)
00101         {
00102             auto fromLength = wcslen(from);
00103             std::wstring::size_type offset;
00104
00105             for (offset = value.find(from); offset != std::wstring::npos; offset = value.find(from, offset))
00106             {
00107                 value.replace(offset, fromLength, to);
00108             }
00109         }
00110
00111         enum NotifyType
00112         {
00113             StatusMessage,
00114             ErrorMessage
00115         };
00116     };
00117 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Device capabilities/C++/Mouse.xaml.cpp Source File

  • Input Device capabilities

Mouse.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 // Mouse.xaml.cpp
00013 // Implementation of the Mouse class
00014 //
00015
00016 #include "pch.h"
00017 #include "Mouse.xaml.h"
00018
00019 using namespace SDKSample::DeviceCaps;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 using namespace Windows::Devices::Input;
00026
00027 Mouse::Mouse()
00028 {
00029     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 void Mouse::OnNavigatedTo(NavigationEventArgs^ e)
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     rootPage = MainPage::Current;
00042 }
00043
00044 void SDKSample::DeviceCaps::Mouse::MouseGetSettings_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00045 {
00046     Button^ b = safe_cast<Button^>(sender);
00047     if (b != nullptr)
00048     {
00049         MouseCapabilities^ pMouseCapabilities = ref new MouseCapabilities();
00050         Platform::String^ Buffer;
00051
00052         Buffer = "There is " + (pMouseCapabilities->MousePresent != 0 ? "a" : "no") + " mouse present\n";
00053         Buffer += "There is " + (pMouseCapabilities->VerticalWheelPresent != 0 ? "a" : "no") + " vertical mouse wheel present\n";
00054         Buffer += "There is " + (pMouseCapabilities->HorizontalWheelPresent != 0 ? "a" : "no") + " horizontal mouse wheel present\n";
00055         Buffer += "The user has " + (pMouseCapabilities->SwapButtons != 0 ? "" : "not ") + "opted to swap the mouse buttons\n";
00056         Buffer += "The mouse has " + pMouseCapabilities->NumberOfButtons.ToString() + " button(s)\n";
00057
00058         MouseOutputTextBlock->Text = Buffer;
00059     }
00060 }
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C#,C++/MediaExtensions/Common/BufferLock.h Source File

  • Media extensions
  • C#,C++
  • MediaExtensions
  • Common

BufferLock.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
00009 #pragma once
00010
00011
00012 //////////////////////////////////////////////////////////////////////////
00013 //  VideoBufferLock
00014 //
00015 //  Description:
00016 //  Locks a video buffer that might or might not support IMF2DBuffer.
00017 //
00018 //////////////////////////////////////////////////////////////////////////
00019
00020 class VideoBufferLock
00021 {
00022 public:
00023     VideoBufferLock(IMFMediaBuffer *pBuffer) : m_p2DBuffer(NULL)
00024     {
00025         m_pBuffer = pBuffer;
00026         m_pBuffer->AddRef();
00027
00028         // Query for the 2-D buffer interface. OK if this fails.
00029         m_pBuffer->QueryInterface(IID_PPV_ARGS(&m_p2DBuffer));
00030     }
00031
00032     ~VideoBufferLock()
00033     {
00034         UnlockBuffer();
00035         SafeRelease(&m_pBuffer);
00036         SafeRelease(&m_p2DBuffer);
00037     }
00038
00039     // LockBuffer:
00040     // Locks the buffer. Returns a pointer to scan line 0 and returns the stride.
00041
00042     // The caller must provide the default stride as an input parameter, in case
00043     // the buffer does not expose IMF2DBuffer. You can calculate the default stride
00044     // from the media type.
00045
00046     HRESULT LockBuffer(
00047         LONG  lDefaultStride,    // Minimum stride (with no padding).
00048         DWORD dwHeightInPixels,  // Height of the image, in pixels.
00049         BYTE  **ppbScanLine0,    // Receives a pointer to the start of scan line 0.
00050         LONG  *plStride          // Receives the actual stride.
00051         )
00052     {
00053         HRESULT hr = S_OK;
00054
00055         // Use the 2-D version if available.
00056         if (m_p2DBuffer)
00057         {
00058             hr = m_p2DBuffer->Lock2D(ppbScanLine0, plStride);
00059         }
00060         else
00061         {
00062             // Use non-2D version.
00063             BYTE *pData = NULL;
00064
00065             hr = m_pBuffer->Lock(&pData, NULL, NULL);
00066             if (SUCCEEDED(hr))
00067             {
00068                 *plStride = lDefaultStride;
00069                 if (lDefaultStride < 0)
00070                 {
00071                     // Bottom-up orientation. Return a pointer to the start of the
00072                     // last row *in memory* which is the top row of the image.
00073                     *ppbScanLine0 = pData + abs(lDefaultStride) * (dwHeightInPixels - 1);
00074                 }
00075                 else
00076                 {
00077                     // Top-down orientation. Return a pointer to the start of the
00078                     // buffer.
00079                     *ppbScanLine0 = pData;
00080                 }
00081             }
00082         }
00083         return hr;
00084     }
00085
00086     HRESULT UnlockBuffer()
00087     {
00088         if (m_p2DBuffer)
00089         {
00090             return m_p2DBuffer->Unlock2D();
00091         }
00092         else
00093         {
00094             return m_pBuffer->Unlock();
00095         }
00096     }
00097
00098 private:
00099     IMFMediaBuffer  *m_pBuffer;
00100     IMF2DBuffer     *m_p2DBuffer;
00101 };
00102
Generated on Sat Nov 23 2024 16:08:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::NotificationContentText Member List

This is the complete list of members for NotificationsExtensions::NotificationContentText, including all inherited members.
Lang | NotificationsExtensions::NotificationContentText |
m_Lang | NotificationsExtensions::NotificationContentText | [private]
m_Text | NotificationsExtensions::NotificationContentText | [private]
NotificationContentText() | NotificationsExtensions::NotificationContentText | [inline, private]
NotificationContentText() | NotificationsExtensions::NotificationContentText | [inline, private]
NotificationContentText() | NotificationsExtensions::NotificationContentText | [inline, private]
NotificationContentText() | NotificationsExtensions::NotificationContentText | [inline, private]
Text | NotificationsExtensions::NotificationContentText |
Generated on Sat Nov 23 2024 16:09:41 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Store device app for camera/C++/MainPage.xaml.cpp Source File

  • Windows Store device app for camera

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Platform;
00026 using namespace DeviceAppForWebcam;
00027 using namespace CppSamplesUtils;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     LayoutRoot->Children->Append(HiddenFrame);
00045
00046     // Populate the sample title from the constant in the Constants.h file.
00047     SetDeviceAppForWebcam(FEATURE_NAME);
00048
00049     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00050
00051     MainPage::Current = this;
00052 }
00053
00054 MainPage::~MainPage()
00055 {
00056 }
00057
00058 /// <summary>
00059 /// Invoked when this page is about to be displayed in a Frame.
00060 /// </summary>
00061 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00062 /// property is typically used to configure the page.</param>
00063 void MainPage::OnNavigatedTo(NavigationEventArgs^ e)
00064 {
00065     InvalidateViewState();
00066 }
00067
00068 /// <summary>
00069 /// We need to handle SizeChanged so that we can make the sample layout property
00070 /// in the various layouts.
00071 /// </summary>
00072 /// <param name="sender"></param>
00073 /// <param name="e"></param>
00074 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00075 {
00076     InvalidateSize();
00077 }
00078
00079 void MainPage::InvalidateSize()
00080 {
00081     // Get the window width
00082     double windowWidth = this->ActualWidth;
00083
00084     if (windowWidth != 0.0)
00085     {
00086         // Get the width of the ContentPanel.
00087         double contentPanelWidth = ContentPanel->ActualWidth;
00088
00089         // Is the ContentPanel using any margins that we need to consider?
00090         double contentPanelMarginLeft = ContentPanel->Margin.Left;
00091         double contentPanelMarginRight = ContentPanel->Margin.Right;
00092
00093         // Figure out how much room is left after considering the ContentPanel width
00094         double availableWidth = windowWidth;
00095
00096         // Is the top most child using margins?
00097         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00098         double layoutRootMarginRight = ContentRoot->Margin.Right;
00099
00100         // We have different widths to use depending on the view state
00101         if (ApplicationView::Value != ApplicationViewState::Snapped)
00102         {
00103             // Make us as big as the the left over space, factoring in the ContentPanel width, the ContentPanel margins,
00104             // and the LayoutRoot's margins
00105             ContentPanel->Width = ((availableWidth) -
00106                 (layoutRootMarginLeft + layoutRootMarginRight + contentPanelMarginLeft + contentPanelMarginRight));
00107         }
00108         else
00109         {
00110             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00111             ContentPanel->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00112         }
00113     }
00114     InvalidateViewState();
00115 }
00116
00117 void MainPage::InvalidateViewState()
00118 {
00119     // Are we going to snapped mode?
00120     if (ApplicationView::Value == ApplicationViewState::Snapped)
00121     {
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(FooterPanel, 1);
00128         Grid::SetColumn(FooterPanel, 1);
00129     }
00130 }
00131
00132 void MainPage::SetDeviceAppForWebcam(String^ strFeature)
00133 {
00134     DeviceAppForWebcam->Text = strFeature;
00135 }
00136
00137 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00138 {
00139     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00140     Windows::System::Launcher::LaunchUriAsync(uri);
00141 }
00142
00143
Generated on Sat Nov 23 2024 16:07:44 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D geometry realization/C++/pch.h Source File

  • Direct2D geometry realization

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 <d3d11_1.h>
00012 #include <d2d1_1.h>
00013 #include <d2d1effects.h>
00014 #include <d2d1_1helper.h>
00015 #include <dwrite_1.h>
00016 #include <wincodec.h>
00017 #include <agile.h>
00018 #define _USE_MATH_DEFINES
00019 #include <math.h>
00020 #include <strsafe.h>
00021
00022 template <class Interface>
00023 inline void
00024 SafeRelease(
00025     Interface **ppInterfaceToRelease
00026     )
00027 {
00028     if (*ppInterfaceToRelease != nullptr)
00029     {
00030         (*ppInterfaceToRelease)->Release();
00031
00032         (*ppInterfaceToRelease) = nullptr;
00033     }
00034 }
00035
00036 template <class DestInterface, class SourceInterace>
00037 inline void
00038 SafeReplace(
00039     DestInterface **ppDestInterface,
00040     SourceInterace *pSourceInterface
00041     )
00042 {
00043     if (*ppDestInterface != nullptr)
00044     {
00045         (*ppDestInterface)->Release();
00046     }
00047
00048     *ppDestInterface = pSourceInterface;
00049
00050     if (pSourceInterface)
00051     {
00052         (*ppDestInterface)->AddRef();
00053     }
00054 }
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Search contract/C++/pch.cpp Source File

  • Search contract

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: AtomPub/C++/common/suspensionmanager.cpp Source File

  • AtomPub
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application resources and localization/C++/Scenario9.xaml.h Source File

  • Application resources and localization

Scenario9.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 "Scenario9.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace ApplicationResources
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 Scenario9 sealed
00031         {
00032         public:
00033             Scenario9();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void Scenario9Button_Show_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040       };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows account authorization/C++/HttpRequest.h Source File

  • Windows account authorization

HttpRequest.h

Go to the documentation of this file.
00001 //-----------------------------------------------------------------------
00002 //
00003 //  Copyright (C) Microsoft Corporation.  All rights reserved.
00004 //
00005 //
00006 // THIS CODE AND INFORMATION ARE PROVIDED AS-IS WITHOUT WARRANTY OF ANY
00007 // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
00008 // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00009 // PARTICULAR PURPOSE.
00010 //-----------------------------------------------------------------------
00011 #pragma once
00012 #include "pch.h"
00013
00014 inline void CheckHResult(HRESULT hResult)
00015 {
00016     if (hResult == E_ABORT)
00017     {
00018         concurrency::cancel_current_task();
00019     }
00020     else if (FAILED(hResult))
00021     {
00022         throw Platform::Exception::CreateException(hResult);
00023     }
00024 }
00025
00026 namespace Web
00027 {
00028
00029 namespace Details
00030 {
00031
00032 // Implementation of IXMLHTTPRequest2Callback used when partial buffers are needed from the response.
00033 // When only the complete response is needed, use HttpRequestStringCallback instead.
00034 class HttpRequestBuffersCallback
00035     : public Microsoft::WRL::RuntimeClass<
00036         Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::ClassicCom>,
00037         IXMLHTTPRequest2Callback,
00038         Microsoft::WRL::FtmBase>
00039 {
00040 public:
00041     HttpRequestBuffersCallback(IXMLHTTPRequest2* httpRequest,
00042         concurrency::cancellation_token ct = concurrency::cancellation_token::none()) :
00043         request(httpRequest), cancellationToken(ct), responseReceived(false), dataHResult(S_OK), statusCode(200)
00044     {
00045         // Register a callback function that aborts the HTTP operation when
00046         // the cancellation token is canceled.
00047         if (cancellationToken != concurrency::cancellation_token::none())
00048         {
00049             registrationToken = cancellationToken.register_callback([this]()
00050             {
00051                 if (request != nullptr)
00052                 {
00053                     request->Abort();
00054                 }
00055             });
00056         }
00057
00058         dataEvent = concurrency::task_completion_event<void>();
00059     }
00060
00061     // Called when the HTTP request is being redirected to a new URL.
00062     IFACEMETHODIMP OnRedirect(IXMLHTTPRequest2*, PCWSTR)
00063     {
00064         return S_OK;
00065     }
00066
00067     // Called when HTTP headers have been received and processed.
00068     IFACEMETHODIMP OnHeadersAvailable(IXMLHTTPRequest2*, DWORD statusCode, PCWSTR reasonPhrase)
00069     {
00070         HRESULT hr = S_OK;
00071
00072         // We must not propagate exceptions back to IXHR2.
00073         try
00074         {
00075             this->statusCode = statusCode;
00076             this->reasonPhrase = reasonPhrase;
00077
00078             concurrency::critical_section::scoped_lock lock(dataEventLock);
00079             dataEvent.set();
00080         }
00081         catch (std::bad_alloc&)
00082         {
00083             hr = E_OUTOFMEMORY;
00084         }
00085         return hr;
00086     }
00087
00088     // Called when a portion of the entity body has been received.
00089     IFACEMETHODIMP OnDataAvailable(IXMLHTTPRequest2*, ISequentialStream* stream)
00090     {
00091         HRESULT hr = S_OK;
00092
00093         // We must not propagate exceptions back to IXHR2.
00094         try
00095         {
00096             // Store a reference on the stream so it can be accessed by the task.
00097             dataStream = stream;
00098
00099             // The work must be done as fast as possible, and must not block this thread,
00100             // for example, waiting on another event object.  Here we simply set an event
00101             // that can be processed by another thread.
00102             concurrency::critical_section::scoped_lock lock(dataEventLock);
00103             dataEvent.set();
00104         }
00105         catch (std::bad_alloc&)
00106         {
00107             hr = E_OUTOFMEMORY;
00108         }
00109         return hr;
00110     }
00111
00112     // Called when the entire entity response has been received.
00113     IFACEMETHODIMP OnResponseReceived(IXMLHTTPRequest2* xhr, ISequentialStream* responseStream)
00114     {
00115         responseReceived = true;
00116         return OnDataAvailable(xhr, responseStream);
00117     }
00118
00119     // Called when an error occurs during the HTTP request.
00120     IFACEMETHODIMP OnError(IXMLHTTPRequest2*, HRESULT hrError)
00121     {
00122         HRESULT hr = S_OK;
00123
00124         // We must not propagate exceptions back to IXHR2.
00125         try
00126         {
00127             concurrency::critical_section::scoped_lock lock(dataEventLock);
00128             dataHResult = hrError;
00129             dataEvent.set();
00130         }
00131         catch (std::bad_alloc&)
00132         {
00133             hr = E_OUTOFMEMORY;
00134         }
00135
00136         return hr;
00137     }
00138
00139     // Create a task that completes when data is available, in an exception-safe way.
00140     concurrency::task<void> CreateDataTask();
00141
00142     HRESULT GetError() const
00143     {
00144         return dataHResult;
00145     }
00146
00147     int GetStatusCode() const
00148     {
00149         return statusCode;
00150     }
00151
00152     std::wstring const& GetReasonPhrase() const
00153     {
00154         return reasonPhrase;
00155     }
00156
00157     bool IsResponseReceived() const
00158     {
00159         return responseReceived;
00160     }
00161
00162     // Copy bytes from the sequential stream into the buffer provided until
00163     // we reach the end of one or the other.
00164     unsigned int ReadData(
00165         _Out_writes_(outputBufferSize) byte* outputBuffer,
00166         unsigned int outputBufferSize);
00167
00168 private:
00169     ~HttpRequestBuffersCallback()
00170     {
00171         // Unregister the callback.
00172         if (cancellationToken != concurrency::cancellation_token::none())
00173         {
00174             cancellationToken.deregister_callback(registrationToken);
00175         }
00176     }
00177
00178     // Signals that the download operation was canceled.
00179     concurrency::cancellation_token cancellationToken;
00180
00181     // Used to unregister the cancellation token callback.
00182     concurrency::cancellation_token_registration registrationToken;
00183
00184     // The IXMLHTTPRequest2 that processes the HTTP request.
00185     Microsoft::WRL::ComPtr<IXMLHTTPRequest2> request;
00186
00187     // Task completion event that is set when data is available or error is triggered.
00188     concurrency::task_completion_event<void> dataEvent;
00189     concurrency::critical_section dataEventLock;
00190
00191     // We cannot store the error obtained from IXHR2 in the dataEvent since any value there is first-writer-wins,
00192     // whereas we want a subsequent error to override an initial success.
00193     HRESULT dataHResult;
00194
00195     // Referenced pointer to the data stream.
00196     Microsoft::WRL::ComPtr<ISequentialStream> dataStream;
00197
00198     // HTTP status code and reason returned by the server.
00199     int statusCode;
00200     std::wstring reasonPhrase;
00201
00202     // Whether the response has been completely received.
00203     bool responseReceived;
00204 };
00205
00206 };
00207
00208 // Utility class for performing asynchronous HTTP requests.
00209 // This class only supports one outstanding request at a time.
00210 class HttpRequest
00211 {
00212 public:
00213     HttpRequest();
00214
00215     int GetStatusCode() const
00216     {
00217         return statusCode;
00218     }
00219
00220     std::wstring const& GetReasonPhrase() const
00221     {
00222         return reasonPhrase;
00223     }
00224
00225     // Whether the response has been completely received, if using ReadAsync().
00226     bool IsResponseComplete() const
00227     {
00228         return responseComplete;
00229     }
00230
00231     // Start an HTTP GET on the specified URI.  The returned task completes once the entire response
00232     // has been received, and the task produces the HTTP response text.  The status code and reason
00233     // can be read with GetStatusCode() and GetReasonPhrase().
00234     concurrency::task<std::wstring> GetAsync(
00235         Windows::Foundation::Uri^ uri,
00236         concurrency::cancellation_token cancellationToken = concurrency::cancellation_token::none());
00237
00238     // Start an HTTP POST on the specified URI, using a string body.  The returned task produces the
00239     // HTTP response text.  The status code and reason can be read with GetStatusCode() and GetReasonPhrase().
00240     concurrency::task<std::wstring> PostAsync(
00241         Windows::Foundation::Uri^ uri,
00242         PCWSTR contentType,
00243         IStream* postStream,
00244         uint64 postStreamSizeToSend,
00245         concurrency::cancellation_token cancellationToken = concurrency::cancellation_token::none());
00246
00247     // Start an HTTP POST on the specified URI, using a stream body.  The returned task produces the
00248     // HTTP response text.  The status code and reason can be read with GetStatusCode() and GetReasonPhrase().
00249     concurrency::task<std::wstring> PostAsync(
00250         Windows::Foundation::Uri^ uri,
00251         const std::wstring& str,
00252         concurrency::cancellation_token cancellationToken = concurrency::cancellation_token::none());
00253
00254     // Send a request but don't return the response.  Instead, let the caller read it with ReadAsync().
00255     concurrency::task<void> SendAsync(
00256         const std::wstring& httpMethod,
00257         Windows::Foundation::Uri^ uri,
00258         concurrency::cancellation_token cancellationToken = concurrency::cancellation_token::none());
00259
00260     // Read a chunk of data from the HTTP response, up to a specified length or until we reach the end
00261     // of the response, and store the value in the provided buffer.  This is useful for large content,
00262     // enabling the streaming of the result.
00263     concurrency::task<void> ReadAsync(
00264         Windows::Storage::Streams::IBuffer^ readBuffer,
00265         unsigned int offsetInBuffer,
00266         unsigned int requestedBytesToRead);
00267
00268     static void CreateMemoryStream(IStream **stream);
00269
00270 private:
00271     // Start a download of the specified URI using the specified method.  The returned task produces the
00272     // HTTP response text.  The status code and reason can be read with GetStatusCode() and GetReasonPhrase().
00273     concurrency::task<std::wstring> DownloadAsync(
00274         PCWSTR httpMethod,
00275         PCWSTR uri,
00276         concurrency::cancellation_token cancellationToken,
00277         PCWSTR contentType,
00278         IStream* postStream,
00279         uint64 postStreamBytesToSend);
00280
00281     // Referenced pointer to the callback, if using SendAsync/ReadAsync.
00282     Microsoft::WRL::ComPtr<Details::HttpRequestBuffersCallback> buffersCallback;
00283
00284     int statusCode;
00285     std::wstring reasonPhrase;
00286
00287     // Whether the response has been completely received, if using ReadAsync().
00288     bool responseComplete;
00289 };
00290
00291 };
Generated on Sat Nov 23 2024 16:07:58 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Network information/C++/ConnectionProfileList.xaml.h Source File

  • Network information

ConnectionProfileList.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 // ConnectionProfileList.xaml.h
00013 // Declaration of the ConnectionProfileList class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "ConnectionProfileList.g.h"
00020 #include "MainPage.xaml.h"
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::System;
00026 using namespace Windows::Foundation;
00027 using namespace Platform;
00028 using namespace Windows::Networking;
00029 using namespace Windows::Networking::Connectivity;
00030
00031 namespace SDKSample
00032 {
00033     namespace NetworkInformationApi
00034     {
00035         /// <summary>
00036         /// An empty page that can be used on its own or navigated to within a Frame.
00037         /// </summary>
00038         [Windows::Foundation::Metadata::WebHostHidden]
00039         public ref class ConnectionProfileList sealed
00040         {
00041         public:
00042             ConnectionProfileList();
00043
00044         protected:
00045             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00046         private:
00047             MainPage^ rootPage;
00048             void ConnectionProfileList_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00049
00050             Windows::Networking::Connectivity::NetworkInformation^ networkInfo;
00051             String ^connectionProfileInfo;
00052             String^ GetConnectionProfile(Windows::Networking::Connectivity::ConnectionProfile^ connectionProfile);
00053             String^ GetConnectionCostInfo(Windows::Networking::Connectivity::ConnectionCost^ connectionCost);
00054             String^ GetCostBasedSuggestions(Windows::Networking::Connectivity::ConnectionCost^ connectionCost);
00055             String^ GetDataPlanStatusInfo(Windows::Networking::Connectivity::DataPlanStatus^ dataPlan);
00056             String^ GetNetworkSecuritySettingsInfo(Windows::Networking::Connectivity::NetworkSecuritySettings^ netSecuritySettings);
00057         };
00058     }
00059 }
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

D2DPerspectiveTransform Member List

This is the complete list of members for D2DPerspectiveTransform, including all inherited members.
__pad0__ | D2DPerspectiveTransform |
CreateDeviceIndependentResources() override | D2DPerspectiveTransform | [virtual]
CreateDeviceResources() override | D2DPerspectiveTransform | [virtual]
CreateWindowSizeDependentResources() override | D2DPerspectiveTransform | [virtual]
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | D2DPerspectiveTransform | [virtual]
Load(_In_ Platform::String^entryPoint) | D2DPerspectiveTransform | [virtual]
m_bitmapPerspective | D2DPerspectiveTransform | [private]
m_gestureRecognizer | D2DPerspectiveTransform | [private]
m_rotationAngle | D2DPerspectiveTransform | [private]
m_sampleOverlay | D2DPerspectiveTransform | [private]
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | D2DPerspectiveTransform | [private]
OnDisplayContentsInvalidated(_In_ Platform::Object^sender) | D2DPerspectiveTransform | [private]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | D2DPerspectiveTransform | [private]
OnManipulationUpdated(_In_ Windows::UI::Input::GestureRecognizer^recognizer, _In_ Windows::UI::Input::ManipulationUpdatedEventArgs^args) | D2DPerspectiveTransform | [private]
OnPointerMoved(_In_ Windows::UI::Core::CoreWindow^window, _In_ Windows::UI::Core::PointerEventArgs^args) | D2DPerspectiveTransform | [private]
OnPointerPressed(_In_ Windows::UI::Core::CoreWindow^window, _In_ Windows::UI::Core::PointerEventArgs^args) | D2DPerspectiveTransform | [private]
OnPointerReleased(_In_ Windows::UI::Core::CoreWindow^window, _In_ Windows::UI::Core::PointerEventArgs^args) | D2DPerspectiveTransform | [private]
OnResuming(_In_ Platform::Object^sender, _In_ Platform::Object^args) | D2DPerspectiveTransform | [private]
OnSuspending(_In_ Platform::Object^sender, _In_ Windows::ApplicationModel::SuspendingEventArgs^args) | D2DPerspectiveTransform | [private]
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | D2DPerspectiveTransform | [private]
Render() override | D2DPerspectiveTransform | [virtual]
Run() | D2DPerspectiveTransform | [virtual]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | D2DPerspectiveTransform | [virtual]
Uninitialize() | D2DPerspectiveTransform | [virtual]
Generated on Sat Nov 23 2024 16:09:11 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Vector4< T > Member List

This is the complete list of members for Vector4< T >, including all inherited members.
a | Vector4< T > |
b | Vector4< T > |
g | Vector4< T > |
operator[](unsigned int index) | Vector4< T > | [inline]
operator[](unsigned int index) | Vector4< T > | [inline]
operator[](unsigned int index) | Vector4< T > | [inline]
operator[](unsigned int index) | Vector4< T > | [inline]
operator[](unsigned int index) | Vector4< T > | [inline]
operator[](unsigned int index) | Vector4< T > | [inline]
operator[](unsigned int index) | Vector4< T > | [inline]
operator[](unsigned int index) | Vector4< T > | [inline]
operator[](unsigned int index) | Vector4< T > | [inline]
operator[](unsigned int index) | Vector4< T > | [inline]
operator[](unsigned int index) | Vector4< T > | [inline]
operator[](unsigned int index) | Vector4< T > | [inline]
operator[](unsigned int index) | Vector4< T > | [inline]
operator[](unsigned int index) | Vector4< T > | [inline]
operator[](unsigned int index) | Vector4< T > | [inline]
operator[](unsigned int index) | Vector4< T > | [inline]
operator[](unsigned int index) | Vector4< T > | [inline]
operator[](unsigned int index) | Vector4< T > | [inline]
operator[](unsigned int index) | Vector4< T > | [inline]
operator[](unsigned int index) | Vector4< T > | [inline]
operator[](unsigned int index) | Vector4< T > | [inline]
operator[](unsigned int index) | Vector4< T > | [inline]
r | Vector4< T > |
Vector4(T _x=0, T _y=0, T _z=0, T _w=0) | Vector4< T > | [inline]
Vector4(T _x=0, T _y=0, T _z=0, T _w=0) | Vector4< T > | [inline]
Vector4(T _x=0, T _y=0, T _z=0, T _w=0) | Vector4< T > | [inline]
Vector4(T _x=0, T _y=0, T _z=0, T _w=0) | Vector4< T > | [inline]
Vector4(T _x=0, T _y=0, T _z=0, T _w=0) | Vector4< T > | [inline]
Vector4(T _x=0, T _y=0, T _z=0, T _w=0) | Vector4< T > | [inline]
Vector4(T _x=0, T _y=0, T _z=0, T _w=0) | Vector4< T > | [inline]
Vector4(T _x=0, T _y=0, T _z=0, T _w=0) | Vector4< T > | [inline]
Vector4(T _x=0, T _y=0, T _z=0, T _w=0) | Vector4< T > | [inline]
Vector4(T _x=0, T _y=0, T _z=0, T _w=0) | Vector4< T > | [inline]
Vector4(T _x=0, T _y=0, T _z=0, T _w=0) | Vector4< T > | [inline]
Vector4(T _x=0, T _y=0, T _z=0, T _w=0) | Vector4< T > | [inline]
Vector4(T _x=0, T _y=0, T _z=0, T _w=0) | Vector4< T > | [inline]
Vector4(T _x=0, T _y=0, T _z=0, T _w=0) | Vector4< T > | [inline]
Vector4(T _x=0, T _y=0, T _z=0, T _w=0) | Vector4< T > | [inline]
Vector4(T _x=0, T _y=0, T _z=0, T _w=0) | Vector4< T > | [inline]
Vector4(T _x=0, T _y=0, T _z=0, T _w=0) | Vector4< T > | [inline]
Vector4(T _x=0, T _y=0, T _z=0, T _w=0) | Vector4< T > | [inline]
Vector4(T _x=0, T _y=0, T _z=0, T _w=0) | Vector4< T > | [inline]
Vector4(T _x=0, T _y=0, T _z=0, T _w=0) | Vector4< T > | [inline]
Vector4(T _x=0, T _y=0, T _z=0, T _w=0) | Vector4< T > | [inline]
Vector4(T _x=0, T _y=0, T _z=0, T _w=0) | Vector4< T > | [inline]
w | Vector4< T > |
x | Vector4< T > |
y | Vector4< T > |
z | Vector4< T > |
Generated on Sat Nov 23 2024 16:09:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

TriColorValueHelper Member List

This is the complete list of members for TriColorValueHelper, including all inherited members.
IsFirst(TriColorValue value) | TriColorValueHelper | [inline, static]
IsLast(TriColorValue value) | TriColorValueHelper | [inline, static]
NextValue(TriColorValue value) | TriColorValueHelper | [inline, static]
PreviousValue(TriColorValue value) | TriColorValueHelper | [inline, static]
ValueToString(TriColorValue value, _Out_ BSTR *pszValue) | TriColorValueHelper | [inline, static]
Generated on Sat Nov 23 2024 16:09:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Compass sensor/C++/pch.h Source File

  • Compass sensor

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::TileContent::ISquareTileInternal Member List

This is the complete list of members for NotificationsExtensions::TileContent::ISquareTileInternal, including all inherited members.
SerializeBinding(string globalLang, string globalBaseUri, TileBranding globalBranding, bool globalAddImageQuery) | NotificationsExtensions::TileContent::ISquareTileInternal
SerializeBinding(string globalLang, string globalBaseUri, TileBranding globalBranding, bool globalAddImageQuery) | NotificationsExtensions::TileContent::ISquareTileInternal
Generated on Sat Nov 23 2024 16:09:41 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::WebSocket::sealed Member List

This is the complete list of members for SDKSample::WebSocket::sealed, including all inherited members.
bytesReceived | SDKSample::WebSocket::sealed | [private]
Close_Click(Object^sender, RoutedEventArgs^e) | SDKSample::WebSocket::sealed | [private]
Closed(IWebSocket^sender, WebSocketClosedEventArgs^args) | SDKSample::WebSocket::sealed | [private]
criticalSection | SDKSample::WebSocket::sealed | [private]
dataSent | SDKSample::WebSocket::sealed | [private]
HandleException(Exception^exception) | SDKSample::WebSocket::sealed | [private]
HandleException(Exception^exception) | SDKSample::WebSocket::sealed | [private]
MarshalText(TextBox^output, String^value) | SDKSample::WebSocket::sealed | [private]
MarshalText(TextBox^output, String^value, bool append) | SDKSample::WebSocket::sealed | [private]
MarshalText(TextBox^output, String^value) | SDKSample::WebSocket::sealed | [private]
MarshalText(TextBox^output, String^value, bool append) | SDKSample::WebSocket::sealed | [private]
MessageReceived(MessageWebSocket^sender, MessageWebSocketMessageReceivedEventArgs^args) | SDKSample::WebSocket::sealed | [private]
messageWebSocket | SDKSample::WebSocket::sealed | [private]
messageWriter | SDKSample::WebSocket::sealed | [private]
OnNavigatedTo(NavigationEventArgs^e) override | SDKSample::WebSocket::sealed | [protected, virtual]
OnNavigatedTo(NavigationEventArgs^e) override | SDKSample::WebSocket::sealed | [protected, virtual]
readBuffer | SDKSample::WebSocket::sealed | [private]
rootPage | SDKSample::WebSocket::sealed | [private]
Scenario1() | SDKSample::WebSocket::sealed |
Scenario2() | SDKSample::WebSocket::sealed |
Scenario2Closed(IWebSocket^sender, WebSocketClosedEventArgs^args) | SDKSample::WebSocket::sealed | [private]
Scenario2ReceiveData() | SDKSample::WebSocket::sealed | [private]
Scenario2SendData() | SDKSample::WebSocket::sealed | [private]
sendBuffer | SDKSample::WebSocket::sealed | [private]
SendMessage() | SDKSample::WebSocket::sealed | [private]
Start_Click(Object^sender, RoutedEventArgs^e) | SDKSample::WebSocket::sealed | [private]
Start_Click(Object^sender, RoutedEventArgs^e) | SDKSample::WebSocket::sealed | [private]
Stop_Click(Object^sender, RoutedEventArgs^e) | SDKSample::WebSocket::sealed | [private]
streamWebSocket | SDKSample::WebSocket::sealed | [private]
~Scenario1() | SDKSample::WebSocket::sealed | [private]
~Scenario2() | SDKSample::WebSocket::sealed | [private]
Generated on Sat Nov 23 2024 16:09:53 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML AppBar control/C++/Sample-Utils/CppSamplesUtils.h Source File

  • XAML AppBar control
  • Sample-Utils

CppSamplesUtils.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 <string>
00014 #include <sstream>
00015 #include <algorithm>
00016 #include <collection.h>
00017 #include <ppltasks.h>
00018
00019 namespace CppSamplesUtils
00020 {
00021     namespace Details
00022     {
00023         static Windows::Foundation::Collections::PropertySet^ sessionState = nullptr;
00024         static Platform::String^ sessionStateFileName = ref new Platform::String(L"_cppSessionState.xml");
00025
00026         concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file);
00027         concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file);
00028     }
00029
00030     class SuspensionManager
00031     {
00032     public:
00033         static Windows::Foundation::Collections::PropertySet^ SessionState()
00034         {
00035             using namespace Windows::Foundation::Collections;
00036             using namespace Details;
00037
00038             if (sessionState == nullptr)
00039             {
00040                 sessionState = ref new PropertySet();
00041             }
00042             return sessionState;
00043         }
00044
00045         static concurrency::task<void> StartRestoreTask()
00046         {
00047             using namespace Windows::Foundation;
00048             using namespace Windows::Storage;
00049             using namespace Windows::Storage::Streams;
00050             using namespace Details;
00051
00052             auto state = SessionState();
00053             state->Clear();
00054
00055             concurrency::task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFileName));
00056             return getFileTask.then([=](StorageFile^ file)
00057             {
00058                 return DeserializeSessionState(file);
00059             });
00060         }
00061
00062         static concurrency::task<void> StartSaveTask()
00063         {
00064             using namespace Windows::Foundation;
00065             using namespace Windows::Storage;
00066             using namespace Windows::Storage::Streams;
00067             using namespace Details;
00068
00069             concurrency::task<StorageFile^> createFileTask(ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFileName, CreationCollisionOption::ReplaceExisting));
00070             return createFileTask.then([=](StorageFile^ file)
00071             {
00072                 return SerializeSessionState(file);
00073             });
00074         }
00075     };
00076
00077     namespace Details
00078     {
00079         template <class T>
00080         inline Platform::String^ ToString(T value)
00081         {
00082             std::wstringstream wss;
00083             wss << value;
00084             return ref new Platform::String(wss.str().c_str());
00085         }
00086
00087         template <class T>
00088         inline T FromStringTo(Platform::String^ str)
00089         {
00090             std::wistringstream wiss(str->Data());
00091             T value = 0;
00092             wiss >> value;
00093             return value;
00094         }
00095
00096         template <class T>
00097         inline T FromHexStringTo(Platform::String^ str)
00098         {
00099             std::wistringstream wiss(str->Data());
00100             T value = 0;
00101             wiss >> std::hex >> value;
00102             return value;
00103         }
00104
00105         template <>
00106         inline Platform::Guid FromStringTo<Platform::Guid>(Platform::String^ str)
00107         {
00108             using namespace Platform;
00109
00110             if (str->Length() != 38)
00111             {
00112                 throw ref new InvalidArgumentException;
00113             }
00114             std::wstring ws(str->Data());
00115             if (ws[0] != L'{' || ws[37] != L'}' || ws[9] != L'-' || ws[14] != L'-' || ws[19] != L'-' || ws[24] != L'-')
00116             {
00117                 throw ref new InvalidArgumentException;
00118             }
00119             ws[0] = ws[37] = ws[9] = ws[14] = ws[19] =ws[24] = L' ';
00120             std::wistringstream wiss(ws);
00121             unsigned int a = 0;
00122             unsigned short b = 0;
00123             unsigned short c = 0;
00124             unsigned short d = 0;
00125             unsigned long long e = 0;
00126             static_assert(sizeof(d) == sizeof(char) * 2, "sizeof(d) == sizeof(char) * 2");
00127             static_assert(sizeof(e) == sizeof(char) * 8, "sizeof(e) == sizeof(char) * 8");
00128             wiss >> std::hex >> a >> b >> c >> d >> e;
00129             unsigned char *ad = (unsigned char*)(&d);
00130             unsigned char *ae = (unsigned char*)(&e);
00131             return Platform::Guid(a, b, c, ad[1], ad[0], ae[5], ae[4], ae[3], ae[2], ae[1], ae[0]);
00132         }
00133
00134         inline Platform::Object^ ConvertStringToObject(Windows::Foundation::PropertyType type, Platform::String^ str)
00135         {
00136             using namespace Platform;
00137             using namespace Windows::Foundation;
00138
00139             if (type == PropertyType::String)
00140             {
00141                 return PropertyValue::CreateString(str);
00142             }
00143
00144             switch (type)
00145             {
00146             case PropertyType::UInt8:
00147                 return PropertyValue::CreateUInt8((unsigned char)FromStringTo<unsigned short>(str));
00148             case PropertyType::UInt16:
00149                 return PropertyValue::CreateUInt16(FromStringTo<unsigned short>(str));
00150             case PropertyType::UInt32:
00151                 return PropertyValue::CreateUInt32(FromStringTo<unsigned int>(str));
00152             case PropertyType::UInt64:
00153                 return PropertyValue::CreateUInt64(FromStringTo<unsigned long long>(str));
00154             case PropertyType::Int16:
00155                 return PropertyValue::CreateInt16(FromStringTo<short>(str));
00156             case PropertyType::Int32:
00157                 return PropertyValue::CreateInt32(FromStringTo<int>(str));
00158             case PropertyType::Int64:
00159                 return PropertyValue::CreateInt64(FromStringTo<long long>(str));
00160             case PropertyType::Single:
00161                 return PropertyValue::CreateSingle(FromStringTo<float>(str));
00162             case PropertyType::Double:
00163                 return PropertyValue::CreateDouble(FromStringTo<double>(str));
00164             case PropertyType::Boolean:
00165                 return PropertyValue::CreateBoolean(FromStringTo<bool>(str));
00166             case PropertyType::Char16:
00167                 return PropertyValue::CreateChar16(str->Data()[0]);
00168             case PropertyType::Guid:
00169                 return PropertyValue::CreateGuid(FromStringTo<Guid>(str));
00170             default:
00171                 throw ref new Platform::InvalidCastException;
00172             }
00173         }
00174
00175         inline Platform::String^ ConvertPropertyValueToString(Windows::Foundation::IPropertyValue^ pv)
00176         {
00177             using namespace Platform;
00178             using namespace Windows::Foundation;
00179
00180             String^ valueString;
00181
00182             switch (pv->Type)
00183             {
00184             case PropertyType::String:
00185                 valueString = pv->GetString();
00186                 break;
00187
00188             case PropertyType::UInt8:
00189             case PropertyType::UInt16:
00190             case PropertyType::UInt32:
00191             case PropertyType::UInt64:
00192                 valueString = ToString(pv->GetUInt64());
00193                 break;
00194
00195             case PropertyType::Int16:
00196             case PropertyType::Int32:
00197             case PropertyType::Int64:
00198                 valueString = ToString(pv->GetInt64());
00199                 break;
00200
00201             case PropertyType::Single:
00202                 valueString = ToString(pv->GetSingle());
00203                 break;
00204
00205             case PropertyType::Double:
00206                 valueString = ToString(pv->GetDouble());
00207                 break;
00208
00209             case PropertyType::Boolean:
00210                 valueString = ToString(pv->GetBoolean());
00211                 break;
00212
00213             case PropertyType::Char16:
00214                 wchar_t buffer[2];
00215                 buffer[0] = pv->GetChar16();
00216                 buffer[1] = 0;
00217                 valueString = ref new String(buffer);
00218                 break;
00219
00220             case PropertyType::Guid:
00221                 valueString = pv->GetGuid().ToString();
00222                 break;
00223
00224             default:
00225                 throw ref new InvalidCastException;
00226             }
00227
00228             return valueString;
00229         }
00230
00231         inline Windows::Data::Xml::Dom::XmlElement^ CreateXmlElementFromObject(Windows::Data::Xml::Dom::XmlDocument^ doc, Platform::String^ name, Platform::Object^ value)
00232         {
00233             using namespace Platform;
00234             using namespace Windows::Foundation;
00235             using namespace Windows::Data::Xml::Dom;
00236
00237             XmlElement^ element = doc->CreateElement("item");
00238             element->SetAttribute("name", name);
00239
00240             IPropertyValue^ pv = (IPropertyValue^)value;
00241             element->SetAttribute("type", ToString((int)pv->Type));
00242             element->SetAttribute("value", ConvertPropertyValueToString(pv));
00243
00244             return element;
00245         }
00246
00247         inline concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file)
00248         {
00249             using namespace Windows::Data::Xml::Dom;
00250             using namespace Windows::Foundation;
00251             namespace WFC = Windows::Foundation::Collections;
00252             typedef Windows::Foundation::Collections::IKeyValuePair<Platform::String^, Platform::Object^> KVPair;
00253
00254             XmlDocument^ doc = ref new XmlDocument;
00255             doc->AppendChild(doc->CreateElement("items"));
00256             auto sessionState = SuspensionManager::SessionState();
00257
00258             std::for_each(WFC::begin(sessionState), WFC::end(sessionState), [doc](KVPair^ item)
00259             {
00260                 doc->DocumentElement->AppendChild(CreateXmlElementFromObject(doc, item->Key, item->Value));
00261             });
00262
00263             return concurrency::task<void>(doc->SaveToFileAsync(file));
00264         }
00265
00266         inline Windows::Foundation::PropertyType PropertyTypeFromString(Platform::String^ str)
00267         {
00268             int value = FromStringTo<int>(str);
00269             return (Windows::Foundation::PropertyType)value;
00270         }
00271
00272         inline concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file)
00273         {
00274             using namespace Platform;
00275             using namespace Windows::Foundation;
00276             using namespace Windows::Data::Xml::Dom;
00277             namespace WFC = Windows::Foundation::Collections;
00278
00279             concurrency::task<XmlDocument^> loadFileTask(XmlDocument::LoadFromFileAsync(file));
00280             return loadFileTask.then([=](concurrency::task<XmlDocument^> docTask)
00281             {
00282                 try
00283                 {
00284                     auto doc = docTask.get();
00285                     auto items = doc->SelectNodes("/items/item");
00286                     auto sessionState = SuspensionManager::SessionState();
00287
00288                     std::for_each(WFC::begin(items), WFC::end(items), [sessionState](IXmlNode^ node)
00289                     {
00290                         auto element = (IXmlElement^)node;
00291                         String^ name = element->GetAttribute("name");
00292                         String^ value = element->GetAttribute("value");
00293                         PropertyType type = PropertyTypeFromString(element->GetAttribute("type"));
00294
00295                         Object^ valueObject = ConvertStringToObject(type, value);
00296                         sessionState->Insert(name, valueObject);
00297                     });
00298
00299                 }
00300                 catch (Platform::Exception^)
00301                 {
00302                     // Restoring is best effort
00303                 }
00304             });
00305         }
00306     } // namespace Details
00307 } // namespace CppSamplesUtils
Generated on Sat Nov 23 2024 16:07:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Credential picker/C++/ScenarioOutput1.xaml.h Source File

  • Credential picker

ScenarioOutput1.xaml.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 //
00009 // Scenario1Output.xaml.h
00010 // Declaration of the Scenario1Output class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioOutput1.g.h"
00017 #include "MainPage.xaml.h"
00018
00019 namespace CredentialPickerCPP
00020 {
00021   [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class ScenarioOutput1 sealed
00023     {
00024     public:
00025         ScenarioOutput1();
00026
00027     protected:
00028         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030
00031     private:
00032         ~ScenarioOutput1();
00033
00034     MainPage^ rootPage;
00035         void rootPage_InputFrameLoaded(Object^ sender, Object^ e);
00036         Windows::Foundation::EventRegistrationToken _frameLoadedToken;
00037     };
00038 }
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

ConvolveMatrixEffect Member List

This is the complete list of members for ConvolveMatrixEffect, including all inherited members.
__pad0__ | ConvolveMatrixEffect |
CreateDeviceIndependentResources() override | ConvolveMatrixEffect | [virtual]
CreateDeviceResources() override | ConvolveMatrixEffect | [virtual]
CreateWindowSizeDependentResources() override | ConvolveMatrixEffect | [virtual]
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | ConvolveMatrixEffect | [virtual]
Load(_In_ Platform::String^entryPoint) | ConvolveMatrixEffect | [virtual]
m_bitmapPixelSize | ConvolveMatrixEffect | [private]
m_bitmapSourceEffect | ConvolveMatrixEffect | [private]
m_convolveMatrixEffect | ConvolveMatrixEffect | [private]
m_gestureRecognizer | ConvolveMatrixEffect | [private]
m_imageSize | ConvolveMatrixEffect | [private]
m_sampleOverlay | ConvolveMatrixEffect | [private]
m_selectedKernel | ConvolveMatrixEffect | [private]
m_wicConvertedSource | ConvolveMatrixEffect | [private]
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | ConvolveMatrixEffect | [private]
OnDisplayContentsInvalidated(_In_ Platform::Object^sender) | ConvolveMatrixEffect | [private]
OnHolding(_In_ Windows::UI::Input::GestureRecognizer^sender, _In_ Windows::UI::Input::HoldingEventArgs^args) | ConvolveMatrixEffect | [private]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | ConvolveMatrixEffect | [private]
OnPointerMoved(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | ConvolveMatrixEffect | [private]
OnPointerPressed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | ConvolveMatrixEffect | [private]
OnPointerReleased(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | ConvolveMatrixEffect | [private]
OnResuming(_In_ Platform::Object^sender, _In_ Platform::Object^args) | ConvolveMatrixEffect | [private]
OnSuspending(_In_ Platform::Object^sender, _In_ Windows::ApplicationModel::SuspendingEventArgs^args) | ConvolveMatrixEffect | [private]
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | ConvolveMatrixEffect | [private]
Render() override | ConvolveMatrixEffect | [virtual]
Run() | ConvolveMatrixEffect | [virtual]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | ConvolveMatrixEffect | [virtual]
ShowMenu(Windows::Foundation::Point position) | ConvolveMatrixEffect | [private]
SwitchKernel(_In_ Windows::UI::Popups::IUICommand^command) | ConvolveMatrixEffect | [private]
Uninitialize() | ConvolveMatrixEffect | [virtual]
Generated on Sat Nov 23 2024 16:09:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: App package information/C++/Scenario1.xaml.cpp Source File

  • App package information

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::PackageSample;
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     OutputTextBlock->Text = "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();
00084 }
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/SoundEffect.cpp Source File

  • DirectX 3D shooting game

SoundEffect.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 "SoundEffect.h"
00010 #include "DirectXSample.h"
00011
00012 SoundEffect::SoundEffect():
00013     m_audioAvailable(false)
00014 {
00015 }
00016
00017 //----------------------------------------------------------------------
00018
00019 void SoundEffect::Initialize(
00020     _In_ IXAudio2 *masteringEngine,
00021     _In_ WAVEFORMATEX *sourceFormat,
00022     _In_ Platform::Array<byte>^ soundData)
00023 {
00024     m_soundData = soundData;
00025
00026     if (masteringEngine == nullptr)
00027     {
00028         // Audio is not available so just return.
00029         m_audioAvailable = false;
00030         return;
00031     }
00032
00033     // Create a source voice for this sound effect.
00034     DX::ThrowIfFailed(
00035         masteringEngine->CreateSourceVoice(
00036             &m_sourceVoice,
00037             sourceFormat
00038             )
00039         );
00040     m_audioAvailable = true;
00041 }
00042
00043 //----------------------------------------------------------------------
00044
00045 void SoundEffect::PlaySound(_In_ float volume)
00046 {
00047     XAUDIO2_BUFFER buffer = {0};
00048
00049     if (!m_audioAvailable)
00050     {
00051         // Audio is not available so just return.
00052         return;
00053     }
00054
00055     // Interrupt sound effect if it is currently playing.
00056     DX::ThrowIfFailed(
00057         m_sourceVoice->Stop()
00058         );
00059     DX::ThrowIfFailed(
00060         m_sourceVoice->FlushSourceBuffers()
00061         );
00062
00063     // Queue the memory buffer for playback and start the voice.
00064     buffer.AudioBytes = m_soundData->Length;
00065     buffer.pAudioData = m_soundData->Data;
00066     buffer.Flags = XAUDIO2_END_OF_STREAM;
00067
00068     DX::ThrowIfFailed(
00069         m_sourceVoice->SetVolume(volume)
00070         );
00071     DX::ThrowIfFailed(
00072         m_sourceVoice->SubmitSourceBuffer(&buffer)
00073         );
00074     DX::ThrowIfFailed(
00075         m_sourceVoice->Start()
00076         );
00077 }
00078
00079 //----------------------------------------------------------------------
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Globalization preferences/C++/Language.xaml.h Source File

  • Globalization preferences

Language.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 // LanguageScenario.xaml.h
00013 // Declaration of the LanguageScenario class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Language.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace GlobalizationPreferencesSample
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 LanguageScenario sealed
00031         {
00032         public:
00033             LanguageScenario();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void Display_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

HighScoreTable Member List

This is the complete list of members for HighScoreTable, including all inherited members.
AddScoreToTable(HighScoreEntry &entry) | HighScoreTable |
CalculateSize() | TextElement | [protected, virtual]
CreateTextLayout() | TextElement | [protected]
ElementBase() | ElementBase | [protected]
FadeOut(float fadeOutTime) | TextElement |
GetBounds() | ElementBase |
GetEntries() | HighScoreTable | [inline]
GetTextStyle() | TextElement | [inline]
HighScoreTable() | HighScoreTable |
Initialize() | HighScoreTable | [virtual]
IsVisible() const | ElementBase | [inline]
m_alignment | ElementBase | [protected]
m_container | ElementBase | [protected]
m_entries | HighScoreTable | [protected]
m_fadeOutTime | TextElement | [protected]
m_fadeOutTimeElapsed | TextElement | [protected]
m_fadeStartingOpacity | TextElement | [protected]
m_isFadingOut | TextElement | [protected]
m_shadowColorBrush | TextElement | [protected]
m_size | ElementBase | [protected]
m_text | TextElement | [protected]
m_textColorBrush | TextElement | [protected]
m_textExtents | TextElement | [protected]
m_textLayout | TextElement | [protected]
m_textStyle | TextElement | [protected]
m_visible | ElementBase | [protected]
Render() | HighScoreTable | [virtual]
Reset() | HighScoreTable |
SetAlignment(AlignType horizontal, AlignType vertical) | ElementBase |
SetContainer(const D2D1_RECT_F &container) | ElementBase | [virtual]
SetText(__nullterminated WCHAR *text) | TextElement |
SetText(Platform::String^text) | TextElement |
SetTextColor(const D2D1_COLOR_F &textColor) | TextElement |
SetTextOpacity(float textOpacity) | TextElement |
SetVisible(bool visible) | ElementBase |
TextElement() | TextElement |
Update(float timeTotal, float timeDelta) | HighScoreTable | [virtual]
UpdateText() | HighScoreTable | [protected]
Generated on Sat Nov 23 2024 16:09:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Custom driver access/C++/app_cpp/App.xaml.h Source File

  • Custom driver access
  • app_cpp

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Programmatic file search/C++/common/suspensionmanager.cpp Source File

  • Programmatic file search
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:37 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CameraOptionsUI/C++/MainPage.xaml.h Source File

  • CameraOptionsUI

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Secondary tiles/C#,C++/LaunchedFromSecondaryTile.xaml.cpp Source File

  • Secondary tiles
  • C#,C++

LaunchedFromSecondaryTile.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 // LaunchedFromSecondaryTile.xaml.cpp
00013 // Implementation of the LaunchedFromSecondaryTile class
00014 //
00015
00016 #include "pch.h"
00017 #include "LaunchedFromSecondaryTile.xaml.h"
00018
00019 using namespace SecondaryTiles;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 LaunchedFromSecondaryTile::LaunchedFromSecondaryTile()
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 LaunchedFromSecondaryTile::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     // Preserve the app bar
00041     appBar = rootPage->BottomAppBar;
00042     // Now null it so we don't show the appbar in this scenario
00043     rootPage->BottomAppBar = nullptr;
00044
00045     if (rootPage->LaunchArgs != nullptr)
00046     {
00047         if (rootPage->LaunchArgs->Arguments != nullptr)
00048         {
00049             rootPage->NotifyUser("Application was activated from a Secondary Tile with the following Activation Arguments : " + rootPage->LaunchArgs->Arguments, NotifyType::StatusMessage);
00050             rootPage->LaunchArgs = nullptr;
00051         }
00052     }
00053 }
00054
00055 /// <summary>
00056 /// Invoked when this page is about to be navigated out 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 LaunchedFromSecondaryTile::OnNavigatingFrom(NavigatingCancelEventArgs^ e)
00061 {
00062     // Restore the app bar
00063     rootPage->BottomAppBar = appBar;
00064 }
Generated on Sat Nov 23 2024 16:08:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX marble maze game/C++/DirectXApp.h Source File

  • DirectX marble maze game

DirectXApp.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 "MarbleMaze.h"
00011
00012 ref class DirectXApp : public Windows::ApplicationModel::Core::IFrameworkView
00013 {
00014 internal:
00015     DirectXApp();
00016
00017 public:
00018     // IFrameworkView Methods
00019     virtual void Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00020     virtual void SetWindow(_In_ Windows::UI::Core::CoreWindow^ window);
00021     virtual void Load(_In_ Platform::String^ entryPoint);
00022     virtual void Run();
00023     virtual void Uninitialize();
00024
00025 private:
00026     // Event Handlers
00027     void OnWindowSizeChanged(
00028         _In_ Windows::UI::Core::CoreWindow^ sender,
00029         _In_ Windows::UI::Core::WindowSizeChangedEventArgs^ args
00030         );
00031
00032     void OnVisibilityChanged(
00033         _In_ Windows::UI::Core::CoreWindow^ sender,
00034         _In_ Windows::UI::Core::VisibilityChangedEventArgs^ args
00035         );
00036
00037     void OnLogicalDpiChanged(
00038         _In_ Platform::Object^ sender
00039         );
00040
00041     void OnActivated(
00042         _In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView,
00043         _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^ args
00044         );
00045
00046     void OnWindowActivationChanged(
00047         _In_ Windows::UI::Core::CoreWindow^ sender,
00048         _In_ Windows::UI::Core::WindowActivatedEventArgs^ args
00049         );
00050
00051     void OnPointerPressed(
00052         _In_ Windows::UI::Core::CoreWindow^ sender,
00053         _In_ Windows::UI::Core::PointerEventArgs^ args
00054         );
00055
00056     void OnPointerReleased(
00057         _In_ Windows::UI::Core::CoreWindow^ sender,
00058         _In_ Windows::UI::Core::PointerEventArgs^ args
00059         );
00060
00061     void OnPointerMoved(
00062         _In_ Windows::UI::Core::CoreWindow^ sender,
00063         _In_ Windows::UI::Core::PointerEventArgs^ args
00064         );
00065
00066     void OnKeyDown(
00067         _In_ Windows::UI::Core::CoreWindow^ sender,
00068         _In_ Windows::UI::Core::KeyEventArgs^ args
00069         );
00070
00071     void OnKeyUp(
00072         _In_ Windows::UI::Core::CoreWindow^ sender,
00073         _In_ Windows::UI::Core::KeyEventArgs^ args
00074         );
00075
00076     void OnSuspending(
00077         _In_ Platform::Object^ sender,
00078         _In_ Windows::ApplicationModel::SuspendingEventArgs^ args
00079         );
00080
00081     void OnResuming(
00082         _In_ Platform::Object^ sender,
00083         _In_ Platform::Object^ args
00084         );
00085
00086     void OnWindowClosed(
00087         _In_ Windows::UI::Core::CoreWindow^ sender,
00088         _In_ Windows::UI::Core::CoreWindowEventArgs^ args
00089         );
00090
00091     MarbleMaze^ m_renderer;
00092     bool m_windowClosed;
00093     bool m_windowVisible;
00094 };
00095
00096 ref class DirectXAppSource : Windows::ApplicationModel::Core::IFrameworkViewSource
00097 {
00098 public:
00099     virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00100 };
Generated on Sat Nov 23 2024 16:08:07 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D magazine app/C++/pch.cpp Source File

  • Direct2D magazine app

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::Common::LayoutAwarePage Member List

This is the complete list of members for SDKSample::Common::LayoutAwarePage, including all inherited members.
__pad0__ | SDKSample::Common::LayoutAwarePage |
_acceleratorKeyEventToken | SDKSample::Common::LayoutAwarePage | [private]
_defaultViewModel | SDKSample::Common::LayoutAwarePage | [private]
_layoutAwareControls | SDKSample::Common::LayoutAwarePage | [private]
_navigationShortcutsRegistered | SDKSample::Common::LayoutAwarePage | [private]
_pageKey | SDKSample::Common::LayoutAwarePage | [private]
_pointerPressedEventToken | SDKSample::Common::LayoutAwarePage | [private]
_this | SDKSample::Common::LayoutAwarePage | [private]
_windowSizeEventToken | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^sender, Windows::UI::Core::AcceleratorKeyEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | SDKSample::Common::LayoutAwarePage | [private]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoBack(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
GoForward(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [virtual]
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
InvalidateVisualState() | SDKSample::Common::LayoutAwarePage |
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
LoadState(Platform::Object^navigationParameter, Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnLoaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Common::LayoutAwarePage | [virtual]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
OnUnloaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^pageState) | SDKSample::Common::LayoutAwarePage | [virtual]
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Common::LayoutAwarePage |
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
WindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::Common::LayoutAwarePage | [private]
Generated on Sat Nov 23 2024 16:09:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/TargetTexture.h Source File

  • XAML DirectX 3D shooting game

TargetTexture.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 // TargetTexture:
00011 // This is a helper class to procedurally generate textures for game
00012 // targets.  There are two versions of the textures, one when it is
00013 // hit and the other is when it is not.
00014 // The class creates the necessary resources to draw the texture into
00015 // an off screen resource at initialization time.
00016
00017 ref class TargetTexture
00018 {
00019 internal:
00020     TargetTexture(
00021         _In_ ID3D11Device1*      d3dDevice,
00022         _In_ ID2D1Factory1*      d2dFactory,
00023         _In_ IDWriteFactory1*    dwriteFactory,
00024         _In_ ID2D1DeviceContext* d2dContext
00025         );
00026
00027     void CreateTextureResourceView(
00028         _In_ Platform::String^ name,
00029         _Out_ ID3D11ShaderResourceView** textureResourceView
00030         );
00031     void CreateHitTextureResourceView(
00032         _In_ Platform::String^ name,
00033         _Out_ ID3D11ShaderResourceView** textureResourceView
00034         );
00035
00036 protected private:
00037     Microsoft::WRL::ComPtr<ID3D11Device1>           m_d3dDevice;
00038     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00039     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00040     Microsoft::WRL::ComPtr<IDWriteFactory1>         m_dwriteFactory;
00041
00042     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_redBrush;
00043     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_blueBrush;
00044     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_greenBrush;
00045     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_whiteBrush;
00046     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_blackBrush;
00047     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_yellowBrush;
00048     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_clearBrush;
00049
00050     Microsoft::WRL::ComPtr<ID2D1EllipseGeometry>    m_circleGeometry1;
00051     Microsoft::WRL::ComPtr<ID2D1EllipseGeometry>    m_circleGeometry2;
00052     Microsoft::WRL::ComPtr<ID2D1EllipseGeometry>    m_circleGeometry3;
00053     Microsoft::WRL::ComPtr<ID2D1EllipseGeometry>    m_circleGeometry4;
00054     Microsoft::WRL::ComPtr<ID2D1EllipseGeometry>    m_circleGeometry5;
00055
00056     Microsoft::WRL::ComPtr<IDWriteTextFormat>       m_textFormat;
00057 };
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/MoveLookController.cpp Source File

  • DirectX 3D shooting game

MoveLookController.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 "MoveLookController.h"
00010 #include "DirectXSample.h"
00011
00012 using namespace Windows::UI::Core;
00013 using namespace Windows::UI::Input;
00014 using namespace Windows::UI;
00015 using namespace Windows::Foundation;
00016 using namespace Microsoft::WRL;
00017 using namespace DirectX;
00018 using namespace Windows::Devices::Input;
00019 using namespace Windows::System;
00020
00021 #define ROTATION_GAIN 0.008f        // Sensitivity adjustment for look controller.
00022 #define MOVEMENT_GAIN 2.f           // Sensitivity adjustment for move controller.
00023
00024 //----------------------------------------------------------------------
00025
00026 MoveLookController::MoveLookController():
00027     m_autoFire(true),
00028     m_isControllerConnected(false)
00029 {
00030 }
00031
00032 //----------------------------------------------------------------------
00033 // Set up the Controls supported by this controller.
00034
00035 void MoveLookController::Initialize(
00036     _In_ CoreWindow^ window
00037     )
00038 {
00039     window->PointerPressed +=
00040         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &MoveLookController::OnPointerPressed);
00041
00042     window->PointerMoved +=
00043         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &MoveLookController::OnPointerMoved);
00044
00045     window->PointerReleased +=
00046         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &MoveLookController::OnPointerReleased);
00047
00048     window->PointerExited +=
00049         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &MoveLookController::OnPointerExited);
00050
00051     window->KeyDown +=
00052         ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &MoveLookController::OnKeyDown);
00053
00054     window->KeyUp +=
00055         ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &MoveLookController::OnKeyUp);
00056
00057     // There is a separate handler for mouse only relative mouse movement events.
00058     MouseDevice::GetForCurrentView()->MouseMoved +=
00059         ref new TypedEventHandler<MouseDevice^, MouseEventArgs^>(this, &MoveLookController::OnMouseMoved);
00060
00061     ResetState();
00062     m_state = MoveLookControllerState::None;
00063
00064     m_pitch = 0.0f;
00065     m_yaw   = 0.0f;
00066 }
00067
00068 //----------------------------------------------------------------------
00069
00070 bool MoveLookController::IsPauseRequested()
00071 {
00072     switch (m_state)
00073     {
00074     case MoveLookControllerState::Active:
00075         UpdateGameController();
00076         if (m_pausePressed)
00077         {
00078 #ifdef MOVELOOKCONTROLLER_TRACE
00079             DebugTrace(L"IsPauseRequested == true\n");
00080 #endif
00081             m_pausePressed = false;
00082             return true;
00083         }
00084         else
00085         {
00086             return false;
00087         }
00088     }
00089     return false;
00090 }
00091
00092 //----------------------------------------------------------------------
00093
00094 bool MoveLookController::IsFiring()
00095 {
00096     if (m_state == MoveLookControllerState::Active)
00097     {
00098         if (m_autoFire)
00099         {
00100             return (m_fireInUse || (m_mouseInUse && m_mouseLeftInUse) || m_xinputTriggerInUse);
00101         }
00102         else
00103         {
00104             if (m_firePressed)
00105             {
00106                 m_firePressed = false;
00107                 return true;
00108             }
00109         }
00110     }
00111     return false;
00112 }
00113
00114 //----------------------------------------------------------------------
00115
00116 bool MoveLookController::IsPressComplete()
00117 {
00118     switch (m_state)
00119     {
00120     case MoveLookControllerState::WaitForInput:
00121         UpdateGameController();
00122         if (m_buttonPressed)
00123         {
00124 #ifdef MOVELOOKCONTROLLER_TRACE
00125             DebugTrace(L"IsPressComplete == true\n");
00126 #endif
00127             m_buttonPressed = false;
00128             return true;
00129         }
00130         else
00131         {
00132             return false;
00133         }
00134         break;
00135     }
00136
00137     return false;
00138 }
00139
00140 //----------------------------------------------------------------------
00141
00142 void MoveLookController::OnPointerPressed(
00143     _In_ CoreWindow^ /* sender */,
00144     _In_ PointerEventArgs^ args
00145     )
00146 {
00147     PointerPoint^ point = args->CurrentPoint;
00148     uint32 pointerID = point->PointerId;
00149     Point pointerPosition = point->Position;
00150     PointerPointProperties^ pointProperties = point->Properties;
00151     auto pointerDevice = point->PointerDevice;
00152     auto pointerDeviceType = pointerDevice->PointerDeviceType;
00153
00154     XMFLOAT2 position = XMFLOAT2(pointerPosition.X, pointerPosition.Y);
00155
00156 #ifdef MOVELOOKCONTROLLER_TRACE
00157     DebugTrace(L"%-7s (%d) at (%4.0f, %4.0f)", L"Pressed", pointerID, position.x, position.y);
00158 #endif
00159
00160     switch (m_state)
00161     {
00162     case MoveLookControllerState::WaitForInput:
00163         if (position.x > m_buttonUpperLeft.x &&
00164             position.x < m_buttonLowerRight.x &&
00165             position.y > m_buttonUpperLeft.y &&
00166             position.y < m_buttonLowerRight.y)
00167         {
00168             // Wait until button released before setting variable.
00169             m_buttonPointerID = pointerID;
00170             m_buttonInUse = true;
00171 #ifdef MOVELOOKCONTROLLER_TRACE
00172             DebugTrace(L"\tWaitForInput(%d) - BUTTON in USE", pointerID);
00173 #endif
00174         }
00175         break;
00176
00177     case MoveLookControllerState::Active:
00178         switch (pointerDeviceType)
00179         {
00180         case Windows::Devices::Input::PointerDeviceType::Touch:
00181             if (position.x > m_moveUpperLeft.x &&
00182                 position.x < m_moveLowerRight.x &&
00183                 position.y > m_moveUpperLeft.y &&
00184                 position.y < m_moveLowerRight.y)
00185             {
00186                 // This pointer is in the move control.
00187                 if (!m_moveInUse)
00188                 {
00189                     // There is not an active pointer in this control yet.
00190                     // Process a DPad touch down event.
00191                     m_moveFirstDown = position;                 // Save location of initial contact.
00192                     m_movePointerID = pointerID;                // Store the pointer using this control.
00193                     m_moveInUse = true;
00194                 }
00195             }
00196             else if (position.x > m_fireUpperLeft.x &&
00197                 position.x < m_fireLowerRight.x &&
00198                 position.y > m_fireUpperLeft.y &&
00199                 position.y < m_fireLowerRight.y)
00200             {
00201                 // This pointer is in the fire control.
00202                 if (!m_fireInUse)
00203                 {
00204                     m_fireLastPoint = position;
00205                     m_firePointerID = pointerID;
00206                     m_fireInUse = true;
00207                     if (!m_autoFire)
00208                     {
00209                         m_firePressed = true;
00210                     }
00211                 }
00212             }
00213             else
00214             {
00215                 if (!m_lookInUse)
00216                 {
00217                     // There is not an active pointer in this control yet.
00218                     m_lookLastPoint = position;                   // Save point for later move.
00219                     m_lookPointerID = pointerID;                  // Store the pointer using this control.
00220                     m_lookLastDelta.x = m_lookLastDelta.y = 0;    // These are for smoothing.
00221                     m_lookInUse = true;
00222                 }
00223             }
00224             break;
00225
00226         default:
00227             bool rightButton = pointProperties->IsRightButtonPressed;
00228             bool leftButton = pointProperties->IsLeftButtonPressed;
00229
00230             if (!m_autoFire && (!m_mouseLeftInUse && leftButton))
00231             {
00232                 m_firePressed = true;
00233             }
00234
00235             if (!m_mouseInUse)
00236             {
00237                 m_mouseInUse = true;
00238                 m_mouseLastPoint = position;
00239                 m_mousePointerID = pointerID;
00240                 m_mouseLeftInUse = leftButton;
00241                 m_mouseRightInUse = rightButton;
00242                 m_lookLastDelta.x = m_lookLastDelta.y = 0;          // These are for smoothing.
00243             }
00244             else
00245             {
00246 #ifdef MOVELOOKCONTROLLER_TRACE
00247                 DebugTrace(L"\tWARNING: OnPointerPressed()  Mouse aleady in use (%d-%s%s) and new event id: %d %s%s",
00248                     m_mousePointerID,
00249                     m_mouseLeftInUse ? "L" : "",
00250                     m_mouseRightInUse ? "R" : "",
00251                     pointerID,
00252                     leftButton ? "L" : "",
00253                     rightButton ? "R" : ""
00254                     );
00255 #endif
00256             }
00257             break;
00258         }
00259 #ifdef MOVELOOKCONTROLLER_TRACE
00260         DebugTrace(
00261             L"\t%s%s%s %s%s%s",
00262             m_moveInUse ? L"Move " : L"",
00263             m_lookInUse ? L"Look " : L"",
00264             m_fireInUse ? L"Fire " : L"",
00265             m_mouseInUse ? L"Mouse:" : L"",
00266             m_mouseLeftInUse ? L"L" : L"-",
00267             m_mouseRightInUse ? L"R" : L"-"
00268             );
00269 #endif
00270         break;
00271     }
00272 #ifdef MOVELOOKCONTROLLER_TRACE
00273     DebugTrace(L"\n");
00274 #endif
00275     return;
00276 }
00277
00278 //----------------------------------------------------------------------
00279
00280 void MoveLookController::OnPointerMoved(
00281     _In_ CoreWindow^ /* sender */,
00282     _In_ PointerEventArgs^ args
00283     )
00284 {
00285     PointerPoint^ point = args->CurrentPoint;
00286     uint32 pointerID = point->PointerId;
00287     Point pointerPosition = point->Position;
00288     PointerPointProperties^ pointProperties = point->Properties;
00289     auto pointerDevice = point->PointerDevice;
00290
00291     XMFLOAT2 position = XMFLOAT2(pointerPosition.X, pointerPosition.Y);     // convert to allow math
00292
00293 #ifdef MOVELOOKCONTROLLER_TRACE
00294     DebugTrace(L"%-7s (%d) at (%4.0f, %4.0f)", L"Moved", pointerID, position.x, position.y);
00295 #endif
00296
00297     switch (m_state)
00298     {
00299     case MoveLookControllerState::Active:
00300         // Decide which control this pointer is operating.
00301         if (pointerID == m_movePointerID)
00302         {
00303             m_movePointerPosition = position;       // Save the current position.
00304         }
00305         else if (pointerID == m_lookPointerID)
00306         {
00307             // Look control.
00308             XMFLOAT2 pointerDelta;
00309             pointerDelta.x = position.x - m_lookLastPoint.x;        // How far did pointer move?
00310             pointerDelta.y = position.y - m_lookLastPoint.y;
00311
00312             XMFLOAT2 rotationDelta;
00313             rotationDelta.x = pointerDelta.x * ROTATION_GAIN;       // Scale for control sensitivity.
00314             rotationDelta.y = pointerDelta.y * ROTATION_GAIN;
00315             m_lookLastPoint = position;                             // Save for next time through.
00316
00317 #ifdef MOVELOOKCONTROLLER_TRACE
00318             DebugTrace(L"\tDelta (%4.0f, %4.0f)", pointerDelta.x, pointerDelta.y);
00319 #endif
00320
00321             // Update our orientation based on the command.
00322             m_pitch -= rotationDelta.y;
00323             m_yaw   += rotationDelta.x;
00324
00325             // Limit pitch to straight up or straight down.
00326             float limit = XM_PI / 2.0f - 0.01f;
00327             m_pitch = __max(-limit, m_pitch);
00328             m_pitch = __min(+limit, m_pitch);
00329
00330             // Keep longitude in sane range by wrapping.
00331             if (m_yaw >  XM_PI)
00332             {
00333                 m_yaw -= XM_PI * 2.0f;
00334             }
00335             else if (m_yaw < -XM_PI)
00336             {
00337                 m_yaw += XM_PI * 2.0f;
00338             }
00339         }
00340         else if (pointerID == m_firePointerID)
00341         {
00342             m_fireLastPoint = position;
00343         }
00344         else if (pointerID == m_mousePointerID)
00345         {
00346             m_mouseLeftInUse  = pointProperties->IsLeftButtonPressed;
00347             m_mouseRightInUse = pointProperties->IsRightButtonPressed;
00348             m_mouseLastPoint = position;                            // Save for next time through.
00349         }
00350
00351         // Mouse movement is handled via a separate relative mouse movement handler (OnMouseMoved).
00352
00353         break;
00354     }
00355 #ifdef MOVELOOKCONTROLLER_TRACE
00356     DebugTrace(L"\n");
00357 #endif
00358 }
00359
00360 //----------------------------------------------------------------------
00361
00362 void MoveLookController::OnMouseMoved(
00363     _In_ MouseDevice^ /* mouseDevice */,
00364     _In_ MouseEventArgs^ args
00365     )
00366 {
00367     // Handle Mouse Input via dedicated relative movement handler.
00368
00369     switch (m_state)
00370     {
00371     case MoveLookControllerState::Active:
00372         XMFLOAT2 mouseDelta;
00373         mouseDelta.x = static_cast<float>(args->MouseDelta.X);
00374         mouseDelta.y = static_cast<float>(args->MouseDelta.Y);
00375
00376         XMFLOAT2 rotationDelta;
00377         rotationDelta.x  = mouseDelta.x * ROTATION_GAIN;   // Scale for control sensitivity.
00378         rotationDelta.y  = mouseDelta.y * ROTATION_GAIN;
00379
00380         // Update our orientation based on the command.
00381         m_pitch -= rotationDelta.y;
00382         m_yaw   += rotationDelta.x;
00383
00384         // Limit pitch to straight up or straight down.
00385         float limit = XM_PI / 2.0f - 0.01f;
00386         m_pitch = __max(-limit, m_pitch);
00387         m_pitch = __min(+limit, m_pitch);
00388
00389         // Keep longitude in sane range by wrapping.
00390         if (m_yaw >  XM_PI)
00391         {
00392             m_yaw -= XM_PI * 2.0f;
00393         }
00394         else if (m_yaw < -XM_PI)
00395         {
00396             m_yaw += XM_PI * 2.0f;
00397         }
00398         break;
00399     }
00400 }
00401
00402 //----------------------------------------------------------------------
00403
00404 void MoveLookController::OnPointerReleased(
00405     _In_ CoreWindow^ /* sender */,
00406     _In_ PointerEventArgs^ args
00407     )
00408 {
00409     PointerPoint^ point = args->CurrentPoint;
00410     uint32 pointerID = point->PointerId;
00411     Point pointerPosition = point->Position;
00412     PointerPointProperties^ pointProperties = point->Properties;
00413
00414     XMFLOAT2 position = XMFLOAT2(pointerPosition.X, pointerPosition.Y);
00415
00416 #ifdef MOVELOOKCONTROLLER_TRACE
00417     DebugTrace(L"%-7s (%d) at (%4.0f, %4.0f)\n", L"Release", pointerID, position.x, position.y);
00418 #endif
00419
00420     switch (m_state)
00421     {
00422     case MoveLookControllerState::WaitForInput:
00423         if (m_buttonInUse && (pointerID == m_buttonPointerID))
00424         {
00425             m_buttonInUse = false;
00426             m_buttonPressed = true;
00427 #ifdef MOVELOOKCONTROLLER_TRACE
00428             DebugTrace(L"\tWaitForInput: ButtonPressed = true\n");
00429 #endif
00430         }
00431         break;
00432
00433     case MoveLookControllerState::Active:
00434         if (pointerID == m_movePointerID)
00435         {
00436             m_velocity = XMFLOAT3(0, 0, 0);      // Stop on release.
00437             m_moveInUse = false;
00438             m_movePointerID = 0;
00439         }
00440         else if (pointerID == m_lookPointerID)
00441         {
00442             m_lookInUse = false;
00443             m_lookPointerID = 0;
00444         }
00445         else if (pointerID == m_firePointerID)
00446         {
00447             m_fireInUse = false;
00448             m_firePointerID = 0;
00449         }
00450         else if (pointerID == m_mousePointerID)
00451         {
00452             bool rightButton = pointProperties->IsRightButtonPressed;
00453             bool leftButton = pointProperties->IsLeftButtonPressed;
00454
00455             m_mouseInUse = false;
00456
00457             // Don't clear the mouse Pointer ID so that Move events still result in Look changes.
00458             m_mouseLeftInUse = leftButton;
00459             m_mouseRightInUse = rightButton;
00460         }
00461         break;
00462     }
00463 }
00464
00465 //----------------------------------------------------------------------
00466
00467 void MoveLookController::OnPointerExited(
00468     _In_ CoreWindow^ /* sender */,
00469     _In_ PointerEventArgs^ args
00470     )
00471 {
00472     PointerPoint^ point = args->CurrentPoint;
00473     uint32 pointerID = point->PointerId;
00474     Point pointerPosition = point->Position;
00475     PointerPointProperties^ pointProperties = point->Properties;
00476
00477     XMFLOAT2 position  = XMFLOAT2(pointerPosition.X, pointerPosition.Y);
00478
00479 #ifdef MOVELOOKCONTROLLER_TRACE
00480     DebugTrace(L"%-7s (%d) at (%4.0f, %4.0f)\n", L"Exit", pointerID, position.x, position.y);
00481 #endif
00482
00483     switch (m_state)
00484     {
00485     case MoveLookControllerState::WaitForInput:
00486         if (m_buttonInUse && (pointerID == m_buttonPointerID))
00487         {
00488             m_buttonInUse = false;
00489             m_buttonPressed = false;
00490 #ifdef MOVELOOKCONTROLLER_TRACE
00491             DebugTrace(L"\tWaitForPress: ButtonPressed = false -- Got Exit Event\n");
00492 #endif
00493         }
00494         break;
00495
00496     case MoveLookControllerState::Active:
00497         if (pointerID == m_movePointerID)
00498         {
00499             m_velocity = XMFLOAT3(0, 0, 0);      // Stop on release.
00500             m_moveInUse = false;
00501             m_movePointerID = 0;
00502         }
00503         else if (pointerID == m_lookPointerID)
00504         {
00505             m_lookInUse = false;
00506             m_lookPointerID = 0;
00507         }
00508         else if (pointerID == m_firePointerID)
00509         {
00510             m_fireInUse = false;
00511             m_firePointerID = 0;
00512         }
00513         else if (pointerID == m_mousePointerID)
00514         {
00515             m_mouseInUse = false;
00516             m_mousePointerID = 0;
00517             m_mouseLeftInUse = false;
00518             m_mouseRightInUse = false;
00519         }
00520         break;
00521     }
00522 }
00523
00524 //----------------------------------------------------------------------
00525
00526 void MoveLookController::OnKeyDown(
00527     _In_ CoreWindow^ /* sender */,
00528     _In_ KeyEventArgs^ args
00529     )
00530 {
00531     Windows::System::VirtualKey Key;
00532     Key = args->VirtualKey;
00533
00534     // Figure out the command from the keyboard.
00535     if (Key == VirtualKey::W)
00536         m_forward = true;
00537     if (Key == VirtualKey::S)
00538         m_back = true;
00539     if (Key == VirtualKey::A)
00540         m_left = true;
00541     if (Key == VirtualKey::D)
00542         m_right = true;
00543     if (Key == VirtualKey::Space)
00544         m_up = true;
00545     if (Key == VirtualKey::X)
00546         m_down = true;
00547     if (Key == VirtualKey::P)
00548         m_pause = true;
00549 }
00550
00551 //----------------------------------------------------------------------
00552
00553 void MoveLookController::OnKeyUp(
00554     _In_ CoreWindow^ /* sender */,
00555     _In_ KeyEventArgs^ args
00556     )
00557 {
00558     Windows::System::VirtualKey Key;
00559     Key = args->VirtualKey;
00560
00561     // Figure out the command from the keyboard.
00562     if (Key == VirtualKey::W)
00563         m_forward = false;
00564     if (Key == VirtualKey::S)
00565         m_back = false;
00566     if (Key == VirtualKey::A)
00567         m_left = false;
00568     if (Key == VirtualKey::D)
00569         m_right = false;
00570     if (Key == VirtualKey::Space)
00571         m_up = false;
00572     if (Key == VirtualKey::X)
00573         m_down = false;
00574     if (Key == VirtualKey::P)
00575     {
00576         if (m_pause)
00577         {
00578             // Trigger pause only once on button release.
00579             m_pausePressed = true;
00580             m_pause = false;
00581         }
00582     }
00583 }
00584
00585 //----------------------------------------------------------------------
00586
00587 void MoveLookController::ResetState()
00588 {
00589     // Reset the state of the controller.
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
00606     m_xinputStartButtonInUse = false;
00607     m_xinputTriggerInUse = false;
00608
00609     m_moveCommand = XMFLOAT3(0.0f, 0.0f, 0.0f);
00610     m_forward = false;
00611     m_back = false;
00612     m_left = false;
00613     m_right = false;
00614     m_up = false;
00615     m_down = false;
00616     m_pause = false;
00617 }
00618
00619 //----------------------------------------------------------------------
00620
00621 void MoveLookController::SetMoveRect (
00622     _In_ XMFLOAT2 upperLeft,
00623     _In_ XMFLOAT2 lowerRight
00624     )
00625 {
00626 #ifdef MOVELOOKCONTROLLER_TRACE
00627     DebugTrace(L"MoveRect (%d, %d) to (%d, %d)", upperLeft.x, upperLeft.y, lowerRight.x, lowerRight.y);
00628 #endif
00629     m_moveUpperLeft  = upperLeft;
00630     m_moveLowerRight = lowerRight;
00631 }
00632
00633 //----------------------------------------------------------------------
00634
00635 void MoveLookController::SetFireRect (
00636     _In_ XMFLOAT2 upperLeft,
00637     _In_ XMFLOAT2 lowerRight
00638     )
00639 {
00640 #ifdef MOVELOOKCONTROLLER_TRACE
00641     DebugTrace(L"FireRect (%d, %d) to (%d, %d)", upperLeft.x, upperLeft.y, lowerRight.x, lowerRight.y);
00642 #endif
00643     m_fireUpperLeft  = upperLeft;
00644     m_fireLowerRight = lowerRight;
00645 }
00646
00647 //----------------------------------------------------------------------
00648
00649 void MoveLookController::WaitForPress(
00650     _In_ XMFLOAT2 upperLeft,
00651     _In_ XMFLOAT2 lowerRight
00652     )
00653 {
00654 #ifdef MOVELOOKCONTROLLER_TRACE
00655     DebugTrace(L"WaitForPress (%.1f, %.1f) to (%.1f, %.1f)\n", upperLeft.x, upperLeft.y, lowerRight.x, lowerRight.y);
00656 #endif
00657
00658     ResetState();
00659     m_state = MoveLookControllerState::WaitForInput;
00660     m_buttonUpperLeft  = upperLeft;
00661     m_buttonLowerRight = lowerRight;
00662
00663     // Turn on mouse cursor.
00664     CoreWindow::GetForCurrentThread()->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
00665 }
00666
00667 //----------------------------------------------------------------------
00668
00669 void MoveLookController::WaitForPress()
00670 {
00671 #ifdef MOVELOOKCONTROLLER_TRACE
00672     DebugTrace(L"WaitForPress (null rect)\n");
00673 #endif
00674
00675     ResetState();
00676     m_state = MoveLookControllerState::WaitForInput;
00677     m_buttonUpperLeft.x = 0.0f;
00678     m_buttonUpperLeft.y = 0.0f;
00679     m_buttonLowerRight.x = 0.0f;
00680     m_buttonLowerRight.y = 0.0f;
00681
00682     // Turn on mouse cursor.
00683     CoreWindow::GetForCurrentThread()->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
00684 }
00685
00686 //----------------------------------------------------------------------
00687
00688 XMFLOAT3 MoveLookController::Velocity()
00689 {
00690     return m_velocity;
00691 }
00692
00693 //----------------------------------------------------------------------
00694
00695 XMFLOAT3 MoveLookController::LookDirection()
00696 {
00697     XMFLOAT3 lookDirection;
00698
00699     float r = cosf(m_pitch);              // In the plane.
00700     lookDirection.y = sinf(m_pitch);      // Vertical.
00701     lookDirection.z = r * cosf(m_yaw);    // Fwd-back.
00702     lookDirection.x = r * sinf(m_yaw);    // Left-right.
00703
00704     return lookDirection;
00705 }
00706
00707 //----------------------------------------------------------------------
00708
00709 float MoveLookController::Pitch()
00710 {
00711     return m_pitch;
00712 }
00713
00714 //----------------------------------------------------------------------
00715
00716 void MoveLookController::Pitch(_In_ float pitch)
00717 {
00718     m_pitch = pitch;
00719 }
00720
00721 //----------------------------------------------------------------------
00722
00723 float MoveLookController::Yaw()
00724 {
00725     return m_yaw;
00726 }
00727
00728 //----------------------------------------------------------------------
00729
00730 void MoveLookController::Yaw(_In_ float yaw)
00731 {
00732     m_yaw = yaw;
00733 }
00734
00735 //----------------------------------------------------------------------
00736
00737 void MoveLookController::Active(_In_ bool active)
00738 {
00739     ResetState();
00740 #ifdef MOVELOOKCONTROLLER_TRACE
00741     DebugTrace(L"Active = %s\n", active ? L"true" : L"false");
00742 #endif
00743
00744     if (active)
00745     {
00746         m_state = MoveLookControllerState::Active;
00747         // Turn mouse cursor off (hidden).
00748         CoreWindow::GetForCurrentThread()->PointerCursor = nullptr;
00749     }
00750     else
00751     {
00752         m_state = MoveLookControllerState::None;
00753         // Turn mouse cursor on.
00754         auto window = CoreWindow::GetForCurrentThread();
00755         if (window)
00756         {
00757             // Protect case where there isn't a window associated with the current thread.
00758             // This happens on initialization.
00759             window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
00760         }
00761     }
00762 }
00763
00764 //----------------------------------------------------------------------
00765
00766 bool MoveLookController::Active()
00767 {
00768     if (m_state == MoveLookControllerState::Active)
00769     {
00770         return true;
00771     }
00772     else
00773     {
00774         return false;
00775     }
00776 }
00777
00778 //----------------------------------------------------------------------
00779
00780 void MoveLookController::AutoFire(_In_ bool autoFire)
00781 {
00782     m_autoFire = autoFire;
00783 }
00784
00785 //----------------------------------------------------------------------
00786
00787 bool MoveLookController::AutoFire()
00788 {
00789     return m_autoFire;
00790 }
00791
00792 //----------------------------------------------------------------------
00793
00794 void MoveLookController::Update()
00795 {
00796     UpdateGameController();
00797
00798     if (m_moveInUse)
00799     {
00800         // Move control.
00801         XMFLOAT2 pointerDelta;
00802
00803         pointerDelta.x = m_movePointerPosition.x - m_moveFirstDown.x;
00804         pointerDelta.y = m_movePointerPosition.y - m_moveFirstDown.y;
00805
00806         // Figure out the command from the virtual joystick.
00807         XMFLOAT3 commandDirection = XMFLOAT3(0.0f, 0.0f, 0.0f);
00808         if (fabsf(pointerDelta.x) > 16.0f)         // Leave 32 pixel-wide dead spot for being still.
00809             m_moveCommand.x -= pointerDelta.x/fabsf(pointerDelta.x);
00810
00811         if (fabsf(pointerDelta.y) > 16.0f)
00812             m_moveCommand.y -= pointerDelta.y/fabsf(pointerDelta.y);
00813     }
00814
00815     // Poll our state bits set by the keyboard input events.
00816     if (m_forward)
00817     {
00818         m_moveCommand.y += 1.0f;
00819     }
00820     if (m_back)
00821     {
00822         m_moveCommand.y -= 1.0f;
00823     }
00824     if (m_left)
00825     {
00826         m_moveCommand.x += 1.0f;
00827     }
00828     if (m_right)
00829     {
00830         m_moveCommand.x -= 1.0f;
00831     }
00832     if (m_up)
00833     {
00834         m_moveCommand.z += 1.0f;
00835     }
00836     if (m_down)
00837     {
00838         m_moveCommand.z -= 1.0f;
00839     }
00840
00841     // Make sure that 45deg cases are not faster.
00842     if (fabsf(m_moveCommand.x) > 0.1f ||
00843         fabsf(m_moveCommand.y) > 0.1f ||
00844         fabsf(m_moveCommand.z) > 0.1f)
00845     {
00846         XMStoreFloat3(&m_moveCommand, XMVector3Normalize(XMLoadFloat3(&m_moveCommand)));
00847     }
00848
00849     // Rotate command to align with our direction (world coordinates).
00850     XMFLOAT3 wCommand;
00851     wCommand.x =  m_moveCommand.x * cosf(m_yaw) - m_moveCommand.y * sinf(m_yaw);
00852     wCommand.y =  m_moveCommand.x * sinf(m_yaw) + m_moveCommand.y * cosf(m_yaw);
00853     wCommand.z =  m_moveCommand.z;
00854
00855     // Scale for sensitivity adjustment.
00856     // Our velocity is based on the command. Y is up.
00857     m_velocity.x = -wCommand.x * MOVEMENT_GAIN;
00858     m_velocity.z =  wCommand.y * MOVEMENT_GAIN;
00859     m_velocity.y =  wCommand.z * MOVEMENT_GAIN;
00860
00861     // Clear movement input accumulator for use during next frame.
00862     m_moveCommand = XMFLOAT3(0.0f, 0.0f, 0.0f);
00863 }
00864
00865 //----------------------------------------------------------------------
00866
00867 void MoveLookController::UpdateGameController()
00868 {
00869     if (!m_isControllerConnected)
00870     {
00871         // Check for controller connection by trying to get the capabilties.
00872         DWORD capsResult = XInputGetCapabilities(0, XINPUT_FLAG_GAMEPAD, &m_xinputCaps);
00873         if (capsResult != ERROR_SUCCESS)
00874         {
00875             return;
00876         }
00877         // Device is connected.
00878         m_isControllerConnected = true;
00879         m_xinputStartButtonInUse = false;
00880         m_xinputTriggerInUse = false;
00881     }
00882
00883     DWORD stateResult = XInputGetState(0, &m_xinputState);
00884     if (stateResult != ERROR_SUCCESS)
00885     {
00886         // Device is no longer connected.
00887         m_isControllerConnected = false;
00888     }
00889
00890     switch (m_state)
00891     {
00892     case MoveLookControllerState::WaitForInput:
00893         if (m_xinputState.Gamepad.wButtons & XINPUT_GAMEPAD_START)
00894         {
00895             m_xinputStartButtonInUse = true;
00896         }
00897         else if (m_xinputStartButtonInUse)
00898         {
00899             // Trigger once only on button release.
00900             m_xinputStartButtonInUse = false;
00901             m_buttonPressed = true;
00902         }
00903         break;
00904
00905     case MoveLookControllerState::Active:
00906         if (m_xinputState.Gamepad.wButtons & XINPUT_GAMEPAD_START)
00907         {
00908             m_xinputStartButtonInUse = true;
00909         }
00910         else if (m_xinputStartButtonInUse)
00911         {
00912             // Trigger once only on button release.
00913             m_xinputStartButtonInUse = false;
00914             m_pausePressed = true;
00915         }
00916         // Use the Left Thumb joystick on the Xbox controller to control
00917         // the eye point position control.
00918         // The controller input goes from -32767 to 32767.  We will normalize
00919         // this from -1 to 1 and keep a dead spot in the middle to avoid drift.
00920
00921         if (m_xinputState.Gamepad.sThumbLX > XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE ||
00922             m_xinputState.Gamepad.sThumbLX < -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE)
00923         {
00924             float x = (float)m_xinputState.Gamepad.sThumbLX/32767.0f;
00925             m_moveCommand.x -= x / fabsf(x);
00926         }
00927
00928         if (m_xinputState.Gamepad.sThumbLY > XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE ||
00929             m_xinputState.Gamepad.sThumbLY < -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE)
00930         {
00931             float y = (float)m_xinputState.Gamepad.sThumbLY/32767.0f;
00932             m_moveCommand.y += y / fabsf(y);
00933         }
00934
00935         // Use the Right Thumb Joystick on the Xbox controller to control
00936         // the look at control.
00937         // The controller input goes from -32767 to 32767.  We will normalize
00938         // this from -1 to 1 and keep a dead spot in the middle to avoid drift.
00939         XMFLOAT2 pointerDelta;
00940         if (m_xinputState.Gamepad.sThumbRX > XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE ||
00941             m_xinputState.Gamepad.sThumbRX < -XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE)
00942         {
00943             pointerDelta.x = (float)m_xinputState.Gamepad.sThumbRX/32767.0f;
00944             pointerDelta.x = pointerDelta.x * pointerDelta.x * pointerDelta.x;
00945         }
00946         else
00947         {
00948             pointerDelta.x = 0.0f;
00949         }
00950         if (m_xinputState.Gamepad.sThumbRY > XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE ||
00951             m_xinputState.Gamepad.sThumbRY < -XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE)
00952         {
00953             pointerDelta.y = (float)m_xinputState.Gamepad.sThumbRY/32767.0f;
00954             pointerDelta.y = pointerDelta.y * pointerDelta.y * pointerDelta.y;
00955         }
00956         else
00957         {
00958             pointerDelta.y = 0.0f;
00959         }
00960
00961         XMFLOAT2 rotationDelta;
00962         rotationDelta.x = pointerDelta.x *  0.08f;       // Scale for control sensitivity.
00963         rotationDelta.y = pointerDelta.y *  0.08f;
00964
00965         // Update our orientation based on the command.
00966         m_pitch += rotationDelta.y;
00967         m_yaw   += rotationDelta.x;
00968
00969         // Limit pitch to straight up or straight down.
00970         m_pitch = __max(-XM_PI / 2.0f, m_pitch);
00971         m_pitch = __min(+XM_PI / 2.0f, m_pitch);
00972
00973         // Check the state of the Right Trigger button.  This is used to indicate fire control.
00974
00975         if (m_xinputState.Gamepad.bRightTrigger > XINPUT_GAMEPAD_TRIGGER_THRESHOLD)
00976         {
00977             if (!m_autoFire && !m_xinputTriggerInUse)
00978             {
00979                 m_firePressed = true;
00980             }
00981             m_xinputTriggerInUse = true;
00982         }
00983         else
00984         {
00985             m_xinputTriggerInUse = false;
00986         }
00987         break;
00988     }
00989 }
00990
00991 //----------------------------------------------------------------------
00992
00993 #ifdef MOVELOOKCONTROLLER_TRACE
00994 void MoveLookController::DebugTrace(const wchar_t *format, ...)
00995 {
00996     // Generate the message string.
00997     va_list args;
00998     va_start(args, format);
00999     wchar_t message[1024];
01000     vswprintf_s(message, 1024, format, args);
01001     OutputDebugStringW(message);
01002 }
01003 #endif
01004
01005 //----------------------------------------------------------------------
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: IXmlReader and IXmlWriter XML data readwrite/C++/pch.cpp Source File

  • IXmlReader and IXmlWriter XML data readwrite

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/BasicReaderWriter.cpp Source File

  • DirectX 3D shooting game

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     m_locationPath = Platform::String::Concat(m_location->Path, "\\");
00023 }
00024
00025 BasicReaderWriter::BasicReaderWriter(
00026     _In_ Windows::Storage::StorageFolder^ folder
00027     )
00028 {
00029     m_location = folder;
00030     Platform::String^ path = m_location->Path;
00031     if (path->Length() == 0)
00032     {
00033         // Applications are not permitted to access certain
00034         // folders, such as the Documents folder, using this
00035         // code path.  In such cases, the Path property for
00036         // the folder will be an empty string.
00037         throw ref new Platform::FailureException();
00038     }
00039     m_locationPath = Platform::String::Concat(path, "\\");
00040 }
00041
00042 Platform::Array<byte>^ BasicReaderWriter::ReadData(
00043     _In_ Platform::String^ filename
00044     )
00045 {
00046     CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {0};
00047     extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
00048     extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
00049     extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN;
00050     extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
00051     extendedParams.lpSecurityAttributes = nullptr;
00052     extendedParams.hTemplateFile = nullptr;
00053
00054     Wrappers::FileHandle file(
00055         CreateFile2(
00056             Platform::String::Concat(m_locationPath, filename)->Data(),
00057             GENERIC_READ,
00058             FILE_SHARE_READ,
00059             OPEN_EXISTING,
00060             &extendedParams
00061             )
00062         );
00063     if (file.Get() == INVALID_HANDLE_VALUE)
00064     {
00065         throw ref new Platform::FailureException();
00066     }
00067
00068     FILE_STANDARD_INFO fileInfo = {0};
00069     if (!GetFileInformationByHandleEx(
00070         file.Get(),
00071         FileStandardInfo,
00072         &fileInfo,
00073         sizeof(fileInfo)
00074         ))
00075     {
00076         throw ref new Platform::FailureException();
00077     }
00078
00079     if (fileInfo.EndOfFile.HighPart != 0)
00080     {
00081         throw ref new Platform::OutOfMemoryException();
00082     }
00083
00084     Platform::Array<byte>^ fileData = ref new Platform::Array<byte>(fileInfo.EndOfFile.LowPart);
00085
00086     if (!ReadFile(
00087         file.Get(),
00088         fileData->Data,
00089         fileData->Length,
00090         nullptr,
00091         nullptr
00092         ))
00093     {
00094         throw ref new Platform::FailureException();
00095     }
00096
00097     return fileData;
00098 }
00099
00100 task<Platform::Array<byte>^> BasicReaderWriter::ReadDataAsync(
00101     _In_ Platform::String^ filename
00102     )
00103 {
00104     return task<StorageFile^>(m_location->GetFileAsync(filename)).then([=](StorageFile^ file)
00105     {
00106         return FileIO::ReadBufferAsync(file);
00107     }).then([=](IBuffer^ buffer)
00108     {
00109         auto fileData = ref new Platform::Array<byte>(buffer->Length);
00110         DataReader::FromBuffer(buffer)->ReadBytes(fileData);
00111         return fileData;
00112     });
00113 }
00114
00115 uint32 BasicReaderWriter::WriteData(
00116     _In_ Platform::String^ filename,
00117     _In_ const Platform::Array<byte>^ fileData
00118     )
00119 {
00120     CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {0};
00121     extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
00122     extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
00123     extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN;
00124     extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
00125     extendedParams.lpSecurityAttributes = nullptr;
00126     extendedParams.hTemplateFile = nullptr;
00127
00128     Wrappers::FileHandle file(
00129         CreateFile2(
00130             Platform::String::Concat(m_locationPath, filename)->Data(),
00131             GENERIC_WRITE,
00132             0,
00133             CREATE_ALWAYS,
00134             &extendedParams
00135             )
00136         );
00137     if (file.Get() == INVALID_HANDLE_VALUE)
00138     {
00139         throw ref new Platform::FailureException();
00140     }
00141
00142     DWORD numBytesWritten;
00143     if (
00144         !WriteFile(
00145             file.Get(),
00146             fileData->Data,
00147             fileData->Length,
00148             &numBytesWritten,
00149             nullptr
00150             ) ||
00151         numBytesWritten != fileData->Length
00152         )
00153     {
00154         throw ref new Platform::FailureException();
00155     }
00156
00157     return numBytesWritten;
00158 }
00159
00160 task<void> BasicReaderWriter::WriteDataAsync(
00161     _In_ Platform::String^ filename,
00162     _In_ const Platform::Array<byte>^ fileData
00163     )
00164 {
00165     return task<StorageFile^>(m_location->CreateFileAsync(filename, CreationCollisionOption::ReplaceExisting)).then([=](StorageFile^ file)
00166     {
00167         FileIO::WriteBytesAsync(file, fileData);
00168     });
00169 }
Generated on Sat Nov 23 2024 16:08:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Print/C++/ScenarioInput2.xaml.h Source File

  • Print

ScenarioInput2.xaml.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 // Scenario2Input.xaml.h
00009 // Declaration of the Scenario2Input class.
00010 //
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "ScenarioInput2.g.h"
00016 #include "MainPage.xaml.h"
00017
00018 using namespace Windows::UI::Xaml;
00019 using namespace Windows::UI::Xaml::Printing;
00020
00021 namespace PrintSample
00022 {
00023     /// <summary>
00024     /// Scenario that demos how to call the Print UI on demand
00025     /// </summary>
00026     [Windows::Foundation::Metadata::WebHostHidden]
00027     public ref class ScenarioInput2 sealed
00028     {
00029     public:
00030         ScenarioInput2();
00031
00032     protected:
00033         virtual void PreparetPrintContent() override;
00034
00035     private:
00036          /// <summary>
00037         /// button click handlers
00038         /// </summary>
00039         void InvokePrintButtonClick(Object^ sender, RoutedEventArgs^ e);
00040
00041     public:
00042         virtual void OnNavigatedTo(NavigationEventArgs^ e) override;
00043         virtual void OnNavigatedFrom(NavigationEventArgs^ e) override;
00044     };
00045 }
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: StreamSocket/C++/Common/LayoutAwarePage.cpp Source File

  • StreamSocket
  • Common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013
00014 using namespace StreamSocketSample::Common;
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::UI::ViewManagement;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Interop;
00024
00025 /// <summary>
00026 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00027 /// </summary>
00028 LayoutAwarePage::LayoutAwarePage()
00029 {
00030     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled) return;
00031
00032     // Create an empty default view model
00033     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00034
00035     // Map application view state to visual state for this page when it is part of the visual tree
00036     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::StartLayoutUpdates);
00037     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::StopLayoutUpdates);
00038 }
00039
00040 static TypeName _thisType = { LayoutAwarePage::typeid->FullName, TypeKind::Custom };
00041 static TypeName _observableMapType = { IObservableMap<Platform::String^, Object^>::typeid->FullName, TypeKind::Metadata };
00042 static Windows::UI::Xaml::DependencyProperty^ _defaultViewModelProperty =
00043     DependencyProperty::Register("DefaultViewModel", _observableMapType, _thisType, nullptr);
00044
00045 /// <summary>
00046 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00047 /// </summary>
00048 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00049 {
00050     return _defaultViewModelProperty;
00051 }
00052
00053 /// <summary>
00054 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00055 /// used as a trivial view model.
00056 /// </summary>
00057 IObservableMap<Platform::String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00058 {
00059     return safe_cast<Windows::Foundation::Collections::IObservableMap<Platform::String^, Object^>^>(GetValue(DefaultViewModelProperty));
00060 }
00061
00062 /// <summary>
00063 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00064 /// used as a trivial view model.
00065 /// </summary>
00066 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<Platform::String^, Object^>^ value)
00067 {
00068     SetValue(DefaultViewModelProperty, value);
00069 }
00070
00071 /// <summary>
00072 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00073 /// until it reaches the top of the navigation stack.
00074 /// </summary>
00075 /// <param name="sender">Instance that triggered the event.</param>
00076 /// <param name="e">Event data describing the conditions that led to the event.</param>
00077 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00078 {
00079     // Use the navigation frame to return to the topmost page
00080     if (Frame != nullptr)
00081     {
00082         while (Frame->CanGoBack) Frame->GoBack();
00083     }
00084 }
00085
00086 /// <summary>
00087 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00088 /// to go back one step on the navigation stack.
00089 /// </summary>
00090 /// <param name="sender">Instance that triggered the event.</param>
00091 /// <param name="e">Event data describing the conditions that led to the event.</param>
00092 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00093 {
00094     // Use the navigation frame to return to the previous page
00095     if (Frame != nullptr && Frame->CanGoBack) Frame->GoBack();
00096 }
00097
00098 /// <summary>
00099 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00100 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00101 /// visual state management changes that correspond to application view state changes.
00102 /// </summary>
00103 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00104 /// corresponding to view states.</param>
00105 /// <param name="e">Event data that describes how the request was made.</param>
00106 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00107 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00108 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00109 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00110 /// events.</remarks>
00111 /// <seealso cref="DetermineVisualState"/>
00112 /// <seealso cref="InvalidateVisualState"/>
00113 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00114 {
00115     auto control = safe_cast<Control^>(sender);
00116     if (_layoutAwareControls == nullptr) {
00117         // Start listening to view state changes when there are controls interested in updates
00118         _layoutAwareControls = ref new Vector<Control^>();
00119         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00120     }
00121     _layoutAwareControls->Append(control);
00122
00123     // Set the initial visual state of the control
00124     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00125 }
00126
00127 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00128 {
00129     InvalidateVisualState();
00130 }
00131
00132 /// <summary>
00133 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00134 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00135 /// management changes that correspond to application view state changes.
00136 /// </summary>
00137 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00138 /// corresponding to view states.</param>
00139 /// <param name="e">Event data that describes how the request was made.</param>
00140 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00141 /// when layout updates are requested.</remarks>
00142 /// <seealso cref="StartLayoutUpdates"/>
00143 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00144 {
00145     auto control = safe_cast<Control^>(sender);
00146     unsigned int index;
00147     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00148     {
00149         _layoutAwareControls->RemoveAt(index);
00150         if (_layoutAwareControls->Size == 0)
00151         {
00152             // Stop listening to view state changes when no controls are interested in updates
00153             Window::Current->SizeChanged -= _windowSizeEventToken;
00154             _layoutAwareControls = nullptr;
00155         }
00156     }
00157 }
00158
00159 /// <summary>
00160 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00161 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00162 /// override this method to control the mapping scheme used.
00163 /// </summary>
00164 /// <param name="viewState">View state for which a visual state is desired.</param>
00165 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00166 /// <seealso cref="InvalidateVisualState"/>
00167 Platform::String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00168 {
00169     switch (viewState)
00170     {
00171     case ApplicationViewState::Filled: return "Filled";
00172     case ApplicationViewState::Snapped: return "Snapped";
00173     case ApplicationViewState::FullScreenPortrait: return "FullScreenPortrait";
00174     default: case ApplicationViewState::FullScreenLandscape: return "FullScreenLandscape";
00175     }
00176 }
00177
00178 /// <summary>
00179 /// Updates all controls that are listening for visual state changes with the correct visual
00180 /// state.
00181 /// </summary>
00182 /// <remarks>
00183 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00184 /// signal that a different value may be returned even though the view state has not changed.
00185 /// </remarks>
00186 void LayoutAwarePage::InvalidateVisualState()
00187 {
00188     if (_layoutAwareControls != nullptr)
00189     {
00190         String^ visualState = DetermineVisualState(ApplicationView::Value);
00191         auto controlIterator = _layoutAwareControls->First();
00192         while (controlIterator->HasCurrent)
00193         {
00194             auto control = controlIterator->Current;
00195             VisualStateManager::GoToState(control, visualState, false);
00196             controlIterator->MoveNext();
00197         }
00198     }
00199 }
Generated on Sat Nov 23 2024 16:07:33 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File and folder thumbnail/C++/common/suspensionmanager.cpp Source File

  • File and folder thumbnail
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:36 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File access/C++/Scenario5.xaml.h Source File

  • File access

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 SDKSample
00023 {
00024     namespace FileAccess
00025     {
00026         /// <summary>
00027         /// An empty page that can be used on its own or navigated to within a Frame.
00028         /// </summary>
00029         public ref class Scenario5 sealed
00030         {
00031         public:
00032             Scenario5();
00033
00034         private:
00035             static Windows::Globalization::DateTimeFormatting::DateTimeFormatter^ dateFormat;
00036             static Windows::Globalization::DateTimeFormatting::DateTimeFormatter^ timeFormat;
00037             static Platform::String^ dateAccessedProperty;
00038             static Platform::String^ fileOwnerProperty;
00039
00040             MainPage^ rootPage;
00041
00042             void ShowPropertiesButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00043         };
00044     }
00045 }
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Gyrometer sensor/C++/common/suspensionmanager.h Source File

  • Gyrometer sensor
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::TileContent::TileWideSmallImageAndText04 Member List

This is the complete list of members for NotificationsExtensions::TileContent::TileWideSmallImageAndText04, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
Branding | NotificationsExtensions::TileContent::TileNotificationBase |
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Image | NotificationsExtensions::TileContent::TileWideSmallImageAndText04 |
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
RequireSquareContent | NotificationsExtensions::TileContent::TileWideBase |
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SquareContent | NotificationsExtensions::TileContent::TileWideBase |
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextBodyWrap | NotificationsExtensions::TileContent::TileWideSmallImageAndText04 |
TextFields | NotificationsExtensions::NotificationBase |
TextHeading | NotificationsExtensions::TileContent::TileWideSmallImageAndText04 |
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWideSmallImageAndText04() | NotificationsExtensions::TileContent::TileWideSmallImageAndText04 | [inline]
TileWideSmallImageAndText04() | NotificationsExtensions::TileContent::TileWideSmallImageAndText04 | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:44 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Lock screen apps/C#,C++/App.xaml.cpp Source File

  • Lock screen apps
  • C#,C++

App.xaml.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 //
00009 // App.xaml.cpp
00010 // Implementation of the App.xaml class.
00011 //
00012
00013 #include "pch.h"
00014 #include "App.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace Windows::UI::Xaml;
00018 using namespace Windows::UI::Xaml::Controls;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::ApplicationModel;
00021 using namespace Windows::ApplicationModel::Activation;
00022 using namespace CppSamplesUtils;
00023 using namespace LockScreenAppsCPP;
00024 using namespace Windows::UI::Xaml::Interop;
00025
00026 App::App()
00027 {
00028     InitializeComponent();
00029     this->Suspending += ref new SuspendingEventHandler(this, &LockScreenAppsCPP::App::OnSuspending);
00030 }
00031
00032 void App::OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs)
00033 {
00034     auto deferral = pArgs->SuspendingOperation->GetDeferral();
00035     SuspensionManager::StartSaveTask().then([deferral] () {
00036         deferral->Complete();
00037     });
00038 }
00039
00040 void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs)
00041 {
00042     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Terminated)
00043     {
00044         SuspensionManager::StartRestoreTask().then([this] () {
00045             auto rootFrame = ref new Frame();
00046             TypeName pageType = { "LockScreenAppsCPP.MainPage", TypeKind::Custom };
00047             rootFrame->Navigate(pageType);
00048             Window::Current->Content = rootFrame;
00049             Window::Current->Activate();
00050         });
00051     }
00052     else
00053     {
00054         auto rootFrame = ref new Frame();
00055         TypeName pageType = { "LockScreenAppsCPP.MainPage", TypeKind::Custom };
00056         rootFrame->Navigate(pageType);
00057         Window::Current->Content = rootFrame;
00058         Window::Current->Activate();
00059     }
00060 }
Generated on Sat Nov 23 2024 16:07:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Compression/C++/Constants.h Source File

  • Compression

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"Data Compression/Decompression C++ Sample");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044
00045
00046 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Scheduled notifications/C#,C++/NotificationData.cpp Source File

  • Scheduled notifications
  • C#,C++

NotificationData.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002 #include "NotificationData.h"
00003
00004 using namespace ScheduledNotificationsSampleCPP;
00005 using namespace Platform;
00006 using namespace Platform::Collections;
00007 using namespace Windows::Foundation::Collections;
00008 using namespace Windows::UI::Notifications;
00009 using namespace Windows::UI::Xaml;
00010 using namespace Windows::UI::Xaml::Data;
00011 using namespace Windows::UI::Xaml::Controls;
00012 using namespace Windows::UI::ViewManagement;
00013
00014 NotificationData::NotificationData(void)
00015 {
00016     _itemType = "";
00017     _itemId = "";
00018     _dueTime = "";
00019     _inputString = "";
00020     _isTile = false;
00021 }
00022
00023 String^ NotificationData::ItemType::get()
00024 {
00025     return _itemType;
00026 }
00027
00028 void NotificationData::ItemType::set(String^ value)
00029 {
00030     if (_itemType != value) _itemType = value;
00031 }
00032
00033 String^ NotificationData::ItemId::get()
00034 {
00035     return _itemId;
00036 }
00037
00038 void NotificationData::ItemId::set(String^ value)
00039 {
00040     if (_itemId != value) _itemId = value;
00041 }
00042
00043 String^ NotificationData::DueTime::get()
00044 {
00045     return _dueTime;
00046 }
00047
00048 void NotificationData::DueTime::set(String^ value)
00049 {
00050     if (_dueTime != value) _dueTime = value;
00051 }
00052
00053 String^ NotificationData::InputString::get()
00054 {
00055     return _inputString;
00056 }
00057
00058 void NotificationData::InputString::set(String^ value)
00059 {
00060     if (_inputString != value) _inputString = value;
00061 }
00062
00063 bool NotificationData::get_IsTile()
00064 {
00065     return _isTile;
00066 }
00067
00068 void NotificationData::set_IsTile(bool isTile)
00069 {
00070   if (_isTile != isTile)
00071   {
00072     _isTile = isTile;
00073   }
00074 }
00075
00076 void NotificationData::OnPropertyChanged(String^ propertyName)
00077 {
00078     PropertyChanged(this, ref new PropertyChangedEventArgs(propertyName));
00079 }
00080
00081 NotificationDataSource::NotificationDataSource()
00082 {
00083     _items = ref new Vector<Object^>();
00084     _formatter = Windows::Globalization::DateTimeFormatting::DateTimeFormatter::LongTime;
00085 }
00086
00087 void NotificationDataSource::LoadData()
00088 {
00089     auto scheduledToasts = ToastNotificationManager::CreateToastNotifier()->GetScheduledToastNotifications();
00090     auto scheduledTiles = TileUpdateManager::CreateTileUpdaterForApplication()->GetScheduledTileNotifications();
00091
00092     int toastLength = scheduledToasts->Size;
00093     int tileLength = scheduledTiles->Size;
00094
00095     for (int i = 0; i < toastLength; i++)
00096     {
00097         auto toast = scheduledToasts->GetAt(i);
00098
00099         AddItem(
00100             "Toast",
00101             toast->Id,
00102             _formatter->Format(toast->DeliveryTime),
00103             toast->Content->GetElementsByTagName("text")->Item(0)->InnerText,
00104             false
00105         );
00106     }
00107
00108     for (int i = 0; i < tileLength; i++)
00109     {
00110         auto tile = scheduledTiles->GetAt(i);
00111         AddItem(
00112             "Tile",
00113             tile->Id,
00114             _formatter->Format(tile->DeliveryTime),
00115             tile->Content->GetElementsByTagName("text")->Item(0)->InnerText,
00116             true
00117         );
00118     }
00119 }
00120
00121 void NotificationDataSource::Clear()
00122 {
00123     _items->Clear();
00124 }
00125
00126 void NotificationDataSource::Refresh()
00127 {
00128     Clear();
00129     LoadData();
00130 }
00131
00132 void NotificationDataSource::AddItem(String^ itemType, String^ itemId, String^ dueTime, String^ inputString, bool isTile)
00133 {
00134     auto newData = ref new NotificationData();
00135
00136     newData->ItemType = itemType;
00137     newData->ItemId = itemId;
00138     newData->DueTime = dueTime;
00139     newData->InputString = inputString;
00140     newData->set_IsTile(isTile);
00141
00142     _items->Append(newData);
00143 }
00144
00145 IObservableVector<Object^>^ NotificationDataSource::Items::get()
00146 {
00147     return _items;
00148 }
Generated on Sat Nov 23 2024 16:08:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D post-processing effects/C++/DirectXBase.cpp Source File

  • Direct3D post-processing effects

DirectXBase.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 "DirectXBase.h"
00010
00011 using namespace Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::Graphics::Display;
00015 using namespace D2D1;
00016
00017 // Constructor.
00018 DirectXBase::DirectXBase() :
00019     m_windowSizeChangeInProgress(false),
00020     m_dpi(-1.0f)
00021 {
00022 }
00023
00024 // Initialize the DirectX resources required to run.
00025 void DirectXBase::Initialize(CoreWindow^ window, float dpi)
00026 {
00027     m_window = window;
00028
00029     CreateDeviceIndependentResources();
00030     CreateDeviceResources();
00031     SetDpi(dpi);
00032 }
00033
00034 // Recreate all device resources and set them back to the current state.
00035 void DirectXBase::HandleDeviceLost()
00036 {
00037     // Reset these member variables to ensure that SetDpi recreates all resources.
00038     float dpi = m_dpi;
00039     m_dpi = -1.0f;
00040     m_windowBounds.Width = 0;
00041     m_windowBounds.Height = 0;
00042     m_swapChain = nullptr;
00043
00044     CreateDeviceResources();
00045     SetDpi(dpi);
00046 }
00047
00048 // These are the resources required independent of the device.
00049 void DirectXBase::CreateDeviceIndependentResources()
00050 {
00051     D2D1_FACTORY_OPTIONS options;
00052     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00053
00054 #if defined(_DEBUG)
00055     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00056     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00057 #endif
00058
00059     DX::ThrowIfFailed(
00060         D2D1CreateFactory(
00061             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00062             __uuidof(ID2D1Factory1),
00063             &options,
00064             &m_d2dFactory
00065             )
00066         );
00067
00068     DX::ThrowIfFailed(
00069         DWriteCreateFactory(
00070             DWRITE_FACTORY_TYPE_SHARED,
00071             __uuidof(IDWriteFactory),
00072             &m_dwriteFactory
00073             )
00074         );
00075
00076     DX::ThrowIfFailed(
00077         CoCreateInstance(
00078             CLSID_WICImagingFactory,
00079             nullptr,
00080             CLSCTX_INPROC_SERVER,
00081             IID_PPV_ARGS(&m_wicFactory)
00082             )
00083         );
00084 }
00085
00086 // These are the resources that depend on the device.
00087 void DirectXBase::CreateDeviceResources()
00088 {
00089     // This flag adds support for surfaces with a different color channel ordering
00090     // than the API default. It is required for compatibility with Direct2D.
00091     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00092     ComPtr<IDXGIDevice> dxgiDevice;
00093
00094 #if defined(_DEBUG)
00095     // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00096     creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00097 #endif
00098
00099     // This array defines the set of DirectX hardware feature levels this app will support.
00100     // Note the ordering should be preserved.
00101     // Don't forget to declare your application's minimum required feature level in its
00102     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00103     D3D_FEATURE_LEVEL featureLevels[] =
00104     {
00105         D3D_FEATURE_LEVEL_11_1,
00106         D3D_FEATURE_LEVEL_11_0,
00107         D3D_FEATURE_LEVEL_10_1,
00108         D3D_FEATURE_LEVEL_10_0,
00109         D3D_FEATURE_LEVEL_9_3,
00110         D3D_FEATURE_LEVEL_9_2,
00111         D3D_FEATURE_LEVEL_9_1
00112     };
00113
00114     // Create the Direct3D 11 API device object and a corresponding context.
00115     ComPtr<ID3D11Device> device;
00116     ComPtr<ID3D11DeviceContext> context;
00117     DX::ThrowIfFailed(
00118         D3D11CreateDevice(
00119             nullptr,                    // Specify nullptr to use the default adapter.
00120             D3D_DRIVER_TYPE_HARDWARE,
00121             0,
00122             creationFlags,              // Set debug and Direct2D compatibility flags.
00123             featureLevels,              // List of feature levels this app can support.
00124             ARRAYSIZE(featureLevels),
00125             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Metro style apps.
00126             &device,                    // Returns the Direct3D device created.
00127             &m_featureLevel,            // Returns feature level of device created.
00128             &context                    // Returns the device immediate context.
00129             )
00130         );
00131
00132     // Get the Direct3D 11.1 API device and context interfaces.
00133     DX::ThrowIfFailed(
00134         device.As(&m_d3dDevice)
00135         );
00136
00137     DX::ThrowIfFailed(
00138         context.As(&m_d3dContext)
00139         );
00140
00141     // Get the underlying DXGI device of the Direct3D device.
00142     DX::ThrowIfFailed(
00143         m_d3dDevice.As(&dxgiDevice)
00144         );
00145
00146     // Create the Direct2D device object and a corresponding context.
00147     DX::ThrowIfFailed(
00148         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00149         );
00150
00151     DX::ThrowIfFailed(
00152         m_d2dDevice->CreateDeviceContext(
00153             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00154             &m_d2dContext
00155             )
00156         );
00157 }
00158
00159 // Helps track the DPI in the helper class.
00160 // This is called in the dpiChanged event handler in the view class.
00161 void DirectXBase::SetDpi(float dpi)
00162 {
00163     if (dpi != m_dpi)
00164     {
00165         // Save the DPI of this display in our class.
00166         m_dpi = dpi;
00167
00168         // Update Direct2D's stored DPI.
00169         m_d2dContext->SetDpi(m_dpi, m_dpi);
00170
00171         // Often a DPI change implies a window size change. In some cases Windows will issue
00172         // both a size changed event and a DPI changed event. In this case, the resulting bounds
00173         // will not change, and the window resize code will only be executed once.
00174         UpdateForWindowSizeChange();
00175     }
00176 }
00177
00178 // This routine is called in the event handler for the view SizeChanged event.
00179 void DirectXBase::UpdateForWindowSizeChange()
00180 {
00181     // Only handle window size changed if there is no pending DPI change.
00182     if (m_dpi != DisplayProperties::LogicalDpi)
00183     {
00184         return;
00185     }
00186
00187     if (m_window->Bounds.Width  != m_windowBounds.Width ||
00188         m_window->Bounds.Height != m_windowBounds.Height)
00189     {
00190         m_d2dContext->SetTarget(nullptr);
00191         m_d2dTargetBitmap = nullptr;
00192         m_d3dRenderTargetView = nullptr;
00193         m_d3dDepthStencilView = nullptr;
00194         m_windowSizeChangeInProgress = true;
00195         CreateWindowSizeDependentResources();
00196     }
00197 }
00198
00199 // Allocate all memory resources that change on a window SizeChanged event.
00200 void DirectXBase::CreateWindowSizeDependentResources()
00201 {
00202     // Store the window bounds so the next time we get a SizeChanged event we can
00203     // avoid rebuilding everything if the size is identical.
00204     m_windowBounds = m_window->Bounds;
00205
00206     if (m_swapChain != nullptr)
00207     {
00208         // If the swap chain already exists, resize it.
00209         HRESULT hr = m_swapChain->ResizeBuffers(2, 0, 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0);
00210
00211         if (hr == DXGI_ERROR_DEVICE_REMOVED)
00212         {
00213             // If the device was removed for any reason, a new device and swapchain will need to be created.
00214             HandleDeviceLost();
00215
00216             // Everything is set up now. Do not continue execution of this method.
00217             return;
00218         }
00219         else
00220         {
00221             DX::ThrowIfFailed(hr);
00222         }
00223     }
00224     else
00225     {
00226         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00227         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00228         swapChainDesc.Width = 0;                                     // Use automatic sizing.
00229         swapChainDesc.Height = 0;
00230         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;           // This is the most common swap chain format.
00231         swapChainDesc.Stereo = false;
00232         swapChainDesc.SampleDesc.Count = 1;                          // Don't use multi-sampling.
00233         swapChainDesc.SampleDesc.Quality = 0;
00234         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00235         swapChainDesc.BufferCount = 2;                               // Use double-buffering to minimize latency.
00236         swapChainDesc.Scaling = DXGI_SCALING_NONE;
00237         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Metro style apps must use this SwapEffect.
00238         swapChainDesc.Flags = 0;
00239
00240         ComPtr<IDXGIDevice1> dxgiDevice;
00241         DX::ThrowIfFailed(
00242             m_d3dDevice.As(&dxgiDevice)
00243             );
00244
00245         ComPtr<IDXGIAdapter> dxgiAdapter;
00246         DX::ThrowIfFailed(
00247             dxgiDevice->GetAdapter(&dxgiAdapter)
00248             );
00249
00250         ComPtr<IDXGIFactory2> dxgiFactory;
00251         DX::ThrowIfFailed(
00252             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00253             );
00254
00255         CoreWindow^ window = m_window.Get();
00256         DX::ThrowIfFailed(
00257             dxgiFactory->CreateSwapChainForCoreWindow(
00258                 m_d3dDevice.Get(),
00259                 reinterpret_cast<IUnknown*>(window),
00260                 &swapChainDesc,
00261                 nullptr,
00262                 &m_swapChain
00263                 )
00264             );
00265
00266         // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
00267         // ensures that the application will only render after each VSync, minimizing power consumption.
00268         DX::ThrowIfFailed(
00269             dxgiDevice->SetMaximumFrameLatency(1)
00270             );
00271     }
00272
00273     // Create a Direct3D render target view of the swap chain back buffer.
00274     ComPtr<ID3D11Texture2D> backBuffer;
00275     DX::ThrowIfFailed(
00276         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00277         );
00278
00279     DX::ThrowIfFailed(
00280         m_d3dDevice->CreateRenderTargetView(
00281             backBuffer.Get(),
00282             nullptr,
00283             &m_d3dRenderTargetView
00284             )
00285         );
00286
00287     // Cache the rendertarget dimensions in our helper class for convenient use.
00288     D3D11_TEXTURE2D_DESC backBufferDesc = {0};
00289     backBuffer->GetDesc(&backBufferDesc);
00290     m_renderTargetSize.Width  = static_cast<float>(backBufferDesc.Width);
00291     m_renderTargetSize.Height = static_cast<float>(backBufferDesc.Height);
00292
00293     // Create a depth stencil view for use with 3D rendering if needed.
00294     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00295         DXGI_FORMAT_D24_UNORM_S8_UINT,
00296         backBufferDesc.Width,
00297         backBufferDesc.Height,
00298         1,
00299         1,
00300         D3D11_BIND_DEPTH_STENCIL
00301         );
00302
00303     ComPtr<ID3D11Texture2D> depthStencil;
00304     DX::ThrowIfFailed(
00305         m_d3dDevice->CreateTexture2D(
00306             &depthStencilDesc,
00307             nullptr,
00308             &depthStencil
00309             )
00310         );
00311
00312     auto viewDesc = CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D);
00313     DX::ThrowIfFailed(
00314         m_d3dDevice->CreateDepthStencilView(
00315             depthStencil.Get(),
00316             &viewDesc,
00317             &m_d3dDepthStencilView
00318             )
00319         );
00320
00321     // Set the 3D rendering viewport to target the entire window.
00322     CD3D11_VIEWPORT viewport(
00323         0.0f,
00324         0.0f,
00325         static_cast<float>(backBufferDesc.Width),
00326         static_cast<float>(backBufferDesc.Height)
00327         );
00328
00329     m_d3dContext->RSSetViewports(1, &viewport);
00330
00331     // Create a Direct2D target bitmap associated with the
00332     // swap chain back buffer and set it as the current target.
00333     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00334         BitmapProperties1(
00335             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00336             PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00337             m_dpi,
00338             m_dpi
00339             );
00340
00341     ComPtr<IDXGISurface> dxgiBackBuffer;
00342     DX::ThrowIfFailed(
00343         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00344         );
00345
00346     DX::ThrowIfFailed(
00347         m_d2dContext->CreateBitmapFromDxgiSurface(
00348             dxgiBackBuffer.Get(),
00349             &bitmapProperties,
00350             &m_d2dTargetBitmap
00351             )
00352         );
00353
00354     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00355
00356     // Grayscale text anti-aliasing is recommended for all Metro style apps.
00357     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00358 }
00359
00360 // Method to deliver the final image to the display.
00361 void DirectXBase::Present()
00362 {
00363     // The application may optionally specify "dirty" or "scroll" rects to improve efficiency
00364     // in certain scenarios.  In this sample, however, we do not utilize those features.
00365     DXGI_PRESENT_PARAMETERS parameters = {0};
00366     parameters.DirtyRectsCount = 0;
00367     parameters.pDirtyRects = nullptr;
00368     parameters.pScrollRect = nullptr;
00369     parameters.pScrollOffset = nullptr;
00370
00371     // The first argument instructs DXGI to block until VSync, putting the application
00372     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00373     // frames that will never be displayed to the screen.
00374     HRESULT hr = m_swapChain->Present1(1, 0, &parameters);
00375
00376     // Discard the contents of the render target.
00377     // This is a valid operation only when the existing contents will be entirely
00378     // overwritten. If dirty or scroll rects are used, this call should be removed.
00379     m_d3dContext->DiscardView(m_d3dRenderTargetView.Get());
00380
00381     // Discard the contents of the depth stencil.
00382     m_d3dContext->DiscardView(m_d3dDepthStencilView.Get());
00383
00384     // If the device was removed either by a disconnect or a driver upgrade, we
00385     // must recreate all device resources.
00386     if (hr == DXGI_ERROR_DEVICE_REMOVED)
00387     {
00388         HandleDeviceLost();
00389     }
00390     else
00391     {
00392         DX::ThrowIfFailed(hr);
00393     }
00394
00395     if (m_windowSizeChangeInProgress)
00396     {
00397         // A window size change has been initiated and the app has just completed presenting
00398         // the first frame with the new size. Notify the resize manager so we can short
00399         // circuit any resize animation and prevent unnecessary delays.
00400         CoreWindowResizeManager::GetForCurrentView()->NotifyLayoutCompleted();
00401         m_windowSizeChangeInProgress = false;
00402     }
00403 }
00404
00405 void DirectXBase::ValidateDevice()
00406 {
00407     // The D3D Device is no longer valid if the default adapter changes or if
00408     // the device has been removed.
00409
00410     // First, get the information for the adapter related to the current device.
00411
00412     ComPtr<IDXGIDevice1> dxgiDevice;
00413     ComPtr<IDXGIAdapter> deviceAdapter;
00414     DXGI_ADAPTER_DESC deviceDesc;
00415     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00416     DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter));
00417     DX::ThrowIfFailed(deviceAdapter->GetDesc(&deviceDesc));
00418
00419     // Next, get the information for the default adapter.
00420
00421     ComPtr<IDXGIFactory2> dxgiFactory;
00422     ComPtr<IDXGIAdapter1> currentAdapter;
00423     DXGI_ADAPTER_DESC currentDesc;
00424     DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)));
00425     DX::ThrowIfFailed(dxgiFactory->EnumAdapters1(0, &currentAdapter));
00426     DX::ThrowIfFailed(currentAdapter->GetDesc(&currentDesc));
00427
00428     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00429     // a new D3D device must be created.
00430
00431     if ((deviceDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart) ||
00432         (deviceDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart) ||
00433         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00434     {
00435         // Release references to resources related to the old device.
00436         dxgiDevice = nullptr;
00437         deviceAdapter = nullptr;
00438
00439         // Create a new device and swap chain.
00440         HandleDeviceLost();
00441     }
00442 }
Generated on Sat Nov 23 2024 16:08:02 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/MediaExtensions/Mpeg1Source/MPEG1Source.idl Source File

  • Media extensions
  • MediaExtensions
  • Mpeg1Source

MPEG1Source.idl

Go to the documentation of this file.
00001 import "Windows.Media.idl";
00002
00003 #include <sdkddkver.h>
00004
00005 namespace MPEG1Source
00006 {
00007   [version(NTDDI_WIN8)]
00008     runtimeclass MPEG1ByteStreamHandler
00009     {
00010     [default] interface Windows.Media.IMediaExtension;
00011     }
00012 }
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Accelerometer sensor/C++/MainPage.xaml.h Source File

  • Accelerometer sensor

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CameraCaptureUI/C++/CaptureVideo.xaml.cpp Source File

  • CameraCaptureUI

CaptureVideo.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 // CaptureVideo.xaml.cpp
00013 // Implementation of the CaptureVideo class
00014 //
00015
00016 #include "pch.h"
00017 #include "CaptureVideo.xaml.h"
00018
00019 using namespace SDKSample::CameraCapture;
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::Media::Capture;
00025 using namespace Windows::Storage;
00026 using namespace Windows::Foundation;
00027
00028
00029 CaptureVideo::CaptureVideo()
00030 {
00031     InitializeComponent();
00032     appSettings = ApplicationData::Current->LocalSettings->Values;
00033     ResetButton->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
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 CaptureVideo::OnNavigatedTo(NavigationEventArgs^ e)
00042 {
00043     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00044     // as NotifyUser()
00045     rootPage = MainPage::Current;
00046
00047     // Set the initial video
00048
00049     // Check for any previously stored photo in application data
00050     if (appSettings->HasKey("capturedVideo"))
00051     {
00052         CaptureVideoButton->IsEnabled = false;
00053
00054         // Load the image from specified path
00055         Platform::String^ filePath = safe_cast<IPropertyValue^>(appSettings->Lookup("capturedVideo"))->GetString();
00056
00057         LoadVideo(filePath);
00058     }
00059     else
00060     {
00061         // Load the placeholder message
00062         rootPage->NotifyUser("The video will be shown here.", NotifyType::StatusMessage);
00063     }
00064 }
00065
00066 /// <summary>
00067 /// Invoked when CaptureVideo button is clicked.
00068 /// Shows the camera capture UI in video mode.
00069 /// When the user takes a video, shows the image in output section.
00070 /// </summary>
00071 void CaptureVideo::CaptureVideo_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00072 {
00073     try
00074     {
00075         CameraCaptureUI^ dialog = ref new CameraCaptureUI();
00076
00077         dialog->VideoSettings->Format = CameraCaptureUIVideoFormat::Mp4;
00078
00079         concurrency::task<StorageFile^>(dialog->CaptureFileAsync(CameraCaptureUIMode::Video)).then([this] (StorageFile^ file)
00080         {
00081             if (file != nullptr)
00082             {
00083                 concurrency::task<Streams::IRandomAccessStream^> (file->OpenAsync(FileAccessMode::Read)).then([this] (Streams::IRandomAccessStream^ stream)
00084                 {
00085                     CapturedVideo->SetSource(stream, "video/mp4");
00086                     ResetButton->Visibility = Windows::UI::Xaml::Visibility::Visible;
00087                     rootPage->NotifyUser("", NotifyType::StatusMessage);
00088                 });
00089
00090                 // Store the path in Application Data
00091                 appSettings->Insert("capturedVideo", PropertyValue::CreateString(file->Path));
00092             }
00093             else
00094             {
00095                 rootPage->NotifyUser("No video captured", NotifyType::ErrorMessage);
00096             }
00097
00098         });
00099     }
00100     catch (Platform::Exception^ ex)
00101     {
00102         rootPage->NotifyUser(ex->Message, NotifyType::ErrorMessage);
00103     }
00104 }
00105
00106 /// <summary>
00107 /// Invoked when Reset button is clicked.
00108 /// Resets the scenario.
00109 /// </summary>
00110 void CaptureVideo::Reset_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112     rootPage->NotifyUser("The video will be shown here.", NotifyType::StatusMessage);
00113     ResetButton->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00114     CapturedVideo->Source = nullptr;
00115
00116     // Remove file from Application Data
00117     appSettings->Remove("capturedVideo");
00118 }
00119
00120 /// <summary>
00121 /// Loads the video from the specified file.
00122 /// </summary>
00123 void CaptureVideo::LoadVideo(Platform::String^ filePath)
00124 {
00125     concurrency::task<StorageFile^>(StorageFile::GetFileFromPathAsync(filePath)).then([this] (StorageFile^ file)
00126     {
00127         return file->OpenAsync(FileAccessMode::Read);
00128     })
00129         .then([this](concurrency::task<Streams::IRandomAccessStream^> openTask)
00130     {
00131         try
00132         {
00133             auto stream = openTask.get();
00134             CapturedVideo->SetSource(stream, "video/mp4");
00135             ResetButton->Visibility = Windows::UI::Xaml::Visibility::Visible;
00136             CaptureVideoButton->IsEnabled = true;
00137             rootPage->NotifyUser("", NotifyType::StatusMessage);
00138         }
00139         catch (Platform::Exception^ ex)
00140         {
00141             CaptureVideoButton->IsEnabled = true;
00142             appSettings->Remove("capturedVideo");
00143             rootPage->NotifyUser(ex->Message, NotifyType::ErrorMessage);
00144         }
00145     });
00146 }
Generated on Sat Nov 23 2024 16:07:58 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/Common/RichTextColumns.cpp Source File

  • Hilo C++
  • Hilo
  • Common

RichTextColumns.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 #include "RichTextColumns.h"
00009
00010 using namespace Hilo::Common;
00011
00012 using namespace Platform;
00013 using namespace Platform::Collections;
00014 using namespace Windows::Foundation;
00015 using namespace Windows::UI::Xaml;
00016 using namespace Windows::UI::Xaml::Controls;
00017 using namespace Windows::UI::Xaml::Interop;
00018
00019 /// <summary>
00020 /// Initializes a new instance of the <see cref="RichTextColumns"/> class.
00021 /// </summary>
00022 RichTextColumns::RichTextColumns()
00023 {
00024   HorizontalAlignment = Windows::UI::Xaml::HorizontalAlignment::Left;
00025 }
00026
00027 static DependencyProperty^ _columnTemplateProperty =
00028   DependencyProperty::Register("ColumnTemplate", TypeName(DataTemplate::typeid), TypeName(RichTextColumns::typeid),
00029   ref new PropertyMetadata(nullptr, ref new PropertyChangedCallback(
00030   &RichTextColumns::ResetOverflowLayout)));
00031
00032 /// <summary>
00033 /// Identifies the <see cref="ColumnTemplate"/> dependency property.
00034 /// </summary>
00035 DependencyProperty^ RichTextColumns::ColumnTemplateProperty::get()
00036 {
00037   return _columnTemplateProperty;
00038 }
00039
00040 static DependencyProperty^ _richTextContentProperty =
00041   DependencyProperty::Register("RichTextContent", TypeName(RichTextBlock::typeid), TypeName(RichTextColumns::typeid),
00042   ref new PropertyMetadata(nullptr, ref new PropertyChangedCallback(
00043   &RichTextColumns::ResetOverflowLayout)));
00044
00045 /// <summary>
00046 /// Identifies the <see cref="RichTextContent"/> dependency property.
00047 /// </summary>
00048 DependencyProperty^ RichTextColumns::RichTextContentProperty::get()
00049 {
00050   return _richTextContentProperty;
00051 }
00052
00053 /// <summary>
00054 /// Invoked when the content or overflow template is changed to recreate the column layout.
00055 /// </summary>
00056 /// <param name="d">Instance of <see cref="RichTextColumns"/> where the change
00057 /// occurred.</param>
00058 /// <param name="e">Event data describing the specific change.</param>
00059 void RichTextColumns::ResetOverflowLayout(DependencyObject^ d, DependencyPropertyChangedEventArgs^ e)
00060 {
00061   (void) e; // Unused parameter
00062
00063   auto target = dynamic_cast<RichTextColumns^>(d);
00064   if (target != nullptr)
00065   {
00066     // When dramatic changes occur, rebuild layout from scratch
00067     target->_overflowColumns = nullptr;
00068     target->Children->Clear();
00069     target->InvalidateMeasure();
00070   }
00071 }
00072
00073 /// <summary>
00074 /// Determines whether additional overflow columns are needed and if existing columns can
00075 /// be removed.
00076 /// </summary>
00077 /// <param name="availableSize">The size of the space available, used to constrain the
00078 /// number of additional columns that can be created.</param>
00079 /// <returns>The resulting size of the original content plus any extra columns.</returns>
00080 Size RichTextColumns::MeasureOverride(Size availableSize)
00081 {
00082   if (RichTextContent == nullptr)
00083   {
00084     Size emptySize(0, 0);
00085     return emptySize;
00086   }
00087
00088   // Make sure the RichTextBlock is a child, using the lack of
00089   // a list of additional columns as a sign that this hasn't been
00090   // done yet
00091   if (_overflowColumns == nullptr)
00092   {
00093     Children->Append(RichTextContent);
00094     _overflowColumns = ref new Vector<RichTextBlockOverflow^>();
00095   }
00096
00097   // Start by measuring the original RichTextBlock content
00098   RichTextContent->Measure(availableSize);
00099   auto maxWidth = RichTextContent->DesiredSize.Width;
00100   auto maxHeight = RichTextContent->DesiredSize.Height;
00101   auto hasOverflow = RichTextContent->HasOverflowContent;
00102
00103   // Make sure there are enough overflow columns
00104   unsigned int overflowIndex = 0;
00105   while (hasOverflow && maxWidth < availableSize.Width && ColumnTemplate != nullptr)
00106   {
00107     // Use existing overflow columns until we run out, then create
00108     // more from the supplied template
00109     RichTextBlockOverflow^ overflow;
00110     if (_overflowColumns->Size > overflowIndex)
00111     {
00112       overflow = _overflowColumns->GetAt(overflowIndex);
00113     }
00114     else
00115     {
00116       overflow = safe_cast<RichTextBlockOverflow^>(ColumnTemplate->LoadContent());
00117       _overflowColumns->Append(overflow);
00118       Children->Append(overflow);
00119       if (overflowIndex == 0)
00120       {
00121         RichTextContent->OverflowContentTarget = overflow;
00122       }
00123       else
00124       {
00125         _overflowColumns->GetAt(overflowIndex - 1)->OverflowContentTarget = overflow;
00126       }
00127     }
00128
00129     // Measure the new column and prepare to repeat as necessary
00130     Size remainingSize(availableSize.Width - maxWidth, availableSize.Height);
00131     overflow->Measure(remainingSize);
00132     maxWidth += overflow->DesiredSize.Width;
00133     maxHeight = __max(maxHeight, overflow->DesiredSize.Height);
00134     hasOverflow = overflow->HasOverflowContent;
00135     overflowIndex++;
00136   }
00137
00138   // Disconnect extra columns from the overflow chain, remove them from our private list
00139   // of columns, and remove them as children
00140   if (_overflowColumns->Size > overflowIndex)
00141   {
00142     if (overflowIndex == 0)
00143     {
00144       RichTextContent->OverflowContentTarget = nullptr;
00145     }
00146     else
00147     {
00148       _overflowColumns->GetAt(overflowIndex - 1)->OverflowContentTarget = nullptr;
00149     }
00150     while (_overflowColumns->Size > overflowIndex)
00151     {
00152       _overflowColumns->RemoveAt(overflowIndex);
00153       Children->RemoveAt(overflowIndex + 1);
00154     }
00155   }
00156
00157   // Report final determined size
00158   Size resultingSize(maxWidth, maxHeight);
00159   return resultingSize;
00160 }
00161
00162 /// <summary>
00163 /// Arranges the original content and all extra columns.
00164 /// </summary>
00165 /// <param name="finalSize">Defines the size of the area the children must be arranged
00166 /// within.</param>
00167 /// <returns>The size of the area the children actually required.</returns>
00168 Size RichTextColumns::ArrangeOverride(Size finalSize)
00169 {
00170   float maxWidth = 0;
00171   float maxHeight = 0;
00172   auto childrenIterator = Children->First();
00173   while (childrenIterator->HasCurrent)
00174   {
00175     auto child = childrenIterator->Current;
00176     Rect childRect(maxWidth, 0, child->DesiredSize.Width, finalSize.Height);
00177     child->Arrange(childRect);
00178     maxWidth += child->DesiredSize.Width;
00179     maxHeight = __max(maxHeight, child->DesiredSize.Height);
00180     childrenIterator->MoveNext();
00181   }
00182   Size resultingSize(maxWidth, maxHeight);
00183   return resultingSize;
00184 }
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/LocalResourceLoader.h Source File

  • Hilo C++
  • Hilo

LocalResourceLoader.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
00009 #include "IResourceLoader.h"
00010
00011 namespace Hilo
00012 {
00013     // The LocalResourceLoader provides a helper method that gets strings from the app's resource file.
00014     public ref class LocalResourceLoader sealed : public IResourceLoader
00015     {
00016     public:
00017         virtual Platform::String^ GetString(Platform::String^ value);
00018     };
00019 }
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Mobile broadband account provisioning/C++/UpdateCost.xaml.h Source File

  • Mobile broadband account provisioning

UpdateCost.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 // UpdateCost.xaml.h
00013 // Declaration of the UpdateCost class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "UpdateCost.g.h"
00020 #include "MainPage.xaml.h"
00021 #include "Util.h"
00022
00023 using namespace Windows::UI::Xaml;
00024 using namespace Windows::UI::Xaml::Controls;
00025 using namespace Windows::Graphics::Display;
00026 using namespace Windows::UI::ViewManagement;
00027 using namespace Platform;
00028
00029 namespace SDKSample
00030 {
00031     namespace ProvisioningAgent
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 UpdateCost sealed
00038         {
00039         public:
00040             UpdateCost();
00041
00042         protected:
00043             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00044         private:
00045             MainPage^ rootPage;
00046             Util^ util;
00047             Windows::Networking::NetworkOperators::ProfileMediaType profileMediaType;
00048             Windows::Networking::Connectivity::NetworkCostType networkCostType;
00049
00050             void MediaType_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e);
00051             void NetworkCostCategory_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e);
00052             void UpdateCost_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00053         };
00054     }
00055 }
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Device capabilities/C++/App.xaml.h Source File

  • Input Device capabilities

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML FlipView control/C++/common/suspensionmanager.h Source File

  • XAML FlipView control
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Context menu/C++/Constants.cpp Source File

  • Context menu

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     { "Show a context menu",            "SDKSample.ContextMenu.Scenario1" },
00020     { "Replace a default context menu", "SDKSample.ContextMenu.Scenario2" },
00021 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File and folder thumbnail/C++/App.xaml.cpp Source File

  • File and folder thumbnail

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D stereoscopic 3D/C++/StereoSimpleD3D.h Source File

  • Direct3D stereoscopic 3D

StereoSimpleD3D.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 "DirectXBase.h"
00011 #include "BasicMath.h"
00012 #include "SampleOverlay.h"
00013 #include "DirectXMath.h"
00014 #include "Stereo3DMatrixHelper.h"
00015
00016 // The constant buffer that is used with the DirectXMath library to draw the cube.
00017 struct ConstantBuffer
00018 {
00019     DirectX::XMFLOAT4X4 model;
00020     DirectX::XMFLOAT4X4 view;
00021     DirectX::XMFLOAT4X4 projection;
00022 };
00023
00024 ref class StereoSimpleD3D : public DirectXBase
00025 {
00026 internal:
00027     StereoSimpleD3D();
00028     virtual void CreateDeviceIndependentResources() override;
00029     virtual void CreateDeviceResources() override;
00030     virtual void CreateWindowSizeDependentResources() override;
00031     virtual void Render() override;
00032
00033     float GetStereoExaggeration();
00034     void RenderEye(_In_ unsigned int eyeIndex);
00035     void SetStereoExaggeration(_In_ float currentExaggeration);
00036     void Update(
00037         _In_ unsigned int eyeIndex,
00038         _In_ float timeTotal,
00039         _In_ float timeDelta
00040         );
00041
00042 private:
00043     SampleOverlay^                                      m_sampleOverlay;
00044     Microsoft::WRL::ComPtr<ID3D11InputLayout>           m_inputLayout;                // cube vertex input layout
00045     Microsoft::WRL::ComPtr<ID3D11Buffer>                m_vertexBuffer;               // cube vertex buffer
00046     Microsoft::WRL::ComPtr<ID3D11Buffer>                m_indexBuffer;                // cube index buffer
00047     Microsoft::WRL::ComPtr<ID3D11VertexShader>          m_vertexShader;               // cube vertex shader
00048     Microsoft::WRL::ComPtr<ID3D11PixelShader>           m_pixelShader;                // cube pixel shader
00049     Microsoft::WRL::ComPtr<ID3D11ShaderResourceView>    m_textureShaderResourceView;  // cube texture view
00050     Microsoft::WRL::ComPtr<ID3D11SamplerState>          m_sampler;                    // cube texture sampler
00051     Microsoft::WRL::ComPtr<ID3D11Buffer>                m_constantBuffer;             // constant buffer resource
00052     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>        m_brush;                      // brush for message drawing
00053     Microsoft::WRL::ComPtr<IDWriteTextFormat>           m_textFormat;                 // text format for message drawing
00054
00055     unsigned int             m_indexCount;                  // cube index count
00056     ConstantBuffer           m_constantBufferData;          // constant buffer resource data
00057     float                    m_projAspect;                  // aspect ratio for projection matrix
00058     float                    m_nearZ;                       // nearest Z-distance at which to draw vertices
00059     float                    m_farZ;                        // farthest Z-distance at which to draw vertices
00060     float                    m_widthInInches;               // estimated screen width in inches
00061     float                    m_heightInInches;              // estimated screen height in inches
00062     float                    m_stereoExaggerationFactor;    // stereo effect that is user adjustable
00063     Platform::String^        m_hintMessage;                 // hint message about customer manipulation
00064     float                    m_worldScale;                  // developer specified world unit
00065 };
Generated on Sat Nov 23 2024 16:08:12 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/Sphere.cpp Source File

  • XAML DirectX 3D shooting game

Sphere.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 "Sphere.h"
00010
00011 using namespace DirectX;
00012
00013 //----------------------------------------------------------------------
00014
00015 Sphere::Sphere()
00016 {
00017     m_position = XMFLOAT3(0.0f, 0.0f, 0.0f);
00018     m_radius = 1.0f;
00019     Update();
00020 }
00021
00022 //----------------------------------------------------------------------
00023
00024 Sphere::Sphere(
00025     DirectX::XMFLOAT3 position,
00026     float radius
00027     )
00028 {
00029     m_position = position;
00030     m_radius = radius;
00031     Update();
00032 }
00033
00034 //----------------------------------------------------------------------
00035
00036 void Sphere::Update()
00037 {
00038     XMStoreFloat4x4(
00039         &m_modelMatrix,
00040         XMMatrixScaling(m_radius, m_radius, m_radius) *
00041         XMMatrixTranslation(m_position.x, m_position.y, m_position.z)
00042         );
00043 }
00044
00045 //----------------------------------------------------------------------
00046
00047 bool Sphere::IsTouching(
00048     XMFLOAT3 point,
00049     float radius,
00050     _Out_ XMFLOAT3 *contact,
00051     _Out_ XMFLOAT3 *normal
00052     )
00053 {
00054     // Check collision between instances One and Two.
00055     // oneToTwo is the collision normal vector.
00056     XMVECTOR oneToTwo = XMLoadFloat3(&m_position) - XMLoadFloat3(&point);
00057
00058     float distance = XMVectorGetX(XMVector3Length(oneToTwo));
00059
00060     oneToTwo = XMVector3Normalize(oneToTwo);
00061     XMStoreFloat3(normal, oneToTwo);
00062     XMStoreFloat3(contact, oneToTwo * m_radius);
00063
00064     if (distance < 0.0f)
00065     {
00066         distance *= -1.0f;
00067     }
00068
00069     if (distance < (radius + m_radius))
00070     {
00071         return true;
00072     }
00073     else
00074     {
00075         return false;
00076     }
00077 }
00078
00079 //----------------------------------------------------------------------
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Print/C++/ScenarioOutput5.xaml.cpp Source File

  • Print

ScenarioOutput5.xaml.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 //
00009 // ScenarioOutput5.xaml.cpp
00010 // Implementation of the ScenarioOutput5 class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioOutput5.xaml.h"
00015
00016 using namespace PrintSample;
00017
00018 ScenarioOutput5::ScenarioOutput5()
00019 {
00020     InitializeComponent();
00021 }
00022
00023 ScenarioOutput5::~ScenarioOutput5()
00024 {
00025 }
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Custom driver access/C++/DLL/support.h Source File

  • Custom driver access
  • DLL

support.h

Go to the documentation of this file.
00001 #include <strsafe.h>
00002 #include <assert.h>
00003
00004 #pragma once
00005
00006 ///<summary>
00007 ///Printf to the debugger
00008 ///</summary>
00009 inline void DbgPrint(PCWSTR FormatString, ...) {
00010   WCHAR buffer[1024];
00011   static ULONG line = 0;
00012   va_list arglist;
00013   va_start(arglist, FormatString);
00014
00015   StringCbPrintf(buffer, sizeof(buffer), L"%03d:", line++);
00016   OutputDebugString(buffer);
00017
00018   StringCbVPrintf(buffer, sizeof(buffer), FormatString, arglist);
00019   OutputDebugString(buffer);
00020 }
00021
00022 namespace Samples {
00023     namespace Devices {
00024
00025         [uuid("999BAD24-9ACD-45BB-8669-2A2FC0288B04")]
00026         delegate void OnIoComplete(HRESULT Result, DWORD BytesReturned);
00027
00028         ///<summary>wrapper class for the result of an IOCTL</summary>
00029         struct DeviceControlResult {
00030             HRESULT Result;
00031             ULONG BytesTransferred;
00032
00033             DeviceControlResult() : Result(E_NOT_SET),
00034                                     BytesTransferred(0)
00035             {
00036                 return;
00037             }
00038
00039             DeviceControlResult(HRESULT Hr, DWORD Cb) : Result(Hr),
00040                                                         BytesTransferred(Cb)
00041             {
00042                 return;
00043             }
00044         };
00045
00046     ///<summary>
00047     ///Starts the requested IOCTL
00048     ///</summary>
00049     ///<returns>returns a task which will complete when the IOCTL completes</returns>
00050         inline
00051         concurrency::task<DeviceControlResult>
00052         StartIoctl(
00053             _In_ IDeviceIoControl* Device,
00054             _In_ ULONG DeviceControlCode,
00055             _In_reads_bytes_opt_(InputBufferCb) PUCHAR InputBuffer,
00056             _In_ ULONG InputBufferCb,
00057             _Out_writes_bytes_opt_(OutputBufferCb) PUCHAR OutputBuffer,
00058             _In_ ULONG OutputBufferCb,
00059             _Out_opt_ ULONG_PTR* CancelToken = NULL
00060             )
00061         {
00062             concurrency::task_completion_event<DeviceControlResult> tce;
00063             concurrency::task<DeviceControlResult> t(tce);
00064
00065             auto callback = ref new OnIoComplete(
00066                 [tce](HRESULT Hr, DWORD Cb) {
00067                     tce.set(DeviceControlResult(Hr, Cb));
00068                 }
00069             );
00070
00071             auto cb2 = (IDeviceRequestCompletionCallback*) callback;
00072
00073             HRESULT hr= Device->DeviceIoControlAsync(
00074                                     DeviceControlCode,
00075                                     InputBuffer,
00076                                     InputBufferCb,
00077                                     OutputBuffer,
00078                                     OutputBufferCb,
00079                                     cb2,
00080                                     CancelToken
00081                                     );
00082
00083             if (hr != S_OK) {
00084                 tce.set(DeviceControlResult(hr, 0));
00085             }
00086
00087             return t;
00088         }
00089     }
00090 }
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text editing/C++/App.xaml.h Source File

  • XAML text editing

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX marble maze game/C++/pch.h Source File

  • DirectX marble maze game

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 <d3d11_1.h>
00012 #include <d2d1_1.h>
00013 #include <d2d1effects.h>
00014 #include <dwrite_1.h>
00015 #include <wincodec.h>
00016 #include <ppltasks.h>
00017 #include <agile.h>
00018
00019 #define XM_STRICT_VECTOR4 1
00020 #include <DirectXMath.h>
00021
00022 #define XAUDIO2_HELPER_FUNCTIONS 1
00023 #include <xaudio2.h>
00024 #include <xaudio2fx.h>
00025
00026 #include <mmreg.h>
00027 #include <mfidl.h>
00028 #include <mfapi.h>
00029 #include <mfreadwrite.h>
00030 #include <mfmediaengine.h>
00031
00032 #include <XInput.h>
00033
00034 #include <stdio.h>
00035 #include <strsafe.h>
00036 #include <vector>
00037 #include <memory>
00038 #include <map>
00039 #include <queue>
00040 #include <string>
00041 #include <set>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D animated text/C++/SampleOverlay.cpp Source File

  • Direct2D animated text

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 Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::UI::ViewManagement;
00015 using namespace Windows::Graphics::Display;
00016 using namespace D2D1;
00017
00018 SampleOverlay::SampleOverlay() :
00019     m_drawOverlay(true)
00020 {
00021 }
00022
00023 void SampleOverlay::Initialize(
00024     _In_ ID2D1Device*         d2dDevice,
00025     _In_ ID2D1DeviceContext*  d2dContext,
00026     _In_ IWICImagingFactory*  wicFactory,
00027     _In_ IDWriteFactory*      dwriteFactory,
00028     _In_ Platform::String^    caption
00029     )
00030 {
00031     m_wicFactory = wicFactory;
00032     m_dwriteFactory = dwriteFactory;
00033     m_sampleName = caption;
00034     m_d2dDevice = d2dDevice;
00035     m_d2dContext = d2dContext;
00036     m_padding = 3.0f;
00037     m_textVerticalOffset = 5.0f;
00038     m_logoSize = D2D1::SizeF(0.0f, 0.0f);
00039     m_overlayWidth = 0.0f;
00040
00041     ComPtr<ID2D1Factory> factory;
00042     d2dDevice->GetFactory(&factory);
00043
00044     DX::ThrowIfFailed(
00045         factory.As(&m_d2dFactory)
00046         );
00047
00048     ResetDirectXResources();
00049 }
00050
00051 void SampleOverlay::ResetDirectXResources()
00052 {
00053     DX::ThrowIfFailed(
00054         m_d2dContext->CreateSolidColorBrush(ColorF(ColorF::White), &m_whiteBrush)
00055         );
00056
00057     ComPtr<IWICBitmapDecoder> wicBitmapDecoder;
00058     DX::ThrowIfFailed(
00059         m_wicFactory->CreateDecoderFromFilename(
00060             L"windowsbig-sdk.png",
00061             nullptr,
00062             GENERIC_READ,
00063             WICDecodeMetadataCacheOnDemand,
00064             &wicBitmapDecoder
00065             )
00066         );
00067
00068     ComPtr<IWICBitmapFrameDecode> wicBitmapFrame;
00069     DX::ThrowIfFailed(
00070         wicBitmapDecoder->GetFrame(0, &wicBitmapFrame)
00071         );
00072
00073     ComPtr<IWICFormatConverter> wicFormatConverter;
00074     DX::ThrowIfFailed(
00075         m_wicFactory->CreateFormatConverter(&wicFormatConverter)
00076         );
00077
00078     DX::ThrowIfFailed(
00079         wicFormatConverter->Initialize(
00080             wicBitmapFrame.Get(),
00081             GUID_WICPixelFormat32bppPBGRA,
00082             WICBitmapDitherTypeNone,
00083             nullptr,
00084             0.0,
00085             WICBitmapPaletteTypeCustom  // the BGRA format has no palette so this value is ignored
00086             )
00087         );
00088
00089     double dpiX = 96.0f;
00090     double dpiY = 96.0f;
00091     DX::ThrowIfFailed(
00092         wicFormatConverter->GetResolution(&dpiX, &dpiY)
00093         );
00094
00095     DX::ThrowIfFailed(
00096         m_d2dContext->CreateBitmapFromWicBitmap(
00097             wicFormatConverter.Get(),
00098             BitmapProperties(
00099                 PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00100                 static_cast<float>(dpiX),
00101                 static_cast<float>(dpiY)
00102                 ),
00103             &m_logoBitmap
00104             )
00105         );
00106
00107     m_logoSize = m_logoBitmap->GetSize();
00108
00109     ComPtr<IDWriteTextFormat> nameTextFormat;
00110     DX::ThrowIfFailed(
00111         m_dwriteFactory->CreateTextFormat(
00112             L"Segoe UI",
00113             nullptr,
00114             DWRITE_FONT_WEIGHT_LIGHT,
00115             DWRITE_FONT_STYLE_NORMAL,
00116             DWRITE_FONT_STRETCH_NORMAL,
00117             36.0f,
00118             L"en-US",
00119             &nameTextFormat
00120             )
00121         );
00122
00123     DX::ThrowIfFailed(
00124         nameTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)
00125         );
00126
00127     DX::ThrowIfFailed(
00128         nameTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)
00129         );
00130
00131     DX::ThrowIfFailed(
00132         m_dwriteFactory->CreateTextLayout(
00133             m_sampleName->Data(),
00134             m_sampleName->Length(),
00135             nameTextFormat.Get(),
00136             4096.0f,
00137             4096.0f,
00138             &m_textLayout
00139             )
00140         );
00141
00142     DWRITE_TEXT_METRICS metrics = {0};
00143     DX::ThrowIfFailed(
00144         m_textLayout->GetMetrics(&metrics)
00145         );
00146
00147     m_overlayWidth = m_padding * 3.0f + m_logoSize.width + metrics.width;
00148
00149     DX::ThrowIfFailed(
00150         m_d2dFactory->CreateDrawingStateBlock(&m_stateBlock)
00151         );
00152
00153     UpdateForWindowSizeChange();
00154 }
00155
00156 void SampleOverlay::UpdateForWindowSizeChange()
00157 {
00158     if (CoreWindow::GetForCurrentThread()->Bounds.Width < m_overlayWidth)
00159     {
00160         m_drawOverlay = false;
00161     }
00162     else
00163     {
00164         m_drawOverlay = true;
00165     }
00166 }
00167
00168 void SampleOverlay::Render()
00169 {
00170     if (m_drawOverlay)
00171     {
00172         m_d2dContext->SaveDrawingState(m_stateBlock.Get());
00173
00174         m_d2dContext->BeginDraw();
00175         m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00176         m_d2dContext->DrawBitmap(
00177             m_logoBitmap.Get(),
00178             D2D1::RectF(m_padding, 0.0f, m_logoSize.width + m_padding, m_logoSize.height)
00179             );
00180
00181         m_d2dContext->DrawTextLayout(
00182             Point2F(m_logoSize.width + 2.0f * m_padding, m_textVerticalOffset),
00183             m_textLayout.Get(),
00184             m_whiteBrush.Get()
00185             );
00186
00187         // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00188         // is lost. It will be handled during the next call to Present.
00189         HRESULT hr = m_d2dContext->EndDraw();
00190         if (hr != D2DERR_RECREATE_TARGET)
00191         {
00192             DX::ThrowIfFailed(hr);
00193         }
00194
00195         m_d2dContext->RestoreDrawingState(m_stateBlock.Get());
00196     }
00197 }
00198
00199 float SampleOverlay::GetTitleHeightInDips()
00200 {
00201     return m_logoSize.height;
00202 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application resources and localization/C++/MainPage.xaml.cpp Source File

  • Application resources and localization

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Transcoding media/C++/Trim.xaml.h Source File

  • Transcoding media

Trim.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 // Trim.xaml.h
00013 // Declaration of the Trim class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Trim.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace Transcode
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 Trim sealed
00031         {
00032         public:
00033             Trim();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037
00038         private:
00039             void GetPresetProfile(Windows::UI::Xaml::Controls::ComboBox^ comboBox);
00040             void PickFile(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041             void OnTargetFormatChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00042             void SetPickFileButton(bool isEnabled);
00043             void StopPlayers();
00044             void PlayFile(Windows::Storage::StorageFile^ MediaFile);
00045
00046             // Trim point setters
00047             void MarkIn(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void MarkOut(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00049
00050             void TranscodeTrim(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00051             void TranscodeCancel(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00052             void TranscodeProgress(Windows::Foundation::IAsyncActionWithProgress<double>^ asyncInfo, double percent);
00053             void TranscodeError(Platform::String^ error);
00054             void TranscodeFailure(Windows::Media::Transcoding::TranscodeFailureReason reason);
00055             void SetCancelButton(bool isEnabled);
00056             void EnableButtons();
00057             void DisableButtons();
00058
00059             // Media Controls
00060             void InputPlayButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             void InputPauseButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             void InputStopButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             void OutputPlayButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00064             void OutputPauseButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00065             void OutputStopButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00066
00067             Platform::String^ _OutputFileName;
00068             Windows::Media::MediaProperties::MediaEncodingProfile^ _Profile;
00069             Windows::Storage::StorageFile^ _InputFile;
00070             Windows::Storage::StorageFile^ _OutputFile;
00071             Windows::Media::Transcoding::MediaTranscoder^ _Transcoder;
00072             Concurrency::cancellation_token_source _CTS;
00073
00074             Windows::Foundation::TimeSpan _start;
00075             Windows::Foundation::TimeSpan _stop;
00076
00077             bool _UseMp4;
00078
00079             MainPage^ rootPage;
00080         };
00081     }
00082 }
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D perspective transform/C++/DirectXSample.h Source File

  • Direct2D perspective transform

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
00010 // This header defines helper utilities to make DirectX APIs work with exceptions.
00011 namespace DX
00012 {
00013     inline void ThrowIfFailed(HRESULT hr)
00014     {
00015         if (FAILED(hr))
00016         {
00017             // Set a breakpoint on this line to catch DX API errors.
00018             throw Platform::Exception::CreateException(hr);
00019         }
00020     }
00021 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Removable storage/C++/S1_ListStorages.xaml.cpp Source File

  • Removable storage

S1_ListStorages.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 // S1_ListStorages.xaml.cpp
00013 // Implementation of the S1_ListStorages class
00014 //
00015
00016 #include "pch.h"
00017 #include "S1_ListStorages.xaml.h"
00018
00019 using namespace SDKSample::RemovableStorageCPP;
00020
00021 using namespace concurrency;
00022 using namespace Windows::Foundation::Collections;
00023 using namespace Windows::Storage;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Controls;
00026 using namespace Windows::UI::Xaml::Navigation;
00027
00028 S1_ListStorages::S1_ListStorages() : rootPage(MainPage::Current)
00029 {
00030     InitializeComponent();
00031 }
00032
00033 /// <summary>
00034 /// This is the click handler for the 'List Storages' button.
00035 /// </summary>
00036 /// <remarks>
00037 /// There are two ways to find removable storages:
00038 /// The first way uses the Removable Devices KnownFolder to get a snapshot of the currently
00039 /// connected devices as StorageFolders.  This is demonstrated in this scenario.
00040 /// The second way uses Windows.Devices.Enumeration and is demonstrated in the second scenario.
00041 /// Windows.Devices.Enumeration supports more advanced scenarios such as subscibing for device
00042 /// arrival, removal and updates. Refer to the DeviceEnumeration sample for details on
00043 /// Windows.Devices.Enumeration.
00044 /// </remarks>
00045 /// <param name="sender"></param>
00046 /// <param name="e"></param>
00047 void S1_ListStorages::ListStorages_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00048 {
00049     ScenarioOutput->Text = "";
00050
00051     // Find all storage devices using the known folder
00052     create_task(KnownFolders::RemovableDevices->GetFoldersAsync()).then([this] (IVectorView<StorageFolder^>^ removableStorages)
00053     {
00054         if (removableStorages->Size > 0)
00055         {
00056             // Display each storage device
00057             std::for_each(begin(removableStorages), end(removableStorages), [this](IStorageFolder^ storage)
00058             {
00059                 ScenarioOutput->Text += safe_cast<StorageFolder^>(storage)->DisplayName + "\n";
00060             });
00061         }
00062         else
00063         {
00064             rootPage->NotifyUser("No removable storages were found. Please attach a removable storage to the system (e.g. a camera or camera memory)", NotifyType::StatusMessage);
00065         }
00066     });
00067 }
Generated on Sat Nov 23 2024 16:08:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML images/C++/Constants.h Source File

  • XAML images

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"XAML Images Sample");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media Play To/C++/common/suspensionmanager.cpp Source File

  • Media Play To
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:36 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite vertical text/C++/FlowLayout.h Source File

  • DirectWrite vertical text

FlowLayout.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 // Contents:    Custom layout, demonstrating usage of shaping and glyph
00009 //              results.
00010 //
00011 //----------------------------------------------------------------------------
00012 #pragma once
00013
00014 #include "FlowSource.h"
00015 #include "FlowSink.h"
00016 #include "TextAnalysis.h"
00017 #include "DirectXBase.h"
00018
00019
00020 class DECLSPEC_UUID("E304E995-6157-48ec-8D44-ACB308A210D0") FlowLayout:
00021     public ComBase<QiListSelf<FlowLayout, QiList<IUnknown>>>
00022 {
00023     // This custom layout processes layout in two stages.
00024     //
00025     // 1. Analyze the text, given the current font and size
00026     //      a. Bidirectional analysis
00027     //      b. Script analysis
00028     //      c. Number substitution analysis
00029     //      d. Shape glyphs
00030     //      e. Intersect run results
00031     //
00032     // 2. Fill the text to the given shape
00033     //      a. Pull next rect from flow source
00034     //      b. Fit as much text as will go in
00035     //      c. Push text to flow sink
00036
00037 public:
00038     struct ClusterPosition
00039     {
00040         ClusterPosition():
00041             textPosition(),
00042             runIndex(),
00043             runEndPosition()
00044         {
00045         }
00046         UINT32 textPosition;    // Current text position
00047         UINT32 runIndex;        // Associated analysis run covering this position
00048         UINT32 runEndPosition;  // Text position where this run ends
00049     };
00050
00051     enum JustificationMode
00052     {
00053         JustificationModeNone,
00054         JustificationModeInterword,
00055     };
00056
00057 public:
00058     FlowLayout(Microsoft::WRL::ComPtr<IDWriteFactory> dwriteFactory)
00059     :   m_dwriteFactory(SafeAcquire(dwriteFactory.Get())),
00060         m_fontFace(),
00061         m_numberSubstitution(),
00062         m_readingDirection(ReadingDirectionLeftToRightTopToBottom),
00063         m_glyphOrientationMode(GlyphOrientationModeDefault),
00064         m_justificationMode(JustificationModeInterword),
00065         m_fontEmSize(12),
00066         m_maxSpaceWidth(8),
00067         m_isTextAnalysisComplete(false)
00068     {
00069     }
00070
00071     void SetTextFormat(Microsoft::WRL::ComPtr<IDWriteTextFormat> textFormat);
00072     void SetNumberSubstitution(Microsoft::WRL::ComPtr<IDWriteNumberSubstitution> numberSubstitution);
00073     void SetReadingDirection(ReadingDirection readingDirection);
00074     void SetGlyphOrientationMode(GlyphOrientationMode glyphOrientationMode);
00075     void SetJustificationMode(JustificationMode justificationMode);
00076     GlyphOrientationMode GetGlyphOrientationMode();
00077     ReadingDirection GetReadingDirection();
00078
00079     void SetText(
00080         const wchar_t* text,
00081         UINT32 textLength
00082         );
00083
00084     void GetText(
00085         _Out_ const wchar_t** text,
00086         _Out_ UINT32* textLength
00087         );
00088
00089     // Perform analysis on the current text, converting text to glyphs.
00090     void AnalyzeText();
00091
00092     // Reflow the text analysis into
00093     void FlowText(
00094         Microsoft::WRL::ComPtr<FlowLayoutSource> flowSource,
00095         Microsoft::WRL::ComPtr<FlowLayoutSink> flowSink
00096         );
00097
00098 protected:
00099     void ShapeGlyphRuns(Microsoft::WRL::ComPtr<IDWriteTextAnalyzer> textAnalyzer);
00100
00101     void ShapeGlyphRun(
00102         Microsoft::WRL::ComPtr<IDWriteTextAnalyzer> textAnalyzer,
00103         UINT32 runIndex,
00104         _Inout_ UINT32& glyphStart
00105         );
00106
00107     void ShapeSimpleGlyphRun(
00108         UINT32 runIndex,
00109         _Inout_ UINT32& glyphStart
00110         );
00111
00112     bool FitText(
00113         const ClusterPosition& clusterStart,
00114         UINT32 textEnd,
00115         float maxWidth,
00116         _Out_ ClusterPosition* clusterEnd
00117         );
00118
00119     bool ProduceGlyphRuns(
00120         Microsoft::WRL::ComPtr<FlowLayoutSink> flowSink,
00121         const FlowLayoutSource::RectF& rect,
00122         const ClusterPosition& clusterStart,
00123         const ClusterPosition& clusterEnd
00124         ) const;
00125
00126     void ProduceJustifiedAdvances(
00127         float maxWidth,
00128         const ClusterPosition& clusterStart,
00129         const ClusterPosition& clusterEnd,
00130         _Out_ std::vector<float>& justifiedAdvances
00131         ) const;
00132
00133     void ProduceBidiOrdering(
00134         UINT32 spanStart,
00135         UINT32 spanCount,
00136         _Out_writes_(spanCount) UINT32* spanIndices
00137         ) const;
00138
00139     void SetClusterPosition(
00140         _Inout_ ClusterPosition& cluster,
00141         UINT32 textPosition
00142         ) const;
00143
00144     void AdvanceClusterPosition(
00145         _Inout_ ClusterPosition& cluster
00146         ) const;
00147
00148     UINT32 GetClusterGlyphStart(
00149         const ClusterPosition& cluster
00150         ) const;
00151
00152     float GetClusterRangeWidth(
00153         const ClusterPosition& clusterStart,
00154         const ClusterPosition& clusterEnd
00155         ) const;
00156
00157     float GetClusterRangeWidth(
00158         UINT32 glyphStart,
00159         UINT32 glyphEnd,
00160         const float* glyphAdvances
00161         ) const;
00162
00163 protected:
00164     Microsoft::WRL::ComPtr<IDWriteFactory> m_dwriteFactory;
00165
00166     // Input information.
00167     std::wstring m_text;
00168     wchar_t m_localeName[LOCALE_NAME_MAX_LENGTH];
00169     ReadingDirection m_readingDirection;
00170     GlyphOrientationMode m_glyphOrientationMode;
00171     JustificationMode m_justificationMode;
00172     Microsoft::WRL::ComPtr<IDWriteFontFace> m_fontFace;
00173     Microsoft::WRL::ComPtr<IDWriteNumberSubstitution> m_numberSubstitution;
00174     float m_fontEmSize;
00175
00176     // Output text analysis results
00177     std::vector<TextAnalysis::Run> m_runs;
00178     std::vector<DWRITE_LINE_BREAKPOINT> m_breakpoints;
00179     std::vector<DWRITE_GLYPH_OFFSET> m_glyphOffsets;
00180     std::vector<UINT16> m_glyphClusters;
00181     std::vector<UINT16> m_glyphIndices;
00182     std::vector<float>  m_glyphAdvances;
00183
00184     float m_maxSpaceWidth;           // maximum stretch of space allowed for justification
00185     bool m_isTextAnalysisComplete;   // text analysis was done.
00186 };
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/ExceptionPolicyFactory.cpp Source File

  • Hilo C++
  • Hilo

ExceptionPolicyFactory.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 #include "ExceptionPolicyFactory.h"
00009 #include "DebugLoggingExceptionPolicy.h"
00010
00011 using namespace Hilo;
00012 using namespace std;
00013
00014 shared_ptr<ExceptionPolicy> ExceptionPolicyFactory::GetCurrentPolicy()
00015 {
00016     return std::make_shared<DebugLoggingExceptionPolicy>();
00017 }
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Contact Picker app/C++/Common/LayoutAwarePage.h Source File

  • Contact Picker app
  • Common

LayoutAwarePage.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 #include <collection.h>
00015
00016 namespace ContactPicker
00017 {
00018     namespace Common
00019     {
00020         /// <summary>
00021         /// Typical implementation of Page that provides several important conveniences: application
00022         /// view state to visual state mapping, GoBack and GoHome event handlers, and a default view
00023         /// model.
00024         /// </summary>
00025         [Windows::Foundation::Metadata::WebHostHidden]
00026         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00027         {
00028         internal:
00029             LayoutAwarePage();
00030
00031         public:
00032             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00033             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00034             void InvalidateVisualState();
00035             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00036             {
00037                 Windows::UI::Xaml::DependencyProperty^ get();
00038             };
00039             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Object^>^ DefaultViewModel
00040             {
00041                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Object^>^ get();
00042                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Object^>^ value);
00043             }
00044
00045         protected:
00046             virtual void GoHome(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             virtual void GoBack(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00049
00050         private:
00051             Platform::Collections::Map<Platform::String^, Object^>^ _defaultViewModel;
00052             Windows::Foundation::EventRegistrationToken _windowSizeEventToken;
00053             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00054             void WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00055         };
00056     }
00057 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D interpolation modes/C++/BasicTimer.h Source File

  • Direct2D interpolation modes

BasicTimer.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 timer class used to drive the render loop of the actively-animated
00011 // DirectX SDK samples. Uses the QueryPerformanceCounter function to retrieve
00012 // high-resolution timing information.
00013 ref class BasicTimer
00014 {
00015 private:
00016     LARGE_INTEGER m_frequency;
00017     LARGE_INTEGER m_currentTime;
00018     LARGE_INTEGER m_startTime;
00019     LARGE_INTEGER m_lastTime;
00020     float m_total;
00021     float m_delta;
00022
00023 internal:
00024     BasicTimer();
00025     void Reset();
00026     void Update();
00027     property float Total
00028     {
00029         float get();
00030     }
00031     property float Delta
00032     {
00033         float get();
00034     }
00035 };
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML accessibility/C++/common/suspensionmanager.cpp Source File

  • XAML accessibility
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML user and custom controls/C++/common/suspensionmanager.h Source File

  • XAML user and custom controls
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Reading and writing data/C++/ReadBytes.xaml.cpp Source File

  • Reading and writing data

ReadBytes.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 // ReadBytes.xaml.cpp
00013 // Implementation of the ReadBytes class
00014 //
00015
00016 #include "pch.h"
00017 #include "ReadBytes.xaml.h"
00018
00019 using namespace SDKSample::DataReaderWriter;
00020
00021 using namespace concurrency;
00022 using namespace Platform;
00023 using namespace Windows::Foundation;
00024 using namespace Windows::Storage;
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::Navigation;
00029
00030 ReadBytes::ReadBytes()
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 void ReadBytes::OnNavigatedTo(NavigationEventArgs^ e)
00041 {
00042     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00043     // as NotifyUser()
00044     rootPage = MainPage::Current;
00045 }
00046
00047 /// <summary>
00048 /// This is the click handler for the 'Hex Dump' button.  Open the image file we want to
00049 /// perform a hex dump on.  Then open a sequential-access stream over the file and use
00050 /// ReadBytes() to extract the binary data.  Finally, convert each byte to hexadecimal, and
00051 /// display the formatted output in the HexDump textblock.
00052 /// </summary>
00053 /// <param name="sender">Contains information about the button that fired the event.</param>
00054 /// <param name="e">Contains state information and event data associated with a routed event.</param>
00055 void ReadBytes::HexDump(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00056 {
00057     // Retrieve the uri of the image and use that to load the file.
00058     Uri^ uri = ref new Uri("ms-appx:///assets/110Strawberry.png");
00059     create_task(StorageFile::GetFileFromApplicationUriAsync(uri)).then([] (StorageFile^ file)
00060     {
00061         // Open a sequential-access stream over the image file.
00062         return file->OpenSequentialReadAsync();
00063     }).then(
00064         // Since this is the last task in the chain, use task<IInputStream ^> instead of IInputStream ^
00065         // as the parameter here in order to handle any exceptions which might have been thrown in
00066         // the previous async calls.
00067         [=] (task<IInputStream ^> inputStream)
00068     {
00069         try
00070         {
00071             currChunk = 0;
00072             ReadBytesOutput->Text = "";
00073
00074             // Use inputStream.get() to pass the input stream returned by OpenSequentialReadAsync() to the
00075             // DataReader, or to catch any exceptions that might have arisen in the chained async calls.
00076             DataReader^ dataReader = ref new DataReader(inputStream.get());
00077
00078             // Read and process the data contained in the input stream.
00079             ReadLoop(dataReader);
00080         }
00081         catch (Exception^ e)
00082         {
00083             ReadBytesOutput->Text = e->Message;
00084         }
00085     });
00086 }
00087
00088 /// <summary>
00089 /// The read loop recursively loads a chunk of bytes from the stream into the DataReader
00090 /// buffer until all elements are read.  After each load, ReadBytes() retrieves and
00091 /// formats one row worth of bytes at a time.
00092 /// </summary>
00093 /// <param name="dataReader">The DataReader which will retrieve the data from the stream.</param>
00094 void ReadBytes::ReadLoop(DataReader^ dataReader)
00095 {
00096     create_task(dataReader->LoadAsync(chunkSize)).then(
00097         // Again, use task<unsigned int> instead of unsigned int as the parameter here in order to
00098         // handle any exceptions which might have been thrown in the LoadAsync() call.
00099         [=] (task<unsigned int> bytesLoaded)
00100     {
00101         try
00102         {
00103             // Use bytesLoaded.get() to determine how many bytes we have left to print, or
00104             // to catch any exceptions that might have arisen in the LoadAsync() call.
00105             int numBytes = bytesLoaded.get();
00106
00107             // Create a byte array which can hold enough bytes to populate a row of the hex dump.
00108             auto bytes = ref new Array<byte>(bytesPerRow);
00109
00110             // Read and print one row at a time.
00111             int numBytesRemaining = numBytes;
00112             while (numBytesRemaining >= bytesPerRow)
00113             {
00114                 // Use the DataReader and ReadBytes() to fill the byte array with one row worth of bytes.
00115                 dataReader->ReadBytes(bytes);
00116
00117                 PrintRow(bytes, (numBytes - numBytesRemaining) + (currChunk * chunkSize));
00118
00119                 numBytesRemaining -= bytesPerRow;
00120             }
00121
00122             // If there are any bytes remaining to be read, allocate a new array that will hold
00123             // the remaining bytes read from the DataReader and print the final row.
00124             // Note: ReadBytes() fills the entire array so if the array being passed in is larger
00125             // than what's remaining in the DataReader buffer, an exception will be thrown.
00126             if (numBytesRemaining > 0)
00127             {
00128                 bytes = ref new Array<byte>(numBytesRemaining);
00129
00130                 // Use the DataReader and ReadBytes() to fill the byte array with the last row worth of bytes.
00131                  dataReader->ReadBytes(bytes);
00132
00133                 PrintRow(bytes, (numBytes - numBytesRemaining) + (currChunk * chunkSize));
00134             }
00135
00136             currChunk++;
00137
00138             // If the number of bytes read is anything but the chunk size, then we've just retrieved the last
00139             // chunk of data from the stream.  Otherwise, keep loading data into the DataReader buffer.
00140             if (numBytes == chunkSize)
00141             {
00142                 ReadLoop(dataReader);
00143             }
00144         }
00145         catch (Exception^ e)
00146         {
00147             ReadBytesOutput->Text = e->Message;
00148         }
00149     });
00150 }
00151
00152 /// <summary>
00153 /// Format and print a row of the hex dump using the data retrieved by ReadBytes().
00154 /// </summary>
00155 /// <param name="bytes">An array that holds the data we want to format and output.</param>
00156 /// <param name="currByte">The first byte of the current row to compute the value of the address.</param>
00157 void ReadBytes::PrintRow(Array<byte>^ bytes, int currByte)
00158 {
00159     String^ rowStr = "";
00160
00161     // Add the address of the current byte to the output string.
00162     rowStr += GetAddress(currByte);
00163
00164     // Format the output:
00165     for (unsigned int i = 0; i < bytes->Length; i++)
00166     {
00167         // If finished with a segment, add a space.
00168         if (i % bytesPerSegment == 0)
00169         {
00170             rowStr += " ";
00171         }
00172
00173         // Convert the current byte value to hex and add it to the output string.
00174         rowStr += ToHex(bytes[i]);
00175     }
00176
00177     // Append the current row to the HexDump textblock.
00178     ReadBytesOutput->Text += rowStr + "\n";
00179 }
00180
00181 /// <summary>
00182 /// Format the address of the current byte by converting currByte to hexadecimal and then
00183 //  left-padding the string with zeroes so that the address always has 8 digits.
00184 /// </summary>
00185 /// <param name="currByte">Value to be formatted into an address.</param>
00186 /// <returns>The formatted address represnted as a Platform::String ^.</returns>
00187 String^ ReadBytes::GetAddress(int currByte)
00188 {
00189     // 8 digits for the address plus '\0'
00190     int const arraySize = 9;
00191
00192     wchar_t address[arraySize] = { 0 };
00193
00194     // Convert to hex.
00195     swprintf_s(address, arraySize, L"%08x", currByte);
00196
00197     return ref new String(address);
00198 }
00199
00200 /// <summary>
00201 /// Convert the byte value to hexadecimal and return the result.
00202 /// </summary>
00203 /// <param name="value">Value to be converted to hexadecimal.</param>
00204 /// <returns>The formatted hex value represnted as a Platform::String ^.</returns>
00205 String^ ReadBytes::ToHex(byte value)
00206 {
00207     // 2 digits for the value plus '\0'
00208     int const arraySize = 3;
00209
00210     wchar_t hexValue[arraySize] = { 0 };
00211
00212     // Convert to hex.
00213     swprintf_s(hexValue, arraySize, L"%02x", (int) value);
00214
00215     return ref new String(hexValue);
00216 }
Generated on Sat Nov 23 2024 16:08:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Compression/C++/common/LayoutAwarePage.cpp Source File

  • Compression
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:30 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Clipboard::Common::LayoutAwarePage Member List

This is the complete list of members for Clipboard::Common::LayoutAwarePage, including all inherited members.
__pad0__ | Clipboard::Common::LayoutAwarePage |
_defaultViewModel | Clipboard::Common::LayoutAwarePage | [private]
_layoutAwareControls | Clipboard::Common::LayoutAwarePage | [private]
_windowSizeEventToken | Clipboard::Common::LayoutAwarePage | [private]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | Clipboard::Common::LayoutAwarePage | [virtual]
GoBack(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Clipboard::Common::LayoutAwarePage | [virtual]
InvalidateVisualState() | Clipboard::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Clipboard::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Clipboard::Common::LayoutAwarePage |
WindowSizeChanged(Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | Clipboard::Common::LayoutAwarePage | [private]
Generated on Sat Nov 23 2024 16:09:36 for Win8-Examples by doxygen 1.7.1


Win8-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.
__pad0__ | Resource |
AcceptChildNode(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^childXmlNode) | Element | [virtual]
AddChild(_In_ Element^element) | Element |
AddSibling(_In_ Element^element) | Element |
BindResource(_In_ Element^rootElement) | Element | [virtual]
Create(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^xmlNode) | Element | [static]
Draw(_In_ Document^document, D2D1::Matrix3x2F const &transform) override | Resource | [virtual]
GetFirstChild() | Element | [inline]
GetName() | Element | [inline]
GetNextSibling() | Element | [inline]
GetOpacity() | Element | [inline, virtual]
GetParent() | Element | [inline]
GetSize() | Element | [inline]
Initialize(_In_ Document^document, _In_ Windows::Data::Xml::Dom::XmlElement^xmlElement) | Element | [virtual]
Measure(_In_ Document^document, D2D1_SIZE_F const &parentSize, _Out_ D2D1_RECT_F *bounds) override | Resource | [virtual]
override | Resource |
PrepareToDraw(_In_ Document^document, D2D1::Matrix3x2F const &transform) override | Resource | [virtual]
ReleaseParent() | Element | [virtual]
Generated on Sat Nov 23 2024 16:09:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Custom driver access/C#,C++/DLL/support.h Source File

  • Custom driver access
  • C#,C++
  • DLL

support.h

Go to the documentation of this file.
00001 #include <strsafe.h>
00002 #include <assert.h>
00003
00004 #pragma once
00005
00006 ///<summary>
00007 ///Printf to the debugger
00008 ///</summary>
00009 inline void DbgPrint(PCWSTR FormatString, ...) {
00010   WCHAR buffer[1024];
00011   static ULONG line = 0;
00012   va_list arglist;
00013   va_start(arglist, FormatString);
00014
00015   StringCbPrintf(buffer, sizeof(buffer), L"%03d:", line++);
00016   OutputDebugString(buffer);
00017
00018   StringCbVPrintf(buffer, sizeof(buffer), FormatString, arglist);
00019   OutputDebugString(buffer);
00020 }
00021
00022 namespace Samples {
00023     namespace Devices {
00024
00025         [uuid("999BAD24-9ACD-45BB-8669-2A2FC0288B04")]
00026         delegate void OnIoComplete(HRESULT Result, DWORD BytesReturned);
00027
00028         ///<summary>wrapper class for the result of an IOCTL</summary>
00029         struct DeviceControlResult {
00030             HRESULT Result;
00031             ULONG BytesTransferred;
00032
00033             DeviceControlResult() : Result(E_NOT_SET),
00034                                     BytesTransferred(0)
00035             {
00036                 return;
00037             }
00038
00039             DeviceControlResult(HRESULT Hr, DWORD Cb) : Result(Hr),
00040                                                         BytesTransferred(Cb)
00041             {
00042                 return;
00043             }
00044         };
00045
00046     ///<summary>
00047     ///Starts the requested IOCTL
00048     ///</summary>
00049     ///<returns>returns a task which will complete when the IOCTL completes</returns>
00050         inline
00051         concurrency::task<DeviceControlResult>
00052         StartIoctl(
00053             _In_ IDeviceIoControl* Device,
00054             _In_ ULONG DeviceControlCode,
00055             _In_reads_bytes_opt_(InputBufferCb) PUCHAR InputBuffer,
00056             _In_ ULONG InputBufferCb,
00057             _Out_writes_bytes_opt_(OutputBufferCb) PUCHAR OutputBuffer,
00058             _In_ ULONG OutputBufferCb,
00059             _Out_opt_ ULONG_PTR* CancelToken = NULL
00060             )
00061         {
00062             concurrency::task_completion_event<DeviceControlResult> tce;
00063             concurrency::task<DeviceControlResult> t(tce);
00064
00065             auto callback = ref new OnIoComplete(
00066                 [tce](HRESULT Hr, DWORD Cb) {
00067                     tce.set(DeviceControlResult(Hr, Cb));
00068                 }
00069             );
00070
00071             auto cb2 = (IDeviceRequestCompletionCallback*) callback;
00072
00073             HRESULT hr= Device->DeviceIoControlAsync(
00074                                     DeviceControlCode,
00075                                     InputBuffer,
00076                                     InputBufferCb,
00077                                     OutputBuffer,
00078                                     OutputBufferCb,
00079                                     cb2,
00080                                     CancelToken
00081                                     );
00082
00083             if (hr != S_OK) {
00084                 tce.set(DeviceControlResult(hr, 0));
00085             }
00086
00087             return t;
00088         }
00089     }
00090 }
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML images/C++/Scenario2.xaml.cpp Source File

  • XAML images

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 <ppltasks.h>
00019 #include <stdio.h>
00020 #include <stdlib.h>
00021
00022 using namespace SDKSample::Images;
00023
00024 using namespace std;
00025 using namespace concurrency;
00026 using namespace Platform;
00027 using namespace Windows::UI::Xaml;
00028 using namespace Windows::UI::Xaml::Controls;
00029 using namespace Windows::UI::Xaml::Navigation;
00030 using namespace Windows::Storage::Pickers;
00031 using namespace Windows::Storage;
00032 using namespace Windows::Storage::Streams;
00033 using namespace Windows::UI::Xaml::Media::Imaging;
00034
00035 Scenario2::Scenario2()
00036 {
00037     InitializeComponent();
00038   Scenario2Button1->Click += ref new RoutedEventHandler(this, &Scenario2::Scenario2Button1_Click);
00039   Scenario2DecodePixelHeight->Text = "100";
00040   Scenario2DecodePixelWidth->Text = "100";
00041 }
00042
00043 // Invoked when this page is about to be displayed in a Frame.
00044
00045 void Scenario2::OnNavigatedTo(NavigationEventArgs^ e)
00046 {
00047     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00048     // as NotifyUser()
00049     rootPage = MainPage::Current;
00050 }
00051
00052 void SDKSample::Images::Scenario2::Scenario2Button1_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00053 {
00054
00055   // Try to parse an integer from the given text. If invalid, default to 100px
00056   auto str = Scenario2DecodePixelHeight->Text;
00057   decodePixelHeight = stoi(str->Data());
00058
00059   if (decodePixelHeight == 0)
00060   {
00061       Scenario2DecodePixelHeight->Text = "100";
00062       decodePixelHeight = 100;
00063   }
00064
00065   // Try to parse an integer from the given text. If invalid, default to 100px
00066   auto str2 = Scenario2DecodePixelWidth->Text;
00067   decodePixelWidth = stoi(str2->Data());
00068
00069   if (decodePixelWidth == 0)
00070   {
00071       Scenario2DecodePixelWidth->Text = "100";
00072       decodePixelWidth = 100;
00073   }
00074
00075   //  Initialize file picker
00076   auto open = ref new FileOpenPicker();
00077   open->SuggestedStartLocation = PickerLocationId::PicturesLibrary;
00078   open->ViewMode = PickerViewMode::Thumbnail;
00079
00080   // Filter to include a sample subset of file types
00081   open->FileTypeFilter->Clear();
00082   open->FileTypeFilter->Append(".bmp");
00083   open->FileTypeFilter->Append(".png");
00084   open->FileTypeFilter->Append(".jpeg");
00085   open->FileTypeFilter->Append(".jpg");
00086
00087
00088   // Open a stream for the selected file
00089   create_task(open->PickSingleFileAsync()).then([this](StorageFile^ file)
00090   {
00091       if (file)
00092       {
00093       // Ensure the stream is disposed once the image is loaded
00094       create_task(file->OpenAsync(Windows::Storage::FileAccessMode::Read)).then([this](IRandomAccessStream^ fileStream)
00095       {
00096          // Set the image source to the selected bitmap
00097          auto bitmapImage = ref new BitmapImage();
00098          bitmapImage->DecodePixelHeight = decodePixelHeight;
00099          bitmapImage->DecodePixelWidth = decodePixelWidth;
00100
00101          bitmapImage->SetSource(fileStream);
00102          Scenario2Image->Source = bitmapImage;
00103       });
00104
00105       }
00106   });
00107 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Language font mapping/C++/ScenarioOutput2.xaml.cpp Source File

  • Language font mapping

ScenarioOutput2.xaml.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 //
00009 // Scenario2Output.xaml.cpp
00010 // Implementation of the Scenario2Output class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioOutput2.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace LanguageFontCPP;
00018
00019 using namespace Platform;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Graphics::Display;
00023 using namespace Windows::UI::ViewManagement;
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 ScenarioOutput2::ScenarioOutput2()
00033 {
00034     InitializeComponent();
00035 }
00036
00037 ScenarioOutput2::~ScenarioOutput2()
00038 {
00039 }
00040
00041 #pragma region Template-Related Code - Do not remove
00042 void ScenarioOutput2::OnNavigatedTo(NavigationEventArgs^ e)
00043 {
00044     // Get a pointer to our main page.
00045     rootPage = dynamic_cast<MainPage^>(e->Parameter);
00046
00047     // We want to be notified with the OutputFrame is loaded so we can get to the content.
00048     _frameLoadedToken = rootPage->InputFrameLoaded += ref new Windows::Foundation::EventHandler<Platform::Object^>(this, &ScenarioOutput2::rootPage_InputFrameLoaded);
00049 }
00050
00051 void ScenarioOutput2::OnNavigatedFrom(NavigationEventArgs^ e)
00052 {
00053     rootPage->InputFrameLoaded -= _frameLoadedToken;
00054 }
00055
00056 #pragma endregion
00057
00058 #pragma region Use this code if you need access to elements in the input frame - otherwise deletea
00059 void ScenarioOutput2::rootPage_InputFrameLoaded(Object^ sender, Object^ e)
00060 {
00061     // Get a pointer to the content within the OutputFrame.
00062     Page^ inputFrame = dynamic_cast<Page^>(rootPage->InputFrame->Content);
00063
00064     // Go find the elements that we need for this scenario
00065     // ex: flipView1 = dynamic_cast<FlipView^>(inputFrame->FindName("FlipView1"));
00066 }
00067
00068 #pragma endregion
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: StreamSocket/C++/Scenario1.xaml.cpp Source File

  • StreamSocket

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 StreamSocketSample;
00020
00021 using namespace Concurrency;
00022 using namespace Platform;
00023 using namespace Windows::ApplicationModel::Core;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Networking::Sockets;
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 Scenario1::Scenario1()
00032 {
00033     InitializeComponent();
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 Scenario1::OnNavigatedTo(NavigationEventArgs^ e)
00042 {
00043     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00044     // as NotifyUser()
00045     rootPage = MainPage::Current;
00046 }
00047
00048 void Scenario1::StartListener_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00049 {
00050     // Overriding the listener here is safe as it will be deleted once all references to it are gone. However, in many cases this
00051     // is a dangerous pattern to override data semi-randomly (each time user clicked the button) so we block it here.
00052     if (CoreApplication::Properties->HasKey("listener"))
00053     {
00054         rootPage->NotifyUser("This step has already been executed. Please move to the next one.", NotifyType::ErrorMessage);
00055         return;
00056     }
00057
00058     if (ServiceNameForListener->Text == nullptr)
00059     {
00060         rootPage->NotifyUser("Please provide a service name.", NotifyType::ErrorMessage);
00061         return;
00062     }
00063
00064     StreamSocketListener^ listener = ref new StreamSocketListener();
00065     ListenerContext^ listenerContext = ref new ListenerContext(rootPage, listener);
00066     listener->ConnectionReceived += ref new TypedEventHandler<StreamSocketListener^, StreamSocketListenerConnectionReceivedEventArgs^>(listenerContext, &ListenerContext::OnConnection);
00067
00068     // Events cannot be hooked up directly to the ScenarioInput1 object, as the object can fall out-of-scope and be deleted. This would render
00069     // any event hooked up to the object ineffective. The ListenerContext guarantees that both the listener and object that serves it's events have the same life time.
00070     CoreApplication::Properties->Insert("listener", listenerContext);
00071
00072     // Start listen operation.
00073     task<void>(listener->BindServiceNameAsync(ServiceNameForListener->Text)).then([this] (task<void> previousTask)
00074     {
00075         try
00076         {
00077             // Try getting all exceptions from the continuation chain above this point.
00078             previousTask.get();
00079             rootPage->NotifyUser("Listening", NotifyType::StatusMessage);
00080         }
00081         catch (Exception^ exception)
00082         {
00083             CoreApplication::Properties->Remove("listener");
00084             rootPage->NotifyUser("Start listening failed with error: " + exception->Message, NotifyType::ErrorMessage);
00085         }
00086     });
00087 }
00088
00089 ListenerContext::ListenerContext(MainPage^ rootPage, StreamSocketListener^ listener)
00090 {
00091     this->rootPage = rootPage;
00092     this->listener = listener;
00093 }
00094
00095 ListenerContext::~ListenerContext()
00096 {
00097     // The listener can be closed in two ways:
00098     //  - explicit: by using delete operator (the listener is closed even if there are outstanding references to it).
00099     //  - implicit: by removing last reference to it (i.e. falling out-of-scope).
00100     // In this case this is the last reference to the listener so both will yield the same result.
00101     delete listener;
00102     listener = nullptr;
00103 }
00104
00105 void ListenerContext::OnConnection(StreamSocketListener^ listener, StreamSocketListenerConnectionReceivedEventArgs^ object)
00106 {
00107     DataReader^ reader = ref new DataReader(object->Socket->InputStream);
00108
00109     // Start a receive loop.
00110     ReceiveStringLoop(reader, object->Socket);
00111 }
00112
00113 void ListenerContext::ReceiveStringLoop(DataReader^ reader, StreamSocket^ socket)
00114 {
00115     // Read first 4 bytes (length of the subsequent string).
00116     task<unsigned int>(reader->LoadAsync(sizeof(UINT32))).then([this, reader, socket] (unsigned int size)
00117     {
00118         if (size < sizeof(UINT32))
00119         {
00120             // The underlying socket was closed before we were able to read the whole data.
00121             cancel_current_task();
00122         }
00123
00124         unsigned int stringLength = reader->ReadUInt32();
00125         return task<unsigned int>(reader->LoadAsync(stringLength)).then([this, reader, stringLength] (unsigned int actualStringLength)
00126         {
00127             if (actualStringLength != stringLength)
00128             {
00129                 // The underlying socket was closed before we were able to read the whole data.
00130                 cancel_current_task();
00131             }
00132
00133             // Display the string on the screen. This thread is invoked on non-UI thread, so we need to marshal the call back to the UI thread.
00134             NotifyUserFromAsyncThread("Received data: \"" + reader->ReadString(actualStringLength) + "\"", NotifyType::StatusMessage);
00135         });
00136     }).then([this, reader, socket] (task<void> previousTask)
00137     {
00138         try
00139         {
00140             // Try getting all exceptions from the continuation chain above this point.
00141             previousTask.get();
00142
00143             // Everything went ok, so try to receive another string. The receive will continue until the stream is broken (i.e. peer closed closed the socket).
00144             ReceiveStringLoop(reader, socket);
00145         }
00146         catch (Exception^ exception)
00147         {
00148             NotifyUserFromAsyncThread("Read stream failed with error: " + exception->Message, NotifyType::ErrorMessage);
00149
00150             // Explicitly close the socket.
00151             delete socket;
00152         }
00153         catch (task_canceled&)
00154         {
00155             // Do not print anything here - this will usually happen because user closed the client socket.
00156
00157             // Explicitly close the socket.
00158             delete socket;
00159         }
00160     });
00161 }
00162
00163 void ListenerContext::NotifyUserFromAsyncThread(String^ message, NotifyType type)
00164 {
00165     rootPage->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, message, type] ()
00166     {
00167         rootPage->NotifyUser(message, type);
00168     }));
00169 }
Generated on Sat Nov 23 2024 16:07:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Transcoding media/C++/pch.cpp Source File

  • Transcoding media

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D bump mapping/C++/BasicShapes.h Source File

  • Direct3D bump mapping

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 Sat Nov 23 2024 16:08:10 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text editing/C++/pch.cpp Source File

  • XAML text editing

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::WebAuthentication::sealed Member List

This is the complete list of members for SDKSample::WebAuthentication::sealed, including all inherited members.
Launch_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::WebAuthentication::sealed | [private]
Launch_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::WebAuthentication::sealed | [private]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::WebAuthentication::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::WebAuthentication::sealed | [protected, virtual]
rootPage | SDKSample::WebAuthentication::sealed | [private]
Scenario1() | SDKSample::WebAuthentication::sealed |
Scenario2() | SDKSample::WebAuthentication::sealed |
Generated on Sat Nov 23 2024 16:09:53 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Connecting with WebSockets/C++/common/suspensionmanager.h Source File

  • Connecting with WebSockets
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Custom driver access/C++/app_cpp/DeviceList.h Source File

  • Custom driver access
  • app_cpp

DeviceList.h

Go to the documentation of this file.
00001 namespace SDKSample
00002 {
00003     namespace CustomDeviceAccess {
00004
00005         [Windows::UI::Xaml::Data::Bindable]
00006         public ref class DeviceListEntry sealed
00007         {
00008
00009             Windows::Devices::Enumeration::DeviceInformation^ m_Device;
00010
00011         public:
00012
00013             property Platform::String^ InstanceId {
00014                 Platform::String^ get(void) {
00015                     return safe_cast<Platform::String^>(m_Device->Properties->Lookup("System.Devices.DeviceInstanceId"));
00016                 }
00017             }
00018
00019             property Platform::String^ Id {
00020                 Platform::String^ get(void) {
00021                     return m_Device->Id;
00022                 }
00023             }
00024
00025             property bool Matched;
00026
00027             DeviceListEntry(Windows::Devices::Enumeration::DeviceInformation^ DeviceInterface) {
00028                 m_Device = DeviceInterface;
00029                 Matched = true;
00030             }
00031         };
00032
00033         typedef Windows::Foundation::EventHandler<Samples::Devices::Fx2::Fx2Device^> DeviceClosingHandler;
00034
00035         ref class DeviceList
00036         {
00037         public:
00038             static property DeviceList^ Current {DeviceList^ get();};
00039
00040             property Windows::Foundation::Collections::IObservableVector<DeviceListEntry^>^ Fx2Devices {
00041                 Windows::Foundation::Collections::IObservableVector<DeviceListEntry^>^ get(void){
00042                     return m_List;
00043                 }
00044             };
00045
00046             property Samples::Devices::Fx2::Fx2Device^ Fx2Device {
00047                 Samples::Devices::Fx2::Fx2Device^ get(){
00048                     return m_Fx2Device;
00049                 }
00050                 void set(Samples::Devices::Fx2::Fx2Device^ value){
00051                     if (m_Fx2Device != nullptr)
00052                     {
00053                         DeviceClosing(this, m_Fx2Device);
00054                     }
00055                     m_Fx2Device = value;
00056                 }
00057             };
00058
00059             property bool WatcherStarted {
00060                 bool get(void) {
00061                     return m_WatcherStarted;
00062                 }
00063                 void set(bool value) {
00064                     m_WatcherStarted = value;
00065                 }
00066             };
00067
00068             void StartFx2Watcher();
00069
00070             void StopFx2Watcher();
00071
00072             static void CreateBooleanTable(
00073                 Windows::UI::Xaml::Documents::InlineCollection^ Table,
00074                 const Platform::Array<bool>^ NewValues,
00075                 const Platform::Array<bool>^ OldValues,
00076                 Platform::String^ IndexTitle,
00077                 Platform::String^ ValueTitle,
00078                 Platform::String^ TrueValue,
00079                 Platform::String^ FalseValue
00080                 );
00081
00082             event DeviceClosingHandler^ DeviceClosing;
00083
00084         private:
00085             static DeviceList^ _Current;
00086             Windows::Devices::Enumeration::DeviceWatcher^ m_Fx2Watcher;
00087             Platform::Collections::Vector<DeviceListEntry^>^ m_List;
00088             Samples::Devices::Fx2::Fx2Device^ m_Fx2Device;
00089             bool m_WatcherSuspended;
00090             bool m_WatcherStarted;
00091
00092             DeviceList();
00093
00094             DeviceListEntry^ FindDevice(Platform::String^ Id);
00095
00096             void InitDeviceWatcher();
00097
00098             void SuspendDeviceWatcher(Object^ Sender, Windows::ApplicationModel::SuspendingEventArgs^ Args);
00099             void ResumeDeviceWatcher(Object^ Sender, Object^ Args);
00100
00101             void OnFx2Added(Windows::Devices::Enumeration::DeviceWatcher^ Sender, Windows::Devices::Enumeration::DeviceInformation^ DevInformation);
00102             void OnFx2Removed(Windows::Devices::Enumeration::DeviceWatcher^ Sender, Windows::Devices::Enumeration::DeviceInformationUpdate^ DevInformation);
00103             void OnFx2EnumerationComplete(Windows::Devices::Enumeration::DeviceWatcher^ Sender, Object^ Args);
00104         };
00105
00106     }
00107 }
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAudio2 audio stream effect/C++/pch.h Source File

  • XAudio2 audio stream effect

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 <d3d11_1.h>
00012 #include <d2d1_1.h>
00013 #include <d2d1effects.h>
00014 #include <dwrite_1.h>
00015 #include <wincodec.h>
00016 #include <agile.h>
00017 #include "BasicMath.h"
00018 #include <vector>
00019 #include "strsafe.h"
00020 #include <xaudio2.h>
00021 #include <xaudio2fx.h>
00022 #include <memory>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

MediaExtensionsCS::ScenarioList Member List

This is the complete list of members for MediaExtensionsCS::ScenarioList, including all inherited members.
__pad0__ | Element |
AcceptChildNode(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^childXmlNode) override | Page | [virtual]
AddChild(_In_ Element^element) | Element |
AddSibling(_In_ Element^element) | Element |
BindResource(_In_ Element^rootElement) | Element | [virtual]
Create(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^xmlNode) | Element | [static]
Draw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
GetFirstChild() | Element | [inline]
GetName() | Element | [inline]
GetNextSibling() | Element | [inline]
GetOpacity() | Element | [inline, virtual]
GetParent() | Element | [inline]
GetSize() | Element | [inline]
Initialize(_In_ Document^document, _In_ Windows::Data::Xml::Dom::XmlElement^xmlElement) | Element | [virtual]
Measure(_In_ Document^document, D2D1_SIZE_F const &parentSize, _Out_ D2D1_RECT_F *bounds) | Element | [virtual]
OnNavigatedTo(NavigationEventArgs e) | MediaExtensionsCS::ScenarioList | [inline, protected]
PrepareToDraw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
ReleaseParent() | Element | [virtual]
rootPage | MediaExtensionsCS::ScenarioList | [private]
ScenarioList() | MediaExtensionsCS::ScenarioList | [inline]
Scenarios_SelectionChanged(object sender, SelectionChangedEventArgs e) | MediaExtensionsCS::ScenarioList | [inline, private]
Generated on Sat Nov 23 2024 16:09:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Toast notifications/C#,C++/ScenarioOutput1.xaml.cpp Source File

  • Toast notifications
  • C#,C++

ScenarioOutput1.xaml.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 //
00009 // Scenario1Output.xaml.cpp
00010 // Implementation of the Scenario1Output class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioOutput1.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace ToastsSampleCPP;
00018
00019 using namespace Platform;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Graphics::Display;
00023 using namespace Windows::UI::ViewManagement;
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 ScenarioOutput1::ScenarioOutput1()
00033 {
00034     InitializeComponent();
00035 }
00036
00037 ScenarioOutput1::~ScenarioOutput1()
00038 {
00039 }
00040
00041 #pragma region Template-Related Code - Do not remove
00042 void ScenarioOutput1::OnNavigatedTo(NavigationEventArgs^ e)
00043 {
00044   // Get a pointer to our main page.
00045   rootPage = dynamic_cast<MainPage^>(e->Parameter);
00046
00047   // We want to be notified with the OutputFrame is loaded so we can get to the content.
00048   _frameLoadedToken = rootPage->InputFrameLoaded += ref new Windows::Foundation::EventHandler<Platform::Object^>(this, &ScenarioOutput1::rootPage_InputFrameLoaded);
00049 }
00050
00051 void ScenarioOutput1::OnNavigatedFrom(NavigationEventArgs^ e)
00052 {
00053     rootPage->OutputFrameLoaded -= _frameLoadedToken;
00054 }
00055
00056 #pragma endregion
00057
00058 #pragma region Use this code if you need access to elements in the input frame - otherwise delete
00059 void ScenarioOutput1::rootPage_InputFrameLoaded(Object^ sender, Object^ e)
00060 {
00061     // Get a pointer to the content within the OutputFrame.
00062     Page^ inputFrame = dynamic_cast<Page^>(rootPage->InputFrame->Content);
00063
00064     // Go find the elements that we need for this scenario
00065     // ex: flipView1 = dynamic_cast<FlipView^>(inputFrame->FindName("FlipView1"));
00066 }
00067
00068 #pragma endregion
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DirectX::BC4_UNORM Member List

This is the complete list of members for DirectX::BC4_UNORM, including all inherited members.
data | DirectX::BC4_UNORM |
DecodeFromIndex(size_t uIndex) const | DirectX::BC4_UNORM | [inline]
GetIndex(size_t uOffset) const | DirectX::BC4_UNORM | [inline]
indices | DirectX::BC4_UNORM |
R(size_t uOffset) const | DirectX::BC4_UNORM | [inline]
red_0 | DirectX::BC4_UNORM |
red_1 | DirectX::BC4_UNORM |
SetIndex(size_t uOffset, size_t uIndex) | DirectX::BC4_UNORM | [inline]
Generated on Sat Nov 23 2024 16:09:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML data binding/C++/Scenario5.xaml.h Source File

  • XAML data binding

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 SDKSample
00023 {
00024     namespace DataBinding
00025     {
00026         /// <summary>
00027         /// An empty page that can be used on its own or navigated to within a Frame.
00028         /// </summary>
00029         public ref class Scenario5 sealed
00030         {
00031         public:
00032             Scenario5();
00033
00034         private:
00035             MainPage^ rootPage;
00036             void Scenario5Reset(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00037
00038         };
00039     }
00040 }
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKMESH_FRAME Member List

This is the complete list of members for SDKMESH_FRAME, including all inherited members.
AnimationDataIndex | SDKMESH_FRAME
ChildFrame | SDKMESH_FRAME
Matrix | SDKMESH_FRAME
Mesh | SDKMESH_FRAME
Name | SDKMESH_FRAME
ParentFrame | SDKMESH_FRAME
SiblingFrame | SDKMESH_FRAME
Generated on Sat Nov 23 2024 16:09:21 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Credential locker/C++/Scenario2.xaml.cpp Source File

  • Credential locker

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 SDKSample::PasswordVaultCPP;
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::Security::Credentials;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
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
00046 void DebugPrint2(Page^ rootPage, Platform::String^ Trace)
00047 {
00048     Page^ outputFrame = (Page^) rootPage;
00049     TextBox^ ErrorMessage = (TextBox^) outputFrame->FindName("ErrorMessage");
00050     ErrorMessage->Text += Trace + "\r\n";
00051  }
00052
00053 void CleanCombobox(Page^ rootPage)
00054 {
00055   Page^ inputFrame = (Page^) rootPage;
00056   ComboBox^ SelectUser = (ComboBox^) inputFrame->FindName("SelectUser");
00057   try
00058     {
00059     SelectUser->SelectedIndex= -1;
00060     SelectUser->ItemsSource = ref new Vector<String ^>();
00061   }
00062     catch (Platform::Exception^ Error)
00063     {
00064     DebugPrint2(rootPage, Error->ToString());
00065     }
00066 }
00067
00068 void Reset2(Page^ rootPage)
00069 {
00070   try
00071     {
00072     Page^ outputFrame = (Page^) rootPage;
00073         Page^ inputFrame = (Page^) rootPage;
00074         TextBox^ InputUserNameValue = (TextBox^) outputFrame->FindName("InputUserNameValue");
00075         InputUserNameValue->Text = "";
00076         PasswordBox^ InputPasswordValue = (PasswordBox^)outputFrame->FindName("InputPasswordValue");
00077         InputPasswordValue->Password= "";
00078         TextBox^ ErrorMessage = (TextBox^) outputFrame->FindName("ErrorMessage");
00079         ErrorMessage->Text = "";
00080         TextBox^ WelcomeMessage = (TextBox^) inputFrame->FindName("WelcomeMessage");
00081         CheckBox^ SaveCredCheck = (CheckBox^) outputFrame->FindName("SaveCredCheck");
00082         SaveCredCheck->IsChecked = false;
00083     CleanCombobox(rootPage);
00084   }
00085     catch (Platform::Exception^ Error)
00086     {
00087     DebugPrint2(rootPage, Error->ToString());
00088   }
00089 }
00090
00091
00092
00093 void SDKSample::PasswordVaultCPP::Scenario2::Launch_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00094 {
00095   try
00096   {
00097     Page^ outputFrame = (Page^) rootPage;
00098         Page^ inputFrame = (Page^) rootPage;
00099
00100     Vector<String^>^ itemSource = ref new Vector<String^>();
00101     Vector <Object^>^ l = ref new Vector<Object^>();
00102
00103     Reset2(rootPage);
00104     CheckBox^ AuthenticationFailCheck = (CheckBox ^) outputFrame->FindName("AuthenticationFailCheck");
00105     TextBox^ WelcomeMessage = (TextBox^) inputFrame->FindName("WelcomeMessage");
00106     ComboBox^ SelectUser = (ComboBox^) inputFrame->FindName("SelectUser");
00107     if (AuthenticationFailCheck->IsChecked->Value == true)
00108     {
00109       WelcomeMessage->Text = "Blocked";
00110     }
00111     else
00112     {
00113       try
00114       {
00115         PasswordCredential^ cred = ref new PasswordCredential();
00116         Windows::Security::Credentials::PasswordVault^ vault = ref new Windows::Security::Credentials::PasswordVault();
00117         Windows::Foundation::Collections::IVectorView<PasswordCredential^>^ creds = vault->FindAllByResource("Scenario 2");
00118         for each (PasswordCredential^ cred in creds)
00119         {
00120           itemSource->InsertAt(0, cred->UserName);
00121         }
00122       }
00123       catch (Platform::COMException^ Error)
00124       {
00125         DebugPrint2(this->rootPage, Error->ToString());
00126       }
00127       itemSource->InsertAt(0, "Add new user");
00128       itemSource->InsertAt(0, "");
00129       SelectUser->ItemsSource = itemSource;
00130       SelectUser->SelectedIndex = 0;
00131
00132       WelcomeMessage->Text = "Scenario is ready, please sign in";
00133
00134     }
00135
00136   }
00137   catch (Platform::Exception^ Error)
00138   {
00139     DebugPrint2(rootPage, Error->ToString());
00140   }
00141 }
00142
00143
00144 void SDKSample::PasswordVaultCPP::Scenario2::Signin_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00145 {
00146   Page^ outputFrame = (Page^) rootPage;
00147   Page^ inputFrame = (Page^) rootPage;
00148
00149   TextBox^ InputUserNameValue = (TextBox^) outputFrame->FindName("InputUserNameValue");
00150   PasswordBox^ InputPasswordValue = (PasswordBox^) outputFrame->FindName("InputPasswordValue");
00151   TextBox^ WelcomeMessage = (TextBox^) inputFrame->FindName("WelcomeMessage");
00152   CheckBox^ SaveCredCheck = (CheckBox^) outputFrame->FindName("SaveCredCheck");
00153     if (InputUserNameValue->Text == "" || InputPasswordValue->Password == "")
00154     {
00155     TextBox^ ErrorMessage = (TextBox ^) outputFrame->FindName("ErrorMessage");
00156         ErrorMessage->Text = "User name and password are not allowed to be empty, Please input user name and password";
00157     }
00158     else
00159     {
00160     try
00161         {
00162       Windows::Security::Credentials::PasswordVault^ vault = ref new Windows::Security::Credentials::PasswordVault();
00163       PasswordCredential^ c = ref new PasswordCredential("Scenario 2", InputUserNameValue->Text, InputPasswordValue->Password);
00164             if (SaveCredCheck->IsChecked->Value)
00165       {
00166         vault->Add(c);
00167       }
00168
00169       WelcomeMessage->Text = "Welcome to " + c->Resource + ", " + c->UserName;
00170         }
00171     catch (Platform::COMException^ Error)// No stored credentials, so none to delete
00172     {
00173       DebugPrint2(rootPage, Error->ToString());
00174         }
00175     }
00176     Reset2(rootPage);
00177
00178     CheckBox^ AuthenticationFailCheck = (CheckBox ^) outputFrame->FindName("AuthenticationFailCheck");
00179     AuthenticationFailCheck->IsChecked = false;
00180 }
00181
00182
00183 void SDKSample::PasswordVaultCPP::Scenario2::ChangeUser_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00184 {
00185   Page^ outputFrame = (Page^) rootPage;
00186   Page^ inputFrame = (Page^) rootPage;
00187
00188   try
00189     {
00190     Windows::Security::Credentials::PasswordVault^ vault = ref new Windows::Security::Credentials::PasswordVault();
00191     Windows::Foundation::Collections::IVectorView<PasswordCredential^>^ creds = vault->FindAllByResource("Scenario 2");
00192
00193     for each (PasswordCredential^ c in creds)
00194         {
00195       try
00196             {
00197         vault->Remove(c);
00198             }
00199       catch (Platform::COMException^ Error) // No stored credentials, so none to delete
00200       {
00201         DebugPrint2(rootPage, Error->ToString());
00202       }
00203     }
00204
00205   }
00206   catch (Platform::COMException^ Error) // No stored credentials, so none to delete
00207   {
00208       DebugPrint2(rootPage, Error->ToString());
00209     }
00210   Reset2(rootPage);
00211     CheckBox^ AuthenticationFailCheck = (CheckBox ^) outputFrame->FindName("AuthenticationFailCheck");
00212   AuthenticationFailCheck->IsChecked = false;
00213     TextBox^ WelcomeMessage = (TextBox^) inputFrame->FindName("WelcomeMessage");
00214     WelcomeMessage->Text = "User has been changed, please resign in with new credentials, choose save and launch scenario again";
00215 }
00216
00217
00218 void SDKSample::PasswordVaultCPP::Scenario2::Reset_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00219 {
00220   Reset2(rootPage);
00221 }
00222
00223
00224 void SDKSample::PasswordVaultCPP::Scenario2::SelectUser_Click(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e)
00225 {
00226   Page^ outputFrame = (Page^) rootPage;
00227   Page^ inputFrame = (Page^) rootPage;
00228
00229   TextBox^ InputUserNameValue = (TextBox^) outputFrame->FindName("InputUserNameValue");
00230   PasswordBox^ InputPasswordValue = (PasswordBox^) outputFrame->FindName("InputPasswordValue");
00231   ComboBox^ SelectUser = (ComboBox^) inputFrame->FindName("SelectUser");
00232
00233   try
00234     {
00235     if (SelectUser->SelectedIndex > 1)
00236     {
00237       InputUserNameValue->Text = SelectUser->SelectedItem->ToString();
00238       Windows::Security::Credentials::PasswordVault^ vault = ref new Windows::Security::Credentials::PasswordVault();
00239       PasswordCredential^ cred = vault->Retrieve("Scenario 2", (String^)SelectUser->SelectedItem);
00240       if(cred->Password != "")
00241       {
00242         InputPasswordValue->Password = cred->Password;
00243       }
00244     }
00245   }
00246   catch (Platform::COMException^ Error) // No stored credentials, so none to delete
00247   {
00248     DebugPrint2(rootPage, Error->ToString());
00249     }
00250 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Context menu/C++/common/LayoutAwarePage.cpp Source File

  • Context menu
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:30 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML personality animations/C++/common/suspensionmanager.cpp Source File

  • XAML personality animations
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML Popup/C++/Scenario1.xaml.h Source File

  • XAML Popup

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 SDKSample
00023 {
00024     namespace XAMLPopup
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 Scenario1 sealed
00031         {
00032         public:
00033             Scenario1();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void ShowPopupOffsetClicked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         void ClosePopupClicked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         };
00042     }
00043 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML WebView control/C++/Scenario4.xaml.cpp Source File

  • XAML WebView control

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::WebViewControl;
00020
00021 using namespace std;
00022 using namespace Platform;
00023 using namespace Windows::UI::Xaml;
00024 using namespace Windows::UI::Xaml::Controls;
00025 using namespace Windows::Foundation;
00026 using namespace Windows::Foundation::Collections;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 Scenario4::Scenario4()
00030 {
00031     InitializeComponent();
00032
00033   // Hook the LoadCompleted event for the WebView to know when the URL is fully loaded
00034   WebView4->ScriptNotify += ref new NotifyEventHandler(this, &Scenario4::WebView4_ScriptNotify);
00035 }
00036
00037
00038 // Invoked when this page is about to be displayed in a Frame.
00039 void Scenario4::OnNavigatedTo(NavigationEventArgs^ e)
00040 {
00041     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00042     // as NotifyUser()
00043     rootPage = MainPage::Current;
00044 }
00045
00046
00047 // Script notify for WebView4
00048 void SDKSample::WebViewControl::Scenario4::WebView4_ScriptNotify(Platform::Object^ sender, Windows::UI::Xaml::Controls::NotifyEventArgs^ e)
00049 {
00050   String^  str = "Response from script: " + e->Value;
00051   rootPage->NotifyUser(str, NotifyType::StatusMessage);
00052 }
00053
00054
00055 // Click handler for 'Fire Script' button
00056 void SDKSample::WebViewControl::Scenario4::FireScript_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00057 {
00058   if (NavToString->IsChecked->Value == true)
00059   {
00060       // We can run script that uses window.external.notify() to send data back to the app
00061       // without having to set the AllowedScriptNotifyUris property because the app is
00062       // trusted and it owns the content of the script.
00063       WebView4->InvokeScript("SayGoodbye", nullptr);
00064   }
00065   else
00066   {
00067       if (Nav->IsChecked->Value == true)
00068       {
00069           // Here we have to set the AllowedScriptNotifyUri property because we are navigating
00070           // to some actual site where we don't own the content and we want to allow window.external.notify()
00071           // to pass back data to our application.
00072       IVector<Uri^>^ allowedUris = ref new Platform::Collections::Vector<Uri^>();
00073           allowedUris->Append(ref new Uri("http://www.bing.com"));
00074           WebView4->AllowedScriptNotifyUris = allowedUris;
00075
00076           // Since this site does not have a function that we can call that actually uses window.external.notify() we have to inject that into
00077           // the page using eval().  See the next scenario for more information on this technique.
00078       Array<String^,1>^ args = ref new Array<String^>(1);
00079       args[0] = "window.external.notify('GoodBye');";
00080           WebView4->InvokeScript("eval", args);
00081
00082       }
00083       else
00084       {
00085           rootPage->NotifyUser("Please choose a navigation method", NotifyType::ErrorMessage);
00086       }
00087   }
00088 }
00089
00090
00091 // Click handler for 'NavToString' button
00092 void SDKSample::WebViewControl::Scenario4::NavToString_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00093 {
00094   rootPage->NotifyUser("", NotifyType::StatusMessage);
00095     // Let's create an HTML fragment that contains some javascript code that we will fire using
00096     // InvokeScript().
00097   String^ htmlFragment = ""
00098   + "\n\t<html>"
00099     + "\n\t   <head>"
00100     + "\n\t     <script type='text/javascript'>"
00101     + "\n\t       function SayGoodbye() "
00102     + "\n\t       {"
00103     + "\n\t         window.external.notify('GoodBye'); "
00104     + "\n\t       }"
00105     + "\n\t     </script>"
00106     + "\n\t   </head>"
00107     + "\n\t   <body>"
00108     + "\n\t     Page with 'Goodbye' script loaded.  Click the 'Fire Script' button to run the script and send data back to the application."
00109     + "\n\t   /body>"
00110   + "\n\t</html>";
00111
00112   // Load the fragment into the HTML text box so it will be visible.
00113   HTML4->Text = htmlFragment;
00114   WebView4->NavigateToString(HTML4->Text);
00115 }
00116
00117
00118 // Click handlerfor 'Nav' button
00119 void SDKSample::WebViewControl::Scenario4::Nav_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00120 {
00121    rootPage->NotifyUser("", NotifyType::StatusMessage);
00122      WebView4->Navigate(ref new Uri("http://www.bing.com"));
00123 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/ThumbnailGenerator.h Source File

  • Hilo C++
  • Hilo

ThumbnailGenerator.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
00009 namespace Hilo
00010 {
00011     // See http://go.microsoft.com/fwlink/?LinkId=267275 for info about Hilo's implementation of tiles.
00012
00013     class ExceptionPolicy;
00014
00015     // The ThumbnailGenerator class creates thumbnail images for a vector of image files.
00016     class ThumbnailGenerator
00017     {
00018     public:
00019         ThumbnailGenerator(std::shared_ptr<ExceptionPolicy> policy);
00020         concurrency::task<Platform::Collections::Vector<Windows::Storage::StorageFile^>^> Generate(Windows::Foundation::Collections::IVector<Windows::Storage::StorageFile^>^ files, Windows::Storage::StorageFolder^ thumbnailsFolder) ;
00021
00022     private:
00023         static concurrency::task<Windows::Storage::Streams::InMemoryRandomAccessStream^> CreateThumbnailFromPictureFileAsync(Windows::Storage::StorageFile^ sourceFile, unsigned int thumbSize);
00024         static concurrency::task<Windows::Storage::StorageFile^> CreateLocalThumbnailAsync(Windows::Storage::StorageFolder^ folder, Windows::Storage::StorageFile^ imageFile, Platform::String^ localFileName, unsigned int thumbSize, std::shared_ptr<ExceptionPolicy> policy);
00025         static concurrency::task<Windows::Storage::StorageFile^> InternalSaveToFile(Windows::Storage::StorageFolder^ folder, Windows::Storage::Streams::InMemoryRandomAccessStream^ stream, Platform::String^ filename);
00026
00027         std::shared_ptr<ExceptionPolicy> m_exceptionPolicy;
00028     } ;
00029 }
00030
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File and folder thumbnail/C++/Scenario4.xaml.cpp Source File

  • File and folder thumbnail

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::FileThumbnails;
00020
00021 using namespace concurrency;
00022 using namespace Platform;
00023 using namespace Windows::Storage;
00024 using namespace Windows::Storage::FileProperties;
00025 using namespace Windows::Storage::Pickers;
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 {
00032     InitializeComponent();
00033     rootPage = MainPage::Current;
00034     GetThumbnailButton->Click += ref new RoutedEventHandler(this, &Scenario4::GetThumbnailButton_Click);
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     if (rootPage->EnsureUnsnapped())
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 ThumbnailMode thumbnailMode = ThumbnailMode::PicturesView;
00061                 const size_t size = 200;
00062                 create_task(folder->GetThumbnailAsync(thumbnailMode, size)).then([this, folder, size](StorageItemThumbnail^ thumbnail)
00063                 {
00064                     if (thumbnail != nullptr)
00065                     {
00066                         MainPage::DisplayResult(ThumbnailImage, OutputTextBlock, "PicturesView", size, folder, thumbnail, false);
00067                     }
00068                     else
00069                     {
00070                         rootPage->NotifyUser(Errors::NoImages, NotifyType::StatusMessage);
00071                     }
00072                 });
00073             }
00074             else
00075             {
00076                 rootPage->NotifyUser(Errors::Cancel, NotifyType::StatusMessage);
00077             }
00078         });
00079     }
00080 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D HLSL fractal generator/C++/DirectXApp.h Source File

  • Direct3D HLSL fractal generator

DirectXApp.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 "DirectXFractal.h"
00011
00012 ref class DirectXApp : public Windows::ApplicationModel::Core::IFrameworkView
00013 {
00014 internal:
00015     DirectXApp();
00016
00017 public:
00018     // IFrameworkView Methods
00019     virtual void Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00020     virtual void SetWindow(_In_ Windows::UI::Core::CoreWindow^ window);
00021     virtual void Load(_In_ Platform::String^ entryPoint);
00022     virtual void Run();
00023     virtual void Uninitialize();
00024
00025 private:
00026     // Event Handlers
00027     void OnWindowSizeChanged(
00028         _In_ Windows::UI::Core::CoreWindow^ sender,
00029         _In_ Windows::UI::Core::WindowSizeChangedEventArgs^ args
00030         );
00031
00032     void OnVisibilityChanged(
00033         _In_ Windows::UI::Core::CoreWindow^ sender,
00034         _In_ Windows::UI::Core::VisibilityChangedEventArgs^ args
00035         );
00036
00037     void OnLogicalDpiChanged(
00038         _In_ Platform::Object^ sender
00039         );
00040
00041     void OnActivated(
00042         _In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView,
00043         _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^ args
00044         );
00045
00046     void OnSuspending(
00047         _In_ Platform::Object^ sender,
00048         _In_ Windows::ApplicationModel::SuspendingEventArgs^ args
00049         );
00050
00051     void OnWindowClosed(
00052         _In_ Windows::UI::Core::CoreWindow^ sender,
00053         _In_ Windows::UI::Core::CoreWindowEventArgs^ args
00054         );
00055
00056     // CoreWindow Input Events
00057     void OnPointerPressed(
00058         _In_ Windows::UI::Core::CoreWindow^ sender,
00059         _In_ Windows::UI::Core::PointerEventArgs^ args
00060         );
00061
00062     void OnPointerReleased(
00063         _In_ Windows::UI::Core::CoreWindow^ sender,
00064         _In_ Windows::UI::Core::PointerEventArgs^ args
00065         );
00066
00067     void OnPointerMoved(
00068         _In_ Windows::UI::Core::CoreWindow^ sender,
00069         _In_ Windows::UI::Core::PointerEventArgs^ args
00070         );
00071
00072     void OnPointerWheelChanged(
00073         _In_ Windows::UI::Core::CoreWindow^ sender,
00074         _In_ Windows::UI::Core::PointerEventArgs^ args
00075         );
00076
00077     void OnKeyDown(
00078         _In_ Windows::UI::Core::CoreWindow^ sender,
00079         _In_ Windows::UI::Core::KeyEventArgs^ args
00080         );
00081
00082     void OnKeyUp(
00083         _In_ Windows::UI::Core::CoreWindow^ sender,
00084         _In_ Windows::UI::Core::KeyEventArgs^ args
00085         );
00086
00087     // Gesture Recognizer Input Events
00088     void OnManipulationUpdated(
00089         _In_ Windows::UI::Input::GestureRecognizer^ sender,
00090         _In_ Windows::UI::Input::ManipulationUpdatedEventArgs^ args
00091         );
00092
00093     DirectXFractal^                                         m_renderer;
00094     Platform::Agile<Windows::UI::Input::GestureRecognizer>  m_gestureRecognizer;
00095     bool                                                    m_windowClosed;
00096     bool                                                    m_windowVisible;
00097     bool                                                    m_rotationKeyDown;
00098 };
00099
00100 ref class DirectXAppSource : Windows::ApplicationModel::Core::IFrameworkViewSource
00101 {
00102 public:
00103     virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00104 };
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Transcoding media/C++/Constants.cpp Source File

  • Transcoding media

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019   // The format here is the following:
00020   //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
00021   { "Transcode using default presets", "SDKSample.Transcode.Presets" },
00022   { "Transcode with custom settings", "SDKSample.Transcode.Custom" },
00023   { "Trim and transcode", "SDKSample.Transcode.Trim" }
00024 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DirectX::D3DX_BC7 Member List

This is the complete list of members for DirectX::D3DX_BC7, including all inherited members.
AssignIndices(_In_ const EncodeParams *pEP, _In_ size_t uShape, _In_ size_t uIndexMode, _In_reads_(BC7_MAX_REGIONS) LDREndPntPair endpts[], _Inout_updates_all_(NUM_PIXELS_PER_BLOCK) size_t aIndices[], _Inout_updates_all_(NUM_PIXELS_PER_BLOCK) size_t aIndices2[], _Out_writes_(BC7_MAX_REGIONS) float afTotErr[]) const | DirectX::D3DX_BC7 | [private]
Decode(_Out_writes_(NUM_PIXELS_PER_BLOCK) HDRColorA *pOut) const | DirectX::D3DX_BC7 |
EmitBlock(_In_ const EncodeParams *pEP, _In_ size_t uShape, _In_ size_t uRotation, _In_ size_t uIndexMode, _In_reads_(BC7_MAX_REGIONS) const LDREndPntPair aEndPts[], _In_reads_(NUM_PIXELS_PER_BLOCK) const size_t aIndex[], _In_reads_(NUM_PIXELS_PER_BLOCK) const size_t aIndex2[]) | DirectX::D3DX_BC7 | [private]
Encode(_In_reads_(NUM_PIXELS_PER_BLOCK) const HDRColorA *const pIn) | DirectX::D3DX_BC7 |
Exhaustive(_In_ const EncodeParams *pEP, _In_reads_(np) const LDRColorA aColors[], _In_ size_t np, _In_ size_t uIndexMode, _In_ size_t ch, _Inout_ float &fOrgErr, _Inout_ LDREndPntPair &optEndPt) const | DirectX::D3DX_BC7 | [private]
GeneratePaletteQuantized(_In_ const EncodeParams *pEP, _In_ size_t uIndexMode, _In_ const LDREndPntPair &endpts, _Out_writes_(BC7_MAX_INDICES) LDRColorA aPalette[]) const | DirectX::D3DX_BC7 | [private]
GetBit(_Inout_ size_t &uStartBit) const | DirectX::CBits< 16 > | [inline, private]
GetBits(_Inout_ size_t &uStartBit, _In_ size_t uNumBits) const | DirectX::CBits< 16 > | [inline, private]
MapColors(_In_ const EncodeParams *pEP, _In_reads_(np) const LDRColorA aColors[], _In_ size_t np, _In_ size_t uIndexMode, _In_ const LDREndPntPair &endPts, _In_ float fMinErr) const | DirectX::D3DX_BC7 | [private]
ms_aInfo | DirectX::D3DX_BC7 | [private, static]
OptimizeEndPoints(_In_ const EncodeParams *pEP, _In_ size_t uShape, _In_ size_t uIndexMode, _In_reads_(BC7_MAX_REGIONS) const float orig_err[], _In_reads_(BC7_MAX_REGIONS) const LDREndPntPair orig_endpts[], _Out_writes_(BC7_MAX_REGIONS) LDREndPntPair opt_endpts[]) const | DirectX::D3DX_BC7 | [private]
OptimizeOne(_In_ const EncodeParams *pEP, _In_reads_(np) const LDRColorA colors[], _In_ size_t np, _In_ size_t uIndexMode, _In_ float orig_err, _In_ const LDREndPntPair &orig_endpts, _Out_ LDREndPntPair &opt_endpts) const | DirectX::D3DX_BC7 | [private]
PerturbOne(_In_ const EncodeParams *pEP, _In_reads_(np) const LDRColorA colors[], _In_ size_t np, _In_ size_t uIndexMode, _In_ size_t ch, _In_ const LDREndPntPair &old_endpts, _Out_ LDREndPntPair &new_endpts, _In_ float old_err, _In_ uint8_t do_b) const | DirectX::D3DX_BC7 | [private]
Quantize(_In_ uint8_t comp, _In_ uint8_t uPrec) | DirectX::D3DX_BC7 | [inline, private, static]
Quantize(_In_ const LDRColorA &c, _In_ const LDRColorA &RGBAPrec) | DirectX::D3DX_BC7 | [inline, private, static]
Refine(_In_ const EncodeParams *pEP, _In_ size_t uShape, _In_ size_t uRotation, _In_ size_t uIndexMode) | DirectX::D3DX_BC7 | [private]
RoughMSE(_Inout_ EncodeParams *pEP, _In_ size_t uShape, _In_ size_t uIndexMode) | DirectX::D3DX_BC7 | [private, static]
SetBit(_Inout_ size_t &uStartBit, _In_ uint8_t uValue) | DirectX::CBits< 16 > | [inline, private]
SetBits(_Inout_ size_t &uStartBit, _In_ size_t uNumBits, _In_ uint8_t uValue) | DirectX::CBits< 16 > | [inline, private]
Unquantize(_In_ uint8_t comp, _In_ size_t uPrec) | DirectX::D3DX_BC7 | [inline, private, static]
Unquantize(_In_ const LDRColorA &c, _In_ const LDRColorA &RGBAPrec) | DirectX::D3DX_BC7 | [inline, private, static]
Generated on Sat Nov 23 2024 16:09:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: OrientationSensor/C++/MainPage.xaml.cpp Source File

  • OrientationSensor

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:43 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D animated text/C++/SampleOverlay.h Source File

  • Direct2D animated text

SampleOverlay.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 "DirectXSample.h"
00011
00012 // This class is responsible for initializing and rendering the title overlay visible
00013 // at the top of the DirectX SDK samples.
00014 ref class SampleOverlay
00015 {
00016 internal:
00017     SampleOverlay();
00018
00019     void Initialize(
00020         _In_ ID2D1Device*         d2dDevice,
00021         _In_ ID2D1DeviceContext*  d2dContext,
00022         _In_ IWICImagingFactory*  wicFactory,
00023         _In_ IDWriteFactory*      dwriteFactory,
00024         _In_ Platform::String^    caption
00025         );
00026
00027     void ResetDirectXResources();
00028
00029     void UpdateForWindowSizeChange();
00030
00031     void Render();
00032
00033     float GetTitleHeightInDips();
00034
00035 private:
00036
00037     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00038     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00039     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00040     Microsoft::WRL::ComPtr<IDWriteFactory>          m_dwriteFactory;
00041     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_whiteBrush;
00042     Microsoft::WRL::ComPtr<ID2D1DrawingStateBlock>  m_stateBlock;
00043
00044     Microsoft::WRL::ComPtr<IWICImagingFactory>      m_wicFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Bitmap>             m_logoBitmap;
00046     Microsoft::WRL::ComPtr<IDWriteTextLayout>       m_textLayout;
00047
00048     UINT                                            m_idIncrement;
00049     bool                                            m_drawOverlay;
00050     Platform::String^                               m_sampleName;
00051     float                                           m_padding;
00052     float                                           m_textVerticalOffset;
00053     D2D1_SIZE_F                                     m_logoSize;
00054     float                                           m_overlayWidth;
00055 };
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D post-processing effects/C++/DirectXApp.h Source File

  • Direct3D post-processing effects

DirectXApp.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 "D3DPostProcessing.h"
00011
00012 ref class DirectXApp : public Windows::ApplicationModel::Core::IFrameworkView
00013 {
00014 internal:
00015     DirectXApp();
00016
00017 public:
00018     // IFrameworkView Methods
00019     virtual void Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00020     virtual void SetWindow(_In_ Windows::UI::Core::CoreWindow^ window);
00021     virtual void Load(_In_ Platform::String^ entryPoint);
00022     virtual void Run();
00023     virtual void Uninitialize();
00024
00025 private:
00026     // Event Handlers
00027     void OnWindowSizeChanged(
00028         _In_ Windows::UI::Core::CoreWindow^ sender,
00029         _In_ Windows::UI::Core::WindowSizeChangedEventArgs^ args
00030         );
00031
00032     void OnVisibilityChanged(
00033         _In_ Windows::UI::Core::CoreWindow^ sender,
00034         _In_ Windows::UI::Core::VisibilityChangedEventArgs^ args
00035         );
00036
00037     void OnLogicalDpiChanged(
00038         _In_ Platform::Object^ sender
00039         );
00040
00041     void OnActivated(
00042         _In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView,
00043         _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^ args
00044         );
00045
00046     void OnWindowClosed(
00047         _In_ Windows::UI::Core::CoreWindow^ sender,
00048         _In_ Windows::UI::Core::CoreWindowEventArgs^ args
00049         );
00050
00051     D3DPostProcessing^ m_renderer;
00052     bool m_windowClosed;
00053     bool m_windowVisible;
00054 };
00055
00056 ref class DirectXAppSource : Windows::ApplicationModel::Core::IFrameworkViewSource
00057 {
00058 public:
00059     virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00060 };
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/BasicLoader.cpp Source File

  • Direct3D resource loading

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 Sat Nov 23 2024 16:08:07 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Print/C++/BasePrintPage.h Source File

  • Print

BasePrintPage.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 "MainPage.xaml.h"
00012
00013
00014 using namespace Windows::UI::Xaml;
00015 using namespace Windows::UI::Xaml::Controls;
00016 using namespace Windows::UI::Xaml::Printing;
00017
00018 namespace PrintSample
00019 {
00020     [Windows::Foundation::Metadata::WebHostHidden]
00021     public ref class BasePrintPage : Page
00022     {
00023     private:
00024         /// <summary>
00025         /// Print task requested event registration token
00026         /// </summary>
00027         EventRegistrationToken                              m_printTaskRequestedEventToken;
00028
00029         /// <summary>
00030         /// a boolean which tracks whether the app has been registered for printing
00031         /// </summary>
00032         bool                                                m_isRegisteredForPrinting;
00033
00034         /// <summary>
00035         /// A pointer back to the main page which is used to gain access to the input and output frames and their content.
00036         /// </summary>
00037         MainPage^                                           m_rootPage;
00038
00039         /// <summary>
00040         /// PrintDocument is used to prepare the pages for printing.
00041         /// Prepare the pages to print in the handlers for the Paginate, GetPreviewPage, and AddPages events.
00042         /// </summary>
00043         PrintDocument^                                      m_printDocument;
00044
00045         /// <summary>
00046         /// Marker interface for document source
00047         /// </summary>
00048         Windows::Graphics::Printing::IPrintDocumentSource^  m_printDocumentSource;
00049
00050         /// <summary>
00051         /// A list of UIElements used to store the print preview pages.  This gives easy access
00052         /// to any desired preview page.
00053         /// </summary>
00054         std::vector<UIElement^>                             m_printPreviewPages;
00055
00056         /// <summary>
00057         /// Current requeted page for preview.
00058         /// </summary>
00059         LONG                                                m_currentPage;
00060
00061         /// <summary>
00062         /// First page in the printing-content series
00063         /// From this "virtual sized" paged content is split(text is flowing) to "printing pages"
00064         /// </summary>
00065         FrameworkElement^ m_firstPage;
00066
00067     protected:
00068
00069         /// <summary>
00070         /// The percent of app's margin width, content is set at 85% (0.85) of the area's width
00071         /// </summary>
00072         property float ApplicationContentMarginLeft
00073         {
00074             float get()
00075             {
00076                 return 0.075f;
00077             }
00078         }
00079
00080         /// <summary>
00081         /// The percent of app's margin height, content is set at 94% (0.94) of tha area's height
00082         /// </summary>
00083         property float ApplicationContentMarginTop
00084         {
00085             float get()
00086             {
00087                 return 0.03f;
00088             }
00089         }
00090
00091         property Canvas^ PrintingRoot
00092         {
00093             Canvas^ get()
00094             {
00095                 return safe_cast<Canvas^>(FindName("printingRoot"));
00096             }
00097         }
00098
00099         property MainPage^ RootPage
00100         {
00101             MainPage^ get()
00102             {
00103                 return m_rootPage;
00104             }
00105         }
00106
00107         property bool RegisteredForPrinting
00108         {
00109             bool get()
00110             {
00111                 return m_isRegisteredForPrinting;
00112             }
00113
00114             void set(bool value)
00115             {
00116                 m_isRegisteredForPrinting = value;
00117             }
00118         }
00119
00120         property FrameworkElement^ FirstPage
00121         {
00122             FrameworkElement^ get()
00123             {
00124                 return m_firstPage;
00125             }
00126             void set(FrameworkElement^ value)
00127             {
00128                 m_firstPage = value;
00129             }
00130         }
00131
00132         property Windows::Graphics::Printing::IPrintDocumentSource^ PrintDocumentSource
00133         {
00134             Windows::Graphics::Printing::IPrintDocumentSource^ get()
00135             {
00136                 return m_printDocumentSource;
00137             }
00138         }
00139
00140         property PrintDocument^ CurrentPrintDocument
00141         {
00142             PrintDocument^ get()
00143             {
00144                 return m_printDocument;
00145             }
00146         }
00147
00148         property size_t PrintPreviewPages
00149         {
00150             size_t get()
00151             {
00152                 return m_printPreviewPages.size();
00153             }
00154         }
00155
00156         /// <summary>
00157         /// Factory method for every scenario that will create/generate print content specific to each scenario
00158         /// For scenarios 1-5: it will create the first page from which content will flow
00159         /// </summary>
00160         virtual void PreparetPrintContent();
00161
00162         /// <summary>
00163         /// Register for print button handler
00164         /// </summary>
00165         void RegisterForPrintingButtonClick(Object^ sender, RoutedEventArgs^ e);
00166
00167         /// <summary>
00168         /// This is the event handler for PrintManager.PrintTaskRequested.
00169         /// 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.
00170         /// Therefore, we use this handler to only create the print task.
00171         /// The print settings customization can be done when the print document source is requested.
00172         /// </summary>
00173         /// <param name="sender">PrintManager</param>
00174         /// <param name="e">PrintTaskRequestedEventArgs</param>
00175         void virtual PrintTaskRequested(Windows::Graphics::Printing::PrintManager^ sender, Windows::Graphics::Printing::PrintTaskRequestedEventArgs^ e);
00176
00177         /// <summary>
00178         /// This function registers the app for printing with Windows and sets up the necessary event handlers for the print process.
00179         /// </summary>
00180         void RegisterForPrinting();
00181
00182         /// <summary>
00183         /// This function unregisters the app for printing with Windows.
00184         /// </summary>
00185         void UnregisterForPrinting();
00186
00187         /// <summary>
00188         /// This is the event handler for PrintDocument.Paginate. It creates print preview pages for the app.
00189         /// </summary>
00190         /// <param name="sender">PrintDocument</param>
00191         /// <param name="e">Paginate Event Arguments</param>
00192         virtual void CreatePrintPreviewPages(Object^ sender, PaginateEventArgs^ e);
00193
00194         virtual void OnContentCreated() {};
00195
00196         /// <summary>
00197         /// This is the event handler for PrintDocument.GetPrintPreviewPage. It provides a specific print preview page,
00198         /// in the form of an UIElement, to an instance of PrintDocument. PrintDocument subsequently converts the UIElement
00199         /// into a page that the Windows print system can deal with.
00200         /// </summary>
00201         /// <param name="sender">The Print Document</param>
00202         /// <param name="e">Arguments containing the preview requested page</param>
00203         virtual void GetPrintPreviewPage(Object^ sender, GetPreviewPageEventArgs^ e);
00204
00205         /// <summary>
00206         /// This is the event handler for PrintDocument.AddPages. It provides all pages to be printed, in the form of
00207         /// UIElements, to an instance of PrintDocument. PrintDocument subsequently converts the UIElements
00208         /// into a pages that the Windows print system can deal with.
00209         /// </summary>
00210         /// <param name="sender"></param>
00211         /// <param name="e">Add page event arguments containing a print task options reference</param>
00212         virtual void AddPrintPages(Object^ sender, AddPagesEventArgs^ e);
00213
00214         /// <summary>
00215         /// This function creates and adds one print preview page to the internal cache of print preview
00216         /// pages stored in m_printPreviewPages.
00217         /// </summary>
00218         /// <param name="lastRTBOAdded">Last RichTextBlockOverflow element added in the current content</param>
00219         /// <param name="printPageDescription">Printer's page description</param>
00220         virtual RichTextBlockOverflow^ AddOnePrintPreviewPage(RichTextBlockOverflow^ lastRTBOAdded, Windows::Graphics::Printing::PrintPageDescription printPageDescription);
00221
00222         /// <summary>
00223         /// Removes a page from the printprreview collection (generated content)
00224         /// </summary>
00225         /// <param name="pageNumber">The page number to remove</param>
00226         void RemovePageFromPrintPreviewCollection(int pageNumber);
00227
00228     public:
00229         virtual void OnNavigatedTo(NavigationEventArgs^ e) override;
00230
00231         virtual void OnNavigatedFrom(NavigationEventArgs^ e) override;
00232     };
00233
00234 };
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Folder enumeration/C++/common/suspensionmanager.h Source File

  • Folder enumeration
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Snap/C++/Scenario1.xaml.cpp Source File

  • Snap

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::SnapSample;
00020
00021 using namespace Platform;
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 Scenario1::Scenario1()
00028 {
00029     InitializeComponent();
00030
00031     // Register for the window resize handler
00032     _layoutHandlerToken = Window::Current->SizeChanged += ref new Windows::UI::Xaml::WindowSizeChangedEventHandler(this, &Scenario1::Page_SizeChanged);
00033
00034     // Bind a click event to the unsnap button
00035     UnsnapButton->Click += ref new RoutedEventHandler(this, &Scenario1::UnsnapButton_Click);
00036
00037     // Update view on load (because you can be launched into any view state)
00038     UpdateForViewState();
00039 }
00040
00041 String^ Scenario1::ConvertViewState(ApplicationViewState state)
00042 {
00043     // Assign text according to view state
00044     switch (state)
00045     {
00046     case ApplicationViewState::Filled:
00047         UnsnapButton->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00048         return "This app is in filled state.";
00049     case ApplicationViewState::FullScreenLandscape:
00050         UnsnapButton->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00051         return "This app is full screen landscape.";
00052     case ApplicationViewState::FullScreenPortrait:
00053         UnsnapButton->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00054         return "This app is full screen portrait.";
00055     case ApplicationViewState::Snapped:
00056         UnsnapButton->Visibility = Windows::UI::Xaml::Visibility::Visible;
00057         return "This app is snapped.";
00058     }
00059     return "";
00060 }
00061
00062 void Scenario1::UpdateForViewState()
00063 {
00064     // Query for the current view state
00065     ApplicationViewState state = ApplicationView::Value;
00066     // Display text
00067     OutputText->Text = ConvertViewState(state);
00068 }
00069
00070 #pragma region Event handlers
00071
00072 void Scenario1::Page_SizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00073 {
00074     // Update view for the new window size
00075     UpdateForViewState();
00076 }
00077
00078 void Scenario1::UnsnapButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00079 {
00080     bool fUnsnapped = ApplicationView::TryUnsnap();
00081
00082     if (!fUnsnapped)
00083     {
00084         Scenario1::OutputText->Text = "Programmatic unsnap did not work.";
00085     }
00086 }
Generated on Sat Nov 23 2024 16:07:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Simplified ink/C++/DirectXBase.h Source File

  • Input Simplified ink

DirectXBase.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 "DirectXSample.h"
00011
00012 // Helper class that initializes DirectX APIs for both 2D and 3D rendering.
00013 // Some of the code in this class may be omitted if only 2D or only 3D rendering is being used.
00014 ref class DirectXBase abstract
00015 {
00016 internal:
00017     DirectXBase();
00018
00019     virtual void Initialize(Windows::UI::Core::CoreWindow^ window, float dpi);
00020     virtual void HandleDeviceLost();
00021     virtual void CreateDeviceIndependentResources();
00022     virtual void CreateDeviceResources();
00023     virtual void SetDpi(float dpi);
00024     virtual void UpdateForWindowSizeChange();
00025     virtual void CreateWindowSizeDependentResources();
00026     virtual void Render() = 0;
00027     virtual void Present();
00028     void ValidateDevice();
00029
00030 protected private:
00031     Platform::Agile<Windows::UI::Core::CoreWindow>  m_window;
00032
00033     // DirectWrite & Windows Imaging Component Objects.
00034     Microsoft::WRL::ComPtr<IDWriteFactory1>         m_dwriteFactory;
00035     Microsoft::WRL::ComPtr<IWICImagingFactory2>     m_wicFactory;
00036
00037     // DirectX Core Objects. Required for 2D and 3D.
00038     Microsoft::WRL::ComPtr<ID3D11Device1>           m_d3dDevice;
00039     Microsoft::WRL::ComPtr<ID3D11DeviceContext1>    m_d3dContext;
00040     Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00041     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00042
00043     // Direct2D Rendering Objects. Required for 2D.
00044     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00046     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00047     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmap;
00048
00049     // Direct3D Rendering Objects. Required for 3D.
00050     Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00051
00052     // Cached renderer properties.
00053     D3D_FEATURE_LEVEL                               m_featureLevel;
00054     Windows::Foundation::Size                       m_renderTargetSize;
00055     Windows::Foundation::Rect                       m_windowBounds;
00056     float                                           m_dpi;
00057     bool                                            m_windowSizeChangeInProgress;
00058     unsigned int                                    m_numBuffers;
00059 };
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2Dapp printing/C++/DirectXApp.cpp Source File

  • Direct2Dapp printing

DirectXApp.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 "DirectXApp.h"
00010
00011 using namespace Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Windows::Graphics::Display;
00014 using namespace Windows::Graphics::Printing;
00015 using namespace Windows::ApplicationModel;
00016 using namespace Windows::ApplicationModel::Core;
00017 using namespace Windows::ApplicationModel::Activation;
00018 using namespace Windows::UI::ViewManagement;
00019
00020 DirectXApp::DirectXApp() :
00021     m_windowClosed(false),
00022     m_windowVisible(true)
00023 {
00024 }
00025
00026 void DirectXApp::Initialize(
00027     _In_ CoreApplicationView^ applicationView
00028     )
00029 {
00030     applicationView->Activated +=
00031         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &DirectXApp::OnActivated);
00032
00033     CoreApplication::Suspending +=
00034         ref new EventHandler<SuspendingEventArgs^>(this, &DirectXApp::OnSuspending);
00035
00036     CoreApplication::Resuming +=
00037         ref new EventHandler<Platform::Object^>(this, &DirectXApp::OnResuming);
00038
00039     m_renderer = ref new PageRenderer();
00040 }
00041
00042 void DirectXApp::SetWindow(
00043     _In_ CoreWindow^ window
00044     )
00045 {
00046     window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
00047
00048     window->SizeChanged +=
00049         ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &DirectXApp::OnWindowSizeChanged);
00050
00051     window->VisibilityChanged +=
00052         ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &DirectXApp::OnVisibilityChanged);
00053
00054     window->Closed +=
00055         ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &DirectXApp::OnWindowClosed);
00056
00057     DisplayProperties::LogicalDpiChanged +=
00058         ref new DisplayPropertiesEventHandler(this, &DirectXApp::OnLogicalDpiChanged);
00059
00060     m_renderer->Initialize(window, DisplayProperties::LogicalDpi);
00061     InitPrintManager();
00062 }
00063
00064 void DirectXApp::Load(
00065     _In_ Platform::String^ entryPoint
00066     )
00067 {
00068 }
00069
00070 void DirectXApp::Run()
00071 {
00072     while (!m_windowClosed)
00073     {
00074         if (m_windowVisible)
00075         {
00076             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(Windows::UI::Core::CoreProcessEventsOption::ProcessAllIfPresent);
00077             m_renderer->Render();
00078         }
00079         else
00080         {
00081             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(Windows::UI::Core::CoreProcessEventsOption::ProcessOneAndAllPending);
00082         }
00083     }
00084 }
00085
00086 void DirectXApp::Uninitialize()
00087 {
00088 }
00089
00090 void DirectXApp::OnWindowSizeChanged(
00091     _In_ Windows::UI::Core::CoreWindow^ sender,
00092     _In_ Windows::UI::Core::WindowSizeChangedEventArgs^ args
00093     )
00094 {
00095     m_renderer->SetSnappedMode(ApplicationView::Value == ApplicationViewState::Snapped);
00096     m_renderer->UpdateForWindowSizeChange();
00097 }
00098
00099 void DirectXApp::OnVisibilityChanged(
00100     _In_ CoreWindow^ sender,
00101     _In_ VisibilityChangedEventArgs^ args
00102     )
00103 {
00104     m_windowVisible = args->Visible;
00105 }
00106
00107 void DirectXApp::OnWindowClosed(
00108     _In_ CoreWindow^ sender,
00109     _In_ CoreWindowEventArgs^ args
00110     )
00111 {
00112     m_windowClosed = true;
00113 }
00114
00115 void DirectXApp::OnLogicalDpiChanged(_In_ Platform::Object^ sender)
00116 {
00117     m_renderer->SetDpi(DisplayProperties::LogicalDpi);
00118 }
00119
00120 void DirectXApp::OnActivated(
00121     _In_ CoreApplicationView^ applicationView,
00122     _In_ IActivatedEventArgs^ args
00123     )
00124 {
00125     CoreWindow::GetForCurrentThread()->Activate();
00126 }
00127
00128 void DirectXApp::OnSuspending(
00129     _In_ Platform::Object^ sender,
00130     _In_ SuspendingEventArgs^ args
00131     )
00132 {
00133 }
00134
00135 void DirectXApp::OnResuming(
00136     _In_ Platform::Object^ sender,
00137     _In_ Platform::Object^ args
00138     )
00139 {
00140 }
00141
00142 void DirectXApp::InitPrintManager()
00143 {
00144     // Call static method to get PrintManager object.
00145     m_printManager = Windows::Graphics::Printing::PrintManager::GetForCurrentView();
00146
00147     // Start print task event.
00148     m_printManager->PrintTaskRequested +=
00149         ref new TypedEventHandler<PrintManager^, PrintTaskRequestedEventArgs^>(this, &DirectXApp::SetPrintTask);
00150 }
00151
00152 void DirectXApp::SetPrintTask(
00153     _In_ PrintManager^ /*sender*/,
00154     _In_ PrintTaskRequestedEventArgs^ args
00155     )
00156 {
00157     PrintTaskSourceRequestedHandler^ sourceHandler =
00158         ref new PrintTaskSourceRequestedHandler([this](PrintTaskSourceRequestedArgs^ args)-> void{
00159             Microsoft::WRL::ComPtr<CDocumentSource> documentSource;
00160             DX::ThrowIfFailed(
00161                 Microsoft::WRL::MakeAndInitialize<CDocumentSource>(&documentSource, reinterpret_cast<IUnknown*>(m_renderer))
00162                 );
00163
00164             // Here CDocumentSource is inherited from IPrintDocumentSource, cast it back to an object.
00165             IPrintDocumentSource^ objSource(
00166                 reinterpret_cast<IPrintDocumentSource^>(documentSource.Get())
00167                 );
00168
00169             args->SetSource(objSource);
00170         });
00171
00172     // Request initializing print task.
00173     PrintTask^ printTask = args->Request->CreatePrintTask(
00174         L"Direct2D Windows Store app printing sample",
00175         sourceHandler
00176         );
00177 }
00178
00179 IFrameworkView^ DirectXAppSource::CreateView()
00180 {
00181     return ref new DirectXApp();
00182 }
00183
00184 [Platform::MTAThread]
00185 int main(Platform::Array<Platform::String^>^)
00186 {
00187     auto directXAppSource = ref new DirectXAppSource();
00188     CoreApplication::Run(directXAppSource);
00189     return 0;
00190 }
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/DDSTextureLoader.cpp Source File

  • Direct3D resource loading

DDSTextureLoader.cpp

Go to the documentation of this file.
00001 //--------------------------------------------------------------------------------------
00002 // File: DDSTextureLoader.cpp
00003 //
00004 // Function for loading a DDS texture and creating a Direct3D 11 runtime resource for it
00005 //
00006 // Note this function is 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
00018 #include "pch.h"
00019 #include <dxgiformat.h>
00020 #include <assert.h>
00021 #include <memory>
00022 #include <algorithm>
00023 #include "DDSTextureLoader.h"
00024 #include "DirectXSample.h"
00025
00026 using namespace Microsoft::WRL;
00027
00028 //--------------------------------------------------------------------------------------
00029 // Macros
00030 //--------------------------------------------------------------------------------------
00031 #ifndef MAKEFOURCC
00032     #define MAKEFOURCC(ch0, ch1, ch2, ch3)                              \
00033                 ((uint32)(byte)(ch0) | ((uint32)(byte)(ch1) << 8) |       \
00034                 ((uint32)(byte)(ch2) << 16) | ((uint32)(byte)(ch3) << 24))
00035 #endif /* defined(MAKEFOURCC) */
00036
00037 //--------------------------------------------------------------------------------------
00038 // DDS file structure definitions
00039 //
00040 // See DDS.h in the 'Texconv' sample and the 'DirectXTex' library
00041 //--------------------------------------------------------------------------------------
00042 #pragma pack(push, 1)
00043
00044 #define DDS_MAGIC 0x20534444 // "DDS "
00045
00046 struct DDS_PIXELFORMAT
00047 {
00048     uint32  size;
00049     uint32  flags;
00050     uint32  fourCC;
00051     uint32  RGBBitCount;
00052     uint32  RBitMask;
00053     uint32  GBitMask;
00054     uint32  BBitMask;
00055     uint32  ABitMask;
00056 };
00057
00058 #define DDS_FOURCC      0x00000004  // DDPF_FOURCC
00059 #define DDS_RGB         0x00000040  // DDPF_RGB
00060 #define DDS_RGBA        0x00000041  // DDPF_RGB | DDPF_ALPHAPIXELS
00061 #define DDS_LUMINANCE   0x00020000  // DDPF_LUMINANCE
00062 #define DDS_LUMINANCEA  0x00020001  // DDPF_LUMINANCE | DDPF_ALPHAPIXELS
00063 #define DDS_ALPHA       0x00000002  // DDPF_ALPHA
00064 #define DDS_PAL8        0x00000020  // DDPF_PALETTEINDEXED8
00065
00066 #define DDS_HEADER_FLAGS_TEXTURE        0x00001007  // DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT
00067 #define DDS_HEADER_FLAGS_MIPMAP         0x00020000  // DDSD_MIPMAPCOUNT
00068 #define DDS_HEADER_FLAGS_VOLUME         0x00800000  // DDSD_DEPTH
00069 #define DDS_HEADER_FLAGS_PITCH          0x00000008  // DDSD_PITCH
00070 #define DDS_HEADER_FLAGS_LINEARSIZE     0x00080000  // DDSD_LINEARSIZE
00071
00072 #define DDS_HEIGHT 0x00000002 // DDSD_HEIGHT
00073 #define DDS_WIDTH  0x00000004 // DDSD_WIDTH
00074
00075 #define DDS_SURFACE_FLAGS_TEXTURE 0x00001000 // DDSCAPS_TEXTURE
00076 #define DDS_SURFACE_FLAGS_MIPMAP  0x00400008 // DDSCAPS_COMPLEX | DDSCAPS_MIPMAP
00077 #define DDS_SURFACE_FLAGS_CUBEMAP 0x00000008 // DDSCAPS_COMPLEX
00078
00079 #define DDS_CUBEMAP_POSITIVEX 0x00000600 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEX
00080 #define DDS_CUBEMAP_NEGATIVEX 0x00000a00 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEX
00081 #define DDS_CUBEMAP_POSITIVEY 0x00001200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEY
00082 #define DDS_CUBEMAP_NEGATIVEY 0x00002200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEY
00083 #define DDS_CUBEMAP_POSITIVEZ 0x00004200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEZ
00084 #define DDS_CUBEMAP_NEGATIVEZ 0x00008200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEZ
00085
00086 #define DDS_CUBEMAP_ALLFACES (DDS_CUBEMAP_POSITIVEX | DDS_CUBEMAP_NEGATIVEX |\
00087                               DDS_CUBEMAP_POSITIVEY | DDS_CUBEMAP_NEGATIVEY |\
00088                               DDS_CUBEMAP_POSITIVEZ | DDS_CUBEMAP_NEGATIVEZ)
00089
00090 #define DDS_CUBEMAP 0x00000200 // DDSCAPS2_CUBEMAP
00091
00092 #define DDS_FLAGS_VOLUME 0x00200000 // DDSCAPS2_VOLUME
00093
00094 typedef struct
00095 {
00096     uint32          size;
00097     uint32          flags;
00098     uint32          height;
00099     uint32          width;
00100     uint32          pitchOrLinearSize;
00101     uint32          depth; // only if DDS_HEADER_FLAGS_VOLUME is set in flags
00102     uint32          mipMapCount;
00103     uint32          reserved1[11];
00104     DDS_PIXELFORMAT ddspf;
00105     uint32          caps;
00106     uint32          caps2;
00107     uint32          caps3;
00108     uint32          caps4;
00109     uint32          reserved2;
00110 } DDS_HEADER;
00111
00112 typedef struct
00113 {
00114     DXGI_FORMAT dxgiFormat;
00115     uint32      resourceDimension;
00116     uint32      miscFlag; // see D3D11_RESOURCE_MISC_FLAG
00117     uint32      arraySize;
00118     uint32      reserved;
00119 } DDS_HEADER_DXT10;
00120
00121 #pragma pack(pop)
00122
00123 //--------------------------------------------------------------------------------------
00124 // Return the BPP for a particular format
00125 //--------------------------------------------------------------------------------------
00126 static size_t BitsPerPixel(_In_ DXGI_FORMAT fmt)
00127 {
00128     switch (fmt)
00129     {
00130     case DXGI_FORMAT_R32G32B32A32_TYPELESS:
00131     case DXGI_FORMAT_R32G32B32A32_FLOAT:
00132     case DXGI_FORMAT_R32G32B32A32_UINT:
00133     case DXGI_FORMAT_R32G32B32A32_SINT:
00134         return 128;
00135
00136     case DXGI_FORMAT_R32G32B32_TYPELESS:
00137     case DXGI_FORMAT_R32G32B32_FLOAT:
00138     case DXGI_FORMAT_R32G32B32_UINT:
00139     case DXGI_FORMAT_R32G32B32_SINT:
00140         return 96;
00141
00142     case DXGI_FORMAT_R16G16B16A16_TYPELESS:
00143     case DXGI_FORMAT_R16G16B16A16_FLOAT:
00144     case DXGI_FORMAT_R16G16B16A16_UNORM:
00145     case DXGI_FORMAT_R16G16B16A16_UINT:
00146     case DXGI_FORMAT_R16G16B16A16_SNORM:
00147     case DXGI_FORMAT_R16G16B16A16_SINT:
00148     case DXGI_FORMAT_R32G32_TYPELESS:
00149     case DXGI_FORMAT_R32G32_FLOAT:
00150     case DXGI_FORMAT_R32G32_UINT:
00151     case DXGI_FORMAT_R32G32_SINT:
00152     case DXGI_FORMAT_R32G8X24_TYPELESS:
00153     case DXGI_FORMAT_D32_FLOAT_S8X24_UINT:
00154     case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS:
00155     case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT:
00156         return 64;
00157
00158     case DXGI_FORMAT_R10G10B10A2_TYPELESS:
00159     case DXGI_FORMAT_R10G10B10A2_UNORM:
00160     case DXGI_FORMAT_R10G10B10A2_UINT:
00161     case DXGI_FORMAT_R11G11B10_FLOAT:
00162     case DXGI_FORMAT_R8G8B8A8_TYPELESS:
00163     case DXGI_FORMAT_R8G8B8A8_UNORM:
00164     case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
00165     case DXGI_FORMAT_R8G8B8A8_UINT:
00166     case DXGI_FORMAT_R8G8B8A8_SNORM:
00167     case DXGI_FORMAT_R8G8B8A8_SINT:
00168     case DXGI_FORMAT_R16G16_TYPELESS:
00169     case DXGI_FORMAT_R16G16_FLOAT:
00170     case DXGI_FORMAT_R16G16_UNORM:
00171     case DXGI_FORMAT_R16G16_UINT:
00172     case DXGI_FORMAT_R16G16_SNORM:
00173     case DXGI_FORMAT_R16G16_SINT:
00174     case DXGI_FORMAT_R32_TYPELESS:
00175     case DXGI_FORMAT_D32_FLOAT:
00176     case DXGI_FORMAT_R32_FLOAT:
00177     case DXGI_FORMAT_R32_UINT:
00178     case DXGI_FORMAT_R32_SINT:
00179     case DXGI_FORMAT_R24G8_TYPELESS:
00180     case DXGI_FORMAT_D24_UNORM_S8_UINT:
00181     case DXGI_FORMAT_R24_UNORM_X8_TYPELESS:
00182     case DXGI_FORMAT_X24_TYPELESS_G8_UINT:
00183     case DXGI_FORMAT_R9G9B9E5_SHAREDEXP:
00184     case DXGI_FORMAT_R8G8_B8G8_UNORM:
00185     case DXGI_FORMAT_G8R8_G8B8_UNORM:
00186     case DXGI_FORMAT_B8G8R8A8_UNORM:
00187     case DXGI_FORMAT_B8G8R8X8_UNORM:
00188     case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM:
00189     case DXGI_FORMAT_B8G8R8A8_TYPELESS:
00190     case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
00191     case DXGI_FORMAT_B8G8R8X8_TYPELESS:
00192     case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB:
00193         return 32;
00194
00195     case DXGI_FORMAT_R8G8_TYPELESS:
00196     case DXGI_FORMAT_R8G8_UNORM:
00197     case DXGI_FORMAT_R8G8_UINT:
00198     case DXGI_FORMAT_R8G8_SNORM:
00199     case DXGI_FORMAT_R8G8_SINT:
00200     case DXGI_FORMAT_R16_TYPELESS:
00201     case DXGI_FORMAT_R16_FLOAT:
00202     case DXGI_FORMAT_D16_UNORM:
00203     case DXGI_FORMAT_R16_UNORM:
00204     case DXGI_FORMAT_R16_UINT:
00205     case DXGI_FORMAT_R16_SNORM:
00206     case DXGI_FORMAT_R16_SINT:
00207     case DXGI_FORMAT_B5G6R5_UNORM:
00208     case DXGI_FORMAT_B5G5R5A1_UNORM:
00209     case DXGI_FORMAT_B4G4R4A4_UNORM:
00210         return 16;
00211
00212     case DXGI_FORMAT_R8_TYPELESS:
00213     case DXGI_FORMAT_R8_UNORM:
00214     case DXGI_FORMAT_R8_UINT:
00215     case DXGI_FORMAT_R8_SNORM:
00216     case DXGI_FORMAT_R8_SINT:
00217     case DXGI_FORMAT_A8_UNORM:
00218         return 8;
00219
00220     case DXGI_FORMAT_R1_UNORM:
00221         return 1;
00222
00223     case DXGI_FORMAT_BC1_TYPELESS:
00224     case DXGI_FORMAT_BC1_UNORM:
00225     case DXGI_FORMAT_BC1_UNORM_SRGB:
00226     case DXGI_FORMAT_BC4_TYPELESS:
00227     case DXGI_FORMAT_BC4_UNORM:
00228     case DXGI_FORMAT_BC4_SNORM:
00229         return 4;
00230
00231     case DXGI_FORMAT_BC2_TYPELESS:
00232     case DXGI_FORMAT_BC2_UNORM:
00233     case DXGI_FORMAT_BC2_UNORM_SRGB:
00234     case DXGI_FORMAT_BC3_TYPELESS:
00235     case DXGI_FORMAT_BC3_UNORM:
00236     case DXGI_FORMAT_BC3_UNORM_SRGB:
00237     case DXGI_FORMAT_BC5_TYPELESS:
00238     case DXGI_FORMAT_BC5_UNORM:
00239     case DXGI_FORMAT_BC5_SNORM:
00240     case DXGI_FORMAT_BC6H_TYPELESS:
00241     case DXGI_FORMAT_BC6H_UF16:
00242     case DXGI_FORMAT_BC6H_SF16:
00243     case DXGI_FORMAT_BC7_TYPELESS:
00244     case DXGI_FORMAT_BC7_UNORM:
00245     case DXGI_FORMAT_BC7_UNORM_SRGB:
00246         return 8;
00247
00248     default:
00249         return 0;
00250     }
00251 }
00252
00253
00254 //--------------------------------------------------------------------------------------
00255 // Get surface information for a particular format
00256 //--------------------------------------------------------------------------------------
00257 static void GetSurfaceInfo(
00258     _In_ size_t width,
00259     _In_ size_t height,
00260     _In_ DXGI_FORMAT fmt,
00261     _Out_opt_ size_t* outNumBytes,
00262     _Out_opt_ size_t* outRowBytes,
00263     _Out_opt_ size_t* outNumRows
00264     )
00265 {
00266     size_t numBytes = 0;
00267     size_t rowBytes = 0;
00268     size_t numRows = 0;
00269
00270     bool bc = false;
00271     bool packed  = false;
00272     size_t bcnumBytesPerBlock = 0;
00273     switch (fmt)
00274     {
00275     case DXGI_FORMAT_BC1_TYPELESS:
00276     case DXGI_FORMAT_BC1_UNORM:
00277     case DXGI_FORMAT_BC1_UNORM_SRGB:
00278     case DXGI_FORMAT_BC4_TYPELESS:
00279     case DXGI_FORMAT_BC4_UNORM:
00280     case DXGI_FORMAT_BC4_SNORM:
00281         bc = true;
00282         bcnumBytesPerBlock = 8;
00283         break;
00284
00285     case DXGI_FORMAT_BC2_TYPELESS:
00286     case DXGI_FORMAT_BC2_UNORM:
00287     case DXGI_FORMAT_BC2_UNORM_SRGB:
00288     case DXGI_FORMAT_BC3_TYPELESS:
00289     case DXGI_FORMAT_BC3_UNORM:
00290     case DXGI_FORMAT_BC3_UNORM_SRGB:
00291     case DXGI_FORMAT_BC5_TYPELESS:
00292     case DXGI_FORMAT_BC5_UNORM:
00293     case DXGI_FORMAT_BC5_SNORM:
00294     case DXGI_FORMAT_BC6H_TYPELESS:
00295     case DXGI_FORMAT_BC6H_UF16:
00296     case DXGI_FORMAT_BC6H_SF16:
00297     case DXGI_FORMAT_BC7_TYPELESS:
00298     case DXGI_FORMAT_BC7_UNORM:
00299     case DXGI_FORMAT_BC7_UNORM_SRGB:
00300         bc = true;
00301         bcnumBytesPerBlock = 16;
00302         break;
00303
00304     case DXGI_FORMAT_R8G8_B8G8_UNORM:
00305     case DXGI_FORMAT_G8R8_G8B8_UNORM:
00306         packed = true;
00307         break;
00308     }
00309
00310     if (bc)
00311     {
00312         size_t numBlocksWide = 0;
00313         if (width > 0)
00314         {
00315             numBlocksWide = std::max<size_t>(1, (width + 3) / 4);
00316         }
00317         size_t numBlocksHigh = 0;
00318         if (height > 0)
00319         {
00320             numBlocksHigh = std::max<size_t>(1, (height + 3) / 4);
00321         }
00322         rowBytes = numBlocksWide * bcnumBytesPerBlock;
00323         numRows = numBlocksHigh;
00324     }
00325     else if (packed)
00326     {
00327         rowBytes = ((width + 1) >> 1) * 4;
00328         numRows = height;
00329     }
00330     else
00331     {
00332         size_t bpp = BitsPerPixel(fmt);
00333         rowBytes = (width * bpp + 7) / 8; // round up to nearest byte
00334         numRows = height;
00335     }
00336
00337     numBytes = rowBytes * numRows;
00338     if (outNumBytes)
00339     {
00340         *outNumBytes = numBytes;
00341     }
00342     if (outRowBytes)
00343     {
00344         *outRowBytes = rowBytes;
00345     }
00346     if (outNumRows)
00347     {
00348         *outNumRows = numRows;
00349     }
00350 }
00351
00352
00353 //--------------------------------------------------------------------------------------
00354 #define ISBITMASK(r, g, b, a) (ddpf.RBitMask == r && ddpf.GBitMask == g && ddpf.BBitMask == b && ddpf.ABitMask == a)
00355
00356 static DXGI_FORMAT GetDXGIFormat(const DDS_PIXELFORMAT& ddpf)
00357 {
00358     if (ddpf.flags & DDS_RGB)
00359     {
00360         // Note that sRGB formats are written using the "DX10" extended header
00361
00362         switch (ddpf.RGBBitCount)
00363         {
00364         case 32:
00365             if (ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000))
00366             {
00367                 return DXGI_FORMAT_R8G8B8A8_UNORM;
00368             }
00369
00370             if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000))
00371             {
00372                 return DXGI_FORMAT_B8G8R8A8_UNORM;
00373             }
00374
00375             if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0x00000000))
00376             {
00377                 return DXGI_FORMAT_B8G8R8X8_UNORM;
00378             }
00379
00380             // No DXGI format maps to ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0x00000000) aka D3DFMT_X8B8G8R8
00381
00382             // Note that many common DDS reader/writers (including D3DX) swap the
00383             // the RED/BLUE masks for 10:10:10:2 formats. We assumme
00384             // below that the 'backwards' header mask is being used since it is most
00385             // likely written by D3DX. The more robust solution is to use the 'DX10'
00386             // header extension and specify the DXGI_FORMAT_R10G10B10A2_UNORM format directly
00387
00388             // For 'correct' writers, this should be 0x000003ff, 0x000ffc00, 0x3ff00000 for RGB data
00389             if (ISBITMASK(0x3ff00000, 0x000ffc00, 0x000003ff, 0xc0000000))
00390             {
00391                 return DXGI_FORMAT_R10G10B10A2_UNORM;
00392             }
00393
00394             // No DXGI format maps to ISBITMASK(0x000003ff, 0x000ffc00, 0x3ff00000, 0xc0000000) aka D3DFMT_A2R10G10B10
00395
00396             if (ISBITMASK(0x0000ffff, 0xffff0000, 0x00000000, 0x00000000))
00397             {
00398                 return DXGI_FORMAT_R16G16_UNORM;
00399             }
00400
00401             if (ISBITMASK(0xffffffff, 0x00000000, 0x00000000, 0x00000000))
00402             {
00403                 // Only 32-bit color channel format in D3D9 was R32F
00404                 return DXGI_FORMAT_R32_FLOAT; // D3DX writes this out as a FourCC of 114
00405             }
00406             break;
00407
00408         case 24:
00409             // No 24bpp DXGI formats aka D3DFMT_R8G8B8
00410             break;
00411
00412         case 16:
00413             if (ISBITMASK(0x7c00, 0x03e0, 0x001f, 0x8000))
00414             {
00415                 return DXGI_FORMAT_B5G5R5A1_UNORM;
00416             }
00417             if (ISBITMASK(0xf800, 0x07e0, 0x001f, 0x0000))
00418             {
00419                 return DXGI_FORMAT_B5G6R5_UNORM;
00420             }
00421
00422             // No DXGI format maps to ISBITMASK(0x7c00, 0x03e0, 0x001f, 0x0000) aka D3DFMT_X1R5G5B5
00423             if (ISBITMASK(0x0f00, 0x00f0, 0x000f, 0xf000))
00424             {
00425                 return DXGI_FORMAT_B4G4R4A4_UNORM;
00426             }
00427
00428             // No DXGI format maps to ISBITMASK(0x0f00, 0x00f0, 0x000f, 0x0000) aka D3DFMT_X4R4G4B4
00429
00430             // No 3:3:2, 3:3:2:8, or paletted DXGI formats aka D3DFMT_A8R3G3B2, D3DFMT_R3G3B2, D3DFMT_P8, D3DFMT_A8P8, etc.
00431             break;
00432         }
00433     }
00434     else if (ddpf.flags & DDS_LUMINANCE)
00435     {
00436         if (8 == ddpf.RGBBitCount)
00437         {
00438             if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x00000000))
00439             {
00440                 return DXGI_FORMAT_R8_UNORM; // D3DX10/11 writes this out as DX10 extension
00441             }
00442
00443             // No DXGI format maps to ISBITMASK(0x0f, 0x00, 0x00, 0xf0) aka D3DFMT_A4L4
00444         }
00445
00446         if (16 == ddpf.RGBBitCount)
00447         {
00448             if (ISBITMASK(0x0000ffff, 0x00000000, 0x00000000, 0x00000000))
00449             {
00450                 return DXGI_FORMAT_R16_UNORM; // D3DX10/11 writes this out as DX10 extension
00451             }
00452             if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x0000ff00))
00453             {
00454                 return DXGI_FORMAT_R8G8_UNORM; // D3DX10/11 writes this out as DX10 extension
00455             }
00456         }
00457     }
00458     else if (ddpf.flags & DDS_ALPHA)
00459     {
00460         if (8 == ddpf.RGBBitCount)
00461         {
00462             return DXGI_FORMAT_A8_UNORM;
00463         }
00464     }
00465     else if (ddpf.flags & DDS_FOURCC)
00466     {
00467         if (MAKEFOURCC('D', 'X', 'T', '1') == ddpf.fourCC)
00468         {
00469             return DXGI_FORMAT_BC1_UNORM;
00470         }
00471         if (MAKEFOURCC('D', 'X', 'T', '3') == ddpf.fourCC)
00472         {
00473             return DXGI_FORMAT_BC2_UNORM;
00474         }
00475         if (MAKEFOURCC('D', 'X', 'T', '5') == ddpf.fourCC)
00476         {
00477             return DXGI_FORMAT_BC3_UNORM;
00478         }
00479
00480         // While pre-mulitplied alpha isn't directly supported by the DXGI formats,
00481         // they are basically the same as these BC formats so they can be mapped
00482         if (MAKEFOURCC('D', 'X', 'T', '2') == ddpf.fourCC)
00483         {
00484             return DXGI_FORMAT_BC2_UNORM;
00485         }
00486         if (MAKEFOURCC('D', 'X', 'T', '4') == ddpf.fourCC)
00487         {
00488             return DXGI_FORMAT_BC3_UNORM;
00489         }
00490
00491         if (MAKEFOURCC('A', 'T', 'I', '1') == ddpf.fourCC)
00492         {
00493             return DXGI_FORMAT_BC4_UNORM;
00494         }
00495         if (MAKEFOURCC('B', 'C', '4', 'U') == ddpf.fourCC)
00496         {
00497             return DXGI_FORMAT_BC4_UNORM;
00498         }
00499         if (MAKEFOURCC('B', 'C', '4', 'S') == ddpf.fourCC)
00500         {
00501             return DXGI_FORMAT_BC4_SNORM;
00502         }
00503
00504         if (MAKEFOURCC('A', 'T', 'I', '2') == ddpf.fourCC)
00505         {
00506             return DXGI_FORMAT_BC5_UNORM;
00507         }
00508         if (MAKEFOURCC('B', 'C', '5', 'U') == ddpf.fourCC)
00509         {
00510             return DXGI_FORMAT_BC5_UNORM;
00511         }
00512         if (MAKEFOURCC('B', 'C', '5', 'S') == ddpf.fourCC)
00513         {
00514             return DXGI_FORMAT_BC5_SNORM;
00515         }
00516
00517         // BC6H and BC7 are written using the "DX10" extended header
00518
00519         if (MAKEFOURCC('R', 'G', 'B', 'G') == ddpf.fourCC)
00520         {
00521             return DXGI_FORMAT_R8G8_B8G8_UNORM;
00522         }
00523         if (MAKEFOURCC('G', 'R', 'G', 'B') == ddpf.fourCC)
00524         {
00525             return DXGI_FORMAT_G8R8_G8B8_UNORM;
00526         }
00527
00528         // Check for D3DFORMAT enums being set here
00529         switch (ddpf.fourCC)
00530         {
00531         case 36: // D3DFMT_A16B16G16R16
00532             return DXGI_FORMAT_R16G16B16A16_UNORM;
00533
00534         case 110: // D3DFMT_Q16W16V16U16
00535             return DXGI_FORMAT_R16G16B16A16_SNORM;
00536
00537         case 111: // D3DFMT_R16F
00538             return DXGI_FORMAT_R16_FLOAT;
00539
00540         case 112: // D3DFMT_G16R16F
00541             return DXGI_FORMAT_R16G16_FLOAT;
00542
00543         case 113: // D3DFMT_A16B16G16R16F
00544             return DXGI_FORMAT_R16G16B16A16_FLOAT;
00545
00546         case 114: // D3DFMT_R32F
00547             return DXGI_FORMAT_R32_FLOAT;
00548
00549         case 115: // D3DFMT_G32R32F
00550             return DXGI_FORMAT_R32G32_FLOAT;
00551
00552         case 116: // D3DFMT_A32B32G32R32F
00553             return DXGI_FORMAT_R32G32B32A32_FLOAT;
00554         }
00555     }
00556
00557     return DXGI_FORMAT_UNKNOWN;
00558 }
00559
00560
00561 //--------------------------------------------------------------------------------------
00562 static void FillInitData(
00563     _In_ size_t width,
00564     _In_ size_t height,
00565     _In_ size_t depth,
00566     _In_ size_t mipCount,
00567     _In_ size_t arraySize,
00568     _In_ DXGI_FORMAT format,
00569     _In_ size_t maxsize,
00570     _In_ size_t bitSize,
00571     _In_reads_bytes_(bitSize) const byte* bitData,
00572     _Out_ size_t& twidth,
00573     _Out_ size_t& theight,
00574     _Out_ size_t& tdepth,
00575     _Out_ size_t& skipMip,
00576     _Out_writes_(mipCount*arraySize) D3D11_SUBRESOURCE_DATA* initData
00577     )
00578 {
00579     if (!bitData || !initData)
00580     {
00581         throw ref new Platform::InvalidArgumentException();
00582     }
00583
00584     skipMip = 0;
00585     twidth = 0;
00586     theight = 0;
00587     tdepth = 0;
00588
00589     size_t NumBytes = 0;
00590     size_t RowBytes = 0;
00591     size_t NumRows = 0;
00592     const byte* pSrcBits = bitData;
00593     const byte* pEndBits = bitData + bitSize;
00594
00595     size_t index = 0;
00596     for (size_t j = 0; j < arraySize; j++)
00597     {
00598         size_t w = width;
00599         size_t h = height;
00600         size_t d = depth;
00601         for (size_t i = 0; i < mipCount; i++)
00602         {
00603             GetSurfaceInfo(w, h, format, &NumBytes, &RowBytes, &NumRows);
00604
00605             if ((mipCount <= 1) || !maxsize || (w <= maxsize && h <= maxsize && d <= maxsize))
00606             {
00607                 if (!twidth)
00608                 {
00609                     twidth = w;
00610                     theight = h;
00611                     tdepth = d;
00612                 }
00613
00614                 initData[index].pSysMem = (const void*)pSrcBits;
00615                 initData[index].SysMemPitch = static_cast<UINT>(RowBytes);
00616                 initData[index].SysMemSlicePitch = static_cast<UINT>(NumBytes);
00617                 ++index;
00618             }
00619             else
00620             {
00621                 ++skipMip;
00622             }
00623
00624             if (pSrcBits + (NumBytes*d) > pEndBits)
00625             {
00626                 throw ref new Platform::OutOfBoundsException();
00627             }
00628
00629             pSrcBits += NumBytes * d;
00630
00631             w = w >> 1;
00632             h = h >> 1;
00633             d = d >> 1;
00634             if (w == 0)
00635             {
00636                 w = 1;
00637             }
00638             if (h == 0)
00639             {
00640                 h = 1;
00641             }
00642             if (d == 0)
00643             {
00644                 d = 1;
00645             }
00646         }
00647     }
00648
00649     if (!index)
00650     {
00651         throw ref new Platform::FailureException();
00652     }
00653 }
00654
00655
00656 //--------------------------------------------------------------------------------------
00657 static HRESULT CreateD3DResources(
00658     _In_ ID3D11Device* d3dDevice,
00659     _In_ uint32 resDim,
00660     _In_ size_t width,
00661     _In_ size_t height,
00662     _In_ size_t depth,
00663     _In_ size_t mipCount,
00664     _In_ size_t arraySize,
00665     _In_ DXGI_FORMAT format,
00666     _In_ bool isCubeMap,
00667     _In_reads_(mipCount*arraySize) D3D11_SUBRESOURCE_DATA* initData,
00668     _Out_opt_ ID3D11Resource** texture,
00669     _Out_opt_ ID3D11ShaderResourceView** textureView
00670     )
00671 {
00672     if (!d3dDevice || !initData)
00673     {
00674         return E_INVALIDARG;
00675     }
00676
00677     HRESULT hr = E_FAIL;
00678
00679     switch (resDim)
00680     {
00681         case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
00682             {
00683                 D3D11_TEXTURE1D_DESC desc;
00684                 desc.Width = static_cast<UINT>(width);
00685                 desc.MipLevels = static_cast<UINT>(mipCount);
00686                 desc.ArraySize = static_cast<UINT>(arraySize);
00687                 desc.Format = format;
00688                 desc.Usage = D3D11_USAGE_DEFAULT;
00689                 desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
00690                 desc.CPUAccessFlags = 0;
00691                 desc.MiscFlags = 0;
00692
00693                 ID3D11Texture1D* tex = nullptr;
00694                 hr = d3dDevice->CreateTexture1D(&desc, initData, &tex);
00695
00696                 if (SUCCEEDED(hr) && tex != 0)
00697                 {
00698                     if (textureView != 0)
00699                     {
00700                         D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
00701                         memset(&SRVDesc, 0, sizeof(SRVDesc));
00702                         SRVDesc.Format = format;
00703
00704                         if (arraySize > 1)
00705                         {
00706                             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE1DARRAY;
00707                             SRVDesc.Texture1DArray.MipLevels = desc.MipLevels;
00708                             SRVDesc.Texture1DArray.ArraySize = static_cast<UINT>(arraySize);
00709                         }
00710                         else
00711                         {
00712                             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE1D;
00713                             SRVDesc.Texture1D.MipLevels = desc.MipLevels;
00714                         }
00715
00716                         hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView);
00717
00718                         if (FAILED(hr))
00719                         {
00720                             tex->Release();
00721                             return hr;
00722                         }
00723                     }
00724
00725                     if (texture != 0)
00726                     {
00727                         *texture = tex;
00728                     }
00729                     else
00730                     {
00731                         tex->Release();
00732                     }
00733                 }
00734             }
00735             break;
00736
00737         case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
00738             {
00739                 D3D11_TEXTURE2D_DESC desc;
00740                 desc.Width = static_cast<UINT>(width);
00741                 desc.Height = static_cast<UINT>(height);
00742                 desc.MipLevels = static_cast<UINT>(mipCount);
00743                 desc.ArraySize = static_cast<UINT>(arraySize);
00744                 desc.Format = format;
00745                 desc.SampleDesc.Count = 1;
00746                 desc.SampleDesc.Quality = 0;
00747                 desc.Usage = D3D11_USAGE_DEFAULT;
00748                 desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
00749                 desc.CPUAccessFlags = 0;
00750                 desc.MiscFlags = (isCubeMap) ? D3D11_RESOURCE_MISC_TEXTURECUBE : 0;
00751
00752                 ID3D11Texture2D* tex = nullptr;
00753                 hr = d3dDevice->CreateTexture2D(&desc, initData, &tex);
00754
00755                 if (SUCCEEDED(hr) && tex != 0)
00756                 {
00757                     if (textureView != 0)
00758                     {
00759                         D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
00760                         memset(&SRVDesc, 0, sizeof(SRVDesc));
00761                         SRVDesc.Format = format;
00762
00763                         if (isCubeMap)
00764                         {
00765                             if (arraySize > 6)
00766                             {
00767                                 SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURECUBEARRAY;
00768                                 SRVDesc.TextureCubeArray.MipLevels = desc.MipLevels;
00769
00770                                 // Earlier we set arraySize to (NumCubes * 6)
00771                                 SRVDesc.TextureCubeArray.NumCubes = static_cast<UINT>(arraySize / 6);
00772                             }
00773                             else
00774                             {
00775                                 SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURECUBE;
00776                                 SRVDesc.TextureCube.MipLevels = desc.MipLevels;
00777                             }
00778                         }
00779                         else if (arraySize > 1)
00780                         {
00781                             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE2DARRAY;
00782                             SRVDesc.Texture2DArray.MipLevels = desc.MipLevels;
00783                             SRVDesc.Texture2DArray.ArraySize = static_cast<UINT>(arraySize);
00784                         }
00785                         else
00786                         {
00787                             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE2D;
00788                             SRVDesc.Texture2D.MipLevels = desc.MipLevels;
00789                         }
00790
00791                         hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView);
00792
00793                         if (FAILED(hr))
00794                         {
00795                             tex->Release();
00796                             return hr;
00797                         }
00798                     }
00799
00800                     if (texture != 0)
00801                     {
00802                         *texture = tex;
00803                     }
00804                     else
00805                     {
00806                         tex->Release();
00807                     }
00808                 }
00809             }
00810             break;
00811
00812         case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
00813             {
00814                 D3D11_TEXTURE3D_DESC desc;
00815                 desc.Width = static_cast<UINT>(width);
00816                 desc.Height = static_cast<UINT>(height);
00817                 desc.Depth = static_cast<UINT>(depth);
00818                 desc.MipLevels = static_cast<UINT>(mipCount);
00819                 desc.Format = format;
00820                 desc.Usage = D3D11_USAGE_DEFAULT;
00821                 desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
00822                 desc.CPUAccessFlags = 0;
00823                 desc.MiscFlags = 0;
00824
00825                 ID3D11Texture3D* tex = nullptr;
00826                 hr = d3dDevice->CreateTexture3D(&desc, initData, &tex);
00827
00828                 if (SUCCEEDED(hr) && tex != 0)
00829                 {
00830                     if (textureView != 0)
00831                     {
00832                         D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
00833                         memset(&SRVDesc, 0, sizeof(SRVDesc));
00834                         SRVDesc.Format = format;
00835                         SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE3D;
00836                         SRVDesc.Texture3D.MipLevels = desc.MipLevels;
00837
00838                         hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView);
00839
00840                         if (FAILED(hr))
00841                         {
00842                             tex->Release();
00843                             return hr;
00844                         }
00845                     }
00846
00847                     if (texture != 0)
00848                     {
00849                         *texture = tex;
00850                     }
00851                     else
00852                     {
00853                         tex->Release();
00854                     }
00855                 }
00856             }
00857             break;
00858     }
00859
00860     return hr;
00861 }
00862
00863
00864 //--------------------------------------------------------------------------------------
00865 static void CreateTextureFromDDS(
00866     _In_ ID3D11Device* d3dDevice,
00867     _In_ const DDS_HEADER* header,
00868     _In_reads_bytes_(bitSize) const byte* bitData,
00869     _In_ size_t bitSize,
00870     _Out_opt_ ID3D11Resource** texture,
00871     _Out_opt_ ID3D11ShaderResourceView** textureView,
00872     _In_ size_t maxsize
00873     )
00874 {
00875     HRESULT hr = S_OK;
00876
00877     size_t width = header->width;
00878     size_t height = header->height;
00879     size_t depth = header->depth;
00880
00881     uint32 resDim = D3D11_RESOURCE_DIMENSION_UNKNOWN;
00882     size_t arraySize = 1;
00883     DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;
00884     bool isCubeMap = false;
00885
00886     size_t mipCount = header->mipMapCount;
00887     if (0 == mipCount)
00888     {
00889         mipCount = 1;
00890     }
00891
00892     if ((header->ddspf.flags & DDS_FOURCC) &&
00893         (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC))
00894     {
00895         const DDS_HEADER_DXT10* d3d10ext = reinterpret_cast<const DDS_HEADER_DXT10*>((const char*)header + sizeof(DDS_HEADER));
00896
00897         arraySize = d3d10ext->arraySize;
00898         if (arraySize == 0)
00899         {
00900             throw ref new Platform::FailureException();
00901         }
00902
00903         if (BitsPerPixel(d3d10ext->dxgiFormat) == 0)
00904         {
00905             throw ref new Platform::FailureException();
00906         }
00907
00908         format = d3d10ext->dxgiFormat;
00909
00910         switch (d3d10ext->resourceDimension)
00911         {
00912         case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
00913             // D3DX writes 1D textures with a fixed Height of 1
00914             if ((header->flags & DDS_HEIGHT) && height != 1)
00915             {
00916                 throw ref new Platform::FailureException();
00917             }
00918             height = depth = 1;
00919             break;
00920
00921         case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
00922             if (d3d10ext->miscFlag & D3D11_RESOURCE_MISC_TEXTURECUBE)
00923             {
00924                 arraySize *= 6;
00925                 isCubeMap = true;
00926             }
00927             depth = 1;
00928             break;
00929
00930         case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
00931             if (!(header->flags & DDS_HEADER_FLAGS_VOLUME))
00932             {
00933                 throw ref new Platform::FailureException();
00934             }
00935
00936             if (arraySize > 1)
00937             {
00938                 throw ref new Platform::FailureException();
00939             }
00940             break;
00941
00942         default:
00943             return throw ref new Platform::FailureException();
00944         }
00945
00946         resDim = d3d10ext->resourceDimension;
00947     }
00948     else
00949     {
00950         format = GetDXGIFormat(header->ddspf);
00951
00952         if (format == DXGI_FORMAT_UNKNOWN)
00953         {
00954             return throw ref new Platform::FailureException();
00955         }
00956
00957         if (header->flags & DDS_HEADER_FLAGS_VOLUME)
00958         {
00959             resDim = D3D11_RESOURCE_DIMENSION_TEXTURE3D;
00960         }
00961         else
00962         {
00963             if (header->caps2 & DDS_CUBEMAP)
00964             {
00965                 // We require all six faces to be defined
00966                 if ((header->caps2 & DDS_CUBEMAP_ALLFACES) != DDS_CUBEMAP_ALLFACES)
00967                 {
00968                     return throw ref new Platform::FailureException();
00969                 }
00970
00971                 arraySize = 6;
00972                 isCubeMap = true;
00973             }
00974
00975             depth = 1;
00976             resDim = D3D11_RESOURCE_DIMENSION_TEXTURE2D;
00977
00978             // Note there's no way for a legacy Direct3D 9 DDS to express a '1D' texture
00979         }
00980
00981         assert(BitsPerPixel(format) != 0);
00982     }
00983
00984     // Bound sizes (for security purposes we don't trust DDS file metadata larger than the D3D 11.x hardware requirements)
00985     if (mipCount > D3D11_REQ_MIP_LEVELS)
00986     {
00987         return throw ref new Platform::FailureException();
00988     }
00989
00990     switch (resDim)
00991     {
00992         case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
00993             if ((arraySize > D3D11_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION) ||
00994                 (width > D3D11_REQ_TEXTURE1D_U_DIMENSION))
00995             {
00996                 return throw ref new Platform::FailureException();
00997             }
00998             break;
00999
01000         case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
01001             if (isCubeMap)
01002             {
01003                 // This is the right bound because we set arraySize to (NumCubes*6) above
01004                 if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) ||
01005                     (width > D3D11_REQ_TEXTURECUBE_DIMENSION) ||
01006                     (height > D3D11_REQ_TEXTURECUBE_DIMENSION))
01007                 {
01008                     return throw ref new Platform::FailureException();
01009                 }
01010             }
01011             else if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) ||
01012                     (width > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION) ||
01013                     (height > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION))
01014             {
01015                 return throw ref new Platform::FailureException();
01016             }
01017             break;
01018
01019         case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
01020             if ((arraySize > 1) ||
01021                 (width > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) ||
01022                 (height > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) ||
01023                 (depth > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION))
01024             {
01025                 return throw ref new Platform::FailureException();
01026             }
01027             break;
01028     }
01029
01030     // Create the texture
01031     std::unique_ptr<D3D11_SUBRESOURCE_DATA> initData(new D3D11_SUBRESOURCE_DATA[mipCount * arraySize]);
01032
01033     size_t skipMip = 0;
01034     size_t twidth = 0;
01035     size_t theight = 0;
01036     size_t tdepth = 0;
01037     FillInitData(width, height, depth, mipCount, arraySize, format, maxsize, bitSize, bitData, twidth, theight, tdepth, skipMip, initData.get());
01038
01039     hr = CreateD3DResources(d3dDevice, resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize, format, isCubeMap, initData.get(), texture, textureView);
01040
01041     if (FAILED(hr) && !maxsize && (mipCount > 1))
01042     {
01043         // Retry with a maxsize determined by feature level
01044         switch (d3dDevice->GetFeatureLevel())
01045         {
01046         case D3D_FEATURE_LEVEL_9_1:
01047         case D3D_FEATURE_LEVEL_9_2:
01048             if (isCubeMap)
01049             {
01050                 maxsize = D3D_FL9_1_REQ_TEXTURECUBE_DIMENSION;
01051             }
01052             else
01053             {
01054                 maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D)
01055                     ? D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION
01056                     : D3D_FL9_1_REQ_TEXTURE2D_U_OR_V_DIMENSION;
01057             }
01058             break;
01059
01060         case D3D_FEATURE_LEVEL_9_3:
01061             maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D)
01062                 ? D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION
01063                 : D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION;
01064             break;
01065
01066         default: // D3D_FEATURE_LEVEL_10_0 & D3D_FEATURE_LEVEL_10_1
01067             maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D)
01068                 ? D3D10_REQ_TEXTURE3D_U_V_OR_W_DIMENSION
01069                 : D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION;
01070             break;
01071         }
01072
01073         FillInitData(width, height, depth, mipCount, arraySize, format, maxsize, bitSize, bitData, twidth, theight, tdepth, skipMip, initData.get());
01074
01075         hr = CreateD3DResources(d3dDevice, resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize, format, isCubeMap, initData.get(), texture, textureView);
01076     }
01077
01078     DX::ThrowIfFailed(hr);
01079 }
01080
01081 //--------------------------------------------------------------------------------------
01082 void CreateDDSTextureFromMemory(
01083     _In_ ID3D11Device* d3dDevice,
01084     _In_reads_bytes_(ddsDataSize) const byte* ddsData,
01085     _In_ size_t ddsDataSize,
01086     _Out_opt_ ID3D11Resource** texture,
01087     _Out_opt_ ID3D11ShaderResourceView** textureView,
01088     _In_ size_t maxsize
01089     )
01090 {
01091     if (!d3dDevice || !ddsData || (!texture && !textureView))
01092     {
01093         throw ref new Platform::InvalidArgumentException();
01094     }
01095
01096     // Validate DDS file in memory
01097     if (ddsDataSize < (sizeof(uint32) + sizeof(DDS_HEADER)))
01098     {
01099         throw ref new Platform::FailureException();
01100     }
01101
01102     uint32 dwMagicNumber = *(const uint32*)(ddsData);
01103     if (dwMagicNumber != DDS_MAGIC)
01104     {
01105         throw ref new Platform::FailureException();
01106     }
01107
01108     const DDS_HEADER* header = reinterpret_cast<const DDS_HEADER*>(ddsData + sizeof(uint32));
01109
01110     // Verify header to validate DDS file
01111     if (header->size != sizeof(DDS_HEADER) ||
01112         header->ddspf.size != sizeof(DDS_PIXELFORMAT))
01113     {
01114         throw ref new Platform::FailureException();
01115     }
01116
01117     // Check for DX10 extension
01118     bool bDXT10Header = false;
01119     if ((header->ddspf.flags & DDS_FOURCC) &&
01120         (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC))
01121     {
01122         // Must be long enough for both headers and magic value
01123         if (ddsDataSize < (sizeof(DDS_HEADER) + sizeof(uint32) + sizeof(DDS_HEADER_DXT10)))
01124         {
01125             throw ref new Platform::FailureException();
01126         }
01127
01128         bDXT10Header = true;
01129     }
01130
01131     ptrdiff_t offset = sizeof(uint32) + sizeof(DDS_HEADER) + (bDXT10Header ? sizeof(DDS_HEADER_DXT10) : 0);
01132
01133     CreateTextureFromDDS(d3dDevice, header, ddsData + offset, ddsDataSize - offset, texture, textureView, maxsize);
01134 }
Generated on Sat Nov 23 2024 16:08:10 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Getting started with C++ simple blog reader/C++/MainPage.xaml.h Source File

  • Getting started with C++ simple blog reader

MainPage.xaml.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 //
00009 // MainPage.xaml.h
00010 // Declaration of the MainPage class.
00011 //
00012
00013 #pragma once
00014
00015 #include "MainPage.g.h"
00016 #include "FeedData.h"
00017 #include "DateConverter.h"
00018
00019
00020
00021
00022
00023 namespace SimpleBlogReader
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 MainPage sealed
00030   {
00031   public:
00032     MainPage();
00033
00034   protected:
00035     virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00036   private:
00037     void GetFeedData(Platform::String^ feedUriString);
00038     FeedData^ feedData;
00039         void PageLoadedHandler(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040        void ItemListView_SelectionChanged(Platform::Object^ sender,
00041                                    Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00042
00043   };
00044 }
Generated on Sat Nov 23 2024 16:07:46 for Win8-Examples by doxygen 1.7.1


Win8-Examples: StreamSocket/C++/pch.cpp Source File

  • StreamSocket

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/GameRenderer.h Source File

  • XAML DirectX 3D shooting game

GameRenderer.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 // GameRenderer:
00011 // This is the renderer for the game.  It derives from DirectXBase.
00012 // It is responsble for creating and maintaining all the D3D11 and D2D objects
00013 // used to generate the game visuals.  It maintains a reference to the Simple3DGame
00014 // object to retrieve the list of objects to render as well as status of the
00015 // game for the Heads Up Display (HUD).
00016 //
00017 // The renderer is designed to use a standard vertex layout across all objects.  This
00018 // simplifies the shader design and allows for easy changes between shaders independent
00019 // of the objects' geometry.  Each vertex is defined by a position, a normal and one set of
00020 // 2D texture coordinates.  The shaders all expect one 2D texture and 4 constant buffers:
00021 //     m_constantBufferNeverChanges - general parameters that are set only once.  This includes
00022 //         all the lights used in scene generation.
00023 //     m_constantBufferChangeOnResize - the projection matrix.  It is typically only changed when
00024 //         the window is resized, however it will be changed 2x per frame when rendering
00025 //         in 3D stereo.
00026 //     m_constantBufferChangesEveryFrame - the view transformation matrix.  This is set once per frame.
00027 //     m_constantBufferChangesEveryPrim - the parameters for each object.  It includes the object to world
00028 //         transformation matrix as well as material properties like color and specular exponent for lighting
00029 //         calculations.
00030 //
00031 // The renderer also maintains a set of texture resources that will be associated with particular game objects.
00032 // It knows which textures are to be associated with which objects and will do that association once the
00033 // textures have been loaded.
00034 //
00035 // The renderer provides a set of methods to allow for a "standard" sequence to be executed for loading general
00036 // game resources and for level specific resources.  Because D3D11 allows free threaded creation of objects,
00037 // textures will be loaded asynchronously and in parallel, however D3D11 does not allow for multiple threads to
00038 // be using the DeviceContext at the same time.
00039 //
00040 // The pattern is:
00041 //     create_task([this]()
00042 //     {
00043 //         // create/load device resources
00044 //     }).then([this]()
00045 //     {
00046 //         // create/load device context resources
00047 //     }, task_continuation_context::use_current());
00048
00049 #include "DirectXBase.h"
00050 #include "GameHud.h"
00051 #include "Simple3DGame.h"
00052
00053 ref class Simple3DGame;
00054 ref class GameHud;
00055
00056 ref class GameRenderer : public DirectXBase
00057 {
00058 internal:
00059     GameRenderer();
00060
00061     virtual void Initialize(
00062         _In_ Windows::UI::Core::CoreWindow^ window,
00063         _In_ Windows::UI::Xaml::Controls::SwapChainBackgroundPanel^ swapChainPanel,
00064         float dpi
00065         ) override;
00066
00067     virtual void CreateDeviceIndependentResources() override;
00068     virtual void CreateDeviceResources() override;
00069     virtual void UpdateForWindowSizeChange() override;
00070     virtual void Render() override;
00071     virtual void HandleDeviceLost() override;
00072
00073     concurrency::task<void> CreateGameDeviceResourcesAsync(_In_ Simple3DGame^ game);
00074     void FinalizeCreateGameDeviceResources();
00075     concurrency::task<void> LoadLevelResourcesAsync();
00076     void FinalizeLoadLevelResources();
00077
00078     void SetBackground(uint32 background);
00079
00080     GameHud^ Hud();
00081
00082 #if defined(_DEBUG)
00083     void ReportLiveDeviceObjects();
00084 #endif
00085
00086 protected private:
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 Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Store device app for camera/C#,C++/Wrapper/SampleMft0.h Source File

  • Windows Store device app for camera
  • C#,C++
  • Wrapper

SampleMft0.h

Go to the documentation of this file.
00001
00002
00003 /* this ALWAYS GENERATED file contains the definitions for the interfaces */
00004
00005
00006  /* File created by MIDL compiler version 8.00.0591 */
00007 /* @@MIDL_FILE_HEADING(  ) */
00008
00009 #pragma warning( disable: 4049 )  /* more than 64k source lines */
00010
00011
00012 /* verify that the <rpcndr.h> version is high enough to compile this file*/
00013 #ifndef __REQUIRED_RPCNDR_H_VERSION__
00014 #define __REQUIRED_RPCNDR_H_VERSION__ 500
00015 #endif
00016
00017 /* verify that the <rpcsal.h> version is high enough to compile this file*/
00018 #ifndef __REQUIRED_RPCSAL_H_VERSION__
00019 #define __REQUIRED_RPCSAL_H_VERSION__ 100
00020 #endif
00021
00022 #include "rpc.h"
00023 #include "rpcndr.h"
00024
00025 #ifndef __RPCNDR_H_VERSION__
00026 #error this stub requires an updated version of <rpcndr.h>
00027 #endif // __RPCNDR_H_VERSION__
00028
00029 #ifndef COM_NO_WINDOWS_H
00030 #include "windows.h"
00031 #include "ole2.h"
00032 #endif /*COM_NO_WINDOWS_H*/
00033
00034 #ifndef __samplemft0_h__
00035 #define __samplemft0_h__
00036
00037 #if defined(_MSC_VER) && (_MSC_VER >= 1020)
00038 #pragma once
00039 #endif
00040
00041 /* Forward Declarations */
00042
00043 #ifndef __IMft0_FWD_DEFINED__
00044 #define __IMft0_FWD_DEFINED__
00045 typedef interface IMft0 IMft0;
00046
00047 #endif  /* __IMft0_FWD_DEFINED__ */
00048
00049
00050 #ifndef __Mft0_FWD_DEFINED__
00051 #define __Mft0_FWD_DEFINED__
00052
00053 #ifdef __cplusplus
00054 typedef class Mft0 Mft0;
00055 #else
00056 typedef struct Mft0 Mft0;
00057 #endif /* __cplusplus */
00058
00059 #endif  /* __Mft0_FWD_DEFINED__ */
00060
00061
00062 /* header files for imported files */
00063 #include "oaidl.h"
00064 #include "ocidl.h"
00065 #include "Inspectable.h"
00066 #include "mftransform.h"
00067
00068 #ifdef __cplusplus
00069 extern "C"{
00070 #endif
00071
00072
00073 #ifndef __IMft0_INTERFACE_DEFINED__
00074 #define __IMft0_INTERFACE_DEFINED__
00075
00076 /* interface IMft0 */
00077 /* [unique][nonextensible][oleautomation][uuid][object] */
00078
00079
00080 EXTERN_C const IID IID_IMft0;
00081
00082 #if defined(__cplusplus) && !defined(CINTERFACE)
00083
00084     MIDL_INTERFACE("F5208B72-A37A-457E-A309-AE3060780E21")
00085     IMft0 : public IUnknown
00086     {
00087     public:
00088         virtual /* [id] */ HRESULT STDMETHODCALLTYPE UpdateDsp(
00089             /* [in] */ UINT32 uiPercentOfScreen) = 0;
00090
00091         virtual /* [id] */ HRESULT STDMETHODCALLTYPE Enable( void) = 0;
00092
00093         virtual /* [id] */ HRESULT STDMETHODCALLTYPE Disable( void) = 0;
00094
00095         virtual /* [id] */ HRESULT STDMETHODCALLTYPE GetDspSetting(
00096             /* [out] */ __RPC__out UINT *puiPercentOfScreen,
00097             /* [out] */ __RPC__out BOOL *pIsEnabled) = 0;
00098
00099     };
00100
00101
00102 #else   /* C style interface */
00103
00104     typedef struct IMft0Vtbl
00105     {
00106         BEGIN_INTERFACE
00107
00108         HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
00109             __RPC__in IMft0 * This,
00110             /* [in] */ __RPC__in REFIID riid,
00111             /* [annotation][iid_is][out] */
00112             __RPC__deref_out _Result_nullonfailure_  void **ppvObject);
00113
00114         ULONG ( STDMETHODCALLTYPE *AddRef )(
00115             __RPC__in IMft0 * This);
00116
00117         ULONG ( STDMETHODCALLTYPE *Release )(
00118             __RPC__in IMft0 * This);
00119
00120         /* [id] */ HRESULT ( STDMETHODCALLTYPE *UpdateDsp )(
00121             __RPC__in IMft0 * This,
00122             /* [in] */ UINT32 uiPercentOfScreen);
00123
00124         /* [id] */ HRESULT ( STDMETHODCALLTYPE *Enable )(
00125             __RPC__in IMft0 * This);
00126
00127         /* [id] */ HRESULT ( STDMETHODCALLTYPE *Disable )(
00128             __RPC__in IMft0 * This);
00129
00130         /* [id] */ HRESULT ( STDMETHODCALLTYPE *GetDspSetting )(
00131             __RPC__in IMft0 * This,
00132             /* [out] */ __RPC__out UINT *puiPercentOfScreen,
00133             /* [out] */ __RPC__out BOOL *pIsEnabled);
00134
00135         END_INTERFACE
00136     } IMft0Vtbl;
00137
00138     interface IMft0
00139     {
00140         CONST_VTBL struct IMft0Vtbl *lpVtbl;
00141     };
00142
00143
00144
00145 #ifdef COBJMACROS
00146
00147
00148 #define IMft0_QueryInterface(This,riid,ppvObject) \
00149     ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )
00150
00151 #define IMft0_AddRef(This)  \
00152     ( (This)->lpVtbl -> AddRef(This) )
00153
00154 #define IMft0_Release(This) \
00155     ( (This)->lpVtbl -> Release(This) )
00156
00157
00158 #define IMft0_UpdateDsp(This,uiPercentOfScreen) \
00159     ( (This)->lpVtbl -> UpdateDsp(This,uiPercentOfScreen) )
00160
00161 #define IMft0_Enable(This)  \
00162     ( (This)->lpVtbl -> Enable(This) )
00163
00164 #define IMft0_Disable(This) \
00165     ( (This)->lpVtbl -> Disable(This) )
00166
00167 #define IMft0_GetDspSetting(This,puiPercentOfScreen,pIsEnabled) \
00168     ( (This)->lpVtbl -> GetDspSetting(This,puiPercentOfScreen,pIsEnabled) )
00169
00170 #endif /* COBJMACROS */
00171
00172
00173 #endif  /* C style interface */
00174
00175
00176
00177
00178 #endif  /* __IMft0_INTERFACE_DEFINED__ */
00179
00180
00181
00182 #ifndef __SampleMft0Lib_LIBRARY_DEFINED__
00183 #define __SampleMft0Lib_LIBRARY_DEFINED__
00184
00185 /* library SampleMft0Lib */
00186 /* [version][uuid] */
00187
00188
00189 EXTERN_C const IID LIBID_SampleMft0Lib;
00190
00191 EXTERN_C const CLSID CLSID_Mft0;
00192
00193 #ifdef __cplusplus
00194
00195 class DECLSPEC_UUID("7BB640D9-33A4-4759-B290-F41A31DCF848")
00196 Mft0;
00197 #endif
00198 #endif /* __SampleMft0Lib_LIBRARY_DEFINED__ */
00199
00200 /* Additional Prototypes for ALL interfaces */
00201
00202 /* end of Additional Prototypes */
00203
00204 #ifdef __cplusplus
00205 }
00206 #endif
00207
00208 #endif
00209
00210
Generated on Sat Nov 23 2024 16:08:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Association launching/C++/ScenarioList.xaml.h Source File

  • Association launching

ScenarioList.xaml.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 //
00009 // ScenarioList.xaml.h
00010 // Declaration of the ScenarioList class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioList.g.h"
00017 #include "MainPage.g.h"
00018
00019 using namespace Windows::UI::Xaml::Controls;
00020 using namespace CppSamplesUtils;
00021
00022 namespace AssociationLaunching
00023 {
00024   [Windows::Foundation::Metadata::WebHostHidden]
00025     public ref class ScenarioList sealed
00026     {
00027     public:
00028         ScenarioList();
00029
00030     protected:
00031         void Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e);
00032         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00033
00034     private:
00035         ~ScenarioList();
00036         MainPage^ rootPage;
00037     };
00038 }
Generated on Sat Nov 23 2024 16:07:57 for Win8-Examples by doxygen 1.7.1


Win8-Examples: UI contrast and settings/C++/common/suspensionmanager.cpp Source File

  • UI contrast and settings
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:37 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media Play To/C++/App.xaml.cpp Source File

  • Media Play To

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: User domain name/C++/Constants.h Source File

  • User domain name

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"UserDomainName");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044
00045
00046 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Touch hit testing/C++/Shape.cpp Source File

  • Input Touch hit testing

Shape.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 "DirectXSample.h"
00010 #include <math.h>
00011 #include "Shape.h"
00012
00013 // Shape Constructor
00014 Shape::Shape() :
00015     m_color(D2D1::ColorF::Blue)
00016 {
00017 }
00018
00019 // Shape Descructor
00020 Shape::~Shape()
00021 {
00022 }
00023
00024 // Initialize shape object
00025 void Shape::InitializeObject(_In_reads_(numPoints) Windows::Foundation::Point const* points, _In_ int numPoints,
00026                              _In_ D2D1::ColorF color)
00027 {
00028     m_polygonRelative.numPoints = numPoints;
00029     m_color = color;
00030
00031     if (numPoints == 2)
00032     {
00033         m_polygonRelative.isRect = true;
00034         m_polygonRelative.rcBound.X = points[0].X;
00035         m_polygonRelative.rcBound.Y = points[0].Y;
00036         m_polygonRelative.rcBound.Width = points[1].X - points[0].X;
00037         m_polygonRelative.rcBound.Height = points[1].Y - points[0].Y;
00038
00039         // Initialize points
00040         m_polygonRelative.points[0] = points[0];
00041         m_polygonRelative.points[1].X = points[1].X;
00042         m_polygonRelative.points[1].Y = points[0].Y;
00043         m_polygonRelative.points[2] = points[1];
00044         m_polygonRelative.points[3].X = points[0].X;
00045         m_polygonRelative.points[3].Y = points[1].Y;
00046         m_polygonRelative.points[4] = points[0];
00047         m_polygonRelative.numPoints = 5;
00048     }
00049     else
00050     {
00051         m_polygonRelative.isRect = false;
00052
00053         // calculate width and height
00054         if (numPoints > 0)
00055         {
00056             m_polygonRelative.points[0] = points[0];
00057
00058             // Copy polygon points to m_polygonRelative object and calculate polygon bounding box
00059             float left, right, top, bottom;
00060             left = right = points[0].X;
00061             top = bottom = points[0].Y;
00062             for (int i = 1; i < numPoints; i++)
00063             {
00064                 m_polygonRelative.points[i] = points[i];
00065                 left = min(left, points[i].X);
00066                 top = min(top, points[i].Y);
00067                 right = max(right, points[i].X);
00068                 bottom = max(bottom, points[i].Y);
00069             }
00070             m_polygonRelative.rcBound.X = left;
00071             m_polygonRelative.rcBound.Y = top;
00072             m_polygonRelative.rcBound.Width = right - left;
00073             m_polygonRelative.rcBound.Height = bottom - top;
00074         }
00075     }
00076     m_polygonAbsolute = m_polygonRelative;
00077 }
00078
00079 // Sets the default position, dimensions and color for the drawing object
00080 void Shape::ResetState(_In_ float startX, _In_ float startY,
00081                        _In_ float width, _In_ float height,
00082                        _In_ float scale)
00083 {
00084     // Set width and height of the client area
00085     // must adjust for dpi aware
00086     m_width = width;
00087     m_height = height;
00088
00089     // Set coordinates used for rendering
00090     m_topLeftX = startX;
00091     m_topLeftY = startY;
00092
00093     // scaling factor
00094     m_scale = scale;
00095 }
00096
00097 // Draw shape object
00098 void Shape::Paint(_In_ ID2D1DeviceContext* d2dDeviceContext)
00099 {
00100     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> brush;
00101     Microsoft::WRL::ComPtr<ID2D1Factory> d2dFactory;
00102     DX::ThrowIfFailed(d2dDeviceContext->CreateSolidColorBrush(D2D1::ColorF(m_color), brush.GetAddressOf()));
00103     d2dDeviceContext->GetFactory(d2dFactory.GetAddressOf());
00104
00105     // Create path to draw
00106     m_pathGeometry = nullptr;
00107     DX::ThrowIfFailed(d2dFactory->CreatePathGeometry(&m_pathGeometry));
00108
00109     Microsoft::WRL::ComPtr<ID2D1GeometrySink> sink;
00110     DX::ThrowIfFailed(m_pathGeometry->Open(&sink));
00111
00112     sink->BeginFigure(
00113         UnscaledToClient(m_polygonRelative.points[0]),
00114         D2D1_FIGURE_BEGIN_FILLED);
00115
00116     // Draw polygon
00117     for (int i = 1; i < m_polygonRelative.numPoints; i++)
00118     {
00119         sink->AddLine(UnscaledToClient(m_polygonRelative.points[i]));
00120     }
00121
00122     sink->EndFigure(D2D1_FIGURE_END_CLOSED);
00123     sink->Close();
00124
00125     // Fill the geometry that was created
00126     d2dDeviceContext->FillGeometry(m_pathGeometry.Get(), brush.Get());
00127
00128     // Create absolute polygon
00129     for (int i = 0; i < m_polygonRelative.numPoints; i++)
00130     {
00131         UnscaledToClient(m_polygonRelative.points[i], &m_polygonAbsolute.points[i]);
00132     }
00133     UnscaledToClient(m_polygonRelative.rcBound, &m_polygonAbsolute.rcBound);
00134 }
00135
00136 // Hit testing method handled with Direct2D
00137 bool Shape::InRegion(Windows::Foundation::Point pt)
00138 {
00139     BOOL b = FALSE;
00140     // The adjusted point returned from TouchHitTesting isn't quite equal to
00141     // the point passed to the corresponding PointerPressed, due to conversion
00142     // between DIPs and screen pixels. To compensate for this difference, it's
00143     // necessary to increase the tolerance passed to FillContainsPoint(). 1.5F
00144     // works for this sample, but some testing is needed to determine the best
00145     // value for other scenarios.
00146     m_pathGeometry->FillContainsPoint(
00147         D2D1::Point2F(pt.X, pt.Y),
00148         D2D1::Matrix3x2F::Identity(),
00149         1.5F,
00150         &b
00151     );
00152
00153     return !!b;
00154 }
00155
00156 // Pointer event handler
00157 void Shape::OnPointerEvent(_In_ Windows::Foundation::Point pt, bool shouldMove)
00158 {
00159     if (shouldMove)
00160     {
00161         Translate(pt.X - m_ptPointerPosition.X, pt.Y - m_ptPointerPosition.Y);
00162     }
00163
00164     m_ptPointerPosition = pt;
00165 }
00166
00167 // Shape polygonal representation
00168 Polygon* Shape::GetPolygon()
00169 {
00170     return &m_polygonAbsolute;
00171 }
00172
00173 // Update shape position to ensure that it stays within client screen
00174 void Shape::EnsureVisible()
00175 {
00176     // Initialize width height of object
00177     float width  = m_polygonRelative.rcBound.Width  * m_scale;
00178     float height = m_polygonRelative.rcBound.Height * m_scale;
00179
00180     float x = m_topLeftX + (m_polygonRelative.rcBound.Left * m_scale);
00181     x = max(0, min(x, m_width - width));
00182     m_topLeftX = x - (m_polygonRelative.rcBound.Left * m_scale);
00183
00184     float y = m_topLeftY + (m_polygonRelative.rcBound.Top * m_scale);
00185     y = max(0, min(y, m_height - height));
00186     m_topLeftY = y - (m_polygonRelative.rcBound.Top * m_scale);
00187 }
00188
00189 // _Translate shape within client screen
00190 void Shape::Translate(_In_ float dx, _In_ float dy)
00191 {
00192     m_topLeftX += dx;
00193     m_topLeftY += dy;
00194
00195     // Make sure object stays on screen
00196     EnsureVisible();
00197 }
00198
00199 // Convert unscaled point to client coordinates
00200 void Shape::UnscaledToClient(_In_ Windows::Foundation::Point ptUnscaled, _Inout_ Windows::Foundation::Point* pptClient)
00201 {
00202     pptClient->X = m_topLeftX + (ptUnscaled.X * m_scale);
00203     pptClient->Y = m_topLeftY + (ptUnscaled.Y * m_scale);
00204 }
00205
00206 // Convert unscaled point to client coordinates
00207 void Shape::UnscaledToClient(_In_ Windows::Foundation::Rect rcUnscaled, _Inout_ Windows::Foundation::Rect* prcClient)
00208 {
00209     prcClient->X = m_topLeftX + (rcUnscaled.X * m_scale);
00210     prcClient->Y = m_topLeftY + (rcUnscaled.Y * m_scale);
00211     prcClient->Width  = rcUnscaled.Width      * m_scale;
00212     prcClient->Height = rcUnscaled.Height     * m_scale;
00213 }
00214
00215 // Convert unscaled point to client coordinates
00216 D2D1_POINT_2F Shape::UnscaledToClient(_In_ Windows::Foundation::Point ptUnscaled)
00217 {
00218     return D2D1::Point2F(m_topLeftX + ptUnscaled.X * m_scale, m_topLeftY + ptUnscaled.Y * m_scale);
00219 }
00220
00221 // Convert unscaled rectangle to client coordinates
00222 D2D1_RECT_F Shape::UnscaledToClient(_In_ Windows::Foundation::Rect rcUnscaled)
00223 {
00224     return D2D1::RectF(
00225         m_topLeftX + rcUnscaled.Left   * m_scale,
00226         m_topLeftY + rcUnscaled.Top    * m_scale,
00227         m_topLeftX + rcUnscaled.Right  * m_scale,
00228         m_topLeftY + rcUnscaled.Bottom * m_scale
00229     );
00230 }
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File access/C++/Scenario8.xaml.h Source File

  • File access

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 SDKSample
00023 {
00024     namespace FileAccess
00025     {
00026         /// <summary>
00027         /// An empty page that can be used on its own or navigated to within a Frame.
00028         /// </summary>
00029         public ref class Scenario8 sealed
00030         {
00031         public:
00032             Scenario8();
00033
00034         private:
00035             MainPage^ rootPage;
00036
00037             void DeleteFileButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038         };
00039     }
00040 }
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DirectX::ConvertData Member List

This is the complete list of members for DirectX::ConvertData, including all inherited members.
datasize | DirectX::ConvertData
flags | DirectX::ConvertData
format | DirectX::ConvertData
Generated on Sat Nov 23 2024 16:09:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Print/C++/App.xaml.cpp Source File

  • Print

App.xaml.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 //
00009 // App.xaml.cpp
00010 // Implementation of the App.xaml class.
00011 //
00012
00013 #include "pch.h"
00014 #include "App.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace Windows::UI::Xaml;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::ApplicationModel;
00020 using namespace Windows::ApplicationModel::Activation;
00021 using namespace CppSamplesUtils;
00022 using namespace PrintSample;
00023 using namespace Windows::UI::Xaml::Interop;
00024
00025 App::App()
00026 {
00027     InitializeComponent();
00028     this->Suspending += ref new SuspendingEventHandler(this, &PrintSample::App::OnSuspending);
00029 }
00030
00031 App::~App()
00032 {
00033 }
00034
00035 void App::OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs)
00036 {
00037     auto deferral = pArgs->SuspendingOperation->GetDeferral();
00038     SuspensionManager::StartSaveTask().then([=]()
00039     {
00040         deferral->Complete();
00041     });
00042 }
00043
00044 void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs)
00045 {
00046
00047     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Terminated)
00048     {
00049         SuspensionManager::StartRestoreTask().then([=]()
00050         {
00051             auto rootFrame = ref new Frame();
00052             TypeName pageType = { "PrintSample.MainPage", TypeKind::Custom };
00053             rootFrame->Navigate(pageType);
00054             Window::Current->Content = rootFrame;
00055             Window::Current->Activate();
00056         });
00057     }
00058     else
00059     {
00060         auto rootFrame = ref new Frame();
00061         TypeName pageType = { "PrintSample.MainPage", TypeKind::Custom };
00062         rootFrame->Navigate(pageType);
00063         Window::Current->Content = rootFrame;
00064         Window::Current->Activate();
00065     }
00066 }
Generated on Sat Nov 23 2024 16:07:28 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Raw notifications/C++/MainAppSample/MainPage.xaml.cpp Source File

  • Raw notifications
  • MainAppSample

MainPage.xaml.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 //
00009 // MainPage.xaml.cpp
00010 // Implementation of the MainPage.xaml class.
00011 //
00012
00013 #include "pch.h"
00014 #include "MainPage.xaml.h"
00015 #include "App.xaml.h"
00016
00017 using namespace Windows::UI::Xaml;
00018 using namespace Windows::UI::Xaml::Controls;
00019 using namespace Windows::UI::Xaml::Data;
00020 using namespace Windows::System;
00021 using namespace Windows::Foundation;
00022 using namespace Platform;
00023 using namespace RawNotificationsSampleCPP;
00024 using namespace CppSamplesUtils;
00025 using namespace Windows::UI::Xaml::Navigation;
00026 using namespace Windows::UI::Xaml::Interop;
00027
00028 MainPage::MainPage()
00029 {
00030   InitializeComponent();
00031
00032   SetFeatureName("RawNotificationsSampleCPP");
00033
00034   _scenariosFrame = ScenarioList;
00035   _inputFrame = ScenarioInput;
00036   _outputFrame = ScenarioOutput;
00037
00038   _layoutHandlerToken = Window::Current->SizeChanged += ref new Windows::UI::Xaml::WindowSizeChangedEventHandler(this, &MainPage::Page_SizeChanged);
00039
00040   _pageLoadedHandlerToken = Loaded += ref new RoutedEventHandler(this, &MainPage::Page_Loaded);
00041   _logicalDpiChangedToken = DisplayProperties::LogicalDpiChanged += ref new DisplayPropertiesEventHandler(this, &MainPage::DisplayProperties_LogicalDpiChanged);
00042
00043 }
00044
00045 MainPage::~MainPage()
00046 {
00047 }
00048
00049 void MainPage::Page_Loaded(Object^ sender, RoutedEventArgs^ e)
00050 {
00051   // Load the ScenarioList page into the proper frame.
00052   TypeName pageType = { "RawNotificationsSampleCPP.ScenarioList", TypeKind::Custom };
00053   ScenarioList->Navigate(pageType, this);
00054
00055   // Figure out what resolution and orientation we are in and respond appropriately.
00056   CheckResolutionAndViewState();
00057 }
00058
00059 void MainPage::SetFeatureName(String^ strFeature)
00060 {
00061   FeatureName->Text = strFeature;
00062 }
00063
00064 void MainPage::Page_SizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00065 {
00066     CheckResolutionAndViewState();
00067 }
00068
00069 void MainPage::DisplayProperties_LogicalDpiChanged(Object^ sender)
00070 {
00071   CheckResolutionAndViewState();
00072 }
00073
00074 void MainPage::CheckResolutionAndViewState()
00075 {
00076   ApplicationViewState state = ApplicationView::Value;
00077   String^ stateString = ConvertViewState(state);
00078
00079   ResolutionScale scale = DisplayProperties::ResolutionScale;
00080   String^ scaleString = ConvertResolution(scale);
00081
00082   VisualStateManager::GoToState(this, stateString + scaleString, false);
00083 }
00084
00085 String^ MainPage::ConvertViewState(ApplicationViewState state)
00086 {
00087   switch (state)
00088   {
00089   case ApplicationViewState::Filled:
00090     return "Filled";
00091   case ApplicationViewState::FullScreenLandscape:
00092     return "FullScreenLandscape";
00093   case ApplicationViewState::FullScreenPortrait:
00094     return "FullScreenPortrait";
00095   case ApplicationViewState::Snapped:
00096     return "Snapped";
00097   }
00098   return "";
00099 }
00100
00101 String^ MainPage::ConvertResolution(ResolutionScale scale)
00102 {
00103   switch (scale)
00104   {
00105   case ResolutionScale::Scale100Percent:
00106     return "Scale100Percent";
00107   case ResolutionScale::Scale140Percent:
00108     return "Scale140Percent";
00109   case ResolutionScale::Scale180Percent:
00110     return "Scale180Percent";
00111   }
00112   return "";
00113 }
00114
00115 void MainPage::DoNavigation(TypeName pageType, Windows::UI::Xaml::Controls::Frame^ frame)
00116 {
00117   frame->Navigate(pageType, this);
00118
00119   std::wstring PageName(pageType.Name->Data());
00120   std::basic_string <wchar_t>::size_type indexSubstring;
00121   indexSubstring = PageName.find(L"Output");
00122   if (indexSubstring != std::wstring::npos)
00123   {
00124     // Raise OutputFrameLoaded so downstream pages know that the output frame content has been loaded.
00125         OutputFrameLoaded(this, nullptr);
00126   }
00127   else
00128   {
00129     // Raise InputFrameLoaded so downstream pages know that the input frame content has been loaded.
00130         InputFrameLoaded(this, nullptr);
00131   }
00132 }
00133
00134 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00135 {
00136   switch (type)
00137   {
00138   case NotifyType::StatusMessage:
00139     StatusBlock->Style = dynamic_cast<Windows::UI::Xaml::Style^>(App::Current->Resources->Lookup("StatusStyle"));
00140     break;
00141   case NotifyType::ErrorMessage:
00142     StatusBlock->Style = dynamic_cast<Windows::UI::Xaml::Style^>(App::Current->Resources->Lookup("ErrorStyle"));
00143     break;
00144   default:
00145     break;
00146   }
00147   StatusBlock->Text = strMessage;
00148 }
00149
00150 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00151 {
00152   auto _hyperlinkButton = (HyperlinkButton^)sender;
00153   auto uri = ref new Windows::Foundation::Uri((String^)_hyperlinkButton->Tag);
00154
00155   Windows::System::Launcher::LaunchUriAsync(uri);
00156 }
Generated on Sat Nov 23 2024 16:07:43 for Win8-Examples by doxygen 1.7.1


Win8-Examples: App settings/C++/AddSettingsScenario.xaml.cpp Source File

  • App settings

AddSettingsScenario.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 // AddSettingsScenario.xaml.cpp
00013 // Implementation of the AddSettingsScenario class
00014 //
00015
00016 #include "pch.h"
00017 #include "AddSettingsScenario.xaml.h"
00018
00019 using namespace SDKSample::ApplicationSettings;
00020
00021 using namespace Windows::Foundation;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Navigation;
00025 using namespace Windows::UI::ApplicationSettings;
00026 using namespace Windows::UI::Popups;
00027
00028 AddSettingsScenario::AddSettingsScenario()
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 AddSettingsScenario::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     rootPage->NotifyUser("To show the settings charm window, invoke the charm bar by swiping your finger on the right edge of the screen or bringing your mouse to the lower right corner of the screen, then select Settings. Or you can just press Windows logo + i. To dismiss the settings charm, tap in the application, swipe a screen edge, right click, invoke another charm or application.", NotifyType::StatusMessage);
00045 }
00046
00047 void AddSettingsScenario::OnNavigatedFrom(NavigationEventArgs^ e)
00048 {
00049     // Added to make sure the event handler for CommandsRequested in cleaned up before other scenarios
00050     if (this->isEventRegistered)
00051     {
00052         SettingsPane::GetForCurrentView()->CommandsRequested -= this->commandsRequestedEventRegistrationToken;
00053         this->isEventRegistered = false;
00054     }
00055 }
00056
00057 void SDKSample::ApplicationSettings::AddSettingsScenario::addSettingsScenarioAdd_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00058 {
00059     Button^ b = safe_cast<Button^>(sender);
00060     if (b != nullptr)
00061     {
00062         rootPage->NotifyUser("You selected the " + b->Content + " button", NotifyType::StatusMessage);
00063         if (!this->isEventRegistered)
00064         {
00065             // Listening for this event lets the app initialize the settings commands and pause its UI until the user closes the pane.
00066             // To ensure your settings are available at all times in your app, place your CommandsRequested handler in the overridden
00067             // OnWindowCreated of App.xaml.cpp
00068             this->commandsRequestedEventRegistrationToken = SettingsPane::GetForCurrentView()->CommandsRequested += ref new TypedEventHandler<SettingsPane^, SettingsPaneCommandsRequestedEventArgs^>(this, &AddSettingsScenario::onCommandsRequested);
00069             this->isEventRegistered = true;
00070         }
00071     }
00072 }
00073
00074 void SDKSample::ApplicationSettings::AddSettingsScenario::onSettingsCommand(Windows::UI::Popups::IUICommand^ command)
00075 {
00076     SettingsCommand^ settingsCommand = safe_cast<SettingsCommand^>(command);
00077     rootPage->NotifyUser("You selected the " + settingsCommand->Label + " settings command which originated from the " + SettingsPane::Edge.ToString(), NotifyType::StatusMessage);
00078 }
00079
00080 void SDKSample::ApplicationSettings::AddSettingsScenario::onCommandsRequested(Windows::UI::ApplicationSettings::SettingsPane^ settingsPane, Windows::UI::ApplicationSettings::SettingsPaneCommandsRequestedEventArgs^ eventArgs)
00081 {
00082     UICommandInvokedHandler^ handler = ref new UICommandInvokedHandler(this, &AddSettingsScenario::onSettingsCommand);
00083
00084     SettingsCommand^ generalCommand = ref new SettingsCommand("generalSettings", "General", handler);
00085     eventArgs->Request->ApplicationCommands->Append(generalCommand);
00086
00087     SettingsCommand^ helpCommand = ref new SettingsCommand("helpPage", "Help", handler);
00088     eventArgs->Request->ApplicationCommands->Append(helpCommand);
00089 }
Generated on Sat Nov 23 2024 16:07:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DirectX::CBits< SizeInBytes > Member List

This is the complete list of members for DirectX::CBits< SizeInBytes >, including all inherited members.
GetBit(_Inout_ size_t &uStartBit) const | DirectX::CBits< SizeInBytes > | [inline]
GetBits(_Inout_ size_t &uStartBit, _In_ size_t uNumBits) const | DirectX::CBits< SizeInBytes > | [inline]
m_uBits | DirectX::CBits< SizeInBytes > | [private]
SetBit(_Inout_ size_t &uStartBit, _In_ uint8_t uValue) | DirectX::CBits< SizeInBytes > | [inline]
SetBits(_Inout_ size_t &uStartBit, _In_ size_t uNumBits, _In_ uint8_t uValue) | DirectX::CBits< SizeInBytes > | [inline]
Generated on Sat Nov 23 2024 16:09:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Audio Session (WASAPI)/C++/common/suspensionmanager.h Source File

  • Windows Audio Session (WASAPI)
  • C++
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CryptoWinRT/C++/Scenario8.xaml.h Source File

  • CryptoWinRT

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 SDKSample
00023 {
00024     namespace CryptoWinRT
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 Scenario8 sealed
00031         {
00032         public:
00033             Scenario8();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040             void RunSample_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         };
00042     }
00043 }
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text editing/C++/Scenario2.xaml.cpp Source File

  • XAML text editing

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 SDKSample::TextEditing;
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
00042
00043 void SDKSample::TextEditing::Scenario2::DoSomething_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00044 {
00045     Button^ b = safe_cast<Button^>(sender);
00046     if (b != nullptr)
00047     {
00048         rootPage->NotifyUser("You clicked the " + b->Name + " button", NotifyType::StatusMessage);
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Getting started with C++ simple blog reader/C++/ItemsPage.xaml.h Source File

  • Getting started with C++ simple blog reader

ItemsPage.xaml.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 //
00009 // ItemsPage.xaml.h
00010 // Declaration of the ItemsPage class
00011 //
00012
00013 #pragma once
00014
00015 #include "Common\LayoutAwarePage.h" // Required by generated header
00016 #include "ItemsPage.g.h"
00017
00018 namespace SimpleBlogReader
00019 {
00020   /// <summary>
00021   /// A page that displays a collection of item previews.  In the Split Application this page
00022   /// is used to display and select one of the available groups.
00023   /// </summary>
00024   [Windows::Foundation::Metadata::WebHostHidden]
00025   public ref class ItemsPage sealed
00026   {
00027   public:
00028     ItemsPage();
00029
00030   protected:
00031     virtual void LoadState(Platform::Object^ navigationParameter,
00032       Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00033         virtual void ItemView_ItemClick(Platform::Object^ sender, Windows::UI::Xaml::Controls::ItemClickEventArgs^ e);
00034   };
00035 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Number formatting and parsing/C++/common/suspensionmanager.h Source File

  • Number formatting and parsing
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Configure keys for media/C++/Constants.cpp Source File

  • Configure keys for media

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully qualified name for the class that implements the scenario" }
00021     { "Listening to hardware media transport events", "SDKSample.MediaButtons.mediabuttons" }
00022 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/Sphere.h Source File

  • XAML DirectX 3D shooting game

Sphere.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 // Sphere:
00011 // This class is a specialization of GameObject that represents a sphere primitive.
00012 // The sphere is defined by a 'position' and radius.
00013
00014 #include "GameObject.h"
00015
00016 ref class Sphere: public GameObject
00017 {
00018 internal:
00019     Sphere();
00020     Sphere(DirectX::XMFLOAT3 pos, float radius);
00021
00022     void Position(DirectX::XMFLOAT3 position);
00023     void Position(DirectX::XMVECTOR position);
00024     void Radius(float radius);
00025     float Radius();
00026
00027     virtual bool IsTouching(
00028         DirectX::XMFLOAT3 point,
00029         float radius,
00030         _Out_ DirectX::XMFLOAT3 *contact,
00031         _Out_ DirectX::XMFLOAT3 *normal
00032         ) override;
00033
00034 private:
00035     void Update();
00036
00037     float m_radius;
00038 };
00039
00040
00041 __forceinline void Sphere::Position(DirectX::XMFLOAT3 position)
00042 {
00043     m_position = position;
00044     Update();
00045 }
00046
00047 __forceinline void Sphere::Position(DirectX::XMVECTOR position)
00048 {
00049     DirectX::XMStoreFloat3(&m_position, position);
00050     Update();
00051 }
00052
00053 __forceinline void Sphere::Radius(float radius)
00054 {
00055     m_radius = radius;
00056     Update();
00057 }
00058
00059 __forceinline float Sphere::Radius()
00060 {
00061     return m_radius;
00062 }
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows account authorization/C++/DelegationTickets.xaml.cpp Source File

  • Windows account authorization

DelegationTickets.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 // DelegationTickets.xaml.cpp
00013 // Implementation of the DelegationTickets class
00014 //
00015
00016 #include "pch.h"
00017 #include "DelegationTickets.xaml.h"
00018
00019 using namespace concurrency;
00020 using namespace Platform;
00021 using namespace SDKSample::MicrosoftAccount;
00022 using namespace Windows::Security::Authentication::OnlineId;
00023 using namespace Windows::UI::Xaml;
00024 using namespace Windows::UI::Xaml::Controls;
00025 using namespace Windows::UI::Xaml::Navigation;
00026
00027 DelegationTickets::DelegationTickets()
00028 {
00029     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 void DelegationTickets::OnNavigatedTo(NavigationEventArgs^ e)
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     rootPage = MainPage::Current;
00042
00043     authenticator = ref new OnlineIdAuthenticator();
00044
00045     AccessTicket = "";
00046
00047     SignOutButton->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00048 }
00049
00050 void DelegationTickets::SignInButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00051 {
00052     ResultText->Text = "Signing in...";
00053     AccessTicket = "";
00054     SignInButton->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00055
00056     // the ticket requests specifies the Target scopes and the Policy,
00057     // which must be configured per application with authentication service provider.
00058     auto request = ref new OnlineIdServiceTicketRequest("wl.basic wl.contacts_photos wl.calendars", "DELEGATION");
00059
00060     // authenticate user and get the ticket for the requested target
00061     create_task(authenticator->AuthenticateUserAsync(request)).then([this](task<UserIdentity^> userIdentity)
00062     {
00063         SignOutButton->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00064         try
00065         {
00066             // .get() will throw if the operation failed
00067             OnlineIdServiceTicket^ ticket = userIdentity.get()->Tickets->GetAt(0);
00068             if (ticket->ErrorCode == S_OK)
00069             {
00070                 AccessTicket = ticket->Value;
00071             }
00072             SignInButton->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00073             ResultText->Text = "Signed in.";
00074         }
00075         catch (const task_canceled &)
00076         {
00077             SignInButton->Visibility = Windows::UI::Xaml::Visibility::Visible;
00078             // programmatic cancel or in the case of this API user dismiss as well.
00079             ResultText->Text = "Canceled by user or programmatic cancel.";
00080             throw; // propagate the task_canceled exception, it will be ignored by the runtime.
00081         }
00082
00083         auto uri = ref new Uri("https://apis.live.net/v5.0/me?access_token=" + AccessTicket);
00084         cancellationTokenSource = cancellation_token_source();
00085
00086         // Do an asynchronous GET.  We need to use use_current() with the continuations since the tasks are completed on
00087         // background threads and we need to run on the UI thread to update the UI.
00088         return httpRequest.GetAsync(uri, cancellationTokenSource.get_token());
00089     }).then([this](task<std::wstring> response)
00090     {
00091         SignOutButton->Visibility = CanSignOut ? Windows::UI::Xaml::Visibility::Visible : Windows::UI::Xaml::Visibility::Collapsed;
00092         try
00093         {
00094             // .get() will throw if the operation failed
00095             std::wstring httpResponse = response.get();
00096             ResultText->Text = ref new String(httpResponse.c_str());
00097         }
00098         catch (const task_canceled&)
00099         {
00100             ResultText->Text = "Request canceled.";
00101         }
00102         catch (Exception^ ex)
00103         {
00104             ResultText->Text = "HTTP Exception: " +  ex->Message;
00105         }
00106         // schedule this back to the UI thread to enable access to UI elements.
00107     }, task_continuation_context::use_current());
00108 }
00109
00110 void DelegationTickets::SignOutButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112     AccessTicket = "";
00113
00114     if (CanSignOut)
00115     {
00116         ResultText->Text = "Signing out...";
00117         SignOutButton->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00118
00119         create_task(authenticator->SignOutUserAsync()).then([this]()
00120         {
00121             ResultText->Text = "Signed out.";
00122
00123             SignInButton->Visibility = NeedsToGetTicket ? Windows::UI::Xaml::Visibility::Visible : Windows::UI::Xaml::Visibility::Collapsed;
00124             SignOutButton->Visibility = CanSignOut ? Windows::UI::Xaml::Visibility::Visible : Windows::UI::Xaml::Visibility::Collapsed;
00125         });
00126     }
00127     else
00128     {
00129         ResultText->Text = "User can't sign out from Application.";
00130     }
00131 }
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D tutorial/C++/Lesson2.Triangles/pch.h Source File

  • Direct3D tutorial
  • Lesson2.Triangles

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 <d3d11_1.h>
00012 #include <agile.h>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/CropImageViewModel.cpp Source File

  • Hilo C++
  • Hilo

CropImageViewModel.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 "CropImageViewModel.h"
00010 #include "DelegateCommand.h"
00011 #include "TaskExceptionsExtensions.h"
00012 #include "IPhoto.h"
00013 #include "ImageNavigationData.h"
00014 #include "NullPhotoGroup.h"
00015 #include "Repository.h"
00016 #include "ExifExtensions.h"
00017 #include "ImageUtilities.h"
00018
00019 #define MINIMUMBMPSIZE 10
00020 #define EXIFOrientationPropertyName "System.Photo.Orientation"
00021
00022 using namespace concurrency;
00023 using namespace Hilo;
00024 using namespace Platform;
00025 using namespace Platform::Collections;
00026 using namespace std;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Graphics::Imaging;
00030 using namespace Windows::UI::ViewManagement;
00031 using namespace Windows::UI::Xaml;
00032 using namespace Windows::UI::Xaml::Controls::Primitives;
00033 using namespace Windows::UI::Xaml::Input;
00034 using namespace Windows::UI::Xaml::Media;
00035 using namespace Windows::UI::Xaml::Media::Imaging;
00036 using namespace Windows::UI::Xaml::Navigation;
00037 using namespace Windows::Storage;
00038 using namespace Windows::Storage::Streams;
00039
00040 CropImageViewModel::CropImageViewModel(shared_ptr<Repository> repository, shared_ptr<ExceptionPolicy> exceptionPolicy) : ImageBase(exceptionPolicy), m_repository(repository),
00041     m_inProgress(false), m_isCropOverlayVisible(false), m_isSaving(false), m_cropX(0u), m_cropY(0u)
00042 {
00043     m_saveCommand = ref new DelegateCommand(ref new ExecuteDelegate(this, &CropImageViewModel::SaveImage), nullptr);
00044     m_cancelCommand = ref new DelegateCommand(ref new ExecuteDelegate(this, &CropImageViewModel::CancelCrop), nullptr);
00045     m_resumeCropCommand = ref new DelegateCommand(ref new ExecuteDelegate(this, &CropImageViewModel::Unsnap), nullptr);
00046
00047     ViewModelBase::m_isAppBarSticky = true;
00048 }
00049
00050 ICommand^ CropImageViewModel::ResumeCropCommand::get()
00051 {
00052     return m_resumeCropCommand;
00053 }
00054
00055 ICommand^ CropImageViewModel::SaveCommand::get()
00056 {
00057     return m_saveCommand;
00058 }
00059
00060 ICommand^ CropImageViewModel::CancelCommand::get()
00061 {
00062     return m_cancelCommand;
00063 }
00064
00065 bool CropImageViewModel::InProgress::get()
00066 {
00067     return m_inProgress;
00068 }
00069
00070 float64 CropImageViewModel::CropOverlayLeft::get()
00071 {
00072     return m_cropOverlayLeft;
00073 }
00074
00075 float64 CropImageViewModel::CropOverlayTop::get()
00076 {
00077     return m_cropOverlayTop;
00078 }
00079
00080 float64 CropImageViewModel::CropOverlayHeight::get()
00081 {
00082     return m_cropOverlayHeight;
00083 }
00084
00085 float64 CropImageViewModel::CropOverlayWidth::get()
00086 {
00087     return m_cropOverlayWidth;
00088 }
00089
00090 bool CropImageViewModel::IsCropOverlayVisible::get()
00091 {
00092     return m_isCropOverlayVisible;
00093 }
00094
00095 ImageSource^ CropImageViewModel::Image::get()
00096 {
00097     return m_image;
00098 }
00099
00100 void CropImageViewModel::OnNavigatedTo(NavigationEventArgs^ e)
00101 {
00102     String^ data = dynamic_cast<String^>(e->Parameter);
00103     ImageNavigationData navigationData(data);
00104
00105     Initialize(navigationData.GetFilePath());
00106 }
00107
00108 void CropImageViewModel::Initialize(String^ photoPath)
00109 {
00110     assert(IsMainThread());
00111     m_photo = nullptr;
00112     m_image = nullptr;
00113     m_photoPath = photoPath;
00114     auto photoStream = make_shared<IRandomAccessStreamWithContentType^>(nullptr);
00115
00116     GetImagePhotoAsync().then([this](IPhoto^ photo)
00117     {
00118         assert(IsMainThread());
00119         // Return to the hub page if the photo is no longer present
00120         if (photo == nullptr)
00121         {
00122             GoHome();
00123             cancel_current_task();
00124         }
00125         m_photo = photo;
00126         return m_photo->OpenReadAsync();
00127
00128     }).then([this, photoStream](IRandomAccessStreamWithContentType^ imageData)
00129     {
00130         assert(IsMainThread());
00131         (*photoStream) = imageData;
00132         return BitmapDecoder::CreateAsync(imageData);
00133
00134     }).then([this, photoStream](BitmapDecoder^ decoder)
00135     {
00136         assert(IsMainThread());
00137         m_image = ref new WriteableBitmap(decoder->PixelWidth, decoder->PixelHeight);
00138         (*photoStream)->Seek(0);
00139         return m_image->SetSourceAsync(*photoStream);
00140
00141     }).then([this]()
00142     {
00143         assert(IsMainThread());
00144         OnPropertyChanged("Image");
00145
00146     }).then(ObserveException<void>(m_exceptionPolicy));
00147 }
00148
00149 task<IPhoto^> CropImageViewModel::GetImagePhotoAsync()
00150 {
00151     assert(IsMainThread());
00152     return m_repository->GetSinglePhotoAsync(m_photoPath);
00153 }
00154
00155 task<IRandomAccessStream^> CropImageViewModel::EncodeImageAsync(IRandomAccessStream^ sourceStream)
00156 {
00157     assert(IsMainThread());
00158     auto backgroundContext = task_continuation_context::use_arbitrary();
00159     auto ras = ref new InMemoryRandomAccessStream();
00160     auto bitmapEncoder = make_shared<BitmapEncoder^>(nullptr);
00161     auto bitmapDecoder = make_shared<BitmapDecoder^>(nullptr);
00162     auto cropRect = make_shared<Rect>(
00163         static_cast<float>(m_cropX),
00164         static_cast<float>(m_cropY),
00165         static_cast<float>(m_image->PixelWidth),
00166         static_cast<float>(m_image->PixelHeight));
00167
00168     return create_task(BitmapDecoder::CreateAsync(sourceStream))
00169         .then([bitmapDecoder](BitmapDecoder^ decoder)
00170     {
00171         // Fetch the System.Photo.Orientation property to find out if the image is rotated.
00172         assert(IsBackgroundThread());
00173         auto requestedProperty = ref new Vector<String^>();
00174         requestedProperty->Append(EXIFOrientationPropertyName);
00175         (*bitmapDecoder) = decoder;
00176         return decoder->BitmapProperties->GetPropertiesAsync(requestedProperty);
00177     }, backgroundContext).then([cropRect, bitmapDecoder](task<BitmapPropertySet^> propertiesTask)
00178     {
00179         // Determine if the image is rotated. This may require handling exceptions.
00180         assert(IsBackgroundThread());
00181         BitmapPropertySet^ properties;
00182         ExifRotations exifOrientation = ExifRotations::NotRotated;
00183         try {
00184             properties = propertiesTask.get();
00185             if (properties->HasKey(EXIFOrientationPropertyName))
00186             {
00187                 exifOrientation = ExifRotations(safe_cast<unsigned short>(properties->Lookup(EXIFOrientationPropertyName)->Value));
00188             }
00189         }
00190         catch(Exception^ ex)
00191         {
00192             // If the file format doesn't support properties, continue without
00193             // using Exif orientation.
00194             switch (ex->HResult)
00195             {
00196             case WINCODEC_ERR_UNSUPPORTEDOPERATION:
00197             case WINCODEC_ERR_PROPERTYNOTSUPPORTED:
00198             case E_INVALIDARG:
00199                 exifOrientation = ExifRotations::NotRotated;
00200                 break;
00201
00202             default:
00203                 throw;
00204             }
00205         }
00206
00207         // If rotated flag has been set, rotate the crop region to match the image's rotation.
00208         Rect originalDimensions(0.f, 0.f, static_cast<float>((*bitmapDecoder)->PixelWidth), static_cast<float>((*bitmapDecoder)->PixelHeight));
00209         Rect unrotatedDimensions = originalDimensions;
00210         if (exifOrientation == ExifRotations::RotatedLeft || exifOrientation == ExifRotations::RotatedRight)
00211         {
00212             unrotatedDimensions.Width = static_cast<float>((*bitmapDecoder)->PixelHeight);
00213             unrotatedDimensions.Height = static_cast<float>((*bitmapDecoder)->PixelWidth);
00214         }
00215
00216         int exifAppliedRotation = static_cast<int>(ExifExtensions::ConvertExifOrientationToDegreesRotation(exifOrientation));
00217
00218         if (exifAppliedRotation != 0)
00219         {
00220             assert(exifAppliedRotation > 0);
00221
00222             // Adjust crop back to original.
00223             auto adjustedCrop = ExifExtensions::RotateClockwise((*cropRect), unrotatedDimensions, -exifAppliedRotation);
00224             (*cropRect) = adjustedCrop;
00225         }
00226     }, backgroundContext).then([ras, bitmapDecoder]
00227     {
00228         // Create the transcoder that will save the image to disk.
00229         return BitmapEncoder::CreateForTranscodingAsync(ras, (*bitmapDecoder));
00230     }, backgroundContext).then([this, cropRect, bitmapEncoder](BitmapEncoder^ encoder)
00231     {
00232         assert(IsBackgroundThread());
00233         BitmapBounds bounds;
00234         bounds.X = static_cast<unsigned int>((*cropRect).X);
00235         bounds.Y = static_cast<unsigned int>((*cropRect).Y);
00236         bounds.Width = static_cast<unsigned int>((*cropRect).Width);
00237         bounds.Height = static_cast<unsigned int>((*cropRect).Height);
00238         encoder->BitmapTransform->Bounds = bounds;
00239
00240         // Force a new thumbnail to reflect any rotation operation.
00241         encoder->IsThumbnailGenerated = true;
00242         (*bitmapEncoder) = encoder;
00243         // Start the encoding.
00244         return encoder->FlushAsync();
00245     }, backgroundContext).then([this, ras, bitmapEncoder](task<void> encodeTask)
00246     {
00247         // When the encoding has finished, check for any errors in creating the thumbnail.
00248         assert(IsBackgroundThread());
00249         try
00250         {
00251             encodeTask.get();
00252         }
00253         catch (Exception^ ex)
00254         {
00255             switch (ex->HResult)
00256             {
00257             case WINCODEC_ERR_UNSUPPORTEDOPERATION:
00258                 // If the encoder does not support writing a thumbnail, then
00259                 // disable thumbnail generation before trying again.
00260                 (*bitmapEncoder)->IsThumbnailGenerated = false;
00261                 break;
00262             default:
00263                 throw ex;
00264             }
00265         }
00266         return ((*bitmapEncoder)->IsThumbnailGenerated == false) ? (*bitmapEncoder)->FlushAsync() : create_async([]{});
00267     }, backgroundContext).then([ras]
00268     {
00269         // Return the result.
00270         assert(IsBackgroundThread());
00271         return dynamic_cast<IRandomAccessStream^>(ras);
00272     }, backgroundContext);
00273 }
00274
00275 void CropImageViewModel::ChangeInProgress(bool value)
00276 {
00277     m_inProgress = value;
00278     OnPropertyChanged("InProgress");
00279 }
00280
00281 void CropImageViewModel::SaveImage(Object^ parameter)
00282 {
00283     if (m_isSaving) return;
00284
00285     m_isSaving = true;
00286     auto sourceStream = make_shared<IRandomAccessStreamWithContentType^>(nullptr);
00287     auto encodedStream = make_shared<IRandomAccessStream^>(nullptr);
00288
00289     GetStreamWithFailCheck().then([this, sourceStream](IRandomAccessStreamWithContentType^ stream)
00290     {
00291         assert(IsMainThread());
00292         (*sourceStream) = stream;
00293         ChangeInProgress(true);
00294         return EncodeImageAsync(stream);
00295     }).then([this, encodedStream](IRandomAccessStream^ stream)
00296     {
00297         (*encodedStream) = stream;
00298         assert(IsMainThread());
00299         // Cancel the task if the user has switched to snapped view before the FileSavePicker has appeared.
00300         if (ApplicationView::Value == ApplicationViewState::Snapped)
00301         {
00302             cancel_current_task();
00303         }
00304         return ImageBase::GetFileNameFromFileSavePickerAsync(m_photo->FileType);
00305     }).then([this, encodedStream](StorageFile^ f)
00306     {
00307         assert(IsMainThread());
00308         return ImageBase::SaveImageAsync(f, (*encodedStream));
00309     }).then([this](task<void> priorTask)
00310     {
00311         assert(IsMainThread());
00312         m_isSaving = false;
00313         ChangeInProgress(false);
00314         try
00315         {
00316             priorTask.get();
00317         }
00318         catch(const concurrency::task_canceled&)
00319         {
00320         }
00321     }).then(ObserveException<void>(m_exceptionPolicy));
00322 }
00323
00324 void CropImageViewModel::CancelCrop(Object^ parameter)
00325 {
00326     ViewModelBase::GoBack();
00327 }
00328
00329 void CropImageViewModel::Unsnap(Object^ parameter)
00330 {
00331     if (ApplicationView::Value == ApplicationViewState::Snapped)
00332     {
00333         ApplicationView::TryUnsnap();
00334     }
00335 }
00336
00337 void CropImageViewModel::CalculateInitialCropOverlayPosition(GeneralTransform^ transform, float width, float height)
00338 {
00339     // Find the onscreen coordinates of the top left corner of the photo.
00340     Point topLeft;
00341     topLeft.X = 0;
00342     topLeft.Y = 0;
00343     if (transform != nullptr)
00344     {
00345         topLeft = transform->TransformPoint(topLeft);
00346     }
00347
00348     m_left = topLeft.X;
00349     m_top = topLeft.Y;
00350     m_bottom = m_top + height;
00351     m_right = m_left + width;
00352     m_cropOverlayTop = m_top;
00353     m_cropOverlayLeft = m_left;
00354     m_cropOverlayHeight = height;
00355     m_cropOverlayWidth = width;
00356     m_actualHeight = height;
00357     m_actualWidth = width;
00358     m_isCropOverlayVisible = true;
00359
00360     OnPropertyChanged("CropOverlayLeft");
00361     OnPropertyChanged("CropOverlayTop");
00362     OnPropertyChanged("CropOverlayHeight");
00363     OnPropertyChanged("CropOverlayWidth");
00364     OnPropertyChanged("IsCropOverlayVisible");
00365 }
00366
00367 void CropImageViewModel::UpdateCropOverlayPostion(Thumb ^thumb, float64 verticalChange, float64 horizontalChange, float64 minWidth, float64 minHeight)
00368 {
00369     if (thumb != nullptr)
00370     {
00371         float64 deltaH;
00372         float64 deltaV;
00373         float64 left;
00374         float64 top;
00375
00376         switch (thumb->VerticalAlignment)
00377         {
00378         case VerticalAlignment::Bottom:
00379             deltaV = min(-verticalChange, m_cropOverlayHeight - minHeight);
00380             m_cropOverlayHeight -= deltaV;
00381             if (m_cropOverlayHeight + m_cropOverlayTop > m_bottom)
00382             {
00383                 m_cropOverlayHeight = m_bottom - m_cropOverlayTop;
00384             }
00385             OnPropertyChanged("CropOverlayHeight");
00386             break;
00387         case VerticalAlignment::Top:
00388             deltaV = min(verticalChange, m_cropOverlayHeight - minHeight);
00389             top = m_cropOverlayTop + deltaV;
00390             if (m_top < top)
00391             {
00392                 m_cropOverlayTop = top;
00393                 m_cropOverlayHeight -= deltaV;
00394                 if (m_cropOverlayHeight > m_actualHeight)
00395                 {
00396                     m_cropOverlayHeight = m_actualHeight;
00397                 }
00398                 OnPropertyChanged("CropOverlayTop");
00399                 OnPropertyChanged("CropOverlayHeight");
00400             }
00401             break;
00402         default:
00403             break;
00404         }
00405
00406         switch (thumb->HorizontalAlignment)
00407         {
00408         case HorizontalAlignment::Left:
00409             deltaH = min(horizontalChange, m_cropOverlayWidth - minWidth);
00410             left = m_cropOverlayLeft + deltaH;
00411             if (m_left < left)
00412             {
00413                 m_cropOverlayLeft = left;
00414                 m_cropOverlayWidth -= deltaH;
00415                 if (m_cropOverlayWidth > m_actualWidth)
00416                 {
00417                     m_cropOverlayWidth = m_actualWidth;
00418                 }
00419                 OnPropertyChanged("CropOverlayLeft");
00420                 OnPropertyChanged("CropOverlayWidth");
00421             }
00422             break;
00423         case HorizontalAlignment::Right:
00424             deltaH = min(-horizontalChange, m_cropOverlayWidth - minWidth);
00425             m_cropOverlayWidth -= deltaH;
00426             if (m_cropOverlayWidth + m_cropOverlayLeft > m_right)
00427             {
00428                 m_cropOverlayWidth = m_right - m_cropOverlayLeft;
00429             }
00430             OnPropertyChanged("CropOverlayWidth");
00431             break;
00432
00433         default:
00434             break;
00435         }
00436     }
00437 }
00438
00439 void CropImageViewModel::DoCrop(uint32_t xOffset, uint32_t yOffset, uint32_t newHeight, uint32_t newWidth, uint32_t oldWidth, byte* pSrcPixels, byte* pDestPixels)
00440 {
00441     assert(IsBackgroundThread());
00442     parallel_for (0u, newHeight, [xOffset, yOffset, newHeight, newWidth, oldWidth, pDestPixels, pSrcPixels](unsigned int y)
00443     {
00444         for (unsigned int x = 0; x < newWidth; x++)
00445         {
00446             pDestPixels[(x + y * newWidth) * 4] =
00447                 pSrcPixels[(x +  xOffset + (y + yOffset) * oldWidth) * 4];     // B
00448             pDestPixels[(x + y * newWidth) * 4 + 1] =
00449                 pSrcPixels[(x +  xOffset + (y + yOffset) * oldWidth) * 4 + 1]; // G
00450             pDestPixels[(x + y * newWidth) * 4 + 2] =
00451                 pSrcPixels[(x +  xOffset + (y + yOffset) * oldWidth) * 4 + 2]; // R
00452             pDestPixels[(x + y * newWidth) * 4 + 3] =
00453                 pSrcPixels[(x +  xOffset + (y + yOffset) * oldWidth) * 4 + 3]; // A
00454         }
00455     });
00456 }
00457
00458 task<void> CropImageViewModel::CropImageAsync(float64 actualWidth)
00459 {
00460     assert(IsMainThread());
00461     ChangeInProgress(true);
00462
00463     // Calculate crop values
00464     float64 scaleFactor = m_image->PixelWidth / actualWidth;
00465     unsigned int xOffset = safe_cast<unsigned int>((m_cropOverlayLeft - m_left) * scaleFactor);
00466     unsigned int yOffset = safe_cast<unsigned int>((m_cropOverlayTop - m_top) * scaleFactor);
00467     unsigned int newWidth = safe_cast<unsigned int>(m_cropOverlayWidth * scaleFactor);
00468     unsigned int newHeight = safe_cast<unsigned int>(m_cropOverlayHeight * scaleFactor);
00469
00470     if (newHeight < MINIMUMBMPSIZE || newWidth < MINIMUMBMPSIZE)
00471     {
00472         ChangeInProgress(false);
00473         m_isCropOverlayVisible = false;
00474         OnPropertyChanged("IsCropOverlayVisible");
00475         return create_empty_task();
00476     }
00477
00478     m_cropX += xOffset;
00479     m_cropY += yOffset;
00480
00481     // Create destination bitmap
00482     WriteableBitmap^ destImage = ref new WriteableBitmap(newWidth, newHeight);
00483
00484     // Get pointers to the source and destination pixel data
00485     byte* pSrcPixels = GetPointerToPixelData(m_image->PixelBuffer);
00486     byte* pDestPixels = GetPointerToPixelData(destImage->PixelBuffer);
00487     auto oldWidth = m_image->PixelWidth;
00488
00489     return create_task([this, xOffset, yOffset, newHeight, newWidth, oldWidth, pSrcPixels, pDestPixels] () {
00490         assert(IsBackgroundThread());
00491         DoCrop(xOffset, yOffset, newHeight, newWidth, oldWidth, pSrcPixels, pDestPixels);
00492     }).then([this, destImage](){
00493         assert(IsMainThread());
00494
00495         // Update image on screen
00496         m_image = destImage;
00497         OnPropertyChanged("Image");
00498         ChangeInProgress(false);
00499     }, task_continuation_context::use_current()).then(ObserveException<void>(m_exceptionPolicy));
00500 }
00501
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: HomeGroup app/C++/App.xaml.cpp Source File

  • HomeGroup app

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D magazine app/C++/Design.h Source File

  • Direct2D magazine app

Design.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 "Element.h"
00011
00012 //  <design> represents a design template of the element tree. Different
00013 //  display size potentially requires different design template in order to
00014 //  preserve visual quality of the content. The design element exposes
00015 //  the design width and height of the template. It is the responsibility
00016 //  of the parent element to decide what design to use based on the aspect
00017 //  ratio of the template.
00018 //
00019 //  Design element accepts the following additional markup attributes.
00020 //      page-width = "<float>"
00021 //          Width of a page in design unit
00022 //      page-height = "<float>"
00023 //          Height of a page in design unit
00024 //
00025 ref class Design : public Element
00026 {
00027 internal:
00028     Design();
00029
00030     virtual bool Initialize(
00031         _In_ Document^ document,
00032         _In_ Windows::Data::Xml::Dom::XmlElement^ xmlElement
00033         ) override;
00034
00035     virtual bool AcceptChildNode(
00036         _In_ Document^ document,
00037         _In_ Windows::Data::Xml::Dom::IXmlNode^ childXmlNode
00038         ) override;
00039
00040     inline D2D1_SIZE_F GetPageSize()
00041     {
00042         return m_pageSize;
00043     }
00044
00045 private:
00046     D2D1_SIZE_F m_pageSize;
00047 };
Generated on Sat Nov 23 2024 16:08:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Network information/C++/NetworkStatusChange.xaml.h Source File

  • Network information

NetworkStatusChange.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 // NetworkStatusChange.xaml.h
00013 // Declaration of the NetworkStatusChange class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "NetworkStatusChange.g.h"
00020 #include "MainPage.xaml.h"
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::System;
00026 using namespace Windows::Foundation;
00027 using namespace Platform;
00028 using namespace Windows::Networking;
00029 using namespace Windows::Networking::Connectivity;
00030
00031 namespace SDKSample
00032 {
00033     namespace NetworkInformationApi
00034     {
00035         /// <summary>
00036         /// An empty page that can be used on its own or navigated to within a Frame.
00037         /// </summary>
00038         public ref class NetworkStatusChange sealed
00039         {
00040         public:
00041             NetworkStatusChange();
00042
00043         protected:
00044             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00045             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00046         private:
00047             MainPage^ rootPage;
00048             void NetworkStatusChange_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00049             bool registeredNetworkStatusNotif;
00050             Windows::Foundation::EventRegistrationToken cookie;
00051             String^ internetProfileInfo;
00052             Windows::Networking::Connectivity::NetworkInformation^ networkInfo;
00053             Windows::Networking::Connectivity::NetworkStatusChangedEventHandler^ networkStatusCallback;
00054
00055             String^ GetConnectionProfile(Windows::Networking::Connectivity::ConnectionProfile^ connectionProfile);
00056             String^ GetConnectionCostInfo(Windows::Networking::Connectivity::ConnectionCost^ connectionCost);
00057             String^ GetCostBasedSuggestions(Windows::Networking::Connectivity::ConnectionCost^ connectionCost);
00058             String^ GetDataPlanStatusInfo(Windows::Networking::Connectivity::DataPlanStatus^ dataPlan);
00059             String^ GetNetworkSecuritySettingsInfo(Windows::Networking::Connectivity::NetworkSecuritySettings^ netSecuritySettings);
00060             void OnNetworkStatusChange(Object^ sender);
00061             void UnRegisterForNetworkStatusChangeNotif ();
00062
00063         };
00064     }
00065 }
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Proximity/C++/ProximityDeviceScenario.xaml.h Source File

  • Proximity

ProximityDeviceScenario.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 // ProximityDeviceScenario.xaml.h
00013 // Declaration of the ProximityDeviceScenario class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "ProximityDeviceScenario.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace ProximityCPP
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 ProximityDeviceScenario sealed
00029     {
00030     public:
00031         ProximityDeviceScenario();
00032
00033     protected:
00034         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00035         virtual void OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs ^ e) override;
00036         void ProximityDevice_PublishMessage(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00037         void MessageReceived(Windows::Networking::Proximity::ProximityDevice^ device, Windows::Networking::Proximity::ProximityMessage^ message);
00038         void ProximityDevice_SubscribeForMessage(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039     private:
00040         MainPage^ m_rootPage;
00041
00042
00043         long long m_publishedMessageId;
00044         Windows::Networking::Proximity::ProximityDevice^ m_proximityDevice;
00045         long long m_subscribedMessageId;
00046     };
00047 }
Generated on Sat Nov 23 2024 16:08:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Association launching/C++/LaunchFileInput.xaml.cpp Source File

  • Association launching

LaunchFileInput.xaml.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 //
00009 // LaunchFileInput.xaml.cpp
00010 // Implementation of the LaunchFileInput class
00011 //
00012
00013 #include "pch.h"
00014 #include "LaunchFileInput.xaml.h"
00015
00016 using namespace AssociationLaunching;
00017
00018 using namespace concurrency;
00019 using namespace CppSamplesUtils;
00020 using namespace Platform;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Foundation::Collections;
00023 using namespace Windows::Graphics::Display;
00024 using namespace Windows::Storage;
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::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
00034 Platform::String^ LaunchFileInput::fileToLaunch = "Icon.Targetsize-256.png";
00035
00036 LaunchFileInput::LaunchFileInput()
00037 {
00038     InitializeComponent();
00039 }
00040
00041 LaunchFileInput::~LaunchFileInput()
00042 {
00043 }
00044
00045 #pragma region Template-Related Code - Do not remove
00046 void LaunchFileInput::OnNavigatedTo(NavigationEventArgs^ e)
00047 {
00048     // Get a pointer to our main page.
00049     rootPage = dynamic_cast<MainPage^>(e->Parameter);
00050 }
00051
00052 void LaunchFileInput::OnNavigatedFrom(NavigationEventArgs^ e)
00053 {
00054 }
00055
00056 #pragma endregion
00057
00058 void LaunchFileInput::LaunchFileButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00059 {
00060     auto installFolder = Windows::ApplicationModel::Package::Current->InstalledLocation;
00061     auto page = this->rootPage;
00062
00063     // Get the file to launch.
00064     create_task(installFolder->GetFileAsync(fileToLaunch)).then([page](StorageFile^ file)
00065     {
00066         // Now launch the file.
00067         return Windows::System::Launcher::LaunchFileAsync(file);
00068     }).then([page](bool launchResult)
00069     {
00070         if (launchResult)
00071         {
00072             page->NotifyUser("File launch succeeded.", NotifyType::StatusMessage);
00073         }
00074         else
00075         {
00076             page->NotifyUser("File launch failed.", NotifyType::ErrorMessage);
00077         }
00078     });
00079 }
00080
00081 void LaunchFileInput::LaunchFileWithWarningButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00082 {
00083     auto installFolder = Windows::ApplicationModel::Package::Current->InstalledLocation;
00084     auto page = this->rootPage;
00085
00086     // Get the file to launch.
00087     create_task(installFolder->GetFileAsync(fileToLaunch)).then([page](StorageFile^ file)
00088     {
00089         // Configure the warning prompt.
00090         auto launchOptions = ref new Windows::System::LauncherOptions();
00091         launchOptions->TreatAsUntrusted = true;
00092
00093         // Now launch the file.
00094         return Windows::System::Launcher::LaunchFileAsync(file, launchOptions);
00095     }).then([page](bool launchResult)
00096     {
00097         if (launchResult)
00098         {
00099             page->NotifyUser("File launch succeeded.", NotifyType::StatusMessage);
00100         }
00101         else
00102         {
00103             page->NotifyUser("File launch failed.", NotifyType::ErrorMessage);
00104         }
00105     });
00106 }
00107
00108 void LaunchFileInput::LaunchFileOpenWithButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00109 {
00110     auto installFolder = Windows::ApplicationModel::Package::Current->InstalledLocation;
00111     auto page = this->rootPage;
00112     auto button = LaunchFileOpenWithButton;
00113
00114     // Get the file to launch.
00115     create_task(installFolder->GetFileAsync(fileToLaunch)).then([page, button](StorageFile^ file)
00116     {
00117         // Calculate the position for the Open With dialog.
00118         Point openWithPosition = GetOpenWithPosition(button);
00119         auto launchOptions = ref new Windows::System::LauncherOptions();
00120         launchOptions->DisplayApplicationPicker = true;
00121         launchOptions->UI->InvocationPoint = dynamic_cast<IBox<Point>^>(PropertyValue::CreatePoint(openWithPosition));
00122         launchOptions->UI->PreferredPlacement = Windows::UI::Popups::Placement::Below;
00123
00124         // Now launch the file.
00125         return Windows::System::Launcher::LaunchFileAsync(file, launchOptions);
00126     }).then([page](bool launchResult)
00127     {
00128         if (launchResult)
00129         {
00130             page->NotifyUser("File launch succeeded.", NotifyType::StatusMessage);
00131         }
00132         else
00133         {
00134             page->NotifyUser("File launch failed.", NotifyType::ErrorMessage);
00135         }
00136     });
00137 }
00138
00139 void LaunchFileInput::PickAndLaunchFileButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00140 {
00141     auto page = this->rootPage;
00142
00143     // Get the file to launch via the picker.
00144     // To use the picker, the sample must not be snapped.
00145     if (Windows::UI::ViewManagement::ApplicationView::Value == Windows::UI::ViewManagement::ApplicationViewState::Snapped)
00146     {
00147         if (!Windows::UI::ViewManagement::ApplicationView::TryUnsnap())
00148         {
00149             page->NotifyUser("Unable to unsnap the sample.", NotifyType::ErrorMessage);
00150             return;
00151         }
00152     }
00153
00154     auto openPicker = ref new Windows::Storage::Pickers::FileOpenPicker();
00155     openPicker->FileTypeFilter->Append("*");
00156
00157     create_task(openPicker->PickSingleFileAsync()).then([page](StorageFile^ file)
00158     {
00159         if (file)
00160         {
00161             // Now launch the file.
00162             task<bool>(Windows::System::Launcher::LaunchFileAsync(file)).then([page](bool launchResult)
00163             {
00164                 if (launchResult)
00165                 {
00166                     page->NotifyUser("File launch succeeded.", NotifyType::StatusMessage);
00167                 }
00168                 else
00169                 {
00170                     page->NotifyUser("File launch failed.", NotifyType::ErrorMessage);
00171                 }
00172             });
00173         }
00174         else
00175         {
00176             page->NotifyUser("No file was picked.", NotifyType::ErrorMessage);
00177         }
00178     });
00179 }
00180
00181 // The Open With dialog will be displayed just under the element that triggered them.
00182 // An alternative to using the point is to set the rect of the bounding element.
00183 Point LaunchFileInput::GetOpenWithPosition(FrameworkElement^ element)
00184 {
00185     Windows::UI::Xaml::Media::GeneralTransform^ buttonTransform = element->TransformToVisual(nullptr);
00186     Point origin(0, 0);
00187
00188     Point desiredLocation = buttonTransform->TransformPoint(origin);
00189     desiredLocation.Y = desiredLocation.Y + safe_cast<float>(element->ActualHeight);
00190
00191     return desiredLocation;
00192 }
Generated on Sat Nov 23 2024 16:07:57 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D animation/C++/D2DBasicAnimation.h Source File

  • Direct2D animation

D2DBasicAnimation.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 "DirectXBase.h"
00011 #include "SampleOverlay.h"
00012
00013 ref class D2DBasicAnimation : public DirectXBase, public Windows::ApplicationModel::Core::IFrameworkView
00014 {
00015 internal:
00016     D2DBasicAnimation();
00017
00018     // DirectXBase Methods
00019     virtual void CreateDeviceIndependentResources() override;
00020     virtual void CreateDeviceResources() override;
00021     virtual void Render() override;
00022
00023 public:
00024     // IFrameworkView Methods
00025     virtual void Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00026     virtual void SetWindow(_In_ Windows::UI::Core::CoreWindow^ window);
00027     virtual void Load(_In_ Platform::String^ entryPoint);
00028     virtual void Run();
00029     virtual void Uninitialize();
00030
00031 private:
00032     // Event Handlers
00033     void OnWindowSizeChanged(
00034         _In_ Windows::UI::Core::CoreWindow^ sender,
00035         _In_ Windows::UI::Core::WindowSizeChangedEventArgs^ args
00036         );
00037
00038     void OnVisibilityChanged(
00039         _In_ Windows::UI::Core::CoreWindow^ sender,
00040         _In_ Windows::UI::Core::VisibilityChangedEventArgs^ args
00041         );
00042
00043     void OnLogicalDpiChanged(
00044         _In_ Platform::Object^ sender
00045         );
00046
00047     void OnActivated(
00048         _In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView,
00049         _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^ args
00050         );
00051
00052     void OnSuspending(
00053         _In_ Platform::Object^ sender,
00054         _In_ Windows::ApplicationModel::SuspendingEventArgs^ args
00055         );
00056
00057     void OnResuming(
00058         _In_ Platform::Object^ sender,
00059         _In_ Platform::Object^ args
00060         );
00061
00062     void OnWindowClosed(
00063         _In_ Windows::UI::Core::CoreWindow^ sender,
00064         _In_ Windows::UI::Core::CoreWindowEventArgs^ args
00065         );
00066
00067     // Sample Methods
00068     void CreateSpiralPathAndTriangle();
00069     float ComputeTriangleLocation(float startPoint, float endPoint, float duration, float elapsedTime);
00070
00071     SampleOverlay^                                                  m_sampleOverlay;
00072     bool                                                            m_windowClosed;
00073     bool                                                            m_windowVisible;
00074     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>                    m_blackBrush;
00075     Microsoft::WRL::ComPtr<IDWriteTextFormat>                       m_textFormat;
00076     Microsoft::WRL::ComPtr<ID2D1PathGeometry>                       m_pathGeometry;
00077     Microsoft::WRL::ComPtr<ID2D1PathGeometry>                       m_objectGeometry;
00078     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>                    m_whiteBrush;
00079     float                                                           m_pathLength;
00080     float                                                           m_elapsedTime;
00081 };
00082
00083 ref class DirectXAppSource : Windows::ApplicationModel::Core::IFrameworkViewSource
00084 {
00085 public:
00086     virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00087 };
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text display/C++/Common/suspensionmanager.h Source File

  • XAML text display
  • Common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML data binding/C++/Scenario2.xaml.h Source File

  • XAML data binding

Scenario2.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.xaml.h
00013 // Declaration of the Scenario2 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario2.g.h"
00020 #include "MainPage.xaml.h"
00021 #include "S2Formatter.h"
00022
00023 namespace SDKSample
00024 {
00025     namespace DataBinding
00026     {
00027         /// <summary>
00028         /// An empty page that can be used on its own or navigated to within a Frame.
00029         /// </summary>
00030         public ref class Scenario2 sealed
00031         {
00032         public:
00033             Scenario2();
00034         private:
00035             MainPage^ rootPage;
00036             void Scenario2Reset(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00037         };
00038     }
00039 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Renderer Member List

This is the complete list of members for Renderer, including all inherited members.
__pad0__ | Renderer |
CreateDeviceIndependentResources() | Renderer | [private]
CreateDeviceResources() | Renderer | [private]
DeviceLost | Renderer |
dpi | Renderer |
GetD2DDeviceContext(_Outptr_ ID2D1DeviceContext **d2dDeviceContext) | Renderer |
GetDisplayHeight() | Renderer | [inline]
GetDisplaySize() | Renderer | [inline]
GetDisplayWidth() | Renderer | [inline]
GetDXGIDevice(_Outptr_ IDXGIDevice **dxgiDevice) | Renderer |
GetWICImagingFactory(_Outptr_ IWICImagingFactory2 **wicFactory) | Renderer |
HandleDeviceLost() | Renderer |
IsOrientationLandscape() | Renderer | [inline]
m_d2dDevice | Renderer | [private]
m_d2dDeviceContext | Renderer | [private]
m_d2dFactory | Renderer | [private]
m_dpi | Renderer | [private]
m_dxgiDevice | Renderer | [private]
m_featureLevel | Renderer | [private]
m_wicFactory | Renderer | [private]
m_windowBounds | Renderer | [private]
SetDpi(float dpi) | Renderer |
UpdateWindowSize() | Renderer |
Generated on Sat Nov 23 2024 16:09:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application data/C++/CompositeSettings.xaml.h Source File

  • Application data

CompositeSettings.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 // CompositeSettings.xaml.h
00013 // Declaration of the CompositeSettings class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "CompositeSettings.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace ApplicationDataSample
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 CompositeSettings sealed
00031         {
00032         public:
00033             CompositeSettings();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             Windows::Storage::ApplicationDataContainer^ roamingSettings;
00040
00041             void WriteCompositeSetting_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00042             void DeleteCompositeSetting_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00043             void DisplayOutput();
00044         };
00045     }
00046 }
Generated on Sat Nov 23 2024 16:07:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application resources and localization/C++/Scenario11.xaml.h Source File

  • Application resources and localization

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 SDKSample
00023 {
00024     namespace ApplicationResources
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 Scenario11 sealed
00031         {
00032         public:
00033             Scenario11();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039         void Scenario11Button_Show_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Sharing content source app/C++/App.xaml.cpp Source File

  • Sharing content source app

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:28 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Audio Session (WASAPI)/C++/Scenario1.xaml.h Source File

  • Windows Audio Session (WASAPI)
  • C++

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 using namespace Windows::Devices::Enumeration;
00023
00024 namespace SDKSample
00025 {
00026     namespace WASAPIAudio
00027     {
00028         // Custom properties defined in mmdeviceapi.h in the format "{GUID} PID"
00029         static Platform::String^ PKEY_AudioEndpoint_Supports_EventDriven_Mode = "{1da5d803-d492-4edd-8c23-e0c0ffee7f0e} 7";
00030
00031         [Windows::Foundation::Metadata::WebHostHidden]
00032         public ref class Scenario1 sealed
00033         {
00034         public:
00035             Scenario1();
00036
00037         protected:
00038             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00039
00040         private:
00041             void ShowStatusMessage( Platform::String^ str, NotifyType messageType );
00042             void Enumerate_Click( Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e );
00043             void EnumerateAudioDevicesAsync();
00044
00045         private:
00046             MainPage^                               rootPage;
00047             Windows::UI::Xaml::Controls::ListBox^   m_DevicesList;
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D-Direct2D interop/C++/BasicLoader.h Source File

  • Direct3D-Direct2D interop

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 Sat Nov 23 2024 16:08:08 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Accelerometer sensor/C++/App.xaml.cpp Source File

  • Accelerometer sensor

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Audio Session (WASAPI)/C++/PlotData.h Source File

  • Windows Audio Session (WASAPI)
  • C++

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 //
00012 // plotdata.h
00013 //
00014
00015 #include "MainPage.xaml.h"
00016
00017 #pragma once
00018
00019 #define MILLISECONDS_TO_VISUALIZE 20
00020
00021 namespace SDKSample
00022 {
00023     namespace WASAPIAudio
00024     {
00025         // Class for PlotDataReady events
00026         public ref class PlotDataReadyEventArgs sealed
00027         {
00028         internal:
00029             PlotDataReadyEventArgs( Platform::Array<int, 1>^ points, UINT32 size ) :
00030                     m_PointArray( points ),
00031                     m_Size( size )
00032             {};
00033
00034             property Platform::Array<int, 1>^ Points
00035             {
00036                 Platform::Array<int, 1>^ get() { return m_PointArray; }
00037             };
00038
00039             property UINT32 Size
00040             {
00041                 UINT32 get() { return m_Size; }
00042             };
00043
00044         private:
00045             Platform::Array<int,1>^     m_PointArray;
00046             UINT32                      m_Size;
00047         };
00048
00049         // PlotDataReady delegate
00050         public delegate void PlotDataReadyHandler( Platform::Object^ sender, PlotDataReadyEventArgs^ e );
00051
00052         // PlotDataReady Event
00053         public ref class PlotDataReadyEvent sealed
00054         {
00055         public:
00056             PlotDataReadyEvent() {};
00057
00058         internal:
00059             static void SendEvent( Object^ obj, Platform::Array<int, 1>^ points, UINT32 size )
00060             {
00061                 PlotDataReadyEventArgs^ e = ref new PlotDataReadyEventArgs( points, size );
00062                 PlotDataReady( obj, e );
00063             }
00064
00065         public:
00066             static event PlotDataReadyHandler^    PlotDataReady;
00067         };
00068     }
00069 }
Generated on Sat Nov 23 2024 16:08:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Real-time communication/C#,C++/sample-utils/SuspensionManager.cs Source File

  • Real-time communication
  • C#,C++
  • sample-utils

SuspensionManager.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.Text;
00015 using System.Threading.Tasks;
00016 using Windows.Storage;
00017 using Windows.Storage.Streams;
00018 using System.Runtime.Serialization;
00019 using System.IO;
00020 using Windows.ApplicationModel;
00021
00022 class SuspensionManager
00023 {
00024     static private Dictionary<string, object> sessionState_ = new Dictionary<string, object>();
00025     static private List<Type> knownTypes_ = new List<Type>();
00026     private const string filename = "_sessionState.xml";
00027
00028     // Provides access to the currect session state
00029     static public Dictionary<string, object> SessionState
00030     {
00031         get { return sessionState_; }
00032     }
00033
00034     // Allows custom types to be added to the list of types that can be serialized
00035     static public List<Type> KnownTypes
00036     {
00037         get { return knownTypes_; }
00038     }
00039
00040     // Save the current session state
00041     static async public Task SaveAsync()
00042     {
00043         // Get the output stream for the SessionState file.
00044         StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
00045         using (StorageStreamTransaction transaction = await file.OpenTransactedWriteAsync())
00046         {
00047             // Serialize the Session State.
00048             DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), knownTypes_);
00049             serializer.WriteObject(transaction.Stream.AsStreamForWrite(), sessionState_);
00050             await transaction.CommitAsync();
00051         }
00052     }
00053
00054     // Restore the saved sesison state
00055     static async public Task RestoreAsync()
00056     {
00057         // Get the input stream for the SessionState file.
00058         try
00059         {
00060             StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(filename);
00061             if (file == null) return;
00062             using (IInputStream inStream = await file.OpenSequentialReadAsync())
00063             {
00064                 // Deserialize the Session State.
00065                 DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), knownTypes_);
00066                 sessionState_ = (Dictionary<string, object>)serializer.ReadObject(inStream.AsStreamForRead());
00067             }
00068         }
00069         catch (Exception)
00070         {
00071             // Restoring state is best-effort.  If it fails, the app will just come up with a new session.
00072         }
00073     }
00074 }
Generated on Sat Nov 23 2024 16:08:21 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Background task/C++/BackgroundTask/Constants.h Source File

  • Background task
  • BackgroundTask

Constants.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
00026 namespace SDKSample
00027 {
00028     public value struct Scenario
00029     {
00030         Platform::String^ Title;
00031         Platform::String^ ClassName;
00032     };
00033
00034     partial ref class MainPage
00035     {
00036     public:
00037         static property Platform::String^ FEATURE_NAME
00038         {
00039             Platform::String^ get()
00040             {
00041                 return ref new Platform::String(L"Background Task");
00042             }
00043         }
00044
00045         static property Platform::Array<Scenario>^ scenarios
00046         {
00047             Platform::Array<Scenario>^ get()
00048             {
00049                 return scenariosInner;
00050             }
00051         }
00052     private:
00053         static Platform::Array<Scenario>^ scenariosInner;
00054     };
00055
00056     namespace BackgroundTask
00057     {
00058         class BackgroundTaskSample
00059         {
00060         public:
00061             static String^ GetBackgroundTaskStatus(Platform::String^ name);
00062             static void InitializeBackgroundTaskStatus();
00063             static BackgroundTaskRegistration^ RegisterBackgroundTask(String^ taskEntryPoint, String^ name, IBackgroundTrigger^ trigger, IBackgroundCondition^ condition);
00064             static void RegisterServicingCompleteBackgroundTask();
00065             static void UnregisterBackgroundTasks(String^ name);
00066             static void UpdateBackgroundTaskStatus(Platform::String^ name, bool registered);
00067
00068             static String^ SampleBackgroundTaskProgress;
00069             static bool SampleBackgroundTaskRegistered;
00070
00071             static String^ SampleBackgroundTaskWithConditionProgress;
00072             static bool SampleBackgroundTaskWithConditionRegistered;
00073
00074             static String^ ServicingCompleteTaskProgress;
00075             static bool ServicingCompleteTaskRegistered;
00076
00077             static String^ TimeTriggeredTaskProgress;
00078             static bool TimeTriggeredTaskRegistered;
00079         };
00080
00081     }
00082 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAudio2 audio stream effect/C++/SampleOverlay.cpp Source File

  • XAudio2 audio stream effect

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 Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::UI::ViewManagement;
00015 using namespace Windows::Graphics::Display;
00016 using namespace D2D1;
00017
00018 SampleOverlay::SampleOverlay() :
00019     m_drawOverlay(true)
00020 {
00021 }
00022
00023 void SampleOverlay::Initialize(
00024     _In_ ID2D1Device*         d2dDevice,
00025     _In_ ID2D1DeviceContext*  d2dContext,
00026     _In_ IWICImagingFactory*  wicFactory,
00027     _In_ IDWriteFactory*      dwriteFactory,
00028     _In_ Platform::String^    caption
00029     )
00030 {
00031     m_wicFactory = wicFactory;
00032     m_dwriteFactory = dwriteFactory;
00033     m_sampleName = caption;
00034     m_d2dDevice = d2dDevice;
00035     m_d2dContext = d2dContext;
00036     m_padding = 3.0f;
00037     m_textVerticalOffset = 5.0f;
00038     m_logoSize = D2D1::SizeF(0.0f, 0.0f);
00039     m_overlayWidth = 0.0f;
00040
00041     ComPtr<ID2D1Factory> factory;
00042     d2dDevice->GetFactory(&factory);
00043
00044     DX::ThrowIfFailed(
00045         factory.As(&m_d2dFactory)
00046         );
00047
00048     ResetDirectXResources();
00049 }
00050
00051 void SampleOverlay::ResetDirectXResources()
00052 {
00053     DX::ThrowIfFailed(
00054         m_d2dContext->CreateSolidColorBrush(ColorF(ColorF::White), &m_whiteBrush)
00055         );
00056
00057     ComPtr<IWICBitmapDecoder> wicBitmapDecoder;
00058     DX::ThrowIfFailed(
00059         m_wicFactory->CreateDecoderFromFilename(
00060             L"windowsbig-sdk.png",
00061             nullptr,
00062             GENERIC_READ,
00063             WICDecodeMetadataCacheOnDemand,
00064             &wicBitmapDecoder
00065             )
00066         );
00067
00068     ComPtr<IWICBitmapFrameDecode> wicBitmapFrame;
00069     DX::ThrowIfFailed(
00070         wicBitmapDecoder->GetFrame(0, &wicBitmapFrame)
00071         );
00072
00073     ComPtr<IWICFormatConverter> wicFormatConverter;
00074     DX::ThrowIfFailed(
00075         m_wicFactory->CreateFormatConverter(&wicFormatConverter)
00076         );
00077
00078     DX::ThrowIfFailed(
00079         wicFormatConverter->Initialize(
00080             wicBitmapFrame.Get(),
00081             GUID_WICPixelFormat32bppPBGRA,
00082             WICBitmapDitherTypeNone,
00083             nullptr,
00084             0.0,
00085             WICBitmapPaletteTypeCustom  // the BGRA format has no palette so this value is ignored
00086             )
00087         );
00088
00089     double dpiX = 96.0f;
00090     double dpiY = 96.0f;
00091     DX::ThrowIfFailed(
00092         wicFormatConverter->GetResolution(&dpiX, &dpiY)
00093         );
00094
00095     DX::ThrowIfFailed(
00096         m_d2dContext->CreateBitmapFromWicBitmap(
00097             wicFormatConverter.Get(),
00098             BitmapProperties(
00099                 PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00100                 static_cast<float>(dpiX),
00101                 static_cast<float>(dpiY)
00102                 ),
00103             &m_logoBitmap
00104             )
00105         );
00106
00107     m_logoSize = m_logoBitmap->GetSize();
00108
00109     ComPtr<IDWriteTextFormat> nameTextFormat;
00110     DX::ThrowIfFailed(
00111         m_dwriteFactory->CreateTextFormat(
00112             L"Segoe UI",
00113             nullptr,
00114             DWRITE_FONT_WEIGHT_LIGHT,
00115             DWRITE_FONT_STYLE_NORMAL,
00116             DWRITE_FONT_STRETCH_NORMAL,
00117             36.0f,
00118             L"en-US",
00119             &nameTextFormat
00120             )
00121         );
00122
00123     DX::ThrowIfFailed(
00124         nameTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)
00125         );
00126
00127     DX::ThrowIfFailed(
00128         nameTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)
00129         );
00130
00131     DX::ThrowIfFailed(
00132         m_dwriteFactory->CreateTextLayout(
00133             m_sampleName->Data(),
00134             m_sampleName->Length(),
00135             nameTextFormat.Get(),
00136             4096.0f,
00137             4096.0f,
00138             &m_textLayout
00139             )
00140         );
00141
00142     DWRITE_TEXT_METRICS metrics = {0};
00143     DX::ThrowIfFailed(
00144         m_textLayout->GetMetrics(&metrics)
00145         );
00146
00147     m_overlayWidth = m_padding * 3.0f + m_logoSize.width + metrics.width;
00148
00149     DX::ThrowIfFailed(
00150         m_d2dFactory->CreateDrawingStateBlock(&m_stateBlock)
00151         );
00152
00153     UpdateForWindowSizeChange();
00154 }
00155
00156 void SampleOverlay::UpdateForWindowSizeChange()
00157 {
00158     if (CoreWindow::GetForCurrentThread()->Bounds.Width < m_overlayWidth)
00159     {
00160         m_drawOverlay = false;
00161     }
00162     else
00163     {
00164         m_drawOverlay = true;
00165     }
00166 }
00167
00168 void SampleOverlay::Render()
00169 {
00170     if (m_drawOverlay)
00171     {
00172         m_d2dContext->SaveDrawingState(m_stateBlock.Get());
00173
00174         m_d2dContext->BeginDraw();
00175         m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00176         m_d2dContext->DrawBitmap(
00177             m_logoBitmap.Get(),
00178             D2D1::RectF(m_padding, 0.0f, m_logoSize.width + m_padding, m_logoSize.height)
00179             );
00180
00181         m_d2dContext->DrawTextLayout(
00182             Point2F(m_logoSize.width + 2.0f * m_padding, m_textVerticalOffset),
00183             m_textLayout.Get(),
00184             m_whiteBrush.Get()
00185             );
00186
00187         // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00188         // is lost. It will be handled during the next call to Present.
00189         HRESULT hr = m_d2dContext->EndDraw();
00190         if (hr != D2DERR_RECREATE_TARGET)
00191         {
00192             DX::ThrowIfFailed(hr);
00193         }
00194
00195         m_d2dContext->RestoreDrawingState(m_stateBlock.Get());
00196     }
00197 }
00198
00199 float SampleOverlay::GetTitleHeightInDips()
00200 {
00201     return m_logoSize.height;
00202 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Portable device API/C++/MainPage.xaml.h Source File

  • Portable device API

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:46 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/ScenarioInput1.xaml.h Source File

  • Media extensions

ScenarioInput1.xaml.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 // ScenarioInput1.xaml.h
00009 // Declaration of the ScenarioInput1 class.
00010 //
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "ScenarioInput1.g.h"
00016 #include "MainPage.xaml.h"
00017
00018 using namespace Windows::UI::Xaml;
00019
00020 namespace MediaExtensionsCPP
00021 {
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class ScenarioInput1 sealed
00024     {
00025     public:
00026         ScenarioInput1();
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         ~ScenarioInput1();
00034         MainPage^ rootPage;
00035         MediaElement^ outputVideo;
00036
00037         void rootPage_OutputFrameLoaded(Object^ sender, Object^ e);
00038         void Open_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039         void Stop_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         Windows::Foundation::EventRegistrationToken _frameLoadedToken;
00041     };
00042 }
Generated on Sat Nov 23 2024 16:07:59 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/BasicLoader.cpp Source File

  • DirectX 3D shooting game

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 Sat Nov 23 2024 16:08:07 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D tutorial/C++/Lesson2.Triangles/DirectXSample.h Source File

  • Direct3D tutorial
  • Lesson2.Triangles

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
00010 // This header defines helper utilities to make DirectX APIs work with exceptions.
00011 namespace DX
00012 {
00013     inline void ThrowIfFailed(HRESULT hr)
00014     {
00015         if (FAILED(hr))
00016         {
00017             // Set a breakpoint on this line to catch DX API errors.
00018             throw Platform::Exception::CreateException(hr);
00019         }
00020     }
00021 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Compression/C++/MainPage.xaml.h Source File

  • Compression

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Credential locker/C++/pch.cpp Source File

  • Credential locker

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 Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D bump mapping/C++/SampleOverlay.cpp Source File

  • Direct3D bump mapping

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 Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::UI::ViewManagement;
00015 using namespace Windows::Graphics::Display;
00016 using namespace D2D1;
00017
00018 SampleOverlay::SampleOverlay() :
00019     m_drawOverlay(true)
00020 {
00021 }
00022
00023 void SampleOverlay::Initialize(
00024     _In_ ID2D1Device*         d2dDevice,
00025     _In_ ID2D1DeviceContext*  d2dContext,
00026     _In_ IWICImagingFactory*  wicFactory,
00027     _In_ IDWriteFactory*      dwriteFactory,
00028     _In_ Platform::String^    caption
00029     )
00030 {
00031     m_wicFactory = wicFactory;
00032     m_dwriteFactory = dwriteFactory;
00033     m_sampleName = caption;
00034     m_d2dDevice = d2dDevice;
00035     m_d2dContext = d2dContext;
00036     m_padding = 3.0f;
00037     m_textVerticalOffset = 5.0f;
00038     m_logoSize = D2D1::SizeF(0.0f, 0.0f);
00039     m_overlayWidth = 0.0f;
00040
00041     ComPtr<ID2D1Factory> factory;
00042     d2dDevice->GetFactory(&factory);
00043
00044     DX::ThrowIfFailed(
00045         factory.As(&m_d2dFactory)
00046         );
00047
00048     ResetDirectXResources();
00049 }
00050
00051 void SampleOverlay::ResetDirectXResources()
00052 {
00053     DX::ThrowIfFailed(
00054         m_d2dContext->CreateSolidColorBrush(ColorF(ColorF::White), &m_whiteBrush)
00055         );
00056
00057     ComPtr<IWICBitmapDecoder> wicBitmapDecoder;
00058     DX::ThrowIfFailed(
00059         m_wicFactory->CreateDecoderFromFilename(
00060             L"windowsbig-sdk.png",
00061             nullptr,
00062             GENERIC_READ,
00063             WICDecodeMetadataCacheOnDemand,
00064             &wicBitmapDecoder
00065             )
00066         );
00067
00068     ComPtr<IWICBitmapFrameDecode> wicBitmapFrame;
00069     DX::ThrowIfFailed(
00070         wicBitmapDecoder->GetFrame(0, &wicBitmapFrame)
00071         );
00072
00073     ComPtr<IWICFormatConverter> wicFormatConverter;
00074     DX::ThrowIfFailed(
00075         m_wicFactory->CreateFormatConverter(&wicFormatConverter)
00076         );
00077
00078     DX::ThrowIfFailed(
00079         wicFormatConverter->Initialize(
00080             wicBitmapFrame.Get(),
00081             GUID_WICPixelFormat32bppPBGRA,
00082             WICBitmapDitherTypeNone,
00083             nullptr,
00084             0.0,
00085             WICBitmapPaletteTypeCustom  // the BGRA format has no palette so this value is ignored
00086             )
00087         );
00088
00089     double dpiX = 96.0f;
00090     double dpiY = 96.0f;
00091     DX::ThrowIfFailed(
00092         wicFormatConverter->GetResolution(&dpiX, &dpiY)
00093         );
00094
00095     DX::ThrowIfFailed(
00096         m_d2dContext->CreateBitmapFromWicBitmap(
00097             wicFormatConverter.Get(),
00098             BitmapProperties(
00099                 PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00100                 static_cast<float>(dpiX),
00101                 static_cast<float>(dpiY)
00102                 ),
00103             &m_logoBitmap
00104             )
00105         );
00106
00107     m_logoSize = m_logoBitmap->GetSize();
00108
00109     ComPtr<IDWriteTextFormat> nameTextFormat;
00110     DX::ThrowIfFailed(
00111         m_dwriteFactory->CreateTextFormat(
00112             L"Segoe UI",
00113             nullptr,
00114             DWRITE_FONT_WEIGHT_LIGHT,
00115             DWRITE_FONT_STYLE_NORMAL,
00116             DWRITE_FONT_STRETCH_NORMAL,
00117             36.0f,
00118             L"en-US",
00119             &nameTextFormat
00120             )
00121         );
00122
00123     DX::ThrowIfFailed(
00124         nameTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)
00125         );
00126
00127     DX::ThrowIfFailed(
00128         nameTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)
00129         );
00130
00131     DX::ThrowIfFailed(
00132         m_dwriteFactory->CreateTextLayout(
00133             m_sampleName->Data(),
00134             m_sampleName->Length(),
00135             nameTextFormat.Get(),
00136             4096.0f,
00137             4096.0f,
00138             &m_textLayout
00139             )
00140         );
00141
00142     DWRITE_TEXT_METRICS metrics = {0};
00143     DX::ThrowIfFailed(
00144         m_textLayout->GetMetrics(&metrics)
00145         );
00146
00147     m_overlayWidth = m_padding * 3.0f + m_logoSize.width + metrics.width;
00148
00149     DX::ThrowIfFailed(
00150         m_d2dFactory->CreateDrawingStateBlock(&m_stateBlock)
00151         );
00152
00153     UpdateForWindowSizeChange();
00154 }
00155
00156 void SampleOverlay::UpdateForWindowSizeChange()
00157 {
00158     if (CoreWindow::GetForCurrentThread()->Bounds.Width < m_overlayWidth)
00159     {
00160         m_drawOverlay = false;
00161     }
00162     else
00163     {
00164         m_drawOverlay = true;
00165     }
00166 }
00167
00168 void SampleOverlay::Render()
00169 {
00170     if (m_drawOverlay)
00171     {
00172         m_d2dContext->SaveDrawingState(m_stateBlock.Get());
00173
00174         m_d2dContext->BeginDraw();
00175         m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00176         m_d2dContext->DrawBitmap(
00177             m_logoBitmap.Get(),
00178             D2D1::RectF(m_padding, 0.0f, m_logoSize.width + m_padding, m_logoSize.height)
00179             );
00180
00181         m_d2dContext->DrawTextLayout(
00182             Point2F(m_logoSize.width + 2.0f * m_padding, m_textVerticalOffset),
00183             m_textLayout.Get(),
00184             m_whiteBrush.Get()
00185             );
00186
00187         // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00188         // is lost. It will be handled during the next call to Present.
00189         HRESULT hr = m_d2dContext->EndDraw();
00190         if (hr != D2DERR_RECREATE_TARGET)
00191         {
00192             DX::ThrowIfFailed(hr);
00193         }
00194
00195         m_d2dContext->RestoreDrawingState(m_stateBlock.Get());
00196     }
00197 }
00198
00199 float SampleOverlay::GetTitleHeightInDips()
00200 {
00201     return m_logoSize.height;
00202 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: USSD message management/C++/common/suspensionmanager.h Source File

  • USSD message management
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Hilo::ObserveException< T > Member List

This is the complete list of members for Hilo::ObserveException< T >, including all inherited members.
m_handler | Hilo::ObserveException< T > | [private]
ObserveException(std::shared_ptr< ExceptionPolicy > handler) | Hilo::ObserveException< T > | [inline]
operator()(concurrency::task< T > antecedent) const | Hilo::ObserveException< T > | [inline]
operator()(concurrency::task< void > antecedent) const | Hilo::ObserveException< T > |
Generated on Sat Nov 23 2024 16:09:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Globalization preferences/C++/common/suspensionmanager.cpp Source File

  • Globalization preferences
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:36 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Number formatting and parsing/C++/MainPage.xaml.cpp Source File

  • Number formatting and parsing

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:43 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DXGI offer and reclaim resources/C++/BasicTimer.cpp Source File

  • DXGI offer and reclaim resources

BasicTimer.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 "BasicTimer.h"
00010
00011 BasicTimer::BasicTimer()
00012 {
00013     if (!QueryPerformanceFrequency(&m_frequency))
00014     {
00015         throw ref new Platform::FailureException();
00016     }
00017     Reset();
00018 }
00019
00020 void BasicTimer::Reset()
00021 {
00022     Update();
00023     m_startTime = m_currentTime;
00024     m_total = 0.0f;
00025     m_delta = 1.0f / 60.0f;
00026 }
00027
00028 void BasicTimer::Update()
00029 {
00030     if (!QueryPerformanceCounter(&m_currentTime))
00031     {
00032         throw ref new Platform::FailureException();
00033     }
00034
00035     m_total = static_cast<float>(
00036         static_cast<double>(m_currentTime.QuadPart-m_startTime.QuadPart) /
00037         static_cast<double>(m_frequency.QuadPart)
00038         );
00039
00040     if (m_lastTime.QuadPart == m_startTime.QuadPart)
00041     {
00042         // If the timer was just reset, report a time delta equivalent to 60Hz frame time.
00043         m_delta = 1.0f / 60.0f;
00044     }
00045     else
00046     {
00047         m_delta = static_cast<float>(
00048             static_cast<double>(m_currentTime.QuadPart-m_lastTime.QuadPart) /
00049             static_cast<double>(m_frequency.QuadPart)
00050             );
00051     }
00052
00053     m_lastTime = m_currentTime;
00054 }
00055
00056 float BasicTimer::Total::get()
00057 {
00058     return m_total;
00059 }
00060
00061 float BasicTimer::Delta::get()
00062 {
00063     return m_delta;
00064 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D bump mapping/C++/DirectXApp.h Source File

  • Direct3D bump mapping

DirectXApp.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 "BumpMapping.h"
00011
00012 ref class DirectXApp : public Windows::ApplicationModel::Core::IFrameworkView
00013 {
00014 internal:
00015     DirectXApp();
00016
00017 public:
00018     // IFrameworkView Methods
00019     virtual void Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00020     virtual void SetWindow(_In_ Windows::UI::Core::CoreWindow^ window);
00021     virtual void Load(_In_ Platform::String^ entryPoint);
00022     virtual void Run();
00023     virtual void Uninitialize();
00024
00025 private:
00026     // Event Handlers
00027     void OnWindowSizeChanged(
00028         _In_ Windows::UI::Core::CoreWindow^ sender,
00029         _In_ Windows::UI::Core::WindowSizeChangedEventArgs^ args
00030         );
00031
00032     void OnVisibilityChanged(
00033         _In_ Windows::UI::Core::CoreWindow^ sender,
00034         _In_ Windows::UI::Core::VisibilityChangedEventArgs^ args
00035         );
00036
00037     void OnLogicalDpiChanged(
00038         _In_ Platform::Object^ sender
00039         );
00040
00041     void OnActivated(
00042         _In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView,
00043         _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^ args
00044         );
00045
00046     void OnSuspending(
00047         _In_ Platform::Object^ sender,
00048         _In_ Windows::ApplicationModel::SuspendingEventArgs^ args
00049         );
00050
00051     void OnResuming(
00052         _In_ Platform::Object^ sender,
00053         _In_ Platform::Object^ args
00054         );
00055
00056     void OnWindowClosed(
00057         _In_ Windows::UI::Core::CoreWindow^ sender,
00058         _In_ Windows::UI::Core::CoreWindowEventArgs^ args
00059         );
00060
00061     BumpMapping^ m_renderer;
00062     bool m_windowClosed;
00063     bool m_windowVisible;
00064 };
00065
00066 ref class DirectXAppSource : Windows::ApplicationModel::Core::IFrameworkViewSource
00067 {
00068 public:
00069     virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00070 };
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Number formatting and parsing/C++/DecimalFormatting.xaml.cpp Source File

  • Number formatting and parsing

DecimalFormatting.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 // DecimalFormatting.xaml.cpp
00013 // Implementation of the DecimalFormatting class
00014 //
00015
00016 #include "pch.h"
00017 #include "DecimalFormatting.xaml.h"
00018
00019 using namespace SDKSample::NumberFormatting;
00020
00021 using namespace Platform;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Navigation;
00025 using namespace Windows::Foundation;
00026 using namespace Windows::Foundation::Collections;
00027 using namespace Windows::Globalization::NumberFormatting;
00028
00029 DecimalFormatting::DecimalFormatting()
00030 {
00031     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 void DecimalFormatting::OnNavigatedTo(NavigationEventArgs^ e)
00040 {
00041     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00042     // as NotifyUser()
00043     rootPage = MainPage::Current;
00044 }
00045
00046 void SDKSample::NumberFormatting::DecimalFormatting::Display_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00047 {
00048     // This scenario uses the Windows.Globalization.NumberFormatting.DecimalFormatter class
00049     // to format a number.
00050
00051     // Create formatter initialized using the current user's preference settings.
00052     DecimalFormatter^ decimalFormat = ref new DecimalFormatter();
00053
00054     // Make a random number.
00055     float randomNumber = (float)rand() / RAND_MAX * 100000.0f;
00056
00057     // Format with the user's default preferences.
00058     String^ decimal = decimalFormat->Format(randomNumber);
00059
00060     // Format with grouping.
00061     DecimalFormatter^ decimalFormat1 = ref new DecimalFormatter();
00062     decimalFormat1->IsGrouped = true;
00063     String^ decimal1 = decimalFormat1->Format(randomNumber);
00064
00065     // Format with grouping using French.
00066     auto fr = ref new Platform::Collections::Vector<String^>();
00067     fr->Append("fr-FR");
00068     DecimalFormatter^ decimalFormatFR = ref new DecimalFormatter(fr, "ZZ");
00069     decimalFormatFR->IsGrouped = true;
00070     String^ decimalFR = decimalFormatFR->Format(randomNumber);
00071
00072     // Illustrate how automatic digit substitution works
00073     auto ar = ref new Platform::Collections::Vector<String^>();
00074     ar->Append("ar");
00075     DecimalFormatter^ decimalFormatAR = ref new DecimalFormatter(ar, "ZZ");
00076     String^ decimalAR = decimalFormatAR->Format(randomNumber);
00077
00078     // Get a fixed number.
00079     long long fixedNumber = 500;
00080
00081     // Format with the user's default preferences.
00082     String^ decimal2 = decimalFormat->Format(fixedNumber);
00083
00084     // Format always with a decimal point.
00085     DecimalFormatter^ decimalFormat3 = ref new DecimalFormatter();
00086     decimalFormat3->IsDecimalPointAlwaysDisplayed = true;
00087     decimalFormat3->FractionDigits = 0;
00088     String^ decimal3 = decimalFormat3->Format(fixedNumber);
00089
00090     // Format with no fractional digits or decimal point.
00091     DecimalFormatter^ decimalFormat4 = ref new DecimalFormatter();
00092     decimalFormat4->FractionDigits = 0;
00093     String^ decimal4 = decimalFormat4->Format(fixedNumber);
00094
00095     // Display the results.
00096     String^ results =
00097         "Random number ("                             + randomNumber + ")\n" +
00098         "With current user preferences: "             + decimal   + "\n" +
00099         "With grouping separators: "                  + decimal1  + "\n" +
00100         "With grouping separators (fr-FR): "          + decimalFR + "\n" +
00101         "With digit substitution (ar): "              + decimalAR + "\n\n" +
00102         "Fixed number ("                              + fixedNumber + ")\n" +
00103         "With current user preferences: "             + decimal2 + "\n" +
00104         "Always with a decimal point: "               + decimal3 + "\n" +
00105         "With no fraction digits or decimal points: " + decimal4;
00106     rootPage->NotifyUser(results, NotifyType::StatusMessage);
00107 }
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/CartoonEffect/PPLCartoon.cpp Source File

  • Hilo C++
  • CartoonEffect

PPLCartoon.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 #include <ppltasks.h>
00009 #include "FrameData.h"
00010 #include "FrameProcessing.h"
00011
00012 using concurrency::cancellation_token;
00013
00014 void InitializeFrameData(FrameData& frameData,
00015                          FrameProcessing& frameProcessing,
00016                          byte* sourcePixels,
00017                          unsigned int width,
00018                          unsigned int height,
00019                          unsigned int neighborWindow,
00020                          unsigned int phases,
00021                          unsigned int size,
00022                          cancellation_token token)
00023 {
00024     frameData.m_BBP = 32;
00025     frameData.m_colorPlanes = 1;
00026     frameData.m_endHeight = height;
00027     frameData.m_endWidth = width;
00028     frameData.m_neighbourArea = neighborWindow;
00029     frameData.m_pFrame = sourcePixels;
00030     frameData.m_pFrameProcessor = nullptr;
00031     frameData.m_phaseCount = phases;
00032     frameData.m_pitch = 4 * width;
00033     frameData.m_size = size;
00034     frameData.m_startHeight = 0;
00035     frameData.m_startWidth = 0;
00036
00037     frameData.m_pFrameProcessor = &frameProcessing;
00038     frameData.m_pFrameProcessor->SetNeighbourArea(frameData.m_neighbourArea);
00039     frameData.m_pFrameProcessor->SetCurrentFrame(frameData.m_pFrame,
00040         frameData.m_size,
00041         frameData.m_endWidth,
00042         frameData.m_endHeight,
00043         frameData.m_pitch,
00044         frameData.m_BBP,
00045         frameData.m_colorPlanes);
00046     frameData.m_pFrameProcessor->SetCancellationToken(token);
00047 }
00048
00049 void ApplyCartoonEffectPPL(byte* sourcePixels,
00050                            unsigned int width,
00051                            unsigned int height,
00052                            unsigned int neighborWindow,
00053                            unsigned int phases,
00054                            unsigned int size,
00055                            cancellation_token token)
00056 {
00057     FrameData frameData;
00058     FrameProcessing frameProcessing;
00059     InitializeFrameData(frameData, frameProcessing, sourcePixels, width, height, neighborWindow, phases, size, token);
00060
00061     frameData.m_pFrameProcessor->ApplyFilters(frameData.m_phaseCount);
00062 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML animation library/C++/Constants.cpp Source File

  • XAML animation library

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully qualified name for the class that implements the scenario" }
00021     { "Animations overview", "SDKSample.Animation.Scenario1" },
00022   { "Types of animations", "SDKSample.Animation.Scenario2" },
00023   { "Easing functions", "SDKSample.Animation.Scenario3" }
00024 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/MeshObject.cpp Source File

  • DirectX 3D shooting game

MeshObject.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 "MeshObject.h"
00010 #include "DirectXSample.h"
00011 #include "ConstantBuffers.h"
00012
00013 using namespace Microsoft::WRL;
00014 using namespace DirectX;
00015
00016 MeshObject::MeshObject():
00017     m_vertexCount(0),
00018     m_indexCount(0)
00019 {
00020 }
00021
00022 //--------------------------------------------------------------------------------
00023
00024 void MeshObject::Render(_In_ ID3D11DeviceContext *context)
00025 {
00026     uint32 stride = sizeof(PNTVertex);
00027     uint32 offset = 0;
00028
00029     context->IASetVertexBuffers(0, 1, m_vertexBuffer.GetAddressOf(), &stride, &offset);
00030     context->IASetIndexBuffer(m_indexBuffer.Get(), DXGI_FORMAT_R16_UINT, 0);
00031     context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
00032     context->DrawIndexed(m_indexCount, 0, 0);
00033 }
00034
00035 //--------------------------------------------------------------------------------
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAudio2 audio file playback/C++/BasicSound.cpp Source File

  • XAudio2 audio file playback

BasicSound.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 "BasicSound.h"
00010
00011 #include "SoundFileReader.h"
00012 #include "DirectXSample.h"
00013
00014 namespace
00015 {
00016 };
00017
00018 namespace
00019 {
00020     const char16* APPLICATION_TITLE = L"XAudio2 sound playback sample";
00021     const float TITLE_MARGIN = 100.0f;
00022
00023     // Audio File Names
00024     const char16* SOUND_FILE_LIST[] = {
00025             L"media\\wavs\\counting_adpcm.wav",
00026             L"media\\wavs\\electro_adpcm.wav",
00027             L"media\\wavs\\heli_adpcm.wav",
00028             L"media\\wavs\\hiphoppy_adpcm.wav",
00029             L"media\\wavs\\musicmono_adpcm.wav",
00030             L"media\\wavs\\pow_adpcm.wav",
00031             L"media\\wavs\\techno_adpcm.wav",
00032             nullptr
00033     };
00034
00035     const uint32 SOUND_SAMPLE_RATE = 48000;
00036
00037
00038     // Constants used for displaying error message
00039     const char16 MSG_NEED_AUDIO[]       = L"No usable audio devices were found; install an audio device and restart the sample.";
00040     const float INFORMATION_START_X     = 32.0f;
00041     const float INFORMATION_START_Y     = 150.0f;
00042
00043     const char16    FONT_LOCALE[]       = L"en-US";
00044     const char16    FONT_NAME[]         = L"Segoe UI";
00045     const float     FONT_SIZE_TEXT      = 18.0f;
00046
00047
00048
00049 }
00050
00051 //--------------------------------------------------------------------------------------
00052 // Name: BasicSound constructor
00053 // Desc: Default construct items
00054 //--------------------------------------------------------------------------------------
00055 BasicSound::BasicSound() :
00056     m_rectangleWidth(0),
00057     m_rectangleHeight(0),
00058     m_whiteBrush(nullptr),
00059     m_greenBrush(nullptr)
00060 {
00061     try
00062     {
00063         m_soundPlayer = new XAudio2SoundPlayer(SOUND_SAMPLE_RATE);
00064     }
00065     catch (Platform::Exception^)
00066     {
00067         //
00068         // This can fail when there are no audio devices
00069         //
00070         m_soundPlayer = nullptr;
00071     }
00072 }
00073
00074 //--------------------------------------------------------------------------------------
00075 // Name: BasicSound destructor
00076 // Desc: Cleanup allocated items
00077 //--------------------------------------------------------------------------------------
00078 BasicSound::~BasicSound()
00079 {
00080     delete m_soundPlayer;
00081     m_soundPlayer = nullptr;
00082 }
00083
00084 //--------------------------------------------------------------------------------------
00085 // Name: BasicSound::CreateDeviceIndependentResources
00086 // Desc: Common sample set up
00087 //--------------------------------------------------------------------------------------
00088 void BasicSound::CreateDeviceIndependentResources()
00089 {
00090     DirectXBase::CreateDeviceIndependentResources();
00091
00092     //
00093     // Read the sound files and add them to the XAudio2 sound player, if we have sound.
00094     //
00095     if (m_soundPlayer == nullptr)
00096     {
00097         // We have no sound devices
00098         return;
00099     }
00100     for (size_t index = 0; SOUND_FILE_LIST[index]; ++index)
00101     {
00102         try
00103         {
00104             SoundFileReader nextSound(ref new Platform::String(SOUND_FILE_LIST[index]));
00105             (void)m_soundPlayer->AddSound(nextSound.GetSoundFormat(), nextSound.GetSoundData());
00106         }
00107         catch (Platform::FailureException^)
00108         {
00109             // If we have a failure, don't play that file, not worth stopping the whole sample
00110         }
00111     }
00112
00113     // We should have at least one sound to play
00114     if (m_soundPlayer->GetSoundCount() == 0)
00115     {
00116         throw ref new Platform::FailureException();
00117     }
00118 }
00119
00120 //--------------------------------------------------------------------------------------
00121 // Name: BasicSound::CreateDeviceResources
00122 // Desc: Common sample set up
00123 //--------------------------------------------------------------------------------------
00124 void BasicSound::CreateDeviceResources()
00125 {
00126     DirectXBase::CreateDeviceResources();
00127
00128     //
00129     // Create the generic sample overlay
00130     //
00131     m_sampleOverlay = ref new SampleOverlay();
00132     m_sampleOverlay->Initialize(
00133         m_d2dDevice.Get(),
00134         m_d2dContext.Get(),
00135         m_wicFactory.Get(),
00136         m_dwriteFactory.Get(),
00137         ref new Platform::String(APPLICATION_TITLE)
00138         );
00139
00140
00141     //
00142     // Create the drawing brushes for the rectangles
00143     //
00144     DX::ThrowIfFailed(
00145         m_d2dContext->CreateSolidColorBrush(
00146             D2D1::ColorF(D2D1::ColorF::White),
00147             &m_whiteBrush
00148             )
00149         );
00150
00151     DX::ThrowIfFailed(
00152         m_d2dContext->CreateSolidColorBrush(
00153             D2D1::ColorF(D2D1::ColorF::Green),
00154             &m_greenBrush
00155             )
00156         );
00157
00158     //
00159     // Setup the graphics objects related to drawing text
00160     //
00161     DX::ThrowIfFailed(
00162         m_dwriteFactory->CreateTextFormat(
00163             FONT_NAME,
00164             nullptr,
00165             DWRITE_FONT_WEIGHT_NORMAL,
00166             DWRITE_FONT_STYLE_NORMAL,
00167             DWRITE_FONT_STRETCH_NORMAL,
00168             FONT_SIZE_TEXT,
00169             FONT_LOCALE,
00170             &m_dataTextFormat
00171             )
00172         );
00173
00174     DX::ThrowIfFailed(
00175         m_dataTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)
00176         );
00177     DX::ThrowIfFailed(
00178         m_dataTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)
00179         );
00180
00181     DX::ThrowIfFailed(
00182         m_d2dContext->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &m_textBrush)
00183         );
00184 }
00185
00186 //--------------------------------------------------------------------------------------
00187 // Name: BasicSound::CreateWindowSizeDependentResources
00188 // Desc:
00189 //          XAudio2Engine
00190 //          Mastering Voice
00191 //          Create the SoundFilePlayer objects
00192 //--------------------------------------------------------------------------------------
00193 void BasicSound::CreateWindowSizeDependentResources()
00194 {
00195     DirectXBase::CreateWindowSizeDependentResources();
00196
00197     if (m_soundPlayer != nullptr)
00198     {
00199         // Devide up the screen into sections based on the number of Wave Files
00200         D2D1_SIZE_F size = m_d2dContext->GetSize();
00201         m_rectangleWidth = (size.width / m_soundPlayer->GetSoundCount()) - 5;
00202         m_rectangleHeight = (size.height - TITLE_MARGIN)/2 - 5;
00203     }
00204
00205     m_sampleOverlay->UpdateForWindowSizeChange();
00206 }
00207
00208
00209 void BasicSound::Render()
00210 {
00211     // bind the render targets
00212     m_d3dContext->OMSetRenderTargets(
00213         1,
00214         m_d3dRenderTargetView.GetAddressOf(),
00215         m_d3dDepthStencilView.Get()
00216         );
00217
00218     // clear both the render target and depth stencil to default values
00219     const float ClearColor[4] = { 0.071f, 0.040f, 0.561f, 1.0f };
00220
00221     m_d3dContext->ClearRenderTargetView(
00222         m_d3dRenderTargetView.Get(),
00223         ClearColor
00224         );
00225
00226     m_sampleOverlay->Render();
00227
00228     m_d2dContext->BeginDraw();
00229
00230     if (m_soundPlayer == nullptr)
00231     {
00232         //
00233         // If there is no audio, render a message.
00234         //
00235         D2D1_SIZE_F size = m_d2dContext->GetSize();
00236         D2D1_RECT_F pos = D2D1::RectF(INFORMATION_START_X, INFORMATION_START_Y, size.width, size.height);
00237
00238         // Display a message when controller is not connected
00239         m_d2dContext->DrawText(
00240             MSG_NEED_AUDIO,
00241             static_cast<uint32>(::wcslen(MSG_NEED_AUDIO)),
00242             m_dataTextFormat.Get(),
00243             pos,
00244             m_textBrush.Get()
00245             );
00246
00247     }
00248     else
00249     {
00250         //
00251         // There is Audio, display rectangles for clicking and playing indication
00252         //
00253         D2D1_RECT_F r = D2D1::RectF(0, TITLE_MARGIN, m_rectangleWidth, m_rectangleHeight + TITLE_MARGIN);
00254         for (size_t next = 0; next < m_soundPlayer->GetSoundCount(); ++next)
00255         {
00256             if (m_soundPlayer->IsSoundPlaying(next))
00257             {
00258                 m_d2dContext->FillRectangle(&r, m_greenBrush.Get());
00259             }
00260             else
00261             {
00262                 m_d2dContext->DrawRectangle(&r, m_whiteBrush.Get());
00263             }
00264             r.left += m_rectangleWidth;
00265             r.right += m_rectangleWidth;
00266         }
00267     }
00268
00269     // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00270     // is lost. It will be handled during the next call to Present.
00271     HRESULT hr = m_d2dContext->EndDraw();
00272     if (hr != D2DERR_RECREATE_TARGET)
00273     {
00274         DX::ThrowIfFailed(hr);
00275     }
00276 }
00277
00278 void BasicSound::OnPointerPressed(_In_ Windows::UI::Input::PointerPoint^ p)
00279 {
00280     if (m_soundPlayer == nullptr)
00281     {
00282         //
00283         // No audio, ignore pointer presses
00284         //
00285         return;
00286     }
00287
00288     if ((p->RawPosition.Y > TITLE_MARGIN) && (p->RawPosition.Y < (m_rectangleHeight + TITLE_MARGIN)))
00289     {
00290         size_t which = static_cast<size_t>(p->RawPosition.X / m_rectangleWidth);
00291         if (which < m_soundPlayer->GetSoundCount())
00292         {
00293             if (m_soundPlayer->IsSoundPlaying(which))
00294             {
00295                 // Stop playing sound
00296                 m_soundPlayer->StopSound(which);
00297             }
00298             else
00299             {
00300                 // Start non-playing sound
00301                 m_soundPlayer->PlaySound(which);
00302             }
00303         }
00304     }
00305 }
00306
00307 void BasicSound::OnSuspending()
00308 {
00309     if (m_soundPlayer != nullptr)
00310     {
00311         m_soundPlayer->Suspend();
00312     }
00313 }
00314
00315 void BasicSound::OnResuming()
00316 {
00317     if (m_soundPlayer != nullptr)
00318     {
00319         m_soundPlayer->Resume();
00320     }
00321 }
00322
Generated on Sat Nov 23 2024 16:08:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::ExpressionBlendSampleDataSampleDataSource::sealed Member List

This is the complete list of members for SDKSample::ExpressionBlendSampleDataSampleDataSource::sealed, including all inherited members.
_Category | SDKSample::ExpressionBlendSampleDataSampleDataSource::sealed | [private]
_Content | SDKSample::ExpressionBlendSampleDataSampleDataSource::sealed | [private]
_Description | SDKSample::ExpressionBlendSampleDataSampleDataSource::sealed | [private]
_Image | SDKSample::ExpressionBlendSampleDataSampleDataSource::sealed | [private]
_items | SDKSample::ExpressionBlendSampleDataSampleDataSource::sealed |
_Link | SDKSample::ExpressionBlendSampleDataSampleDataSource::sealed | [private]
_PropertyChanged | SDKSample::ExpressionBlendSampleDataSampleDataSource::sealed | [private]
_Subtitle | SDKSample::ExpressionBlendSampleDataSampleDataSource::sealed | [private]
_Title | SDKSample::ExpressionBlendSampleDataSampleDataSource::sealed | [private]
Add(Item^item) | SDKSample::ExpressionBlendSampleDataSampleDataSource::sealed | [inline]
Item() | SDKSample::ExpressionBlendSampleDataSampleDataSource::sealed |
itemCollection | SDKSample::ExpressionBlendSampleDataSampleDataSource::sealed | [private]
ItemCollection() | SDKSample::ExpressionBlendSampleDataSampleDataSource::sealed | [inline]
MessageData() | SDKSample::ExpressionBlendSampleDataSampleDataSource::sealed | [inline]
OnPropertyChanged(Platform::String^propertyName) | SDKSample::ExpressionBlendSampleDataSampleDataSource::sealed | [inline]
Generated on Sat Nov 23 2024 16:09:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Sharing content source app/C++/App.xaml.h Source File

  • Sharing content source app

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/DesignTimeData.cpp Source File

  • Hilo C++
  • Hilo

DesignTimeData.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 #include "DesignTimeData.h"
00009
00010 using namespace Hilo;
00011 using namespace Platform;
00012 using namespace Platform::Collections;
00013 using namespace Windows::Foundation;
00014 using namespace Windows::Foundation::Collections;
00015 using namespace Windows::UI::Xaml::Media;
00016 using namespace Windows::UI::Xaml::Media::Imaging;
00017
00018 #pragma region DesignTimePhoto Members
00019
00020 ImageSource^ DesignTimePhoto::Image::get()
00021 {
00022     return ref new BitmapImage(ref new Uri("ms-appx:///Assets/HiloLogo.png"));
00023 }
00024
00025 ImageSource^ DesignTimePhoto::Thumbnail::get()
00026 {
00027     return Image;
00028 }
00029
00030 String^ DesignTimePhoto::Name::get()
00031 {
00032     return "Photo name";
00033 }
00034
00035 String^ DesignTimePhoto::DisplayType::get()
00036 {
00037     return "JPG File";
00038 }
00039
00040 String^ DesignTimePhoto::Resolution::get()
00041 {
00042     return "1024 x 768";
00043 }
00044
00045 String^ DesignTimePhoto::FormattedDateTaken::get()
00046 {
00047     return "01/01/2012";
00048 }
00049
00050 String^ DesignTimePhoto::FormattedTimeTaken::get()
00051 {
00052     return "10:48";
00053 }
00054
00055 uint64 DesignTimePhoto::FileSize::get()
00056 {
00057     return 1234567;
00058 }
00059
00060 String^ DesignTimePhoto::FormattedPath::get()
00061 {
00062     return "C:\\Users";
00063 }
00064
00065 int DesignTimePhoto::RowSpan::get()
00066 {
00067     return m_rowSpan;
00068 }
00069
00070 void DesignTimePhoto::RowSpan::set(int value)
00071 {
00072     m_rowSpan = value;
00073 }
00074
00075 int DesignTimePhoto::ColumnSpan::get()
00076 {
00077     return m_columnSpan;
00078 }
00079
00080 void DesignTimePhoto::ColumnSpan::set(int value)
00081 {
00082     m_columnSpan = value;
00083 }
00084
00085 #pragma endregion
00086
00087 #pragma region DesignTimePhotoGroup Members
00088
00089 DesignTimePhotoGroup::DesignTimePhotoGroup(String^ title) : m_title(title)
00090 {
00091 }
00092
00093 IObservableVector<DesignTimePhoto^>^ DesignTimePhotoGroup::Items::get()
00094 {
00095     auto photos = ref new Vector<DesignTimePhoto^>();
00096     auto designTimePhoto = ref new DesignTimePhoto();
00097     bool firstPhoto = true;
00098     for (int i = 0; i < 6; i++)
00099     {
00100         if (firstPhoto)
00101         {
00102             auto photo = ref new DesignTimePhoto();
00103             photo->ColumnSpan = 2;
00104             photo->RowSpan = 2;
00105             photos->Append(photo);
00106             firstPhoto = false;
00107         }
00108         else
00109         {
00110             photos->Append(designTimePhoto);
00111         }
00112     }
00113     return photos;
00114 }
00115
00116 String^ DesignTimePhotoGroup::Title::get()
00117 {
00118     return m_title;
00119 }
00120
00121 #pragma endregion
00122
00123 #pragma region DesignTimeMonthBlock Members
00124
00125 DesignTimeMonthBlock::DesignTimeMonthBlock(bool hasPhotos) : m_hasPhotos(hasPhotos)
00126 {
00127 }
00128
00129 String^ DesignTimeMonthBlock::Name::get()
00130 {
00131     return "Month";
00132 }
00133
00134 bool DesignTimeMonthBlock::HasPhotos::get()
00135 {
00136     return m_hasPhotos;
00137 }
00138
00139 #pragma endregion
00140
00141 #pragma region DesignTimeYearGroup Members
00142
00143 DesignTimeYearGroup::DesignTimeYearGroup(String^ title) : m_title(title), m_months(nullptr)
00144 {
00145 }
00146
00147 String^ DesignTimeYearGroup::Title::get()
00148 {
00149     return m_title;
00150 }
00151
00152 IObservableVector<DesignTimeMonthBlock^>^ DesignTimeYearGroup::Items::get()
00153 {
00154     if (m_months == nullptr)
00155     {
00156         const unsigned int months = 12;
00157         bool hasPhotos = true;
00158         std::vector<DesignTimeMonthBlock^> monthBlocks;
00159         monthBlocks.reserve(months);
00160         for (int i = 0; i < months; i++)
00161         {
00162             auto monthBlock = ref new DesignTimeMonthBlock(hasPhotos);
00163             monthBlocks.push_back(monthBlock);
00164             hasPhotos = !hasPhotos;
00165         }
00166         m_months = ref new Vector<DesignTimeMonthBlock^>(std::move(monthBlocks));
00167     }
00168     return m_months;
00169 }
00170
00171 #pragma endregion
00172
00173 #pragma region DesignTimeData Members
00174
00175 DesignTimeData::DesignTimeData() : m_designTimePhoto(ref new DesignTimePhoto())
00176 {
00177 }
00178
00179 ImageSource^ DesignTimeData::Image::get()
00180 {
00181     return m_designTimePhoto->Image;
00182 }
00183
00184 IObservableVector<DesignTimePhoto^>^ DesignTimeData::Photos::get()
00185 {
00186     auto photos = ref new Vector<DesignTimePhoto^>();
00187     for (int i = 0; i < 10; i++)
00188     {
00189         photos->Append(m_designTimePhoto);
00190     }
00191     return photos;
00192 }
00193
00194 IObservableVector<DesignTimePhotoGroup^>^ DesignTimeData::HubPhotosGroup::get()
00195 {
00196     auto photosGroup = ref new Vector<DesignTimePhotoGroup^>();
00197     auto photoGroup = ref new DesignTimePhotoGroup("Pictures");
00198     photosGroup->Append(photoGroup);
00199     return photosGroup;
00200 }
00201
00202 IObservableVector<DesignTimePhotoGroup^>^ DesignTimeData::MonthGroups::get()
00203 {
00204     auto monthsGroup = ref new Vector<DesignTimePhotoGroup^>();
00205     auto photoGroup = ref new DesignTimePhotoGroup("Month and year");
00206     monthsGroup->Append(photoGroup);
00207     monthsGroup->Append(photoGroup);
00208     return monthsGroup;
00209 }
00210
00211 IObservableVector<DesignTimeYearGroup^>^ DesignTimeData::YearGroups::get()
00212 {
00213     auto yearsGroup = ref new Vector<DesignTimeYearGroup^>();
00214     auto yearGroup1 = ref new DesignTimeYearGroup("Year");
00215     auto yearGroup2 = ref new DesignTimeYearGroup("Year");
00216     yearsGroup->Append(yearGroup1);
00217     yearsGroup->Append(yearGroup2);
00218     return yearsGroup;
00219 }
00220
00221 DesignTimePhoto^ DesignTimeData::Photo::get()
00222 {
00223     return m_designTimePhoto;
00224 }
00225
00226 DesignTimePhoto^ DesignTimeData::SelectedItem::get()
00227 {
00228     return Photo;
00229 }
00230
00231 String^ DesignTimeData::Coarseness::get()
00232 {
00233     return "Coarseness";
00234 }
00235
00236 String^ DesignTimeData::Passes::get()
00237 {
00238     return "Passes";
00239 }
00240
00241 String^ DesignTimeData::MonthAndYear::get()
00242 {
00243     return "Month and year";
00244 }
00245
00246 String^ DesignTimeData::AppName::get()
00247 {
00248     return "Hilo";
00249 }
00250
00251 String^ DesignTimeData::ImageBrowserPageTitle::get()
00252 {
00253     return "Pictures";
00254 }
00255
00256 #pragma endregion
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DatagramSocket/C++/Scenario3.xaml.cpp Source File

  • DatagramSocket

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 "Scenario2.xaml.h"
00018 #include "Scenario3.xaml.h"
00019
00020 using namespace DatagramSocketSample;
00021
00022 using namespace Concurrency;
00023 using namespace Platform;
00024 using namespace Windows::ApplicationModel::Core;
00025 using namespace Windows::Networking::Sockets;
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 Scenario3::Scenario3()
00032 {
00033     InitializeComponent();
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::OnNavigatedTo(NavigationEventArgs^ e)
00042 {
00043     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00044     // as NotifyUser()
00045     rootPage = MainPage::Current;
00046 }
00047
00048
00049 void Scenario3::SendHello_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00050 {
00051     if (!CoreApplication::Properties->HasKey("clientSocket"))
00052     {
00053         rootPage->NotifyUser("Please run previous steps before doing this one.", NotifyType::ErrorMessage);
00054         return;
00055     }
00056
00057     SocketContext^ socketContext = dynamic_cast<SocketContext^>(CoreApplication::Properties->Lookup("clientSocket"));
00058     if (!socketContext->IsConnected())
00059     {
00060         rootPage->NotifyUser("The socket is not yet connected. Please wait.", NotifyType::ErrorMessage);
00061         return;
00062     }
00063
00064     String^ stringToSend("Hello");
00065     try
00066     {
00067         socketContext->GetWriter()->WriteString(stringToSend);
00068     }
00069     catch (Exception^ ex)
00070     {
00071         rootPage->NotifyUser("Send failed with error: " + ex->Message, NotifyType::ErrorMessage);
00072     }
00073
00074     // Write the locally buffered data to the network. Please note that write operation will succeed
00075     // even if the server is not listening.
00076     task<unsigned int>(socketContext->GetWriter()->StoreAsync()).then([this, stringToSend] (task<unsigned int> writeTask)
00077     {
00078         try
00079         {
00080             // Try getting an excpetion.
00081             writeTask.get();
00082             SendOutput->Style = dynamic_cast<Windows::UI::Xaml::Style^>(rootPage->Resources->Lookup("StatusStyle"));
00083             SendOutput->Text = "\"" + stringToSend + "\" sent successfully";
00084         }
00085         catch (Exception^ exception)
00086         {
00087             rootPage->NotifyUser("Send failed with error: " + exception->Message, NotifyType::ErrorMessage);
00088         }
00089     });
00090 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Custom driver access/C#,C++/app_cs/Properties/AssemblyInfo.cs Source File

  • Custom driver access
  • C#,C++
  • app_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("FeatureName CS 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 Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Animation metrics/C++/pch.cpp Source File

  • Animation metrics

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 Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Removable storage/C++/S3_GetFromStorage.xaml.cpp Source File

  • Removable storage

S3_GetFromStorage.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 // S3_GetFromStorage.xaml.cpp
00013 // Implementation of the S3_GetFromStorage class
00014 //
00015
00016 #include "pch.h"
00017 #include "S3_GetFromStorage.xaml.h"
00018
00019 using namespace SDKSample::RemovableStorageCPP;
00020
00021 using namespace concurrency;
00022 using namespace Platform;
00023 using namespace Platform::Collections;
00024 using namespace Windows::Devices::Enumeration;
00025 using namespace Windows::Devices::Portable;
00026 using namespace Windows::Foundation::Collections;
00027 using namespace Windows::Globalization::DateTimeFormatting;
00028 using namespace Windows::Storage;
00029 using namespace Windows::Storage::FileProperties;
00030 using namespace Windows::Storage::Search;
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::Media::Imaging;
00036 using namespace Windows::UI::Xaml::Navigation;
00037
00038 S3_GetFromStorage::S3_GetFromStorage() : rootPage(MainPage::Current)
00039 {
00040     InitializeComponent();
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 S3_GetFromStorage::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     DeviceSelector->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00053     ScenarioOutputImage->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00054 }
00055
00056 /// <summary>
00057 /// This is the click handler for the 'Get Image' button.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void S3_GetFromStorage::GetImage_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00062 {
00063     ShowDeviceSelectorAsync();
00064 }
00065
00066 /// <summary>
00067 /// Enumerates all storages and populates the device selection list.
00068 /// </summary>
00069 void S3_GetFromStorage::ShowDeviceSelectorAsync()
00070 {
00071     _deviceInfoCollection = nullptr;
00072
00073     // Find all storage devices using Windows.Devices.Enumeration
00074     task<DeviceInformationCollection^>(DeviceInformation::FindAllAsync(StorageDevice::GetDeviceSelector())).then([this] (task<DeviceInformationCollection^> findTask)
00075     {
00076         _deviceInfoCollection = findTask.get();
00077         if (_deviceInfoCollection->Size > 0)
00078         {
00079             auto items = ref new Vector<String^>();
00080             std::for_each(begin(_deviceInfoCollection), end(_deviceInfoCollection), [items](IDeviceInformation^ deviceInfo)
00081             {
00082                 items->Append(ref new String(deviceInfo->Name->Begin()));
00083             });
00084             cvs->Source = items;
00085             DeviceSelector->Visibility = Windows::UI::Xaml::Visibility::Visible;
00086         }
00087         else
00088         {
00089             rootPage->NotifyUser("No removable storages were found. Please attach a removable storage to the system (e.g. a camera or camera memory)", NotifyType::StatusMessage);
00090         }
00091     });
00092 }
00093
00094 /// <summary>
00095 /// This is the tapped handler for the device selection list. It runs the scenario
00096 /// for the selected storage.
00097 /// </summary>
00098 /// <param name="sender"></param>
00099 /// <param name="e"></param>
00100 void S3_GetFromStorage::DeviceList_Tapped(Platform::Object^ sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^ e)
00101 {
00102     DeviceSelector->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00103     if (_deviceInfoCollection == nullptr)
00104     {
00105         return; // not yet populated
00106     }
00107
00108     auto deviceInfo = _deviceInfoCollection->GetAt(DeviceList->SelectedIndex);
00109     GetFirstImageFromStorageAsync(deviceInfo);
00110 }
00111
00112 /// <summary>
00113 /// Finds and displays the first image file on the storage referenced by the device information element.
00114 /// </summary>
00115 /// <param name="deviceInfoElement">Contains information about a selected device.</param>
00116 void S3_GetFromStorage::GetFirstImageFromStorageAsync(DeviceInformation^ deviceInfoElement)
00117 {
00118     // Convert the selected device information element to a StorageFolder
00119     auto storage = StorageDevice::FromId(deviceInfoElement->Id);
00120     auto storageName = deviceInfoElement->Name;
00121
00122     // Construct the query for image files
00123     auto filter = ref new Vector<String^>();
00124     filter->Append(".jpg");
00125     filter->Append(".png");
00126     filter->Append(".gif");
00127     auto queryOptions = ref new QueryOptions(CommonFileQuery::OrderByName, filter);
00128     auto imageFileQuery = storage->CreateFileQueryWithOptions(queryOptions);
00129
00130     // Run the query for image files
00131     rootPage->NotifyUser("Looking for images on " + storageName + " ...", NotifyType::StatusMessage);
00132     create_task(imageFileQuery->GetFilesAsync()).then([this, storageName] (IVectorView<StorageFile^>^ imageFiles)
00133     {
00134         if (imageFiles->Size > 0)
00135         {
00136             auto imageFile = imageFiles->GetAt(0);
00137             rootPage->NotifyUser("Found " + imageFile->Name + " on " + storageName, NotifyType::StatusMessage);
00138             DisplayImageAsync(imageFile);
00139         }
00140         else
00141         {
00142             rootPage->NotifyUser("No images were found on " + storageName + ". You can use scenario 2 to transfer an image to it", NotifyType::StatusMessage);
00143         }
00144     });
00145 }
00146
00147 /// <summary>
00148 /// Displays an image file in the 'ScenarioOutputImage' element.
00149 /// </summary>
00150 /// <param name="imageFile">The image file to display.</param>
00151 void S3_GetFromStorage::DisplayImageAsync(Windows::Storage::StorageFile^ imageFile)
00152 {
00153     create_task(imageFile->GetBasicPropertiesAsync()).then([this, imageFile] (BasicProperties^ imageProperties)
00154     {
00155         if (imageProperties->Size > 0)
00156         {
00157             auto dateFormatter = ref new DateTimeFormatter("longdate");
00158             auto timeFormatter = ref new DateTimeFormatter("longtime");
00159             rootPage->NotifyUser("Displaying: " + imageFile->Name + ", date modified: " +
00160                 dateFormatter->Format(imageProperties->DateModified) + " " +
00161                 timeFormatter->Format(imageProperties->DateModified) + ", size: " +
00162                 imageProperties->Size + " bytes", NotifyType::StatusMessage);
00163
00164             // Note: The following task is nested instead of chained from the previous task because it runs only when the image size is > 0.
00165             create_task(imageFile->OpenAsync(FileAccessMode::Read)).then([this] (IRandomAccessStream^ stream)
00166             {
00167                 // BitmapImage.SetSource needs to be called in the UI thread
00168                 Dispatcher->RunAsync(
00169                     CoreDispatcherPriority::Normal,
00170                     ref new DispatchedHandler(
00171                         [this, stream]()
00172                         {
00173                             ScenarioOutputImage->Visibility = Windows::UI::Xaml::Visibility::Visible;
00174                             auto bitmap = ref new BitmapImage();
00175                             bitmap->SetSource(stream);
00176                             ScenarioOutputImage->SetValue(Image::SourceProperty, bitmap);
00177                         },
00178                         CallbackContext::Any
00179                     )
00180                 );
00181             });
00182         }
00183         else
00184         {
00185             rootPage->NotifyUser("Cannot display " + imageFile->Name + " because its size is 0", NotifyType::ErrorMessage);
00186         }
00187     });
00188 }
Generated on Sat Nov 23 2024 16:08:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Print/C++/ScenarioInput1.xaml.cpp Source File

  • Print

ScenarioInput1.xaml.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 //
00009 // Scenario1Input.xaml.cpp
00010 // Implementation of the Scenario1Input class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioOutput1.xaml.h"
00015 #include "ScenarioInput1.xaml.h"
00016
00017 using namespace PrintSample;
00018
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Graphics::Display;
00022 using namespace Windows::Graphics::Printing;
00023 using namespace Windows::UI;
00024 using namespace Windows::UI::Text;
00025 using namespace Windows::UI::Xaml::Controls;
00026 using namespace Windows::UI::Xaml::Documents;
00027 using namespace Windows::UI::Xaml::Media;
00028 using namespace Windows::UI::Xaml::Media::Imaging;
00029 using namespace Windows::UI::Xaml::Navigation;
00030
00031 ScenarioInput1::ScenarioInput1()
00032 {
00033     InitializeComponent();
00034 }
00035
00036 /// <summary>
00037 /// Provide print content for scenario 1 first page
00038 /// </summary>
00039 void ScenarioInput1::PreparetPrintContent()
00040 {
00041     if (FirstPage == nullptr)
00042     {
00043         FirstPage = ref new ScenarioOutput1();
00044         StackPanel^ header = safe_cast<StackPanel^>(FirstPage->FindName("header"));
00045         header->Visibility = Windows::UI::Xaml::Visibility::Visible;
00046     }
00047
00048     // Add the (newley created) page to the printing root which is part of the visual tree and force it to go
00049     // through layout so that the linked containers correctly distribute the content inside them.
00050     PrintingRoot->Children->Append(FirstPage);
00051     PrintingRoot->InvalidateMeasure();
00052     PrintingRoot->UpdateLayout();
00053 }
00054
00055 /// <summary>
00056 /// Register for print button handler
00057 /// </summary>
00058 void ScenarioInput1::RegisterForPrintingButtonClick(Object^ sender, RoutedEventArgs^ e)
00059 {
00060     Button^ clickedButton = safe_cast<Button^>(sender);
00061
00062     // check to see if the application is registered for printing
00063     if (RegisteredForPrinting)
00064     {
00065         // unregister for printing
00066         UnregisterForPrinting();
00067
00068         // change the text on the button
00069         clickedButton->Content = "Register";
00070
00071         // tell the user that the print contract has been unregistered
00072         RootPage->NotifyUser("Print contract unregistered.", NotifyType::StatusMessage);
00073     }
00074     else
00075     {
00076         // register for printing
00077         RegisterForPrinting();
00078
00079         // change the text on the button
00080         clickedButton->Content = "Unregister";
00081
00082         // tell the user that the print contract has been registered
00083         RootPage->NotifyUser("Print contract registered, use the Charms Bar to print.", NotifyType::StatusMessage);
00084     }
00085
00086     // toggel the value of isRegisteredForPrinting
00087     RegisteredForPrinting = !RegisteredForPrinting;
00088 }
Generated on Sat Nov 23 2024 16:07:59 for Win8-Examples by doxygen 1.7.1


Win8-Examples: OrientationSensor/C++/Scenario1.xaml.cpp Source File

  • OrientationSensor

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::OrientationSensorCPP;
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::Devices::Sensors;
00025 using namespace Windows::Foundation;
00026 using namespace Windows::UI::Core;
00027 using namespace Platform;
00028
00029 Scenario1::Scenario1() : rootPage(MainPage::Current), desiredReportInterval(0)
00030 {
00031     InitializeComponent();
00032
00033     sensor = OrientationSensor::GetDefault();
00034     if (sensor != nullptr)
00035     {
00036         // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
00037         // This value will be used later to activate the sensor.
00038         uint32 minReportInterval = sensor->MinimumReportInterval;
00039         desiredReportInterval = minReportInterval > 16 ? minReportInterval : 16;
00040     }
00041     else
00042     {
00043         rootPage->NotifyUser("No orientation sensor found", NotifyType::ErrorMessage);
00044     }
00045 }
00046
00047 /// <summary>
00048 /// Invoked when this page is about to be displayed in a Frame.
00049 /// </summary>
00050 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00051 /// property is typically used to configure the page.</param>
00052 void Scenario1::OnNavigatedTo(NavigationEventArgs^ e)
00053 {
00054     ScenarioEnableButton->IsEnabled = true;
00055     ScenarioDisableButton->IsEnabled = false;
00056 }
00057
00058 /// <summary>
00059 /// Invoked when this page is no longer displayed.
00060 /// </summary>
00061 /// <param name="e"></param>
00062 void Scenario1::OnNavigatedFrom(NavigationEventArgs^ e)
00063 {
00064     if (ScenarioDisableButton->IsEnabled)
00065     {
00066         Window::Current->VisibilityChanged::remove(visibilityToken);
00067         sensor->ReadingChanged::remove(readingToken);
00068
00069         // Restore the default report interval to release resources while the sensor is not in use
00070         sensor->ReportInterval = 0;
00071     }
00072 }
00073
00074 /// <summary>
00075 /// This is the event handler for VisibilityChanged events. You would register for these notifications
00076 /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00077 /// </summary>
00078 /// <param name="sender"></param>
00079 /// <param name="e">
00080 /// Event data that can be examined for the current visibility state.
00081 /// </param>
00082 void Scenario1::VisibilityChanged(Object^ sender, VisibilityChangedEventArgs^ e)
00083 {
00084     // The app should watch for VisibilityChanged events to disable and re-enable sensor input as appropriate
00085     if (ScenarioDisableButton->IsEnabled)
00086     {
00087         if (e->Visible)
00088         {
00089             // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00090             readingToken = sensor->ReadingChanged::add(ref new TypedEventHandler<OrientationSensor^, OrientationSensorReadingChangedEventArgs^>(this, &Scenario1::ReadingChanged));
00091         }
00092         else
00093         {
00094             // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00095             sensor->ReadingChanged::remove(readingToken);
00096         }
00097     }
00098 }
00099
00100 void Scenario1::ReadingChanged(OrientationSensor^ sender, OrientationSensorReadingChangedEventArgs^ e)
00101 {
00102     // We need to dispatch to the UI thread to display the output
00103     Dispatcher->RunAsync(
00104         CoreDispatcherPriority::Normal,
00105         ref new DispatchedHandler(
00106             [this, e]()
00107             {
00108                 OrientationSensorReading^ reading = e->Reading;
00109
00110                 // Quaternion values
00111                 SensorQuaternion^ quaternion = reading->Quaternion; // get a reference to the object to avoid re-creating it for each access
00112                 ScenarioOutput_X->Text = quaternion->X.ToString();
00113                 ScenarioOutput_Y->Text = quaternion->Y.ToString();
00114                 ScenarioOutput_Z->Text = quaternion->Z.ToString();
00115                 ScenarioOutput_W->Text = quaternion->W.ToString();
00116
00117                 // Rotation Matrix values
00118                 SensorRotationMatrix^ rotationMatrix = reading->RotationMatrix;
00119                 ScenarioOutput_M11->Text = rotationMatrix->M11.ToString();
00120                 ScenarioOutput_M12->Text = rotationMatrix->M12.ToString();
00121                 ScenarioOutput_M13->Text = rotationMatrix->M13.ToString();
00122                 ScenarioOutput_M21->Text = rotationMatrix->M21.ToString();
00123                 ScenarioOutput_M22->Text = rotationMatrix->M22.ToString();
00124                 ScenarioOutput_M23->Text = rotationMatrix->M23.ToString();
00125                 ScenarioOutput_M31->Text = rotationMatrix->M31.ToString();
00126                 ScenarioOutput_M32->Text = rotationMatrix->M32.ToString();
00127                 ScenarioOutput_M33->Text = rotationMatrix->M33.ToString();
00128             },
00129             CallbackContext::Any
00130             )
00131         );
00132 }
00133
00134 void Scenario1::ScenarioEnable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00135 {
00136     if (sensor != nullptr)
00137     {
00138         // Establish the report interval
00139         sensor->ReportInterval = desiredReportInterval;
00140
00141         visibilityToken = Window::Current->VisibilityChanged::add(ref new WindowVisibilityChangedEventHandler(this, &Scenario1::VisibilityChanged));
00142         readingToken = sensor->ReadingChanged::add(ref new TypedEventHandler<OrientationSensor^, OrientationSensorReadingChangedEventArgs^>(this, &Scenario1::ReadingChanged));
00143
00144         ScenarioEnableButton->IsEnabled = false;
00145         ScenarioDisableButton->IsEnabled = true;
00146     }
00147     else
00148     {
00149         rootPage->NotifyUser("No orientation sensor found", NotifyType::ErrorMessage);
00150     }
00151 }
00152
00153 void Scenario1::ScenarioDisable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00154 {
00155     Window::Current->VisibilityChanged::remove(visibilityToken);
00156     sensor->ReadingChanged::remove(readingToken);
00157
00158     // Restore the default report interval to release resources while the sensor is not in use
00159     sensor->ReportInterval = 0;
00160
00161     ScenarioEnableButton->IsEnabled = true;
00162     ScenarioDisableButton->IsEnabled = false;
00163 }
Generated on Sat Nov 23 2024 16:07:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX touch input/C++/BasicTimer.cpp Source File

  • DirectX touch input

BasicTimer.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 "BasicTimer.h"
00010
00011 BasicTimer::BasicTimer()
00012 {
00013     if (!QueryPerformanceFrequency(&m_frequency))
00014     {
00015         throw ref new Platform::FailureException();
00016     }
00017     Reset();
00018 }
00019
00020 void BasicTimer::Reset()
00021 {
00022     Update();
00023     m_startTime = m_currentTime;
00024     m_total = 0.0f;
00025     m_delta = 1.0f / 60.0f;
00026 }
00027
00028 void BasicTimer::Update()
00029 {
00030     if (!QueryPerformanceCounter(&m_currentTime))
00031     {
00032         throw ref new Platform::FailureException();
00033     }
00034
00035     m_total = static_cast<float>(
00036         static_cast<double>(m_currentTime.QuadPart-m_startTime.QuadPart) /
00037         static_cast<double>(m_frequency.QuadPart)
00038         );
00039
00040     if (m_lastTime.QuadPart == m_startTime.QuadPart)
00041     {
00042         // If the timer was just reset, report a time delta equivalent to 60Hz frame time.
00043         m_delta = 1.0f / 60.0f;
00044     }
00045     else
00046     {
00047         m_delta = static_cast<float>(
00048             static_cast<double>(m_currentTime.QuadPart-m_lastTime.QuadPart) /
00049             static_cast<double>(m_frequency.QuadPart)
00050             );
00051     }
00052
00053     m_lastTime = m_currentTime;
00054 }
00055
00056 float BasicTimer::Total::get()
00057 {
00058     return m_total;
00059 }
00060
00061 float BasicTimer::Delta::get()
00062 {
00063     return m_delta;
00064 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Device enumeration/C++/Interfaces.xaml.h Source File

  • Device enumeration

Interfaces.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 // Interfaces.xaml.h
00013 // Declaration of the Interfaces class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Interfaces.g.h"
00020 #include "MainPage.xaml.h"
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::ViewManagement;
00026 using namespace Platform;
00027 using namespace concurrency;
00028 using namespace Windows::Devices::Enumeration;
00029 using namespace Windows::Devices::Enumeration::Pnp;
00030
00031 namespace SDKSample
00032 {
00033     namespace DeviceEnumeration
00034     {
00035         /// <summary>
00036         /// An empty page that can be used on its own or navigated to within a Frame.
00037         /// </summary>
00038       [Windows::Foundation::Metadata::WebHostHidden]
00039         public ref class Interfaces sealed
00040         {
00041         public:
00042             Interfaces();
00043
00044         protected:
00045             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00046         private:
00047             MainPage^ rootPage;
00048         void InterfaceClasses_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ eventArgs);
00049         void EnumerateDeviceInterfaces(Object^ sender, RoutedEventArgs^ eventArgs);
00050             void DisplayDeviceInterface(DeviceInformation^ deviceInterface);
00051         };
00052
00053       [Windows::UI::Xaml::Data::Bindable]
00054       [Windows::Foundation::Metadata::WebHostHidden]
00055         public ref class InterfaceDisplayItem sealed
00056         {
00057             public:
00058                 InterfaceDisplayItem(String^ id, String^ name, String^ isEnabled):
00059                     id(id), name(name), isEnabled(isEnabled), thumbnail(ref new BitmapImage), glyphThumbnail(ref new BitmapImage) {}
00060
00061                 property String^ Id { String^ get() { return id; }}
00062                 property String^ Name { String^ get() { return name; }}
00063                 property String^ IsEnabled { String^ get() { return isEnabled; }}
00064                 property BitmapImage^ Thumbnail { BitmapImage^ get() { return thumbnail; }}
00065                 property BitmapImage^ GlyphThumbnail { BitmapImage^ get() { return glyphThumbnail; }}
00066
00067             private protected:
00068                 String^ id;
00069                 String^ name;
00070                 String^ isEnabled;
00071                 BitmapImage^ thumbnail;
00072                 BitmapImage^ glyphThumbnail;
00073         };
00074
00075     }
00076 }
Generated on Sat Nov 23 2024 16:08:02 for Win8-Examples by doxygen 1.7.1


Win8-Examples: UI contrast and settings/C++/Constants.h Source File

  • UI contrast and settings

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"High Contrast C++ sample");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044
00045
00046 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application resources and localization/C++/Scenario7.xaml.h Source File

  • Application resources and localization

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 SDKSample
00023 {
00024     namespace ApplicationResources
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 Scenario7 sealed
00031         {
00032         public:
00033             Scenario7();
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             MainPage^ rootPage;
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 Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application data/C++/App.xaml.h Source File

  • Application data

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Web authentication broker/C++/pch.h Source File

  • Web authentication broker

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D magazine app/C++/TreeIterator.h Source File

  • Direct2D magazine app

TreeIterator.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 template <typename T>
00011 class TreeIterator
00012 {
00013 public:
00014     TreeIterator(T^ rootNode)
00015         : m_currentNode(rootNode)
00016     {}
00017
00018     inline T^ GetCurrentNode()
00019     {
00020         return m_currentNode;
00021     }
00022
00023     size_t operator++()
00024     {
00025         if (m_currentNode == nullptr)
00026         {
00027             return 0;
00028         }
00029
00030         T^ nextNode = m_currentNode->GetFirstChild();
00031
00032         if (nextNode != nullptr)
00033         {
00034             // Go to the first child if exists.
00035             m_currentNode = nextNode;
00036         }
00037         else
00038         {
00039             nextNode = m_currentNode->GetNextSibling();
00040
00041             if (nextNode != nullptr)
00042             {
00043                 // It's a leaf node, go to the next sibling.
00044                 m_currentNode = nextNode;
00045             }
00046             else
00047             {
00048                 // It's the last leaf node, find a parent with a sibling
00049                 // and go to that sibling.
00050                 T^ node = m_currentNode;
00051
00052                 do
00053                 {
00054                     node = node->GetParent();
00055
00056                     if (node == nullptr)
00057                     {
00058                         return 0;
00059                     }
00060
00061                     nextNode = node->GetNextSibling();
00062
00063                 } while (nextNode == nullptr);
00064
00065                 m_currentNode = nextNode;
00066             }
00067         }
00068
00069         return 1;
00070     }
00071
00072 private:
00073     // The node in the tree the iterator is at
00074     T^ m_currentNode;
00075 };
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

D2D3DTransformsRenderer Member List

This is the complete list of members for D2D3DTransformsRenderer, including all inherited members.
__pad0__ | D2D3DTransformsRenderer |
CreateDeviceIndependentResources() override | D2D3DTransformsRenderer | [virtual]
CreateDeviceResources() override | D2D3DTransformsRenderer | [virtual]
CreateWindowSizeDependentResources() override | D2D3DTransformsRenderer | [virtual]
Draw3DPerspectiveProperty(Platform::String^caption, Platform::String^value, float horizontalOffset) | D2D3DTransformsRenderer | [private]
DrawMatrix(Platform::String^caption, D2D1_MATRIX_4X4_F matrix, float horizontalOffset) | D2D3DTransformsRenderer | [private]
DrawSymbol(Platform::String^symbol, float horizontalOffset) | D2D3DTransformsRenderer | [private]
m_3DPerspectiveTransformEffect | D2D3DTransformsRenderer | [private]
m_3DTransformEffect | D2D3DTransformsRenderer | [private]
m_bitmapSourceEffect | D2D3DTransformsRenderer | [private]
m_captionFormat | D2D3DTransformsRenderer | [private]
m_captionHeight | D2D3DTransformsRenderer | [private]
m_captionTop | D2D3DTransformsRenderer | [private]
m_currentEffect | D2D3DTransformsRenderer | [private]
m_globalOffsetX | D2D3DTransformsRenderer | [private]
m_globalOffsetY | D2D3DTransformsRenderer | [private]
m_globalOffsetZ | D2D3DTransformsRenderer | [private]
m_imageSize | D2D3DTransformsRenderer | [private]
m_localOffsetX | D2D3DTransformsRenderer | [private]
m_localOffsetY | D2D3DTransformsRenderer | [private]
m_localOffsetZ | D2D3DTransformsRenderer | [private]
m_matrixHeight | D2D3DTransformsRenderer | [private]
m_matrixTop | D2D3DTransformsRenderer | [private]
m_matrixValueFormat | D2D3DTransformsRenderer | [private]
m_matrixWidth | D2D3DTransformsRenderer | [private]
m_perspective | D2D3DTransformsRenderer | [private]
m_propertyHeight | D2D3DTransformsRenderer | [private]
m_propertyTop | D2D3DTransformsRenderer | [private]
m_propertyValueFormat | D2D3DTransformsRenderer | [private]
m_propertyWidth | D2D3DTransformsRenderer | [private]
m_rotationX | D2D3DTransformsRenderer | [private]
m_rotationY | D2D3DTransformsRenderer | [private]
m_rotationZ | D2D3DTransformsRenderer | [private]
m_scaleX | D2D3DTransformsRenderer | [private]
m_scaleY | D2D3DTransformsRenderer | [private]
m_snappedViewFormat | D2D3DTransformsRenderer | [private]
m_symbolFormat | D2D3DTransformsRenderer | [private]
m_whiteBrush | D2D3DTransformsRenderer | [private]
m_wicFormatConverter | D2D3DTransformsRenderer | [private]
m_windowState | D2D3DTransformsRenderer | [private]
Render() override | D2D3DTransformsRenderer | [virtual]
Render3DPerspectiveTransformEffect() | D2D3DTransformsRenderer |
Render3DTransformEffect() | D2D3DTransformsRenderer |
SetTransformEffect(TransformEffect transformEffect) | D2D3DTransformsRenderer |
SetTransformProperty(TransformProperty transformProperty, float value) | D2D3DTransformsRenderer |
UpdateForViewStateChanged(Windows::UI::ViewManagement::ApplicationViewState state) | D2D3DTransformsRenderer |
Generated on Sat Nov 23 2024 16:09:10 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Proximity/C++/App.xaml.h Source File

  • Proximity

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace ProximityCPP
00023 {
00024     ref class App sealed
00025     {
00026     public:
00027         App();
00028         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00029         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00030
00031     private:
00032         void SetupWindowing(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs);
00033
00034     };
00035 }
00036
00037
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Device enumeration/C++/Constants.h Source File

  • Device enumeration

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"Device Enumeration");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044
00045
00046 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D 3D transform effect/C++/MainPage.xaml.h Source File

  • Direct2D 3D transform effect

MainPage.xaml.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 "MainPage.g.h"
00011
00012 namespace D2D3DTransforms
00013 {
00014     public ref class MainPage sealed
00015     {
00016     public:
00017         MainPage();
00018
00019         void InitializeValues();
00020         void ResetValues();
00021
00022         void OnSuspending(
00023             Object^ sender,
00024             Windows::ApplicationModel::SuspendingEventArgs^ args
00025             );
00026
00027     private:
00028         void SetTransformEffect(TransformEffect transformEffect);
00029         void SetTransformProperty(TransformProperty transformProperty, float value);
00030
00031         void OnEffectSelectorSelectionChanged(
00032             Object^ sender,
00033             Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ args
00034             );
00035
00036         void OnScaleXValueChanged(
00037             Object^ sender,
00038             Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ args
00039             );
00040
00041         void OnScaleYValueChanged(
00042             Object^ sender,
00043             Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ args
00044             );
00045
00046         void OnLocalOffsetXValueChanged(
00047             Object^ sender,
00048             Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ args
00049             );
00050
00051         void OnLocalOffsetYValueChanged(
00052             Object^ sender,
00053             Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ args
00054             );
00055
00056         void OnLocalOffsetZValueChanged(
00057             Object^ sender,
00058             Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ args
00059             );
00060
00061         void OnRotationXValueChanged(
00062             Object^ sender,
00063             Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ args
00064             );
00065
00066         void OnRotationYValueChanged(
00067             Object^ sender,
00068             Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ args
00069             );
00070
00071         void OnRotationZValueChanged(
00072             Object^ sender,
00073             Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ args
00074             );
00075
00076         void OnGlobalOffsetXValueChanged(
00077             Object^ sender,
00078             Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ args
00079             );
00080
00081         void OnGlobalOffsetYValueChanged(
00082             Object^ sender,
00083             Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ args
00084             );
00085
00086         void OnGlobalOffsetZValueChanged(
00087             Object^ sender,
00088             Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ args
00089             );
00090
00091         void OnPerspectiveValueChanged(
00092             Object^ sender,
00093             Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ args
00094             );
00095
00096         void OnRestoreDefaultsClick(
00097             Object^ sender,
00098             Windows::UI::Xaml::RoutedEventArgs^ args
00099             );
00100
00101         void OnLogicalDpiChanged(
00102             Object^ sender
00103             );
00104
00105         void OnDisplayContentsInvalidated(
00106             Object^ sender
00107             );
00108
00109         void OnWindowSizeChanged(
00110             Windows::UI::Core::CoreWindow^ sender,
00111             Windows::UI::Core::WindowSizeChangedEventArgs^ args
00112             );
00113
00114         D2D3DTransformsRenderer^ m_renderer;
00115     };
00116 }
Generated on Sat Nov 23 2024 16:07:46 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D post-processing effects/C++/DirectXBase.h Source File

  • Direct3D post-processing effects

DirectXBase.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 "DirectXSample.h"
00011
00012 // Helper class that initializes DirectX APIs for both 2D and 3D rendering.
00013 // Some of the code in this class may be omitted if only 2D or only 3D rendering is being used.
00014 ref class DirectXBase abstract
00015 {
00016 internal:
00017     DirectXBase();
00018
00019     virtual void Initialize(Windows::UI::Core::CoreWindow^ window, float dpi);
00020     virtual void HandleDeviceLost();
00021     virtual void CreateDeviceIndependentResources();
00022     virtual void CreateDeviceResources();
00023     virtual void SetDpi(float dpi);
00024     virtual void UpdateForWindowSizeChange();
00025     virtual void CreateWindowSizeDependentResources();
00026     virtual void Render() = 0;
00027     virtual void Present();
00028     void ValidateDevice();
00029
00030 protected private:
00031     Platform::Agile<Windows::UI::Core::CoreWindow>  m_window;
00032
00033     // DirectWrite & Windows Imaging Component Objects.
00034     Microsoft::WRL::ComPtr<IDWriteFactory1>         m_dwriteFactory;
00035     Microsoft::WRL::ComPtr<IWICImagingFactory2>     m_wicFactory;
00036
00037     // DirectX Core Objects. Required for 2D and 3D.
00038     Microsoft::WRL::ComPtr<ID3D11Device1>           m_d3dDevice;
00039     Microsoft::WRL::ComPtr<ID3D11DeviceContext1>    m_d3dContext;
00040     Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00041     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00042
00043     // Direct2D Rendering Objects. Required for 2D.
00044     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00046     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00047     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmap;
00048
00049     // Direct3D Rendering Objects. Required for 3D.
00050     Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00051
00052     // Cached renderer properties.
00053     D3D_FEATURE_LEVEL                               m_featureLevel;
00054     Windows::Foundation::Size                       m_renderTargetSize;
00055     Windows::Foundation::Rect                       m_windowBounds;
00056     float                                           m_dpi;
00057     bool                                            m_windowSizeChangeInProgress;
00058 };
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Store device app for camera/C++/Common/LayoutAwarePage.h Source File

  • Windows Store device app for camera
  • Common

LayoutAwarePage.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 #include <collection.h>
00015
00016 namespace DeviceAppForWebcam
00017 {
00018     namespace Common
00019     {
00020         /// <summary>
00021         /// Typical implementation of Page that provides several important conveniences: application
00022         /// view state to visual state mapping, GoBack and GoHome event handlers, and a default view
00023         /// model.
00024         /// </summary>
00025         [Windows::Foundation::Metadata::WebHostHidden]
00026         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00027         {
00028         internal:
00029             LayoutAwarePage();
00030
00031         public:
00032             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00033             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00034             void InvalidateVisualState();
00035             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00036             {
00037                 Windows::UI::Xaml::DependencyProperty^ get();
00038             };
00039             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Object^>^ DefaultViewModel
00040             {
00041                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Object^>^ get();
00042                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Object^>^ value);
00043             }
00044
00045         protected:
00046             virtual void GoHome(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             virtual void GoBack(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00049
00050         private:
00051             Platform::Collections::Map<Platform::String^, Object^>^ _defaultViewModel;
00052             Windows::Foundation::EventRegistrationToken _windowSizeEventToken;
00053             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00054             void WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00055         };
00056     }
00057 }
Generated on Sat Nov 23 2024 16:07:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Gyrometer sensor/C++/Scenario1.xaml.cpp Source File

  • Gyrometer sensor

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::GyrometerCPP;
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::Devices::Sensors;
00025 using namespace Windows::Foundation;
00026 using namespace Windows::UI::Core;
00027 using namespace Platform;
00028
00029 Scenario1::Scenario1() : rootPage(MainPage::Current), desiredReportInterval(0)
00030 {
00031     InitializeComponent();
00032
00033     gyrometer = Gyrometer::GetDefault();
00034     if (gyrometer != nullptr)
00035     {
00036         // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
00037         // This value will be used later to activate the sensor.
00038         uint32 minReportInterval = gyrometer->MinimumReportInterval;
00039         desiredReportInterval = minReportInterval > 16 ? minReportInterval : 16;
00040     }
00041     else
00042     {
00043         rootPage->NotifyUser("No gyrometer found", NotifyType::ErrorMessage);
00044     }
00045 }
00046
00047 /// <summary>
00048 /// Invoked when this page is about to be displayed in a Frame.
00049 /// </summary>
00050 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00051 /// property is typically used to configure the page.</param>
00052 void Scenario1::OnNavigatedTo(NavigationEventArgs^ e)
00053 {
00054     ScenarioEnableButton->IsEnabled = true;
00055     ScenarioDisableButton->IsEnabled = false;
00056 }
00057
00058 /// <summary>
00059 /// Invoked when this page is no longer displayed.
00060 /// </summary>
00061 /// <param name="e"></param>
00062 void Scenario1::OnNavigatedFrom(NavigationEventArgs^ e)
00063 {
00064     if (ScenarioDisableButton->IsEnabled)
00065     {
00066         Window::Current->VisibilityChanged::remove(visibilityToken);
00067         gyrometer->ReadingChanged::remove(readingToken);
00068
00069         // Restore the default report interval to release resources while the sensor is not in use
00070         gyrometer->ReportInterval = 0;
00071     }
00072 }
00073
00074 /// <summary>
00075 /// This is the event handler for VisibilityChanged events. You would register for these notifications
00076 /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00077 /// </summary>
00078 /// <param name="sender"></param>
00079 /// <param name="e">
00080 /// Event data that can be examined for the current visibility state.
00081 /// </param>
00082 void Scenario1::VisibilityChanged(Object^ sender, VisibilityChangedEventArgs^ e)
00083 {
00084     // The app should watch for VisibilityChanged events to disable and re-enable sensor input as appropriate
00085     if (ScenarioDisableButton->IsEnabled)
00086     {
00087         if (e->Visible)
00088         {
00089             // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00090             readingToken = gyrometer->ReadingChanged::add(ref new TypedEventHandler<Gyrometer^, GyrometerReadingChangedEventArgs^>(this, &Scenario1::ReadingChanged));
00091         }
00092         else
00093         {
00094             // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00095             gyrometer->ReadingChanged::remove(readingToken);
00096         }
00097     }
00098 }
00099
00100 void Scenario1::ReadingChanged(Gyrometer^ sender, GyrometerReadingChangedEventArgs^ e)
00101 {
00102     // We need to dispatch to the UI thread to display the output
00103     Dispatcher->RunAsync(
00104         CoreDispatcherPriority::Normal,
00105         ref new DispatchedHandler(
00106             [this, e]()
00107             {
00108                 GyrometerReading^ reading = e->Reading;
00109
00110                 ScenarioOutput_X->Text = reading->AngularVelocityX.ToString();
00111                 ScenarioOutput_Y->Text = reading->AngularVelocityY.ToString();
00112                 ScenarioOutput_Z->Text = reading->AngularVelocityZ.ToString();
00113             },
00114             CallbackContext::Any
00115             )
00116         );
00117 }
00118
00119 void Scenario1::ScenarioEnable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00120 {
00121     if (gyrometer != nullptr)
00122     {
00123         // Establish the report interval
00124         gyrometer->ReportInterval = desiredReportInterval;
00125
00126         visibilityToken = Window::Current->VisibilityChanged::add(ref new WindowVisibilityChangedEventHandler(this, &Scenario1::VisibilityChanged));
00127         readingToken = gyrometer->ReadingChanged::add(ref new TypedEventHandler<Gyrometer^, GyrometerReadingChangedEventArgs^>(this, &Scenario1::ReadingChanged));
00128
00129         ScenarioEnableButton->IsEnabled = false;
00130         ScenarioDisableButton->IsEnabled = true;
00131     }
00132     else
00133     {
00134         rootPage->NotifyUser("No gyrometer found", NotifyType::ErrorMessage);
00135     }
00136 }
00137
00138 void Scenario1::ScenarioDisable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00139 {
00140     Window::Current->VisibilityChanged::remove(visibilityToken);
00141     gyrometer->ReadingChanged::remove(readingToken);
00142
00143     // Restore the default report interval to release resources while the sensor is not in use
00144     gyrometer->ReportInterval = 0;
00145
00146     ScenarioEnableButton->IsEnabled = true;
00147     ScenarioDisableButton->IsEnabled = false;
00148 }
Generated on Sat Nov 23 2024 16:07:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Account picture name/C++/GetUserFirstAndLastName.xaml.cpp Source File

  • Account picture name

GetUserFirstAndLastName.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 // GetUserFirstAndLastName.xaml.cpp
00013 // Implementation of the GetUserFirstAndLastName class
00014 //
00015
00016 #include "pch.h"
00017 #include "GetUserFirstAndLastName.xaml.h"
00018
00019 using namespace AccountPictureName;
00020 using namespace concurrency;
00021 using namespace Platform;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Navigation;
00025 using namespace Windows::UI::Xaml::Navigation;
00026 using namespace Windows::System::UserProfile;
00027 using namespace Windows::Foundation;
00028 using namespace Microsoft::WRL;
00029 using namespace Microsoft::WRL::Wrappers;
00030
00031 GetUserFirstAndLastName::GetUserFirstAndLastName()
00032 {
00033     InitializeComponent();
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 GetUserFirstAndLastName::OnNavigatedTo(NavigationEventArgs^ e)
00042 {
00043     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00044     // as NotifyUser()
00045     rootPage = MainPage::Current;
00046 }
00047
00048 void GetUserFirstAndLastName::GetFirstNameButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00049 {
00050     if (UserInformation::NameAccessAllowed)
00051     {
00052         create_task(UserInformation::GetFirstNameAsync()).then([this](String^ firstName)
00053         {
00054             if (firstName != nullptr)
00055             {
00056                 rootPage->NotifyUser("First name = " + firstName, NotifyType::StatusMessage);
00057             }
00058             else
00059             {
00060                 rootPage->NotifyUser("No first name returned for current user.", NotifyType::ErrorMessage);
00061             }
00062         });
00063     }
00064     else
00065     {
00066         rootPage->NotifyUser("Access to Name disabled by Privacy Setting or Group Policy", NotifyType::ErrorMessage);
00067     }
00068 }
00069
00070 void GetUserFirstAndLastName::GetLastNameButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00071 {
00072     if (UserInformation::NameAccessAllowed)
00073     {
00074         create_task(UserInformation::GetLastNameAsync()).then([this](String^ lastName)
00075         {
00076             if (lastName != nullptr)
00077             {
00078                 rootPage->NotifyUser("Last name = " + lastName, NotifyType::StatusMessage);
00079             }
00080             else
00081             {
00082                 rootPage->NotifyUser("No last name returned for current user.", NotifyType::ErrorMessage);
00083             }
00084         });
00085     }
00086     else
00087     {
00088         rootPage->NotifyUser("Access to Name disabled by Privacy Setting or Group Policy", NotifyType::ErrorMessage);
00089     }
00090 }
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playback Manager Companion/C++/Constants.cpp Source File

  • Playback Manager Companion

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
00021     { "Stream type: BackgroundCapableMedia", "SDKSample.PlaybackManager2.StreamTypeBackgroundCapableMedia" },
00022     { "Stream type: Communications", "SDKSample.PlaybackManager2.StreamTypeCommunications" },
00023     { "Stream type: Other", "SDKSample.PlaybackManager2.StreamTypeOther" },
00024     { "Stream type: ForegroundOnlyMedia", "SDKSample.PlaybackManager2.StreamTypeForegroundOnlyMedia" },
00025     { "Stream type: Alert", "SDKSample.PlaybackManager2.StreamTypeAlert" }
00026 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Simplified ink/C++/DirectXBase.cpp Source File

  • Input Simplified ink

DirectXBase.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 "DirectXBase.h"
00010
00011 using namespace Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::Graphics::Display;
00015 using namespace D2D1;
00016
00017 // Constructor.
00018 DirectXBase::DirectXBase() :
00019     m_windowSizeChangeInProgress(false),
00020     m_numBuffers(2),
00021     m_dpi(-1.0f)
00022 {
00023 }
00024
00025 // Initialize the DirectX resources required to run.
00026 void DirectXBase::Initialize(CoreWindow^ window, float dpi)
00027 {
00028     m_window = window;
00029
00030     CreateDeviceIndependentResources();
00031     CreateDeviceResources();
00032     SetDpi(dpi);
00033 }
00034
00035 // Recreate all device resources and set them back to the current state.
00036 void DirectXBase::HandleDeviceLost()
00037 {
00038     // Reset these member variables to ensure that SetDpi recreates all resources.
00039     float dpi = m_dpi;
00040     m_dpi = -1.0f;
00041     m_windowBounds.Width = 0;
00042     m_windowBounds.Height = 0;
00043     m_swapChain = nullptr;
00044
00045     CreateDeviceResources();
00046     SetDpi(dpi);
00047 }
00048
00049 // These are the resources required independent of the device.
00050 void DirectXBase::CreateDeviceIndependentResources()
00051 {
00052     D2D1_FACTORY_OPTIONS options;
00053     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00054
00055 #if defined(_DEBUG)
00056     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00057     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00058 #endif
00059
00060     DX::ThrowIfFailed(
00061         D2D1CreateFactory(
00062             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00063             __uuidof(ID2D1Factory1),
00064             &options,
00065             &m_d2dFactory
00066             )
00067         );
00068
00069     DX::ThrowIfFailed(
00070         DWriteCreateFactory(
00071             DWRITE_FACTORY_TYPE_SHARED,
00072             __uuidof(IDWriteFactory),
00073             &m_dwriteFactory
00074             )
00075         );
00076
00077     DX::ThrowIfFailed(
00078         CoCreateInstance(
00079             CLSID_WICImagingFactory,
00080             nullptr,
00081             CLSCTX_INPROC_SERVER,
00082             IID_PPV_ARGS(&m_wicFactory)
00083             )
00084         );
00085 }
00086
00087 // These are the resources that depend on the device.
00088 void DirectXBase::CreateDeviceResources()
00089 {
00090     // This flag adds support for surfaces with a different color channel ordering
00091     // than the API default. It is required for compatibility with Direct2D.
00092     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00093     ComPtr<IDXGIDevice> dxgiDevice;
00094
00095 #if defined(_DEBUG)
00096     // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00097     creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00098 #endif
00099
00100     // This array defines the set of DirectX hardware feature levels this app will support.
00101     // Note the ordering should be preserved.
00102     // Don't forget to declare your application's minimum required feature level in its
00103     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00104     D3D_FEATURE_LEVEL featureLevels[] =
00105     {
00106         D3D_FEATURE_LEVEL_11_1,
00107         D3D_FEATURE_LEVEL_11_0,
00108         D3D_FEATURE_LEVEL_10_1,
00109         D3D_FEATURE_LEVEL_10_0,
00110         D3D_FEATURE_LEVEL_9_3,
00111         D3D_FEATURE_LEVEL_9_2,
00112         D3D_FEATURE_LEVEL_9_1
00113     };
00114
00115     // Create the Direct3D 11 API device object and a corresponding context.
00116     ComPtr<ID3D11Device> device;
00117     ComPtr<ID3D11DeviceContext> context;
00118     DX::ThrowIfFailed(
00119         D3D11CreateDevice(
00120             nullptr,                    // Specify nullptr to use the default adapter.
00121             D3D_DRIVER_TYPE_HARDWARE,
00122             0,
00123             creationFlags,              // Set debug and Direct2D compatibility flags.
00124             featureLevels,              // List of feature levels this app can support.
00125             ARRAYSIZE(featureLevels),
00126             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Metro style apps.
00127             &device,                    // Returns the Direct3D device created.
00128             &m_featureLevel,            // Returns feature level of device created.
00129             &context                    // Returns the device immediate context.
00130             )
00131         );
00132
00133     // Get the Direct3D 11.1 API device and context interfaces.
00134     DX::ThrowIfFailed(
00135         device.As(&m_d3dDevice)
00136         );
00137
00138     DX::ThrowIfFailed(
00139         context.As(&m_d3dContext)
00140         );
00141
00142     // Get the underlying DXGI device of the Direct3D device.
00143     DX::ThrowIfFailed(
00144         m_d3dDevice.As(&dxgiDevice)
00145         );
00146
00147     // Create the Direct2D device object and a corresponding context.
00148     DX::ThrowIfFailed(
00149         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00150         );
00151
00152     DX::ThrowIfFailed(
00153         m_d2dDevice->CreateDeviceContext(
00154             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00155             &m_d2dContext
00156             )
00157         );
00158 }
00159
00160 // Helps track the DPI in the helper class.
00161 // This is called in the dpiChanged event handler in the view class.
00162 void DirectXBase::SetDpi(float dpi)
00163 {
00164     if (dpi != m_dpi)
00165     {
00166         // Save the DPI of this display in our class.
00167         m_dpi = dpi;
00168
00169         // Update Direct2D's stored DPI.
00170         m_d2dContext->SetDpi(m_dpi, m_dpi);
00171
00172         // Often a DPI change implies a window size change. In some cases Windows will issue
00173         // both a size changed event and a DPI changed event. In this case, the resulting bounds
00174         // will not change, and the window resize code will only be executed once.
00175         UpdateForWindowSizeChange();
00176     }
00177 }
00178
00179 // This routine is called in the event handler for the view SizeChanged event.
00180 void DirectXBase::UpdateForWindowSizeChange()
00181 {
00182     // Only handle window size changed if there is no pending DPI change.
00183     if (m_dpi != DisplayProperties::LogicalDpi)
00184     {
00185         return;
00186     }
00187
00188     if (m_window->Bounds.Width  != m_windowBounds.Width ||
00189         m_window->Bounds.Height != m_windowBounds.Height)
00190     {
00191         m_d2dContext->SetTarget(nullptr);
00192         m_d2dTargetBitmap = nullptr;
00193         m_d3dRenderTargetView = nullptr;
00194         m_d3dDepthStencilView = nullptr;
00195         m_windowSizeChangeInProgress = true;
00196         CreateWindowSizeDependentResources();
00197     }
00198 }
00199
00200 // Allocate all memory resources that change on a window SizeChanged event.
00201 void DirectXBase::CreateWindowSizeDependentResources()
00202 {
00203     // Store the window bounds so the next time we get a SizeChanged event we can
00204     // avoid rebuilding everything if the size is identical.
00205     m_windowBounds = m_window->Bounds;
00206
00207     if (m_swapChain != nullptr)
00208     {
00209         // If the swap chain already exists, resize it.
00210         HRESULT hr = m_swapChain->ResizeBuffers(2, 0, 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0);
00211
00212         if (hr == DXGI_ERROR_DEVICE_REMOVED)
00213         {
00214             // If the device was removed for any reason, a new device and swapchain will need to be created.
00215             HandleDeviceLost();
00216
00217             // Everything is set up now. Do not continue execution of this method.
00218             return;
00219         }
00220         else
00221         {
00222             DX::ThrowIfFailed(hr);
00223         }
00224     }
00225     else
00226     {
00227         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00228         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00229         swapChainDesc.Width = 0;                                     // Use automatic sizing.
00230         swapChainDesc.Height = 0;
00231         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;           // This is the most common swapchain format.
00232         swapChainDesc.Stereo = false;
00233         swapChainDesc.SampleDesc.Count = 1;                          // Don't use multi-sampling.
00234         swapChainDesc.SampleDesc.Quality = 0;
00235         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00236         swapChainDesc.BufferCount = m_numBuffers;                    // Use multiple buffering to enable flip.
00237         swapChainDesc.Scaling = DXGI_SCALING_NONE;
00238         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Metro style apps must use this SwapEffect.
00239         swapChainDesc.Flags = 0;
00240
00241         ComPtr<IDXGIDevice1> dxgiDevice;
00242         DX::ThrowIfFailed(
00243             m_d3dDevice.As(&dxgiDevice)
00244             );
00245
00246         ComPtr<IDXGIAdapter> dxgiAdapter;
00247         DX::ThrowIfFailed(
00248             dxgiDevice->GetAdapter(&dxgiAdapter)
00249             );
00250
00251         ComPtr<IDXGIFactory2> dxgiFactory;
00252         DX::ThrowIfFailed(
00253             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00254             );
00255
00256         CoreWindow^ window = m_window.Get();
00257         DX::ThrowIfFailed(
00258             dxgiFactory->CreateSwapChainForCoreWindow(
00259                 m_d3dDevice.Get(),
00260                 reinterpret_cast<IUnknown*>(window),
00261                 &swapChainDesc,
00262                 nullptr,
00263                 &m_swapChain
00264                 )
00265             );
00266
00267         // Ensure that DXGI does not queue too many frames. This reduces latency and
00268         // ensures that the application will only render after each VSync, minimizing
00269         // power consumption.
00270         DX::ThrowIfFailed(
00271             dxgiDevice->SetMaximumFrameLatency(m_numBuffers - 1)
00272             );
00273     }
00274
00275     // Create a Direct3D render target view of the swap chain back buffer.
00276     ComPtr<ID3D11Texture2D> backBuffer;
00277     DX::ThrowIfFailed(
00278         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00279         );
00280
00281     DX::ThrowIfFailed(
00282         m_d3dDevice->CreateRenderTargetView(
00283             backBuffer.Get(),
00284             nullptr,
00285             &m_d3dRenderTargetView
00286             )
00287         );
00288
00289     // Cache the rendertarget dimensions in our helper class for convenient use.
00290     D3D11_TEXTURE2D_DESC backBufferDesc = {0};
00291     backBuffer->GetDesc(&backBufferDesc);
00292     m_renderTargetSize.Width  = static_cast<float>(backBufferDesc.Width);
00293     m_renderTargetSize.Height = static_cast<float>(backBufferDesc.Height);
00294
00295     // Create a depth stencil view for use with 3D rendering if needed.
00296     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00297         DXGI_FORMAT_D24_UNORM_S8_UINT,
00298         backBufferDesc.Width,
00299         backBufferDesc.Height,
00300         1,
00301         1,
00302         D3D11_BIND_DEPTH_STENCIL
00303         );
00304
00305     ComPtr<ID3D11Texture2D> depthStencil;
00306     DX::ThrowIfFailed(
00307         m_d3dDevice->CreateTexture2D(
00308             &depthStencilDesc,
00309             nullptr,
00310             &depthStencil
00311             )
00312         );
00313
00314     auto viewDesc = CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D);
00315     DX::ThrowIfFailed(
00316         m_d3dDevice->CreateDepthStencilView(
00317             depthStencil.Get(),
00318             &viewDesc,
00319             &m_d3dDepthStencilView
00320             )
00321         );
00322
00323     // Set the 3D rendering viewport to target the entire window.
00324     CD3D11_VIEWPORT viewport(
00325         0.0f,
00326         0.0f,
00327         static_cast<float>(backBufferDesc.Width),
00328         static_cast<float>(backBufferDesc.Height)
00329         );
00330
00331     m_d3dContext->RSSetViewports(1, &viewport);
00332
00333     // Create a Direct2D target bitmap associated with the
00334     // swap chain back buffer and set it as the current target.
00335     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00336         BitmapProperties1(
00337             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00338             PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00339             m_dpi,
00340             m_dpi
00341             );
00342
00343     ComPtr<IDXGISurface> dxgiBackBuffer;
00344     DX::ThrowIfFailed(
00345         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00346         );
00347
00348     DX::ThrowIfFailed(
00349         m_d2dContext->CreateBitmapFromDxgiSurface(
00350             dxgiBackBuffer.Get(),
00351             &bitmapProperties,
00352             &m_d2dTargetBitmap
00353             )
00354         );
00355
00356     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00357
00358     // Grayscale text anti-aliasing is recommended for all Metro style apps.
00359     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00360 }
00361
00362 // Method to deliver the final image to the display.
00363 void DirectXBase::Present()
00364 {
00365     // The application may optionally specify "dirty" or "scroll" rects to improve efficiency
00366     // in certain scenarios.  In this sample, however, we do not utilize those features.
00367     DXGI_PRESENT_PARAMETERS parameters = {0};
00368     parameters.DirtyRectsCount = 0;
00369     parameters.pDirtyRects = nullptr;
00370     parameters.pScrollRect = nullptr;
00371     parameters.pScrollOffset = nullptr;
00372
00373     // The first argument instructs DXGI to block until VSync, putting the application
00374     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00375     // frames that will never be displayed to the screen.
00376     HRESULT hr = m_swapChain->Present1(1, 0, &parameters);
00377
00378     // Discard the contents of the render target.
00379     // This is a valid operation only when the existing contents will be entirely
00380     // overwritten. If dirty or scroll rects are used, this call should be removed.
00381     m_d3dContext->DiscardView(m_d3dRenderTargetView.Get());
00382
00383     // Discard the contents of the depth stencil.
00384     m_d3dContext->DiscardView(m_d3dDepthStencilView.Get());
00385
00386     // If the device was removed either by a disconnect or a driver upgrade, we
00387     // must recreate all device resources.
00388     if (hr == DXGI_ERROR_DEVICE_REMOVED)
00389     {
00390         HandleDeviceLost();
00391     }
00392     else
00393     {
00394         DX::ThrowIfFailed(hr);
00395     }
00396
00397     if (m_windowSizeChangeInProgress)
00398     {
00399         // A window size change has been initiated and the app has just completed presenting
00400         // the first frame with the new size. Notify the resize manager so we can short
00401         // circuit any resize animation and prevent unnecessary delays.
00402         CoreWindowResizeManager::GetForCurrentView()->NotifyLayoutCompleted();
00403         m_windowSizeChangeInProgress = false;
00404     }
00405 }
00406
00407 void DirectXBase::ValidateDevice()
00408 {
00409     // The D3D Device is no longer valid if the default adapter changes or if
00410     // the device has been removed.
00411
00412     // First, get the information for the adapter related to the current device.
00413
00414     ComPtr<IDXGIDevice1> dxgiDevice;
00415     ComPtr<IDXGIAdapter> deviceAdapter;
00416     DXGI_ADAPTER_DESC deviceDesc;
00417     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00418     DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter));
00419     DX::ThrowIfFailed(deviceAdapter->GetDesc(&deviceDesc));
00420
00421     // Next, get the information for the default adapter.
00422
00423     ComPtr<IDXGIFactory2> dxgiFactory;
00424     ComPtr<IDXGIAdapter1> currentAdapter;
00425     DXGI_ADAPTER_DESC currentDesc;
00426     DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)));
00427     DX::ThrowIfFailed(dxgiFactory->EnumAdapters1(0, &currentAdapter));
00428     DX::ThrowIfFailed(currentAdapter->GetDesc(&currentDesc));
00429
00430     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00431     // a new D3D device must be created.
00432
00433     if ((deviceDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart) ||
00434         (deviceDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart) ||
00435         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00436     {
00437         // Release references to resources related to the old device.
00438         dxgiDevice = nullptr;
00439         deviceAdapter = nullptr;
00440
00441         // Create a new device and swap chain.
00442         HandleDeviceLost();
00443     }
00444 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

QiList< InterfaceName, QiListNil > Member List

This is the complete list of members for QiList< InterfaceName, QiListNil >, including all inherited members.
QueryInterfaceInternal(IID const &iid, OUT void **ppObject) QiList< InterfaceName, QiListNil > [inline]
Generated on Sat Nov 23 2024 16:09:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D HLSL fractal generator/C++/BasicShapes.h Source File

  • Direct3D HLSL fractal generator

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 Sat Nov 23 2024 16:08:10 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Date and time formatting/C++/common/LayoutAwarePage.cpp Source File

  • Date and time formatting
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:31 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML high contrast style/C++/Scenario1.xaml.cpp Source File

  • XAML high contrast style

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::HighContrast;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 Scenario1::Scenario1()
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 Scenario1::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 SDKSample::HighContrast::Scenario1::Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00043 {
00044     Button^ b = safe_cast<Button^>(sender);
00045     if (b != nullptr)
00046     {
00047         rootPage->NotifyUser("You clicked the " + b->Name + " button", NotifyType::StatusMessage);
00048     }
00049 }
00050
00051 void SDKSample::HighContrast::Scenario1::Other_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00052 {
00053     Button^ b = safe_cast<Button^>(sender);
00054     if (b != nullptr)
00055     {
00056         rootPage->NotifyUser("You clicked the " + b->Name + " button", NotifyType::StatusMessage);
00057     }
00058 }
Generated on Sat Nov 23 2024 16:07:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media Server client/C++/Constants.h Source File

  • Media Server client

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"Media Server Client");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044
00045
00046 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D bump mapping/C++/DirectXBase.cpp Source File

  • Direct3D bump mapping

DirectXBase.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 "DirectXBase.h"
00010
00011 using namespace Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::Graphics::Display;
00015 using namespace D2D1;
00016
00017 // Constructor.
00018 DirectXBase::DirectXBase() :
00019     m_windowSizeChangeInProgress(false),
00020     m_dpi(-1.0f)
00021 {
00022 }
00023
00024 // Initialize the DirectX resources required to run.
00025 void DirectXBase::Initialize(CoreWindow^ window, float dpi)
00026 {
00027     m_window = window;
00028
00029     CreateDeviceIndependentResources();
00030     CreateDeviceResources();
00031     SetDpi(dpi);
00032 }
00033
00034 // Recreate all device resources and set them back to the current state.
00035 void DirectXBase::HandleDeviceLost()
00036 {
00037     // Reset these member variables to ensure that SetDpi recreates all resources.
00038     float dpi = m_dpi;
00039     m_dpi = -1.0f;
00040     m_windowBounds.Width = 0;
00041     m_windowBounds.Height = 0;
00042     m_swapChain = nullptr;
00043
00044     CreateDeviceResources();
00045     SetDpi(dpi);
00046 }
00047
00048 // These are the resources required independent of the device.
00049 void DirectXBase::CreateDeviceIndependentResources()
00050 {
00051     D2D1_FACTORY_OPTIONS options;
00052     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00053
00054 #if defined(_DEBUG)
00055     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00056     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00057 #endif
00058
00059     DX::ThrowIfFailed(
00060         D2D1CreateFactory(
00061             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00062             __uuidof(ID2D1Factory1),
00063             &options,
00064             &m_d2dFactory
00065             )
00066         );
00067
00068     DX::ThrowIfFailed(
00069         DWriteCreateFactory(
00070             DWRITE_FACTORY_TYPE_SHARED,
00071             __uuidof(IDWriteFactory),
00072             &m_dwriteFactory
00073             )
00074         );
00075
00076     DX::ThrowIfFailed(
00077         CoCreateInstance(
00078             CLSID_WICImagingFactory,
00079             nullptr,
00080             CLSCTX_INPROC_SERVER,
00081             IID_PPV_ARGS(&m_wicFactory)
00082             )
00083         );
00084 }
00085
00086 // These are the resources that depend on the device.
00087 void DirectXBase::CreateDeviceResources()
00088 {
00089     // This flag adds support for surfaces with a different color channel ordering
00090     // than the API default. It is required for compatibility with Direct2D.
00091     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00092     ComPtr<IDXGIDevice> dxgiDevice;
00093
00094 #if defined(_DEBUG)
00095     // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00096     creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00097 #endif
00098
00099     // This array defines the set of DirectX hardware feature levels this app will support.
00100     // Note the ordering should be preserved.
00101     // Don't forget to declare your application's minimum required feature level in its
00102     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00103     D3D_FEATURE_LEVEL featureLevels[] =
00104     {
00105         D3D_FEATURE_LEVEL_11_1,
00106         D3D_FEATURE_LEVEL_11_0,
00107         D3D_FEATURE_LEVEL_10_1,
00108         D3D_FEATURE_LEVEL_10_0,
00109         D3D_FEATURE_LEVEL_9_3,
00110         D3D_FEATURE_LEVEL_9_2,
00111         D3D_FEATURE_LEVEL_9_1
00112     };
00113
00114     // Create the Direct3D 11 API device object and a corresponding context.
00115     ComPtr<ID3D11Device> device;
00116     ComPtr<ID3D11DeviceContext> context;
00117     DX::ThrowIfFailed(
00118         D3D11CreateDevice(
00119             nullptr,                    // Specify nullptr to use the default adapter.
00120             D3D_DRIVER_TYPE_HARDWARE,
00121             0,
00122             creationFlags,              // Set debug and Direct2D compatibility flags.
00123             featureLevels,              // List of feature levels this app can support.
00124             ARRAYSIZE(featureLevels),
00125             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Metro style apps.
00126             &device,                    // Returns the Direct3D device created.
00127             &m_featureLevel,            // Returns feature level of device created.
00128             &context                    // Returns the device immediate context.
00129             )
00130         );
00131
00132     // Get the Direct3D 11.1 API device and context interfaces.
00133     DX::ThrowIfFailed(
00134         device.As(&m_d3dDevice)
00135         );
00136
00137     DX::ThrowIfFailed(
00138         context.As(&m_d3dContext)
00139         );
00140
00141     // Get the underlying DXGI device of the Direct3D device.
00142     DX::ThrowIfFailed(
00143         m_d3dDevice.As(&dxgiDevice)
00144         );
00145
00146     // Create the Direct2D device object and a corresponding context.
00147     DX::ThrowIfFailed(
00148         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00149         );
00150
00151     DX::ThrowIfFailed(
00152         m_d2dDevice->CreateDeviceContext(
00153             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00154             &m_d2dContext
00155             )
00156         );
00157 }
00158
00159 // Helps track the DPI in the helper class.
00160 // This is called in the dpiChanged event handler in the view class.
00161 void DirectXBase::SetDpi(float dpi)
00162 {
00163     if (dpi != m_dpi)
00164     {
00165         // Save the DPI of this display in our class.
00166         m_dpi = dpi;
00167
00168         // Update Direct2D's stored DPI.
00169         m_d2dContext->SetDpi(m_dpi, m_dpi);
00170
00171         // Often a DPI change implies a window size change. In some cases Windows will issue
00172         // both a size changed event and a DPI changed event. In this case, the resulting bounds
00173         // will not change, and the window resize code will only be executed once.
00174         UpdateForWindowSizeChange();
00175     }
00176 }
00177
00178 // This routine is called in the event handler for the view SizeChanged event.
00179 void DirectXBase::UpdateForWindowSizeChange()
00180 {
00181     // Only handle window size changed if there is no pending DPI change.
00182     if (m_dpi != DisplayProperties::LogicalDpi)
00183     {
00184         return;
00185     }
00186
00187     if (m_window->Bounds.Width  != m_windowBounds.Width ||
00188         m_window->Bounds.Height != m_windowBounds.Height)
00189     {
00190         m_d2dContext->SetTarget(nullptr);
00191         m_d2dTargetBitmap = nullptr;
00192         m_d3dRenderTargetView = nullptr;
00193         m_d3dDepthStencilView = nullptr;
00194         m_windowSizeChangeInProgress = true;
00195         CreateWindowSizeDependentResources();
00196     }
00197 }
00198
00199 // Allocate all memory resources that change on a window SizeChanged event.
00200 void DirectXBase::CreateWindowSizeDependentResources()
00201 {
00202     // Store the window bounds so the next time we get a SizeChanged event we can
00203     // avoid rebuilding everything if the size is identical.
00204     m_windowBounds = m_window->Bounds;
00205
00206     if (m_swapChain != nullptr)
00207     {
00208         // If the swap chain already exists, resize it.
00209         HRESULT hr = m_swapChain->ResizeBuffers(2, 0, 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0);
00210
00211         if (hr == DXGI_ERROR_DEVICE_REMOVED)
00212         {
00213             // If the device was removed for any reason, a new device and swapchain will need to be created.
00214             HandleDeviceLost();
00215
00216             // Everything is set up now. Do not continue execution of this method.
00217             return;
00218         }
00219         else
00220         {
00221             DX::ThrowIfFailed(hr);
00222         }
00223     }
00224     else
00225     {
00226         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00227         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00228         swapChainDesc.Width = 0;                                     // Use automatic sizing.
00229         swapChainDesc.Height = 0;
00230         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;           // This is the most common swap chain format.
00231         swapChainDesc.Stereo = false;
00232         swapChainDesc.SampleDesc.Count = 1;                          // Don't use multi-sampling.
00233         swapChainDesc.SampleDesc.Quality = 0;
00234         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00235         swapChainDesc.BufferCount = 2;                               // Use double-buffering to minimize latency.
00236         swapChainDesc.Scaling = DXGI_SCALING_NONE;
00237         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Metro style apps must use this SwapEffect.
00238         swapChainDesc.Flags = 0;
00239
00240         ComPtr<IDXGIDevice1> dxgiDevice;
00241         DX::ThrowIfFailed(
00242             m_d3dDevice.As(&dxgiDevice)
00243             );
00244
00245         ComPtr<IDXGIAdapter> dxgiAdapter;
00246         DX::ThrowIfFailed(
00247             dxgiDevice->GetAdapter(&dxgiAdapter)
00248             );
00249
00250         ComPtr<IDXGIFactory2> dxgiFactory;
00251         DX::ThrowIfFailed(
00252             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00253             );
00254
00255         CoreWindow^ window = m_window.Get();
00256         DX::ThrowIfFailed(
00257             dxgiFactory->CreateSwapChainForCoreWindow(
00258                 m_d3dDevice.Get(),
00259                 reinterpret_cast<IUnknown*>(window),
00260                 &swapChainDesc,
00261                 nullptr,
00262                 &m_swapChain
00263                 )
00264             );
00265
00266         // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
00267         // ensures that the application will only render after each VSync, minimizing power consumption.
00268         DX::ThrowIfFailed(
00269             dxgiDevice->SetMaximumFrameLatency(1)
00270             );
00271     }
00272
00273     // Create a Direct3D render target view of the swap chain back buffer.
00274     ComPtr<ID3D11Texture2D> backBuffer;
00275     DX::ThrowIfFailed(
00276         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00277         );
00278
00279     DX::ThrowIfFailed(
00280         m_d3dDevice->CreateRenderTargetView(
00281             backBuffer.Get(),
00282             nullptr,
00283             &m_d3dRenderTargetView
00284             )
00285         );
00286
00287     // Cache the rendertarget dimensions in our helper class for convenient use.
00288     D3D11_TEXTURE2D_DESC backBufferDesc = {0};
00289     backBuffer->GetDesc(&backBufferDesc);
00290     m_renderTargetSize.Width  = static_cast<float>(backBufferDesc.Width);
00291     m_renderTargetSize.Height = static_cast<float>(backBufferDesc.Height);
00292
00293     // Create a depth stencil view for use with 3D rendering if needed.
00294     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00295         DXGI_FORMAT_D24_UNORM_S8_UINT,
00296         backBufferDesc.Width,
00297         backBufferDesc.Height,
00298         1,
00299         1,
00300         D3D11_BIND_DEPTH_STENCIL
00301         );
00302
00303     ComPtr<ID3D11Texture2D> depthStencil;
00304     DX::ThrowIfFailed(
00305         m_d3dDevice->CreateTexture2D(
00306             &depthStencilDesc,
00307             nullptr,
00308             &depthStencil
00309             )
00310         );
00311
00312     auto viewDesc = CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D);
00313     DX::ThrowIfFailed(
00314         m_d3dDevice->CreateDepthStencilView(
00315             depthStencil.Get(),
00316             &viewDesc,
00317             &m_d3dDepthStencilView
00318             )
00319         );
00320
00321     // Set the 3D rendering viewport to target the entire window.
00322     CD3D11_VIEWPORT viewport(
00323         0.0f,
00324         0.0f,
00325         static_cast<float>(backBufferDesc.Width),
00326         static_cast<float>(backBufferDesc.Height)
00327         );
00328
00329     m_d3dContext->RSSetViewports(1, &viewport);
00330
00331     // Create a Direct2D target bitmap associated with the
00332     // swap chain back buffer and set it as the current target.
00333     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00334         BitmapProperties1(
00335             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00336             PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00337             m_dpi,
00338             m_dpi
00339             );
00340
00341     ComPtr<IDXGISurface> dxgiBackBuffer;
00342     DX::ThrowIfFailed(
00343         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00344         );
00345
00346     DX::ThrowIfFailed(
00347         m_d2dContext->CreateBitmapFromDxgiSurface(
00348             dxgiBackBuffer.Get(),
00349             &bitmapProperties,
00350             &m_d2dTargetBitmap
00351             )
00352         );
00353
00354     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00355
00356     // Grayscale text anti-aliasing is recommended for all Metro style apps.
00357     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00358 }
00359
00360 // Method to deliver the final image to the display.
00361 void DirectXBase::Present()
00362 {
00363     // The application may optionally specify "dirty" or "scroll" rects to improve efficiency
00364     // in certain scenarios.  In this sample, however, we do not utilize those features.
00365     DXGI_PRESENT_PARAMETERS parameters = {0};
00366     parameters.DirtyRectsCount = 0;
00367     parameters.pDirtyRects = nullptr;
00368     parameters.pScrollRect = nullptr;
00369     parameters.pScrollOffset = nullptr;
00370
00371     // The first argument instructs DXGI to block until VSync, putting the application
00372     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00373     // frames that will never be displayed to the screen.
00374     HRESULT hr = m_swapChain->Present1(1, 0, &parameters);
00375
00376     // Discard the contents of the render target.
00377     // This is a valid operation only when the existing contents will be entirely
00378     // overwritten. If dirty or scroll rects are used, this call should be removed.
00379     m_d3dContext->DiscardView(m_d3dRenderTargetView.Get());
00380
00381     // Discard the contents of the depth stencil.
00382     m_d3dContext->DiscardView(m_d3dDepthStencilView.Get());
00383
00384     // If the device was removed either by a disconnect or a driver upgrade, we
00385     // must recreate all device resources.
00386     if (hr == DXGI_ERROR_DEVICE_REMOVED)
00387     {
00388         HandleDeviceLost();
00389     }
00390     else
00391     {
00392         DX::ThrowIfFailed(hr);
00393     }
00394
00395     if (m_windowSizeChangeInProgress)
00396     {
00397         // A window size change has been initiated and the app has just completed presenting
00398         // the first frame with the new size. Notify the resize manager so we can short
00399         // circuit any resize animation and prevent unnecessary delays.
00400         CoreWindowResizeManager::GetForCurrentView()->NotifyLayoutCompleted();
00401         m_windowSizeChangeInProgress = false;
00402     }
00403 }
00404
00405 void DirectXBase::ValidateDevice()
00406 {
00407     // The D3D Device is no longer valid if the default adapter changes or if
00408     // the device has been removed.
00409
00410     // First, get the information for the adapter related to the current device.
00411
00412     ComPtr<IDXGIDevice1> dxgiDevice;
00413     ComPtr<IDXGIAdapter> deviceAdapter;
00414     DXGI_ADAPTER_DESC deviceDesc;
00415     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00416     DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter));
00417     DX::ThrowIfFailed(deviceAdapter->GetDesc(&deviceDesc));
00418
00419     // Next, get the information for the default adapter.
00420
00421     ComPtr<IDXGIFactory2> dxgiFactory;
00422     ComPtr<IDXGIAdapter1> currentAdapter;
00423     DXGI_ADAPTER_DESC currentDesc;
00424     DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)));
00425     DX::ThrowIfFailed(dxgiFactory->EnumAdapters1(0, &currentAdapter));
00426     DX::ThrowIfFailed(currentAdapter->GetDesc(&currentDesc));
00427
00428     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00429     // a new D3D device must be created.
00430
00431     if ((deviceDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart) ||
00432         (deviceDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart) ||
00433         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00434     {
00435         // Release references to resources related to the old device.
00436         dxgiDevice = nullptr;
00437         deviceAdapter = nullptr;
00438
00439         // Create a new device and swap chain.
00440         HandleDeviceLost();
00441     }
00442 }
Generated on Sat Nov 23 2024 16:08:02 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XInput audio controller playback/C++/MediaStreamer.cpp Source File

  • XInput audio controller playback

MediaStreamer.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
00010 #include "DirectXBase.h"
00011 #include "directxsample.h"
00012
00013 #include <initguid.h>
00014 #include "MediaStreamer.h"
00015
00016 MediaStreamer::MediaStreamer(_In_ Platform::String^ url)
00017 {
00018     Microsoft::WRL::ComPtr<IMFMediaType> outputMediaType;
00019     Microsoft::WRL::ComPtr<IMFMediaType> mediaType;
00020
00021     DX::ThrowIfFailed(
00022         MFStartup(MF_VERSION)
00023         );
00024
00025     DX::ThrowIfFailed(
00026         MFCreateSourceReaderFromURL(url->Data(), nullptr, &m_reader)
00027         );
00028
00029     // Set the decoded output format as PCM
00030     // XAudio2 on Windows can process PCM and ADPCM-encoded buffers.
00031     // When using MF, this sample always decodes into PCM.
00032
00033     DX::ThrowIfFailed(
00034         MFCreateMediaType(&mediaType)
00035         );
00036
00037     DX::ThrowIfFailed(
00038         mediaType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Audio)
00039         );
00040
00041     DX::ThrowIfFailed(
00042         mediaType->SetGUID(MF_MT_SUBTYPE, MFAudioFormat_PCM)
00043         );
00044
00045     DX::ThrowIfFailed(
00046         m_reader->SetCurrentMediaType(MF_SOURCE_READER_FIRST_AUDIO_STREAM, 0, mediaType.Get())
00047         );
00048
00049     // Get the complete WAVEFORMAT from the Media Type
00050     DX::ThrowIfFailed(
00051         m_reader->GetCurrentMediaType(MF_SOURCE_READER_FIRST_AUDIO_STREAM, &outputMediaType)
00052         );
00053
00054     uint32 formatByteCount = 0;
00055     WAVEFORMATEX* waveFormat;
00056     DX::ThrowIfFailed(
00057         MFCreateWaveFormatExFromMFMediaType(outputMediaType.Get(), &waveFormat, &formatByteCount)
00058         );
00059     CopyMemory(&m_waveFormat, waveFormat, sizeof(m_waveFormat));
00060     CoTaskMemFree(waveFormat);
00061
00062     // Get the total length of the stream in bytes
00063     PROPVARIANT var;
00064     DX::ThrowIfFailed(
00065         m_reader->GetPresentationAttribute(MF_SOURCE_READER_MEDIASOURCE, MF_PD_DURATION, &var)
00066         );
00067     LONGLONG duration = var.uhVal.QuadPart;
00068     float64 durationInSeconds = (duration / (float64)(10000 * 1000));
00069     m_maxStreamLengthInBytes = (uint32)(durationInSeconds * m_waveFormat.nAvgBytesPerSec);
00070 }
00071
00072 std::vector<byte> MediaStreamer::GetNextBuffer()
00073 {
00074     std::vector<byte> resultData;
00075
00076     Microsoft::WRL::ComPtr<IMFSample> sample;
00077     Microsoft::WRL::ComPtr<IMFMediaBuffer> mediaBuffer;
00078
00079     uint8* audioData = nullptr;
00080     uint32 sampleBufferLength = 0;
00081     uint32 flags = 0;
00082
00083     DX::ThrowIfFailed(
00084         m_reader->ReadSample(MF_SOURCE_READER_FIRST_AUDIO_STREAM, 0, nullptr, reinterpret_cast<DWORD*>(&flags), nullptr, &sample)
00085         );
00086
00087     // End of stream
00088     if (flags & MF_SOURCE_READERF_ENDOFSTREAM)
00089     {
00090         return resultData;
00091     }
00092     if (sample == nullptr)
00093     {
00094         throw ref new Platform::FailureException();
00095     }
00096
00097     DX::ThrowIfFailed(
00098         sample->ConvertToContiguousBuffer(&mediaBuffer)
00099         );
00100
00101     DX::ThrowIfFailed(
00102         mediaBuffer->Lock(&audioData, nullptr, reinterpret_cast<DWORD*>(&sampleBufferLength))
00103         );
00104
00105     //
00106     // Prepare and return the resultant array of data
00107     //
00108     resultData.resize(sampleBufferLength);
00109     CopyMemory(&resultData[0], audioData, sampleBufferLength);
00110
00111     // Release the lock
00112     DX::ThrowIfFailed(
00113         mediaBuffer->Unlock()
00114         );
00115
00116     return resultData;
00117 }
00118
00119 std::vector<byte> MediaStreamer::ReadAll()
00120 {
00121     std::vector<byte> resultData;
00122
00123     for (;;)
00124     {
00125         std::vector<byte> nextBuffer = GetNextBuffer();
00126         if (nextBuffer.size() == 0)
00127         {
00128             break;
00129         }
00130
00131         // Append the new buffer to the running total
00132         size_t lastBufferSize = resultData.size();
00133         resultData.resize(lastBufferSize + nextBuffer.size());
00134         CopyMemory(&resultData[lastBufferSize], &nextBuffer[0], nextBuffer.size());
00135     }
00136
00137     return resultData;
00138 }
00139
00140 void MediaStreamer::Restart()
00141 {
00142     PROPVARIANT var;
00143     ZeroMemory(&var, sizeof(var));
00144     var.vt = VT_I8;
00145
00146     DX::ThrowIfFailed(
00147         m_reader->SetCurrentPosition(GUID_NULL, var)
00148     );
00149
00150 }
Generated on Sat Nov 23 2024 16:08:15 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::TileContent::TileContentFactory Member List

This is the complete list of members for NotificationsExtensions::TileContent::TileContentFactory, including all inherited members.
CreateTileSquareBlock() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileSquareBlock() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileSquareImage() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileSquareImage() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileSquarePeekImageAndText01() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileSquarePeekImageAndText01() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileSquarePeekImageAndText02() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileSquarePeekImageAndText02() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileSquarePeekImageAndText03() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileSquarePeekImageAndText03() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileSquarePeekImageAndText04() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileSquarePeekImageAndText04() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileSquareText01() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileSquareText01() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileSquareText02() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileSquareText02() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileSquareText03() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileSquareText03() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileSquareText04() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileSquareText04() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideBlockAndText01() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideBlockAndText01() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideBlockAndText02() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideBlockAndText02() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideImage() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideImage() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideImageAndText01() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideImageAndText01() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideImageAndText02() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideImageAndText02() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideImageCollection() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideImageCollection() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWidePeekImage01() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWidePeekImage01() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWidePeekImage02() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWidePeekImage02() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWidePeekImage03() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWidePeekImage03() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWidePeekImage04() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWidePeekImage04() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWidePeekImage05() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWidePeekImage05() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWidePeekImage06() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWidePeekImage06() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWidePeekImageAndText01() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWidePeekImageAndText01() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWidePeekImageAndText02() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWidePeekImageAndText02() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWidePeekImageCollection01() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWidePeekImageCollection01() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWidePeekImageCollection02() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWidePeekImageCollection02() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWidePeekImageCollection03() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWidePeekImageCollection03() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWidePeekImageCollection04() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWidePeekImageCollection04() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWidePeekImageCollection05() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWidePeekImageCollection05() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWidePeekImageCollection06() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWidePeekImageCollection06() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideSmallImageAndText01() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideSmallImageAndText01() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideSmallImageAndText02() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideSmallImageAndText02() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideSmallImageAndText03() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideSmallImageAndText03() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideSmallImageAndText04() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideSmallImageAndText04() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideSmallImageAndText05() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideSmallImageAndText05() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideText01() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideText01() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideText02() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideText02() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideText03() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideText03() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideText04() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideText04() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideText05() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideText05() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideText06() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideText06() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideText07() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideText07() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideText08() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideText08() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideText09() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideText09() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideText10() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideText10() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideText11() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
CreateTileWideText11() | NotificationsExtensions::TileContent::TileContentFactory | [inline, static]
Generated on Sat Nov 23 2024 16:09:43 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Syndication/C++/common/suspensionmanager.h Source File

  • Syndication
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: SimpleOrientationSensor/C++/pch.cpp Source File

  • SimpleOrientationSensor

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML high contrast style/C++/Scenario2.xaml.h Source File

  • XAML high contrast style

Scenario2.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.xaml.h
00013 // Declaration of the Scenario2 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario2.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024   namespace HighContrast
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::WebHostHiddenAttribute]
00030     public ref class Scenario2 sealed
00031     {
00032     public:
00033       Scenario2();
00034
00035     protected:
00036       virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037     private:
00038       MainPage^ rootPage;
00039       void DoSomething_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040     };
00041   }
00042 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAudio2 audio file playback/C++/SoundFileReader.cpp Source File

  • XAudio2 audio file playback

SoundFileReader.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 "SoundFileReader.h"
00010 #include "RandomAccessReader.h"
00011
00012 namespace
00013 {
00014     //
00015     // 4 Character Tags in the RIFF File of Interest (read backwards)
00016     //
00017     const uint32 FOURCC_RIFF_TAG      = 'FFIR';
00018     const uint32 FOURCC_FORMAT_TAG    = ' tmf';
00019     const uint32 FOURCC_DATA_TAG      = 'atad';
00020     const uint32 FOURCC_WAVE_FILE_TAG = 'EVAW';
00021
00022     //
00023     // The header of every 'chunk' of data in the RIFF file
00024     //
00025     struct ChunkHeader
00026     {
00027         uint32 tag;
00028         uint32 size;
00029     };
00030
00031     //
00032     // Helper function to find a riff-chunk with-in the sent bounds.
00033     // It is assumed the bounds begin at the start of a chunk
00034     //
00035     uint64 FindChunk(
00036         RandomAccessReader^ file,
00037         uint32 tag,
00038         uint64 startLoc,
00039         uint64 endLoc
00040         )
00041     {
00042         // Move to start of search
00043         file->SeekAbsolute(startLoc);
00044
00045         uint64 newLoc = startLoc;
00046         while (endLoc > (newLoc + sizeof(ChunkHeader)))
00047         {
00048             Platform::Array<byte>^ headerBytes = file->Read(sizeof(ChunkHeader));
00049             ChunkHeader* header = reinterpret_cast<ChunkHeader*>(headerBytes->Data);
00050             if (header->tag == tag)
00051             {
00052                 // Found the requested tag
00053                 return newLoc;
00054             }
00055             file->SeekRelative(static_cast<int64>(header->size));
00056             newLoc += header->size + sizeof(*header);
00057         }
00058
00059         // Chunk with sent tag was not found
00060         throw ref new Platform::FailureException();
00061     }
00062
00063     //
00064     // Read the riff chunk header at the send location
00065     //
00066     void ReadHeader(
00067         RandomAccessReader^ file,
00068         uint64 loc,
00069         ChunkHeader& header
00070         )
00071     {
00072         // Move to read location
00073         file->SeekAbsolute(loc);
00074         Platform::Array<byte>^ headerBytes = file->Read(sizeof(ChunkHeader));
00075         header = *reinterpret_cast<ChunkHeader*>(headerBytes->Data);
00076     }
00077 }
00078
00079 //--------------------------------------------------------------------------------------
00080 // Name: SoundFileReader constructor
00081 // Desc: Any failure to construct will throw.
00082 //       If the constructor succeeds this is a fully usable object
00083 //--------------------------------------------------------------------------------------
00084 SoundFileReader::SoundFileReader(
00085     _In_ Platform::String^ fileName
00086     )
00087 {
00088     //
00089     // Open the file for random read access
00090     //
00091     RandomAccessReader^ riffFile = ref new RandomAccessReader(fileName);
00092     uint64 fileSize = riffFile->GetFileSize();
00093
00094     //
00095     // Locate, read and validate the RIFF chunk
00096     //
00097     uint64 riffLoc = FindChunk(riffFile, FOURCC_RIFF_TAG, 0, fileSize);
00098
00099     // Read beyond the riff header.
00100     ChunkHeader chunkHeader;
00101     ReadHeader(riffFile, riffLoc, chunkHeader);
00102
00103     uint32 tag = 0;
00104     Platform::Array<byte>^ riffData = riffFile->Read(sizeof(tag));
00105     tag = *reinterpret_cast<uint32*>(riffData->Data);
00106     if (tag != FOURCC_WAVE_FILE_TAG)
00107     {
00108         // Only support .wav files
00109         throw ref new Platform::FailureException();
00110     }
00111     uint64 riffChildrenStart = riffLoc + sizeof(chunkHeader) + sizeof(tag);
00112     uint64 riffChildrenEnd   = riffLoc + sizeof(chunkHeader) + chunkHeader.size;
00113
00114     //
00115     // Find, read and validate the format chunk (a child within the RIFF chunk)
00116     //
00117     uint64 formatLoc = FindChunk(riffFile, FOURCC_FORMAT_TAG, riffChildrenStart, riffChildrenEnd);
00118     ReadHeader(riffFile, formatLoc, chunkHeader);
00119     if (chunkHeader.size < sizeof(WAVEFORMATEX))
00120     {
00121         // Format data of unsupported size; must be unsupported format
00122         throw ref new Platform::FailureException();
00123     }
00124     m_soundFormat = riffFile->Read(chunkHeader.size);
00125     WAVEFORMATEX format = *reinterpret_cast<WAVEFORMATEX*>(m_soundFormat->Data);
00126     if (format.wFormatTag != WAVE_FORMAT_PCM
00127         && format.wFormatTag != WAVE_FORMAT_ADPCM)
00128     {
00129         // This is not PCM or ADPCM, which is all we support
00130         throw ref new Platform::FailureException();
00131     }
00132
00133     //
00134     // Locate, the PCM data in the data chunk
00135     //
00136     uint64 dataChunkStart = FindChunk(riffFile, FOURCC_DATA_TAG, riffChildrenStart, riffChildrenEnd);
00137     ReadHeader(riffFile, dataChunkStart, chunkHeader);
00138
00139     //
00140     // Now read the PCM data and setup the buffer
00141     //
00142     m_soundData = riffFile->Read(chunkHeader.size);
00143 }
00144
00145 //--------------------------------------------------------------------------------------
00146 // Name: SoundFileReader::GetSoundData
00147 // Desc: Sound Data accessor
00148 //--------------------------------------------------------------------------------------
00149 Platform::Array<byte>^ SoundFileReader::GetSoundData() const
00150 {
00151     return m_soundData;
00152 }
00153
00154 //--------------------------------------------------------------------------------------
00155 // Name: SoundFileReader::GetSoundFormat
00156 // Desc: Sound Format Accessor
00157 //--------------------------------------------------------------------------------------
00158 WAVEFORMATEX* SoundFileReader::GetSoundFormat() const
00159 {
00160     return reinterpret_cast<WAVEFORMATEX*>(m_soundFormat->Data);
00161 }
Generated on Sat Nov 23 2024 16:08:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File access/C++/Constants.h Source File

  • File access

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"File access C++ sample");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041
00042         static property Platform::String^ Filename
00043         {
00044             Platform::String^ get()
00045             {
00046                 return ref new Platform::String(L"sample.dat");
00047             }
00048         }
00049
00050         property Windows::Storage::StorageFile^ SampleFile
00051         {
00052             Windows::Storage::StorageFile^ get()
00053             {
00054                 return sampleFile;
00055             }
00056             void set(Windows::Storage::StorageFile^ value)
00057             {
00058                 sampleFile = value;
00059             }
00060         }
00061
00062         property Platform::String^ MruToken
00063         {
00064             Platform::String^ get()
00065             {
00066                 return mruToken;
00067             }
00068             void set(Platform::String^ value)
00069             {
00070                 mruToken = value;
00071             }
00072         }
00073
00074         property Platform::String^ FalToken
00075         {
00076             Platform::String^ get()
00077             {
00078                 return falToken;
00079             }
00080             void set(Platform::String^ value)
00081             {
00082                 falToken = value;
00083             }
00084         }
00085
00086     internal:
00087         void ResetScenarioOutput(Windows::UI::Xaml::Controls::TextBlock^ output);
00088         void NotifyUserFileNotExist();
00089         void HandleFileNotFoundException(Platform::COMException^ e);
00090
00091     private:
00092         void Initialize();
00093         void ValidateFile(Platform::String^ scenarioName);
00094
00095         static Platform::Array<Scenario>^ scenariosInner;
00096         Windows::Storage::StorageFile^ sampleFile;
00097         Platform::String^ mruToken;
00098         Platform::String^ falToken;
00099     };
00100 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::TileContent::TileSquarePeekImageAndText02 Member List

This is the complete list of members for NotificationsExtensions::TileContent::TileSquarePeekImageAndText02, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
Branding | NotificationsExtensions::TileContent::TileNotificationBase |
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
NotificationsExtensions::GetContent() | NotificationsExtensions::TileContent::TileSquareBase | [inline]
NotificationsExtensions::GetContent() | NotificationsExtensions::TileContent::TileSquareBase | [inline]
NotificationsExtensions::TileContent::TileNotificationBase::GetContent() | NotificationsExtensions::NotificationBase | [pure virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Image | NotificationsExtensions::TileContent::TileSquarePeekImageAndText02 |
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeBinding(string globalLang, string globalBaseUri, TileBranding globalBranding, bool globalAddImageQuery) | NotificationsExtensions::TileContent::TileSquareBase | [inline]
SerializeBinding(string globalLang, string globalBaseUri, TileBranding globalBranding, bool globalAddImageQuery) | NotificationsExtensions::TileContent::TileSquareBase | [inline]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextBodyWrap | NotificationsExtensions::TileContent::TileSquarePeekImageAndText02 |
TextFields | NotificationsExtensions::NotificationBase |
TextHeading | NotificationsExtensions::TileContent::TileSquarePeekImageAndText02 |
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileSquareBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileSquareBase | [inline]
TileSquareBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileSquareBase | [inline]
TileSquarePeekImageAndText02() | NotificationsExtensions::TileContent::TileSquarePeekImageAndText02 | [inline]
TileSquarePeekImageAndText02() | NotificationsExtensions::TileContent::TileSquarePeekImageAndText02 | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:43 for Win8-Examples by doxygen 1.7.1


Win8-Examples: App tiles and badges/C#,C++/common/LayoutAwarePage.cpp Source File

  • App tiles and badges
  • C#,C++
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:30 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML vector-based drawing/C++/MainPage.xaml.h Source File

  • XAML vector-based drawing

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: UI contrast and settings/C++/pch.cpp Source File

  • UI contrast and settings

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML data binding/C++/Scenario7.xaml.h Source File

  • XAML data binding

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 #include "Team.h"
00022
00023 namespace SDKSample
00024 {
00025     namespace DataBinding
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 Scenario7 sealed
00032         {
00033         public:
00034             Scenario7();
00035         property Teams^ _observableTeams;
00036
00037         protected:
00038             void BtnRemoveTeam_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039         void VectorChanged(Windows::Foundation::Collections::IObservableVector<Object^>^ sender, Windows::Foundation::Collections::IVectorChangedEventArgs^ e);
00040         void Scenario7Reset(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         private:
00042             MainPage^ rootPage;
00043
00044
00045         };
00046     }
00047 }
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML user and custom controls/C++/Scenario2.xaml.cpp Source File

  • XAML user and custom controls

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 SDKSample::UserAndCustomControls;
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
00042
00043 void SDKSample::UserAndCustomControls::Scenario2::DoSomething_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00044 {
00045     Button^ b = safe_cast<Button^>(sender);
00046     if (b != nullptr)
00047     {
00048         rootPage->NotifyUser("You clicked the " + b->Name + " button", NotifyType::StatusMessage);
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Lock screen personalization/C++/common/LayoutAwarePage.cpp Source File

  • Lock screen personalization
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:32 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite hello world/C++/DWriteHelloWorld.h Source File

  • DirectWrite hello world

DWriteHelloWorld.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 "DirectXBase.h"
00011 #include "SampleOverlay.h"
00012
00013 ref class DWriteHelloWorld : public DirectXBase, public Windows::ApplicationModel::Core::IFrameworkView
00014 {
00015 internal:
00016     DWriteHelloWorld();
00017
00018     // DirectXBase Methods
00019     virtual void CreateDeviceIndependentResources() override;
00020     virtual void CreateDeviceResources() override;
00021     virtual void CreateWindowSizeDependentResources() override;
00022     virtual void Render() override;
00023
00024 public:
00025     // IFrameworkView Methods
00026     virtual void Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00027     virtual void SetWindow(_In_ Windows::UI::Core::CoreWindow^ window);
00028     virtual void Load(_In_ Platform::String^ entryPoint);
00029     virtual void Run();
00030     virtual void Uninitialize();
00031
00032 private:
00033     // Event Handlers
00034     void OnWindowSizeChanged(
00035         _In_ Windows::UI::Core::CoreWindow^ sender,
00036         _In_ Windows::UI::Core::WindowSizeChangedEventArgs^ args
00037         );
00038
00039     void OnLogicalDpiChanged(
00040         _In_ Platform::Object^ sender
00041         );
00042
00043     void OnDisplayContentsInvalidated(
00044         _In_ Platform::Object^ sender
00045         );
00046
00047     void OnActivated(
00048         _In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView,
00049         _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^ args
00050         );
00051
00052     void OnSuspending(
00053         _In_ Platform::Object^ sender,
00054         _In_ Windows::ApplicationModel::SuspendingEventArgs^ args
00055         );
00056
00057     void OnResuming(
00058         _In_ Platform::Object^ sender,
00059         _In_ Platform::Object^ args
00060         );
00061
00062     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>                    m_blackBrush;
00063     Microsoft::WRL::ComPtr<IDWriteTextFormat>                       m_textFormat;
00064     Microsoft::WRL::ComPtr<IDWriteTypography>                       m_textTypography;
00065     Microsoft::WRL::ComPtr<IDWriteTextLayout>                       m_textLayout;
00066     SampleOverlay^                                                  m_sampleOverlay;
00067 };
00068
00069 ref class DirectXAppSource : Windows::ApplicationModel::Core::IFrameworkViewSource
00070 {
00071 public:
00072     virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00073 };
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX marble maze game/C++/Camera.h Source File

  • DirectX marble maze game

Camera.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
00009 #pragma once
00010
00011 #include "BasicMath.h"
00012
00013 // a simple camera class
00014 ref class Camera
00015 {
00016 private:
00017     float3 m_position;      // the position of the camera
00018     float3 m_direction;     // the unit vector of the viewing direction
00019     float4x4 m_view;        // view matrix
00020     float4x4 m_projection;  // projection matrix
00021
00022 internal:
00023     void GetViewMatrix(_Out_ float4x4 *viewMatrix);
00024     void GetProjectionMatrix(_Out_ float4x4 *projectionMatrix);
00025
00026     // this method updates the view matrix based on new position and focus coordinates
00027     void SetViewParameters(
00028         _In_ float3 eyePosition,    // the position of the camera
00029         _In_ float3 lookPosition,   // the point the camera should look at
00030         _In_ float3 up              // the durection vector for up
00031         );
00032
00033     // this method updates the projection matrix based on new parameters
00034     void SetProjectionParameters(
00035         _In_ float minimumFieldOfView,  // the minimum horizontal or vertical field of view, in degrees
00036         _In_ float aspectRatio,         // the aspect ratio of the projection (width / height)
00037         _In_ float nearPlane,           // depth to map to 0
00038         _In_ float farPlane             // depth to map to 1
00039         );
00040 };
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Credential picker/C++/CppSamplesUtils.h Source File

  • Credential picker

CppSamplesUtils.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 <string>
00014 #include <sstream>
00015 #include <algorithm>
00016 #include <collection.h>
00017 #include <ppltasks.h>
00018
00019 namespace CppSamplesUtils
00020 {
00021     namespace Details
00022     {
00023         static Windows::Foundation::Collections::PropertySet^ sessionState = nullptr;
00024         static Platform::String^ sessionStateFileName = ref new Platform::String(L"_cppSessionState.xml");
00025
00026         concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file);
00027         concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file);
00028     }
00029
00030     class SuspensionManager
00031     {
00032     public:
00033         static Windows::Foundation::Collections::PropertySet^ SessionState()
00034         {
00035             using namespace Windows::Foundation::Collections;
00036             using namespace Details;
00037
00038             if (sessionState == nullptr)
00039             {
00040                 sessionState = ref new PropertySet();
00041             }
00042             return sessionState;
00043         }
00044
00045         static concurrency::task<void> StartRestoreTask()
00046         {
00047             using namespace Windows::Foundation;
00048             using namespace Windows::Storage;
00049             using namespace Windows::Storage::Streams;
00050             using namespace Details;
00051
00052             auto state = SessionState();
00053             state->Clear();
00054
00055             concurrency::task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFileName));
00056             return getFileTask.then([=](StorageFile^ file)
00057             {
00058                 return DeserializeSessionState(file);
00059             });
00060         }
00061
00062         static concurrency::task<void> StartSaveTask()
00063         {
00064             using namespace Windows::Foundation;
00065             using namespace Windows::Storage;
00066             using namespace Windows::Storage::Streams;
00067             using namespace Details;
00068
00069             concurrency::task<StorageFile^> createFileTask(ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFileName, CreationCollisionOption::ReplaceExisting));
00070             return createFileTask.then([=](StorageFile^ file)
00071             {
00072                 return SerializeSessionState(file);
00073             });
00074         }
00075     };
00076
00077     namespace Details
00078     {
00079         template <class T>
00080         inline Platform::String^ ToString(T value)
00081         {
00082             std::wstringstream wss;
00083             wss << value;
00084             return ref new Platform::String(wss.str().c_str());
00085         }
00086
00087         template <class T>
00088         inline T FromStringTo(Platform::String^ str)
00089         {
00090             std::wistringstream wiss(str->Data());
00091             T value = 0;
00092             wiss >> value;
00093             return value;
00094         }
00095
00096         template <class T>
00097         inline T FromHexStringTo(Platform::String^ str)
00098         {
00099             std::wistringstream wiss(str->Data());
00100             T value = 0;
00101             wiss >> std::hex >> value;
00102             return value;
00103         }
00104
00105         template <>
00106         inline Platform::Guid FromStringTo<Platform::Guid>(Platform::String^ str)
00107         {
00108             using namespace Platform;
00109
00110             if (str->Length() != 38)
00111             {
00112                 throw ref new InvalidArgumentException;
00113             }
00114             std::wstring ws(str->Data());
00115             if (ws[0] != L'{' || ws[37] != L'}' || ws[9] != L'-' || ws[14] != L'-' || ws[19] != L'-' || ws[24] != L'-')
00116             {
00117                 throw ref new InvalidArgumentException;
00118             }
00119             ws[0] = ws[37] = ws[9] = ws[14] = ws[19] =ws[24] = L' ';
00120             std::wistringstream wiss(ws);
00121             unsigned int a = 0;
00122             unsigned short b = 0;
00123             unsigned short c = 0;
00124             unsigned short d = 0;
00125             unsigned long long e = 0;
00126             static_assert(sizeof(d) == sizeof(char) * 2, "sizeof(d) == sizeof(char) * 2");
00127             static_assert(sizeof(e) == sizeof(char) * 8, "sizeof(e) == sizeof(char) * 8");
00128             wiss >> std::hex >> a >> b >> c >> d >> e;
00129             unsigned char *ad = (unsigned char*)(&d);
00130             unsigned char *ae = (unsigned char*)(&e);
00131             return Platform::Guid(a, b, c, ad[1], ad[0], ae[5], ae[4], ae[3], ae[2], ae[1], ae[0]);
00132         }
00133
00134         inline Platform::Object^ ConvertStringToObject(Windows::Foundation::PropertyType type, Platform::String^ str)
00135         {
00136             using namespace Platform;
00137             using namespace Windows::Foundation;
00138
00139             if (type == PropertyType::String)
00140             {
00141                 return PropertyValue::CreateString(str);
00142             }
00143
00144             switch (type)
00145             {
00146             case PropertyType::UInt8:
00147                 return PropertyValue::CreateUInt8((unsigned char)FromStringTo<unsigned short>(str));
00148             case PropertyType::UInt16:
00149                 return PropertyValue::CreateUInt16(FromStringTo<unsigned short>(str));
00150             case PropertyType::UInt32:
00151                 return PropertyValue::CreateUInt32(FromStringTo<unsigned int>(str));
00152             case PropertyType::UInt64:
00153                 return PropertyValue::CreateUInt64(FromStringTo<unsigned long long>(str));
00154             case PropertyType::Int16:
00155                 return PropertyValue::CreateInt16(FromStringTo<short>(str));
00156             case PropertyType::Int32:
00157                 return PropertyValue::CreateInt32(FromStringTo<int>(str));
00158             case PropertyType::Int64:
00159                 return PropertyValue::CreateInt64(FromStringTo<long long>(str));
00160             case PropertyType::Single:
00161                 return PropertyValue::CreateSingle(FromStringTo<float>(str));
00162             case PropertyType::Double:
00163                 return PropertyValue::CreateDouble(FromStringTo<double>(str));
00164             case PropertyType::Boolean:
00165                 return PropertyValue::CreateBoolean(FromStringTo<bool>(str));
00166             case PropertyType::Char16:
00167                 return PropertyValue::CreateChar16(str->Data()[0]);
00168             case PropertyType::Guid:
00169                 return PropertyValue::CreateGuid(FromStringTo<Guid>(str));
00170             default:
00171                 throw ref new Platform::InvalidCastException;
00172             }
00173         }
00174
00175         inline Platform::String^ ConvertPropertyValueToString(Windows::Foundation::IPropertyValue^ pv)
00176         {
00177             using namespace Platform;
00178             using namespace Windows::Foundation;
00179
00180             String^ valueString;
00181
00182             switch (pv->Type)
00183             {
00184             case PropertyType::String:
00185                 valueString = pv->GetString();
00186                 break;
00187
00188             case PropertyType::UInt8:
00189             case PropertyType::UInt16:
00190             case PropertyType::UInt32:
00191             case PropertyType::UInt64:
00192                 valueString = ToString(pv->GetUInt64());
00193                 break;
00194
00195             case PropertyType::Int16:
00196             case PropertyType::Int32:
00197             case PropertyType::Int64:
00198                 valueString = ToString(pv->GetInt64());
00199                 break;
00200
00201             case PropertyType::Single:
00202                 valueString = ToString(pv->GetSingle());
00203                 break;
00204
00205             case PropertyType::Double:
00206                 valueString = ToString(pv->GetDouble());
00207                 break;
00208
00209             case PropertyType::Boolean:
00210                 valueString = ToString(pv->GetBoolean());
00211                 break;
00212
00213             case PropertyType::Char16:
00214                 wchar_t buffer[2];
00215                 buffer[0] = pv->GetChar16();
00216                 buffer[1] = 0;
00217                 valueString = ref new String(buffer);
00218                 break;
00219
00220             case PropertyType::Guid:
00221                 valueString = pv->GetGuid().ToString();
00222                 break;
00223
00224             default:
00225                 throw ref new InvalidCastException;
00226             }
00227
00228             return valueString;
00229         }
00230
00231         inline Windows::Data::Xml::Dom::XmlElement^ CreateXmlElementFromObject(Windows::Data::Xml::Dom::XmlDocument^ doc, Platform::String^ name, Platform::Object^ value)
00232         {
00233             using namespace Platform;
00234             using namespace Windows::Foundation;
00235             using namespace Windows::Data::Xml::Dom;
00236
00237             XmlElement^ element = doc->CreateElement("item");
00238             element->SetAttribute("name", name);
00239
00240             IPropertyValue^ pv = (IPropertyValue^)value;
00241             element->SetAttribute("type", ToString((int)pv->Type));
00242             element->SetAttribute("value", ConvertPropertyValueToString(pv));
00243
00244             return element;
00245         }
00246
00247         inline concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file)
00248         {
00249             using namespace Windows::Data::Xml::Dom;
00250             using namespace Windows::Foundation;
00251             namespace WFC = Windows::Foundation::Collections;
00252             typedef Windows::Foundation::Collections::IKeyValuePair<Platform::String^, Platform::Object^> KVPair;
00253
00254             XmlDocument^ doc = ref new XmlDocument;
00255             doc->AppendChild(doc->CreateElement("items"));
00256             auto sessionState = SuspensionManager::SessionState();
00257
00258             std::for_each(WFC::begin(sessionState), WFC::end(sessionState), [doc](KVPair^ item)
00259             {
00260                 doc->DocumentElement->AppendChild(CreateXmlElementFromObject(doc, item->Key, item->Value));
00261             });
00262
00263             return concurrency::task<void>(doc->SaveToFileAsync(file));
00264         }
00265
00266         inline Windows::Foundation::PropertyType PropertyTypeFromString(Platform::String^ str)
00267         {
00268             int value = FromStringTo<int>(str);
00269             return (Windows::Foundation::PropertyType)value;
00270         }
00271
00272         inline concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file)
00273         {
00274             using namespace Platform;
00275             using namespace Windows::Foundation;
00276             using namespace Windows::Data::Xml::Dom;
00277             namespace WFC = Windows::Foundation::Collections;
00278
00279             concurrency::task<XmlDocument^> loadFileTask(XmlDocument::LoadFromFileAsync(file));
00280             return loadFileTask.then([=](concurrency::task<XmlDocument^> docTask)
00281             {
00282                 try
00283                 {
00284                     auto doc = docTask.get();
00285                     auto items = doc->SelectNodes("/items/item");
00286                     auto sessionState = SuspensionManager::SessionState();
00287
00288                     std::for_each(WFC::begin(items), WFC::end(items), [sessionState](IXmlNode^ node)
00289                     {
00290                         auto element = (IXmlElement^)node;
00291                         String^ name = element->GetAttribute("name");
00292                         String^ value = element->GetAttribute("value");
00293                         PropertyType type = PropertyTypeFromString(element->GetAttribute("type"));
00294
00295                         Object^ valueObject = ConvertStringToObject(type, value);
00296                         sessionState->Insert(name, valueObject);
00297                     });
00298
00299                 }
00300                 catch (Platform::Exception^)
00301                 {
00302                     // Restoring is best effort
00303                 }
00304             });
00305         }
00306     } // namespace Details
00307 } // namespace CppSamplesUtils
Generated on Sat Nov 23 2024 16:07:53 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D bump mapping/C++/DirectXSample.h Source File

  • Direct3D bump mapping

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
00010 // This header defines helper utilities to make DirectX APIs work with exceptions.
00011 namespace DX
00012 {
00013     inline void ThrowIfFailed(HRESULT hr)
00014     {
00015         if (FAILED(hr))
00016         {
00017             // Set a breakpoint on this line to catch DX API errors.
00018             throw Platform::Exception::CreateException(hr);
00019         }
00020     }
00021 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/MediaExtensions/Mpeg1Decoder/decoder.cpp Source File

  • Media extensions
  • MediaExtensions
  • Mpeg1Decoder

decoder.cpp

Go to the documentation of this file.
00001 //////////////////////////////////////////////////////////////////////////
00002 //
00003 // decoder.cpp
00004 // Implements the MPEG-1 decoder.
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 #include "decoder.h"
00016 #include "BufferLock.h"
00017 #include <strsafe.h>
00018
00019 void    OurFillRect(PBYTE pbScanline0, DWORD dwWidth, DWORD dwHeight, LONG lStrideInBytes, COLORREF color);
00020
00021 #ifndef LODWORD
00022 #define LODWORD(x)  ((DWORD)(((DWORD_PTR)(x)) & 0xffffffff))
00023 #endif
00024
00025 const UINT32 MAX_VIDEO_WIDTH = 4095;        // per ISO/IEC 11172-2
00026 const UINT32 MAX_VIDEO_HEIGHT = 4095;
00027
00028 //-------------------------------------------------------------------
00029 // CDecoder class
00030 //-------------------------------------------------------------------
00031
00032 CDecoder::CDecoder() :
00033     m_pInputType(nullptr),
00034     m_pOutputType(nullptr),
00035     m_pBuffer(nullptr),
00036     m_pbData(nullptr),
00037     m_cbData(0),
00038     m_imageWidthInPixels(0),
00039     m_imageHeightInPixels(0),
00040     m_cbImageSize(0),
00041     m_rtFrame(0),
00042     m_rtLength(0),
00043     m_bPicture(false),
00044     m_bLowLatencyMode(false)
00045 {
00046     InitializeCriticalSectionEx(&m_critSec, 100, 0);
00047
00048     m_frameRate.Numerator = m_frameRate.Denominator = 0;
00049
00050 }
00051
00052 CDecoder::~CDecoder()
00053 {
00054     SafeRelease(&m_pBuffer);
00055     DeleteCriticalSection(&m_critSec);
00056 }
00057
00058 // IMediaExtension methods
00059
00060 //-------------------------------------------------------------------
00061 // Name: SetProperties
00062 // Sets the configuration of the decoder
00063 //-------------------------------------------------------------------
00064 IFACEMETHODIMP CDecoder::SetProperties (ABI::Windows::Foundation::Collections::IPropertySet *pConfiguration)
00065 {
00066     return S_OK;
00067 }
00068
00069 // IMFTransform methods. Refer to the Media Foundation SDK documentation for details.
00070
00071 //-------------------------------------------------------------------
00072 // Name: GetStreamLimits
00073 // Returns the minimum and maximum number of streams.
00074 //-------------------------------------------------------------------
00075
00076 HRESULT CDecoder::GetStreamLimits(
00077     DWORD   *pdwInputMinimum,
00078     DWORD   *pdwInputMaximum,
00079     DWORD   *pdwOutputMinimum,
00080     DWORD   *pdwOutputMaximum
00081 )
00082 {
00083
00084     if ((pdwInputMinimum == NULL) ||
00085         (pdwInputMaximum == NULL) ||
00086         (pdwOutputMinimum == NULL) ||
00087         (pdwOutputMaximum == NULL))
00088     {
00089         return E_POINTER;
00090     }
00091
00092
00093     // This MFT has a fixed number of streams.
00094     *pdwInputMinimum = 1;
00095     *pdwInputMaximum = 1;
00096     *pdwOutputMinimum = 1;
00097     *pdwOutputMaximum = 1;
00098
00099     return S_OK;
00100 }
00101
00102
00103 //-------------------------------------------------------------------
00104 // Name: GetStreamCount
00105 // Returns the actual number of streams.
00106 //-------------------------------------------------------------------
00107
00108 HRESULT CDecoder::GetStreamCount(
00109     DWORD   *pcInputStreams,
00110     DWORD   *pcOutputStreams
00111 )
00112 {
00113     if ((pcInputStreams == NULL) || (pcOutputStreams == NULL))
00114
00115     {
00116         return E_POINTER;
00117     }
00118
00119     // This MFT has a fixed number of streams.
00120     *pcInputStreams = 1;
00121     *pcOutputStreams = 1;
00122
00123     return S_OK;
00124 }
00125
00126
00127
00128 //-------------------------------------------------------------------
00129 // Name: GetStreamIDs
00130 // Returns stream IDs for the input and output streams.
00131 //-------------------------------------------------------------------
00132
00133 HRESULT CDecoder::GetStreamIDs(
00134     DWORD   /*dwInputIDArraySize*/,
00135     DWORD   * /*pdwInputIDs*/,
00136     DWORD   /*dwOutputIDArraySize*/,
00137     DWORD   * /*pdwOutputIDs*/
00138 )
00139 {
00140     // Do not need to implement, because this MFT has a fixed number of
00141     // streams and the stream IDs match the stream indexes.
00142     return E_NOTIMPL;
00143 }
00144
00145
00146 //-------------------------------------------------------------------
00147 // Name: GetInputStreamInfo
00148 // Returns information about an input stream.
00149 //-------------------------------------------------------------------
00150
00151 HRESULT CDecoder::GetInputStreamInfo(
00152     DWORD                     dwInputStreamID,
00153     MFT_INPUT_STREAM_INFO *   pStreamInfo
00154 )
00155 {
00156     if (pStreamInfo == NULL)
00157     {
00158         return E_POINTER;
00159     }
00160
00161     if (!IsValidInputStream(dwInputStreamID))
00162     {
00163         return MF_E_INVALIDSTREAMNUMBER;
00164     }
00165
00166     pStreamInfo->hnsMaxLatency = 0;
00167
00168     //  We can process data on any boundary.
00169     pStreamInfo->dwFlags = 0;
00170
00171     pStreamInfo->cbSize = 1;
00172     pStreamInfo->cbMaxLookahead = 0;
00173     pStreamInfo->cbAlignment = 1;
00174
00175     return S_OK;
00176 }
00177
00178
00179
00180 //-------------------------------------------------------------------
00181 // Name: GetOutputStreamInfo
00182 // Returns information about an output stream.
00183 //-------------------------------------------------------------------
00184
00185 HRESULT CDecoder::GetOutputStreamInfo(
00186     DWORD                     dwOutputStreamID,
00187     MFT_OUTPUT_STREAM_INFO *  pStreamInfo
00188 )
00189 {
00190     if (pStreamInfo == NULL)
00191     {
00192         return E_POINTER;
00193     }
00194
00195     if (!IsValidOutputStream(dwOutputStreamID))
00196     {
00197         return MF_E_INVALIDSTREAMNUMBER;
00198     }
00199
00200     EnterCriticalSection(&m_critSec);
00201
00202     // NOTE: This method should succeed even when there is no media type on the
00203     //       stream. If there is no media type, we only need to fill in the dwFlags
00204     //       member of MFT_OUTPUT_STREAM_INFO. The other members depend on having a
00205     //       a valid media type.
00206
00207     pStreamInfo->dwFlags =
00208         MFT_OUTPUT_STREAM_WHOLE_SAMPLES |
00209         MFT_OUTPUT_STREAM_SINGLE_SAMPLE_PER_BUFFER |
00210         MFT_OUTPUT_STREAM_FIXED_SAMPLE_SIZE ;
00211
00212     if (m_pOutputType == NULL)
00213     {
00214         pStreamInfo->cbSize = 0;
00215         pStreamInfo->cbAlignment = 0;
00216     }
00217     else
00218     {
00219         pStreamInfo->cbSize = m_cbImageSize;
00220         pStreamInfo->cbAlignment = 1;
00221     }
00222
00223     LeaveCriticalSection(&m_critSec);
00224
00225     return S_OK;
00226 }
00227
00228
00229
00230 //-------------------------------------------------------------------
00231 // Name: GetAttributes
00232 // Returns the attributes for the MFT.
00233 //-------------------------------------------------------------------
00234
00235 HRESULT CDecoder::GetAttributes(IMFAttributes** /*pAttributes*/)
00236 {
00237     // This MFT does not support any attributes, so the method is not implemented.
00238     return E_NOTIMPL;
00239 }
00240
00241
00242
00243 //-------------------------------------------------------------------
00244 // Name: GetInputStreamAttributes
00245 // Returns stream-level attributes for an input stream.
00246 //-------------------------------------------------------------------
00247
00248 HRESULT CDecoder::GetInputStreamAttributes(
00249     DWORD           /*dwInputStreamID*/,
00250     IMFAttributes   ** /*ppAttributes*/
00251 )
00252 {
00253     // This MFT does not support any attributes, so the method is not implemented.
00254     return E_NOTIMPL;
00255 }
00256
00257
00258
00259 //-------------------------------------------------------------------
00260 // Name: GetOutputStreamAttributes
00261 // Returns stream-level attributes for an output stream.
00262 //-------------------------------------------------------------------
00263
00264 HRESULT CDecoder::GetOutputStreamAttributes(
00265     DWORD           /*dwOutputStreamID*/,
00266     IMFAttributes   ** /*ppAttributes*/
00267 )
00268 {
00269     // This MFT does not support any attributes, so the method is not implemented.
00270     return E_NOTIMPL;
00271 }
00272
00273
00274
00275 //-------------------------------------------------------------------
00276 // Name: DeleteInputStream
00277 //-------------------------------------------------------------------
00278
00279 HRESULT CDecoder::DeleteInputStream(DWORD /*dwStreamID*/)
00280 {
00281     // This MFT has a fixed number of input streams, so the method is not implemented.
00282     return E_NOTIMPL;
00283 }
00284
00285
00286
00287 //-------------------------------------------------------------------
00288 // Name: AddInputStreams
00289 //-------------------------------------------------------------------
00290
00291 HRESULT CDecoder::AddInputStreams(
00292     DWORD   /*cStreams*/,
00293     DWORD   * /*adwStreamIDs*/
00294 )
00295 {
00296     // This MFT has a fixed number of output streams, so the method is not implemented.
00297     return E_NOTIMPL;
00298 }
00299
00300
00301
00302 //-------------------------------------------------------------------
00303 // Name: GetInputAvailableType
00304 // Description: Return a preferred input type.
00305 //-------------------------------------------------------------------
00306
00307 HRESULT CDecoder::GetInputAvailableType(
00308     DWORD           /*dwInputStreamID*/,
00309     DWORD           /*dwTypeIndex*/,
00310     IMFMediaType    ** /*ppType*/
00311 )
00312 {
00313     return MF_E_NO_MORE_TYPES;
00314 }
00315
00316
00317
00318 //-------------------------------------------------------------------
00319 // Name: GetOutputAvailableType
00320 // Description: Return a preferred output type.
00321 //-------------------------------------------------------------------
00322
00323 HRESULT CDecoder::GetOutputAvailableType(
00324     DWORD           dwOutputStreamID,
00325     DWORD           dwTypeIndex, // 0-based
00326     IMFMediaType    **ppType
00327 )
00328 {
00329     if (ppType == NULL)
00330     {
00331         return E_INVALIDARG;
00332     }
00333
00334     if (!IsValidOutputStream(dwOutputStreamID))
00335     {
00336         return MF_E_INVALIDSTREAMNUMBER;
00337     }
00338
00339     if (dwTypeIndex != 0)
00340     {
00341         return MF_E_NO_MORE_TYPES;
00342     }
00343
00344     EnterCriticalSection(&m_critSec);
00345
00346     HRESULT hr = S_OK;
00347
00348     IMFMediaType *pOutputType = NULL;
00349
00350     if (m_pInputType == NULL)
00351     {
00352         hr = MF_E_TRANSFORM_TYPE_NOT_SET;
00353     }
00354
00355     if (SUCCEEDED(hr))
00356     {
00357         hr = MFCreateMediaType(&pOutputType);
00358     }
00359
00360     if (SUCCEEDED(hr))
00361     {
00362         hr = pOutputType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video);
00363     }
00364
00365     if (SUCCEEDED(hr))
00366     {
00367         hr = pOutputType->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_RGB32);
00368     }
00369
00370     if (SUCCEEDED(hr))
00371     {
00372         hr = pOutputType->SetUINT32(MF_MT_FIXED_SIZE_SAMPLES, TRUE);
00373     }
00374
00375     if (SUCCEEDED(hr))
00376     {
00377         hr = pOutputType->SetUINT32(MF_MT_ALL_SAMPLES_INDEPENDENT, TRUE);
00378     }
00379
00380     if (SUCCEEDED(hr))
00381     {
00382         hr = pOutputType->SetUINT32(MF_MT_SAMPLE_SIZE, m_imageHeightInPixels * m_imageWidthInPixels * 4);
00383     }
00384
00385     if (SUCCEEDED(hr))
00386     {
00387         hr = MFSetAttributeSize(pOutputType, MF_MT_FRAME_SIZE, m_imageWidthInPixels, m_imageHeightInPixels);
00388     }
00389
00390     if (SUCCEEDED(hr))
00391     {
00392         hr = MFSetAttributeRatio(pOutputType, MF_MT_FRAME_RATE, m_frameRate.Numerator, m_frameRate.Denominator);
00393     }
00394
00395     if (SUCCEEDED(hr))
00396     {
00397         hr = pOutputType->SetUINT32(MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive);
00398     }
00399
00400     if (SUCCEEDED(hr))
00401     {
00402         hr = MFSetAttributeRatio(pOutputType, MF_MT_PIXEL_ASPECT_RATIO, 1, 1);
00403     }
00404
00405     if (SUCCEEDED(hr))
00406     {
00407         *ppType = pOutputType;
00408         (*ppType)->AddRef();
00409     }
00410
00411     SafeRelease(&pOutputType);
00412     LeaveCriticalSection(&m_critSec);
00413     return hr;
00414 }
00415
00416
00417
00418 //-------------------------------------------------------------------
00419 // Name: SetInputType
00420 //-------------------------------------------------------------------
00421
00422 HRESULT CDecoder::SetInputType(
00423     DWORD           dwInputStreamID,
00424     IMFMediaType    *pType, // Can be NULL to clear the input type.
00425     DWORD           dwFlags
00426 )
00427 {
00428     if (!IsValidInputStream(dwInputStreamID))
00429     {
00430         return MF_E_INVALIDSTREAMNUMBER;
00431     }
00432
00433     // Validate flags.
00434     if (dwFlags & ~MFT_SET_TYPE_TEST_ONLY)
00435     {
00436         return E_INVALIDARG;
00437     }
00438
00439     HRESULT hr = S_OK;
00440
00441     EnterCriticalSection(&m_critSec);
00442
00443     // Does the caller want us to set the type, or just test it?
00444     BOOL bReallySet = ((dwFlags & MFT_SET_TYPE_TEST_ONLY) == 0);
00445
00446     // If we have an input sample, the client cannot change the type now.
00447     if (HasPendingOutput())
00448     {
00449         hr = MF_E_TRANSFORM_CANNOT_CHANGE_MEDIATYPE_WHILE_PROCESSING;
00450     }
00451
00452     // Validate the type, if non-NULL.
00453     if (SUCCEEDED(hr))
00454     {
00455         if (pType)
00456         {
00457             hr = OnCheckInputType(pType);
00458         }
00459     }
00460
00461     if (SUCCEEDED(hr))
00462     {
00463         // The type is OK.
00464         // Set the type, unless the caller was just testing.
00465         if (bReallySet)
00466         {
00467             hr = OnSetInputType(pType);
00468         }
00469     }
00470
00471     LeaveCriticalSection(&m_critSec);
00472     return hr;
00473 }
00474
00475
00476
00477 //-------------------------------------------------------------------
00478 // Name: SetOutputType
00479 //-------------------------------------------------------------------
00480
00481 HRESULT CDecoder::SetOutputType(
00482     DWORD           dwOutputStreamID,
00483     IMFMediaType    *pType, // Can be NULL to clear the output type.
00484     DWORD           dwFlags
00485 )
00486 {
00487     if (!IsValidOutputStream(dwOutputStreamID))
00488     {
00489         return MF_E_INVALIDSTREAMNUMBER;
00490     }
00491
00492     // Validate flags.
00493     if (dwFlags & ~MFT_SET_TYPE_TEST_ONLY)
00494     {
00495         return E_INVALIDARG;
00496     }
00497
00498     HRESULT hr = S_OK;
00499
00500     EnterCriticalSection(&m_critSec);
00501
00502     // Does the caller want us to set the type, or just test it?
00503      BOOL bReallySet = ((dwFlags & MFT_SET_TYPE_TEST_ONLY) == 0);
00504
00505     // If we have an input sample, the client cannot change the type now.
00506     if (HasPendingOutput())
00507     {
00508         hr = MF_E_TRANSFORM_CANNOT_CHANGE_MEDIATYPE_WHILE_PROCESSING;
00509     }
00510
00511     // Validate the type, if non-NULL.
00512     if (SUCCEEDED(hr))
00513     {
00514         if (pType)
00515         {
00516             hr = OnCheckOutputType(pType);
00517         }
00518     }
00519
00520     if (SUCCEEDED(hr))
00521     {
00522         if (bReallySet)
00523         {
00524             // The type is OK.
00525             // Set the type, unless the caller was just testing.
00526             hr = OnSetOutputType(pType);
00527         }
00528     }
00529
00530     LeaveCriticalSection(&m_critSec);
00531     return hr;
00532 }
00533
00534
00535
00536 //-------------------------------------------------------------------
00537 // Name: GetInputCurrentType
00538 // Description: Returns the current input type.
00539 //-------------------------------------------------------------------
00540
00541 HRESULT CDecoder::GetInputCurrentType(
00542     DWORD           dwInputStreamID,
00543     IMFMediaType    **ppType
00544 )
00545 {
00546     if (ppType == NULL)
00547     {
00548         return E_POINTER;
00549     }
00550
00551     if (!IsValidInputStream(dwInputStreamID))
00552     {
00553         return MF_E_INVALIDSTREAMNUMBER;
00554     }
00555
00556     EnterCriticalSection(&m_critSec);
00557
00558     HRESULT hr = S_OK;
00559
00560     if (!m_pInputType)
00561     {
00562         hr = MF_E_TRANSFORM_TYPE_NOT_SET;
00563     }
00564
00565     if (SUCCEEDED(hr))
00566     {
00567         *ppType = m_pInputType;
00568         (*ppType)->AddRef();
00569     }
00570
00571     LeaveCriticalSection(&m_critSec);
00572     return hr;
00573 }
00574
00575
00576
00577 //-------------------------------------------------------------------
00578 // Name: GetOutputCurrentType
00579 // Description: Returns the current output type.
00580 //-------------------------------------------------------------------
00581
00582 HRESULT CDecoder::GetOutputCurrentType(
00583     DWORD           dwOutputStreamID,
00584     IMFMediaType    **ppType
00585 )
00586 {
00587     if (ppType == NULL)
00588     {
00589         return E_POINTER;
00590     }
00591
00592     if (!IsValidOutputStream(dwOutputStreamID))
00593     {
00594         return MF_E_INVALIDSTREAMNUMBER;
00595     }
00596
00597     EnterCriticalSection(&m_critSec);
00598
00599     HRESULT hr = S_OK;
00600
00601     if (!m_pOutputType)
00602     {
00603         hr = MF_E_TRANSFORM_TYPE_NOT_SET;
00604     }
00605
00606     if (SUCCEEDED(hr))
00607     {
00608         *ppType = m_pOutputType;
00609         (*ppType)->AddRef();
00610     }
00611
00612     LeaveCriticalSection(&m_critSec);
00613     return hr;
00614 }
00615
00616
00617
00618 //-------------------------------------------------------------------
00619 // Name: GetInputStatus
00620 // Description: Query if the MFT is accepting more input.
00621 //-------------------------------------------------------------------
00622
00623 HRESULT CDecoder::GetInputStatus(
00624     DWORD           dwInputStreamID,
00625     DWORD           *pdwFlags
00626 )
00627 {
00628     if (pdwFlags == NULL)
00629     {
00630         return E_POINTER;
00631     }
00632
00633     if (!IsValidInputStream(dwInputStreamID))
00634     {
00635         return MF_E_INVALIDSTREAMNUMBER;
00636     }
00637
00638     EnterCriticalSection(&m_critSec);
00639
00640     // If we already have an input sample, we don't accept
00641     // another one until the client calls ProcessOutput or Flush.
00642     if (HasPendingOutput())
00643     {
00644         *pdwFlags = MFT_INPUT_STATUS_ACCEPT_DATA;
00645     }
00646     else
00647     {
00648         *pdwFlags = 0;
00649     }
00650
00651     LeaveCriticalSection(&m_critSec);
00652     return S_OK;
00653 }
00654
00655
00656
00657 //-------------------------------------------------------------------
00658 // Name: GetOutputStatus
00659 // Description: Query if the MFT can produce output.
00660 //-------------------------------------------------------------------
00661
00662 HRESULT CDecoder::GetOutputStatus(DWORD *pdwFlags)
00663 {
00664     if (pdwFlags == NULL)
00665     {
00666         return E_POINTER;
00667     }
00668
00669     EnterCriticalSection(&m_critSec);
00670
00671     // We can produce an output sample if (and only if)
00672     // we have an input sample.
00673     if (HasPendingOutput())
00674     {
00675         *pdwFlags = MFT_OUTPUT_STATUS_SAMPLE_READY;
00676     }
00677     else
00678     {
00679         *pdwFlags = 0;
00680     }
00681
00682     LeaveCriticalSection(&m_critSec);
00683     return S_OK;
00684 }
00685
00686
00687
00688 //-------------------------------------------------------------------
00689 // Name: SetOutputBounds
00690 // Sets the range of time stamps that the MFT will output.
00691 //-------------------------------------------------------------------
00692
00693 HRESULT CDecoder::SetOutputBounds(
00694     LONGLONG        /*hnsLowerBound*/,
00695     LONGLONG        /*hnsUpperBound*/
00696 )
00697 {
00698     // Implementation of this method is optional.
00699     return E_NOTIMPL;
00700 }
00701
00702
00703
00704 //-------------------------------------------------------------------
00705 // Name: ProcessEvent
00706 // Sends an event to an input stream.
00707 //-------------------------------------------------------------------
00708
00709 HRESULT CDecoder::ProcessEvent(
00710     DWORD              /*dwInputStreamID*/,
00711     IMFMediaEvent      * /*pEvent */
00712 )
00713 {
00714     // This MFT does not handle any stream events, so the method can
00715     // return E_NOTIMPL. This tells the pipeline that it can stop
00716     // sending any more events to this MFT.
00717     return E_NOTIMPL;
00718 }
00719
00720
00721
00722 //-------------------------------------------------------------------
00723 // Name: ProcessMessage
00724 //-------------------------------------------------------------------
00725
00726 HRESULT CDecoder::ProcessMessage(
00727     MFT_MESSAGE_TYPE    eMessage,
00728     ULONG_PTR           /*ulParam*/
00729 )
00730 {
00731     EnterCriticalSection(&m_critSec);
00732
00733     HRESULT hr = S_OK;
00734
00735     switch (eMessage)
00736     {
00737     case MFT_MESSAGE_COMMAND_FLUSH:
00738         // Flush the MFT.
00739         hr = OnFlush();
00740         break;
00741
00742     case MFT_MESSAGE_COMMAND_DRAIN:
00743         // Set the discontinuity flag on all of the input.
00744         hr = OnDiscontinuity();
00745         break;
00746
00747     case MFT_MESSAGE_SET_D3D_MANAGER:
00748         // The pipeline should never send this message unless the MFT
00749         // has the MF_SA_D3D_AWARE attribute set to TRUE. However, if we
00750         // do get this message, it's invalid and we don't implement it.
00751         hr = E_NOTIMPL;
00752         break;
00753
00754
00755     case MFT_MESSAGE_NOTIFY_BEGIN_STREAMING:
00756         hr = AllocateStreamingResources();
00757         break;
00758
00759     case MFT_MESSAGE_NOTIFY_END_STREAMING:
00760         hr = FreeStreamingResources();
00761         break;
00762
00763     // These messages do not require a response.
00764     case MFT_MESSAGE_NOTIFY_START_OF_STREAM:
00765     case MFT_MESSAGE_NOTIFY_END_OF_STREAM:
00766         break;
00767
00768     }
00769
00770     LeaveCriticalSection(&m_critSec);
00771     return hr;
00772 }
00773
00774
00775
00776 //-------------------------------------------------------------------
00777 // Name: ProcessInput
00778 // Description: Process an input sample.
00779 //-------------------------------------------------------------------
00780
00781 HRESULT CDecoder::ProcessInput(
00782     DWORD               dwInputStreamID,
00783     IMFSample           *pSample,
00784     DWORD               dwFlags
00785 )
00786 {
00787     if (pSample == NULL)
00788     {
00789         return E_POINTER;
00790     }
00791
00792     if (!IsValidInputStream(dwInputStreamID))
00793     {
00794         return MF_E_INVALIDSTREAMNUMBER;
00795     }
00796
00797     if (dwFlags != 0)
00798     {
00799         return E_INVALIDARG; // dwFlags is reserved and must be zero.
00800     }
00801
00802     EnterCriticalSection(&m_critSec);
00803
00804     HRESULT hr = S_OK;
00805     LONGLONG rtTimestamp = 0;
00806
00807     if (!m_pInputType || !m_pOutputType)
00808     {
00809         hr = MF_E_NOTACCEPTING;   // Client must set input and output types.
00810     }
00811     else if (HasPendingOutput())
00812     {
00813         hr = MF_E_NOTACCEPTING;   // We already have an input sample.
00814     }
00815
00816     // Convert to a single contiguous buffer.
00817     if (SUCCEEDED(hr))
00818     {
00819         // NOTE: This does not cause a copy unless there are multiple buffers
00820         hr = pSample->ConvertToContiguousBuffer(&m_pBuffer);
00821     }
00822
00823     if (SUCCEEDED(hr))
00824     {
00825         hr = m_pBuffer->Lock(&m_pbData, NULL, &m_cbData);
00826     }
00827
00828     if (SUCCEEDED(hr))
00829     {
00830         // Get the time stamp. It is OK if this call fails.
00831         if (FAILED(pSample->GetSampleTime(&rtTimestamp)))
00832         {
00833             rtTimestamp = INVALID_TIME;
00834         }
00835
00836         m_StreamState.TimeStamp(rtTimestamp);
00837
00838         hr = Process();
00839     }
00840
00841     LeaveCriticalSection(&m_critSec);
00842     return hr;
00843 }
00844
00845
00846
00847 //-------------------------------------------------------------------
00848 // Name: ProcessOutput
00849 // Description: Process an output sample.
00850 //-------------------------------------------------------------------
00851
00852 HRESULT CDecoder::ProcessOutput(
00853     DWORD                   dwFlags,
00854     DWORD                   cOutputBufferCount,
00855     MFT_OUTPUT_DATA_BUFFER  *pOutputSamples, // one per stream
00856     DWORD                   *pdwStatus
00857 )
00858 {
00859     // Check input parameters...
00860
00861     // There are no flags that we accept in this MFT.
00862     // The only defined flag is MFT_PROCESS_OUTPUT_DISCARD_WHEN_NO_BUFFER. This
00863     // flag only applies when the MFT marks an output stream as lazy or optional.
00864     // However there are no lazy or optional streams on this MFT, so the flag is
00865     // not valid.
00866     if (dwFlags != 0)
00867     {
00868         return E_INVALIDARG;
00869     }
00870
00871     if (pOutputSamples == NULL || pdwStatus == NULL)
00872     {
00873         return E_POINTER;
00874     }
00875
00876     // Must be exactly one output buffer.
00877     if (cOutputBufferCount != 1)
00878     {
00879         return E_INVALIDARG;
00880     }
00881
00882     // It must contain a sample.
00883     if (pOutputSamples[0].pSample == NULL)
00884     {
00885         return E_INVALIDARG;
00886     }
00887
00888     EnterCriticalSection(&m_critSec);
00889
00890     HRESULT hr = S_OK;
00891     DWORD cbData = 0;
00892
00893     IMFMediaBuffer *pOutput = NULL;
00894
00895     // If we don't have an input sample, we need some input before
00896     // we can generate any output.
00897     if (!HasPendingOutput())
00898     {
00899         hr = MF_E_TRANSFORM_NEED_MORE_INPUT;
00900     }
00901
00902     // Get the output buffer.
00903
00904     if (SUCCEEDED(hr))
00905     {
00906         hr = pOutputSamples[0].pSample->GetBufferByIndex(0, &pOutput);
00907     }
00908
00909     if (SUCCEEDED(hr))
00910     {
00911         hr = pOutput->GetMaxLength(&cbData);
00912     }
00913
00914     if (SUCCEEDED(hr))
00915     {
00916         if (cbData < m_cbImageSize)
00917         {
00918             hr = E_INVALIDARG;
00919         }
00920     }
00921
00922     if (SUCCEEDED(hr))
00923     {
00924         hr = InternalProcessOutput(pOutputSamples[0].pSample, pOutput);
00925     }
00926
00927     if (SUCCEEDED(hr))
00928     {
00929         //  Update our state
00930         m_bPicture = false;
00931
00932         //  Is there any more data to output at this point?
00933         if (S_OK == Process())
00934         {
00935             pOutputSamples[0].dwStatus |= MFT_OUTPUT_DATA_BUFFER_INCOMPLETE;
00936         }
00937     }
00938
00939     SafeRelease(&pOutput);
00940     LeaveCriticalSection(&m_critSec);
00941     return hr;
00942 }
00943
00944 // Private class methods
00945
00946
00947 HRESULT CDecoder::InternalProcessOutput(IMFSample *pSample, IMFMediaBuffer *pOutputBuffer)
00948 {
00949     VideoBufferLock buffer(pOutputBuffer);
00950
00951     HRESULT hr = S_OK;
00952
00953     BYTE *pbData = NULL;
00954     LONG lDefaultStride = 0;
00955     LONG lActualStride = 0;
00956
00957     DWORD dwTimeCode = 0;
00958     LONGLONG rt = 0;
00959     TCHAR szBuffer[20];
00960
00961     lDefaultStride = m_imageWidthInPixels * 4; // Works only for RGB32
00962
00963     if (SUCCEEDED(hr))
00964     {
00965         hr = buffer.LockBuffer(lDefaultStride, m_imageHeightInPixels, &pbData, &lActualStride);
00966     }
00967
00968     //  Generate our data
00969     if (SUCCEEDED(hr))
00970     {
00971         rt = m_StreamState.PictureTime(&dwTimeCode);
00972
00973         hr = StringCchPrintf(szBuffer, ARRAYSIZE(szBuffer),
00974             TEXT("%2.2d:%2.2d:%2.2d:%2.2d\0"),
00975              (dwTimeCode >> 19) & 0x1F,
00976              (dwTimeCode >> 13) & 0x3F,
00977              (dwTimeCode >> 6) & 0x3F,
00978               dwTimeCode & 0x3F
00979               );
00980     }
00981
00982     if (SUCCEEDED(hr))
00983     {
00984         // Update our bitmap with turquoise
00985         OurFillRect(pbData, m_imageWidthInPixels, m_imageHeightInPixels, lActualStride, RGB(0xFF,0x80,0x80));
00986         OurFillRect(pbData, m_imageWidthInPixels/2, m_imageHeightInPixels/2, lActualStride, RGB(0x00,0xff,0x00));
00987
00988     }
00989
00990     if (SUCCEEDED(hr))
00991     {
00992         hr = pOutputBuffer->SetCurrentLength(m_cbImageSize);
00993     }
00994
00995     // Clean point / key frame
00996     if (SUCCEEDED(hr))
00997     {
00998         hr = pSample->SetUINT32(MFSampleExtension_CleanPoint, TRUE);
00999     }
01000
01001     //  Set the timestamp
01002     //  Uncompressed video must always have a timestamp
01003
01004     if (SUCCEEDED(hr))
01005     {
01006         rt = m_StreamState.PictureTime(&dwTimeCode);
01007         if (rt == INVALID_TIME)
01008         {
01009             rt = m_rtFrame;
01010         }
01011         hr = pSample->SetSampleTime(rt);
01012     }
01013
01014     if (SUCCEEDED(hr))
01015     {
01016         hr = pSample->SetSampleDuration(m_rtLength);
01017
01018     }
01019
01020     if (SUCCEEDED(hr))
01021     {
01022         m_rtFrame = rt + m_rtLength;
01023     }
01024
01025     return hr;
01026 }
01027
01028
01029 HRESULT CDecoder::OnCheckInputType(IMFMediaType *pmt)
01030 {
01031     HRESULT hr = S_OK;
01032
01033     //  Check if the type is already set and if so reject any type that's not identical.
01034     if (m_pInputType)
01035     {
01036         DWORD dwFlags = 0;
01037         if (S_OK == m_pInputType->IsEqual(pmt, &dwFlags))
01038         {
01039             return S_OK;
01040         }
01041         else
01042         {
01043             return MF_E_INVALIDTYPE;
01044         }
01045     }
01046
01047     GUID majortype = { 0 };
01048     GUID subtype = { 0 };
01049     UINT32 width = 0, height = 0;
01050     MFRatio fps = { 0 };
01051     UINT32 cbSeqHeader = 0;
01052
01053     //  We accept MFMediaType_Video, MEDIASUBTYPE_MPEG1Video
01054
01055     hr = pmt->GetMajorType(&majortype);
01056
01057     if (SUCCEEDED(hr))
01058     {
01059         if (majortype != MFMediaType_Video)
01060         {
01061             hr = MF_E_INVALIDTYPE;
01062         }
01063     }
01064
01065     if (SUCCEEDED(hr))
01066     {
01067         hr = pmt->GetGUID(MF_MT_SUBTYPE, &subtype);
01068     }
01069
01070     if (SUCCEEDED(hr))
01071     {
01072         if (subtype != MFVideoFormat_MPG1)
01073         {
01074             hr = MF_E_INVALIDTYPE;
01075         }
01076     }
01077
01078     // At this point a real decoder would validate the MPEG-1 format.
01079
01080     // Validate the frame size.
01081
01082     if (SUCCEEDED(hr))
01083     {
01084         hr = MFGetAttributeSize(pmt, MF_MT_FRAME_SIZE, &width, &height);
01085     }
01086
01087     if (SUCCEEDED(hr))
01088     {
01089         if (width > MAX_VIDEO_WIDTH || height > MAX_VIDEO_HEIGHT)
01090         {
01091             hr = MF_E_INVALIDTYPE;
01092         }
01093     }
01094
01095     // Make sure there is a frame rate.
01096     // *** A real decoder would also validate this. ***
01097
01098     if (SUCCEEDED(hr))
01099     {
01100         hr = MFGetAttributeRatio(pmt, MF_MT_FRAME_RATE, (UINT32*)&fps.Numerator, (UINT32*)&fps.Denominator);
01101     }
01102
01103     // Check for a sequence header.
01104     // We don't actually look at it for this sample.
01105     // *** A real decoder would validate the sequence header. ***
01106
01107     if (SUCCEEDED(hr))
01108     {
01109         (void)pmt->GetBlobSize(MF_MT_MPEG_SEQUENCE_HEADER, &cbSeqHeader);
01110
01111         if (cbSeqHeader < MPEG1_VIDEO_SEQ_HEADER_MIN_SIZE)
01112         {
01113             hr = MF_E_INVALIDTYPE;
01114         }
01115     }
01116
01117     return hr;
01118 }
01119
01120
01121 HRESULT CDecoder::OnSetInputType(IMFMediaType *pmt)
01122 {
01123     HRESULT hr = S_OK;
01124
01125     SafeRelease(&m_pInputType);
01126
01127     hr = MFGetAttributeSize(pmt, MF_MT_FRAME_SIZE, &m_imageWidthInPixels, &m_imageHeightInPixels);
01128
01129     if (SUCCEEDED(hr))
01130     {
01131        hr = MFGetAttributeRatio(pmt, MF_MT_FRAME_RATE, (UINT32*)&m_frameRate.Numerator, (UINT32*)&m_frameRate.Denominator);
01132     }
01133
01134     // Also store the frame duration, derived from the frame rate.
01135     if (SUCCEEDED(hr))
01136     {
01137
01138         if (m_frameRate.Numerator == 0 || m_frameRate.Denominator == 0) {
01139             m_rtLength = 0;
01140             return E_FAIL;
01141         }
01142
01143         double fRate = (double)m_frameRate.Numerator / m_frameRate.Denominator;
01144
01145         m_rtLength = (UINT64)((10000000 / fRate) + 0.5);
01146     }
01147
01148     if (SUCCEEDED(hr))
01149     {
01150         m_cbImageSize = m_imageWidthInPixels * m_imageHeightInPixels * 4;
01151
01152         m_pInputType = pmt;
01153         m_pInputType->AddRef();
01154     }
01155
01156     return hr;
01157 }
01158
01159 HRESULT CDecoder::OnCheckOutputType(IMFMediaType *pmt)
01160 {
01161     //  Check if the type is already set and if so reject any type that's not identical.
01162     if (m_pOutputType)
01163     {
01164         DWORD dwFlags = 0;
01165         if (S_OK == m_pOutputType->IsEqual(pmt, &dwFlags))
01166         {
01167             return S_OK;
01168         }
01169         else
01170         {
01171             return MF_E_INVALIDTYPE;
01172         }
01173     }
01174
01175     if (m_pInputType == NULL)
01176     {
01177         return MF_E_TRANSFORM_TYPE_NOT_SET; // Input type must be set first.
01178     }
01179
01180
01181     HRESULT hr = S_OK;
01182     BOOL bMatch = FALSE;
01183
01184     IMFMediaType *pOurType = NULL;
01185
01186     // Make sure their type is a superset of our proposed output type.
01187     hr = GetOutputAvailableType(0, 0, &pOurType);
01188
01189     if (SUCCEEDED(hr))
01190     {
01191         hr = pOurType->Compare(pmt, MF_ATTRIBUTES_MATCH_OUR_ITEMS, &bMatch);
01192     }
01193
01194     if (SUCCEEDED(hr))
01195     {
01196         if (!bMatch)
01197         {
01198             hr = MF_E_INVALIDTYPE;
01199         }
01200     }
01201
01202     SafeRelease(&pOurType);
01203     return hr;
01204 }
01205
01206
01207 HRESULT CDecoder::OnSetOutputType(IMFMediaType *pmt)
01208 {
01209     SafeRelease(&m_pOutputType);
01210
01211     m_pOutputType = pmt;
01212     m_pOutputType->AddRef();
01213
01214     return S_OK;
01215 }
01216
01217
01218 HRESULT CDecoder::AllocateStreamingResources()
01219 {
01220     //  Reinitialize variables
01221     OnDiscontinuity();
01222
01223     return S_OK;
01224 }
01225
01226 HRESULT CDecoder::FreeStreamingResources()
01227 {
01228     return S_OK;
01229 }
01230
01231 HRESULT CDecoder::OnDiscontinuity()
01232 {
01233     //  Zero our timestamp
01234     m_rtFrame = 0;
01235
01236     //  No pictures yet
01237    m_bPicture   = false;
01238
01239    //  Reset state machine
01240    m_StreamState.Reset();
01241    return S_OK;
01242 }
01243
01244 HRESULT CDecoder::OnFlush()
01245 {
01246     OnDiscontinuity();
01247
01248     //  Release buffer
01249     SafeRelease(&m_pBuffer);
01250
01251     return S_OK;
01252 }
01253
01254
01255 //  Scan input data until either we're exhausted or we find
01256 //  a picture start code
01257 //  Note GOP time codes as we encounter them so we can
01258 //  output time codes
01259
01260 HRESULT CDecoder::Process()
01261 {
01262     //  Process bytes and update our state machine
01263     while (m_cbData && !m_bPicture)
01264     {
01265         m_bPicture = m_StreamState.NextByte(*m_pbData);
01266         m_cbData--;
01267         m_pbData++;
01268     }
01269
01270     //  Release buffer if we're done with it
01271     if (m_cbData == 0)
01272     {
01273         m_pBuffer->Unlock();
01274
01275         m_pbData = NULL;
01276
01277         SafeRelease(&m_pBuffer);
01278     }
01279
01280     //  assert that if have no picture to output then we ate all the data
01281     assert(m_bPicture || m_cbData == 0);
01282     return S_OK;
01283 }
01284
01285
01286 //-------------------------------------------------------------------
01287 // CStreamState
01288 //-------------------------------------------------------------------
01289 void CStreamState::TimeStamp(REFERENCE_TIME rt)
01290 {
01291     DWORD dwIndex = m_cbBytes >= 4 ? 0 : m_cbBytes;
01292
01293     m_arTS[dwIndex].bValid = true;
01294     m_arTS[dwIndex].rt = rt;
01295 }
01296
01297 void CStreamState::Reset()
01298 {
01299     m_cbBytes = 0;
01300     m_dwNextTimeCode = 0;
01301
01302     for (int i = 0; i < 4; i++) {
01303         m_arTS[i].bValid = false;
01304     }
01305 }
01306
01307 bool CStreamState::NextByte(BYTE bData)
01308 {
01309     assert(m_arTS[0].bValid);
01310
01311     switch (m_cbBytes)
01312     {
01313         case 0:
01314             if (bData == 0) {
01315                 m_cbBytes++;
01316             }
01317             return false;
01318
01319         case 1:
01320             if (bData == 0) {
01321                 m_cbBytes++;
01322             } else {
01323                 m_cbBytes = 0;
01324
01325                 //  Pick up new timestamp if there was one
01326                 if (m_arTS[1].bValid) {
01327                     m_arTS[0].rt = m_arTS[1].rt;
01328                     m_arTS[1].bValid = false;
01329                 }
01330             }
01331             return false;
01332
01333         case 2:
01334             if (bData == 1) {
01335                 m_cbBytes++;
01336             } else {
01337                 if (bData == 0) {
01338                    if (m_arTS[1].bValid) {
01339                        m_arTS[0].rt = m_arTS[1].rt;
01340                        m_arTS[1].bValid = false;
01341                    }
01342                    if (m_arTS[2].bValid) {
01343                        m_arTS[1] = m_arTS[2];
01344                        m_arTS[2].bValid = false;
01345                    }
01346                 } else {
01347                     //  Not 0 or 1, revert
01348                     m_cbBytes = 0;
01349
01350                     //  and pick up latest timestamp
01351                     if (m_arTS[1].bValid) {
01352                         m_arTS[0].rt = m_arTS[1].rt;
01353                         m_arTS[1].bValid = false;
01354                     }
01355                     if (m_arTS[2].bValid) {
01356                         m_arTS[0].rt = m_arTS[2].rt;
01357                         m_arTS[2].bValid = false;
01358                     }
01359                 }
01360             }
01361             return false;
01362
01363         case 3:
01364         {
01365             //  It's a start code
01366             //  Return the timestamp and reset everything
01367             m_rt = m_arTS[0].rt;
01368
01369             //  If it's a picture start code can't use this timestamp again.
01370             if (0 == bData) {
01371                 m_arTS[0].rt = INVALID_TIME;
01372                 m_cbBytes = 0;
01373             }
01374
01375             //  Catch up and clean out timestamps
01376             for (int i = 1; i < 4; i++) {
01377                 if (m_arTS[i].bValid) {
01378                     m_arTS[0].rt = m_arTS[i].rt;
01379                     m_arTS[i].bValid = false;
01380                 }
01381             }
01382
01383             // Picture start code?
01384             if (0 == bData) {
01385                 m_cbBytes = 0;
01386                 m_dwTimeCode = m_dwNextTimeCode;
01387                 m_dwNextTimeCode++;
01388                 return true;
01389             } else {
01390                 //  Is it a GOP start code?
01391                 if (bData == 0xb8) {
01392                     m_cbBytes++;
01393                 } else {
01394                     m_cbBytes = 0;
01395                 }
01396                 return false;
01397             }
01398         }
01399
01400         case 4:
01401         case 5:
01402         case 6:
01403         case 7:
01404             m_bGOPData[m_cbBytes - 4] = bData;
01405             m_cbBytes++;
01406
01407             if (m_cbBytes == 8) {
01408                 m_cbBytes = 0;
01409                 m_dwNextTimeCode = ((DWORD)m_bGOPData[0] << 17) +
01410                                    ((DWORD)m_bGOPData[1] << 9) +
01411                                    ((DWORD)m_bGOPData[2] << 1) +
01412                                    ((DWORD)m_bGOPData[3] >> 7);
01413             }
01414             return false;
01415     }
01416
01417     // Should never reach here
01418     return false;
01419 };
01420
01421
01422
01423 //-------------------------------------------------------------------
01424 // Static functions
01425 //-------------------------------------------------------------------
01426
01427
01428 //-------------------------------------------------------------------
01429 // OurFillRect
01430 //
01431 // Fills a bitmap with a specified color.
01432 //
01433 // pvih: Pointer to a VIDEOINFOHEADER structure that describes the
01434 //       bitmap.
01435 // pbData: Pointer to the start of the bitmap.
01436 // color: Fill color.
01437 //-------------------------------------------------------------------
01438
01439 void OurFillRect(PBYTE pbScanline0, DWORD dwWidth, DWORD dwHeight, LONG lStrideInBytes, COLORREF color)
01440 {
01441     PBYTE pbPixels = pbScanline0;
01442
01443     // For just filling we don't care which way up the bitmap is -
01444     // we just start at pbData
01445     for(DWORD dwCount = 0; dwCount < dwHeight; dwCount++) {
01446         DWORD *pWord = (DWORD *)pbPixels;
01447
01448         for(DWORD dwPixel = 0; dwPixel < dwWidth; dwPixel++) {
01449             pWord[dwPixel] = (DWORD)color;
01450         }
01451
01452         //  biWidth is the stride
01453         pbPixels += lStrideInBytes;
01454     }
01455 }
01456
01457
Generated on Sat Nov 23 2024 16:08:21 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Folder enumeration/C++/Scenario2.xaml.cpp Source File

  • Folder enumeration

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 SDKSample::FolderEnumeration;
00020
00021 using namespace concurrency;
00022 using namespace Platform;
00023 using namespace Windows::Foundation::Collections;
00024 using namespace Windows::Storage;
00025 using namespace Windows::Storage::Search;
00026 using namespace Windows::UI;
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     GroupByMonthButton->Click  += ref new RoutedEventHandler(this, &Scenario2::GroupByMonthButton_Click);
00035     GroupByRatingButton->Click += ref new RoutedEventHandler(this, &Scenario2::GroupByRatingButton_Click);
00036     GroupByTagButton->Click    += ref new RoutedEventHandler(this, &Scenario2::GroupByTagButton_Click);
00037 }
00038
00039 void Scenario2::GroupByMonthButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00040 {
00041     GroupByHelper(ref new QueryOptions(CommonFolderQuery::GroupByMonth));
00042 }
00043
00044 void Scenario2::GroupByRatingButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00045 {
00046     GroupByHelper(ref new QueryOptions(CommonFolderQuery::GroupByRating));
00047 }
00048
00049 void Scenario2::GroupByTagButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00050 {
00051     GroupByHelper(ref new QueryOptions(CommonFolderQuery::GroupByTag));
00052 }
00053
00054 void Scenario2::GroupByHelper(QueryOptions^ queryOptions)
00055 {
00056     OutputPanel->Children->Clear();
00057
00058     StorageFolder^ picturesFolder = KnownFolders::PicturesLibrary;
00059     StorageFolderQueryResult^ queryResult = picturesFolder->CreateFolderQueryWithOptions(queryOptions);
00060
00061     create_task(queryResult->GetFoldersAsync()).then([this](IVectorView<StorageFolder^>^ folders)
00062     {
00063         // Add all file retrieval tasks to an array of tasks
00064         std::vector<task<std::pair<StorageFolder^, IVectorView<StorageFile^>^>>> fileTasks;
00065         std::for_each(begin(folders), end(folders), [&fileTasks](StorageFolder^ folder)
00066         {
00067             auto getFilesTask = create_task(folder->GetFilesAsync());
00068             fileTasks.push_back(getFilesTask.then([folder](IVectorView<StorageFile^>^ files)
00069             {
00070                 // put the results in std::pair to create the association of folder and its files.
00071                 return std::pair<StorageFolder^, IVectorView<StorageFile^>^>(folder, files);
00072             }));
00073         });
00074
00075         // Aggregate the results of multiple asynchronous operations
00076         // so that they are returned after all are completed. This
00077         // ensures that all groups are displayed in order.
00078         when_all(fileTasks.begin(), fileTasks.end()).then([this, folders](std::vector<std::pair<StorageFolder^, IVectorView<StorageFile^>^>> folderContents)
00079         {
00080             std::for_each(begin(folderContents), end(folderContents), [this](std::pair<StorageFolder^, IVectorView<StorageFile^>^> folderContent)
00081             {
00082                 auto folder = folderContent.first;
00083                 auto files = folderContent.second;
00084
00085                 OutputPanel->Children->Append(CreateHeaderTextBlock(folder->DisplayName + " (" + files->Size.ToString() + ")"));
00086                 std::for_each(begin(files), end(files), [this](StorageFile^ file)
00087                 {
00088                     OutputPanel->Children->Append(CreateLineItemTextBlock(file->Name));
00089                 });
00090             });
00091         });
00092     });
00093 }
00094
00095 TextBlock^ Scenario2::CreateHeaderTextBlock(String^ contents)
00096 {
00097     TextBlock^ textBlock = ref new TextBlock();
00098     textBlock->Text = contents;
00099     textBlock->Style = static_cast<Xaml::Style^>(::Application::Current->Resources->Lookup("H2Style"));
00100     textBlock->TextWrapping = TextWrapping::Wrap;
00101     return textBlock;
00102 }
00103
00104 TextBlock^ Scenario2::CreateLineItemTextBlock(String^ contents)
00105 {
00106     TextBlock^ textBlock = ref new TextBlock();
00107     textBlock->Text = contents;
00108     textBlock->Style = static_cast<Xaml::Style^>(::Application::Current->Resources->Lookup("BasicTextStyle"));
00109     textBlock->TextWrapping = TextWrapping::Wrap;
00110     Thickness margin = textBlock->Margin;
00111     margin.Left = 20;
00112     textBlock->Margin = margin;
00113     return textBlock;
00114 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/MainPage.xaml.cpp Source File

  • XAML DirectX 3D shooting game

MainPage.xaml.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.xaml.h"
00010 #include "MainPage.xaml.h"
00011 #include "ProductItem.h"
00012
00013 using namespace Simple3DGameXaml;
00014
00015 using namespace Microsoft::WRL;
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::ViewManagement;
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::ApplicationModel::Store;
00030 using namespace concurrency;
00031
00032 //----------------------------------------------------------------------
00033
00034 MainPage::MainPage() :
00035     m_possiblePurchaseUpgrade(false)
00036 {
00037     InitializeComponent();
00038
00039 #ifdef USE_STORE_SIMULATOR
00040     ResetLicense->Visibility = ::Visibility::Visible;
00041 #endif
00042 }
00043
00044 //----------------------------------------------------------------------
00045
00046 void MainPage::SetApp(App^ app)
00047 {
00048     m_app = app;
00049 }
00050
00051 //----------------------------------------------------------------------
00052
00053 void MainPage::HideGameInfoOverlay()
00054 {
00055     VisualStateManager::GoToState(this, "NormalState", true);
00056
00057     StoreFlyout->IsOpen = false;
00058     StoreFlyout->Visibility = ::Visibility::Collapsed;
00059     GameAppBar->IsOpen = false;
00060 }
00061
00062 //----------------------------------------------------------------------
00063
00064 void MainPage::ShowGameInfoOverlay()
00065 {
00066     VisualStateManager::GoToState(this, "GameInfoOverlayState", true);
00067 }
00068
00069 //----------------------------------------------------------------------
00070
00071 void MainPage::SetAction(GameInfoOverlayCommand action)
00072 {
00073     // Enable only one of the four possible commands at the bottom of the
00074     // Game Info Overlay.
00075
00076     PlayAgain->Visibility = ::Visibility::Collapsed;
00077     PleaseWait->Visibility = ::Visibility::Collapsed;
00078     TapToContinue->Visibility = ::Visibility::Collapsed;
00079
00080     switch (action)
00081     {
00082     case GameInfoOverlayCommand::PlayAgain:
00083         PlayAgain->Visibility = ::Visibility::Visible;
00084         break;
00085     case GameInfoOverlayCommand::PleaseWait:
00086         PleaseWait->Visibility = ::Visibility::Visible;
00087         break;
00088     case GameInfoOverlayCommand::TapToContinue:
00089         TapToContinue->Visibility = ::Visibility::Visible;
00090         break;
00091     case GameInfoOverlayCommand::None:
00092         break;
00093     }
00094 }
00095
00096 //----------------------------------------------------------------------
00097
00098 void MainPage::SetGameLoading()
00099 {
00100     GameInfoOverlayTitle->Text = "Loading Resources";
00101
00102     Loading->Visibility = ::Visibility::Visible;
00103     Stats->Visibility = ::Visibility::Collapsed;
00104     LevelStart->Visibility = ::Visibility::Collapsed;
00105     PauseData->Visibility = ::Visibility::Collapsed;
00106     LoadingProgress->IsActive = true;
00107 }
00108
00109 //----------------------------------------------------------------------
00110
00111 void MainPage::SetGameStats(
00112     int maxLevel,
00113     int hitCount,
00114     int shotCount
00115     )
00116 {
00117     GameInfoOverlayTitle->Text = "Game Statistics";
00118     m_possiblePurchaseUpgrade = true;
00119     OptionalTrialUpgrade();
00120
00121     Loading->Visibility = ::Visibility::Collapsed;
00122     Stats->Visibility = ::Visibility::Visible;
00123     LevelStart->Visibility = ::Visibility::Collapsed;
00124     PauseData->Visibility = ::Visibility::Collapsed;
00125
00126     static const int bufferLength = 20;
00127     static char16 wsbuffer[bufferLength];
00128
00129     int length = swprintf_s(wsbuffer, bufferLength, L"%d", maxLevel);
00130     LevelsCompleted->Text = ref new Platform::String(wsbuffer, length);
00131
00132     length = swprintf_s(wsbuffer, bufferLength, L"%d", hitCount);
00133     TotalPoints->Text = ref new Platform::String(wsbuffer, length);
00134
00135     length = swprintf_s(wsbuffer, bufferLength, L"%d", shotCount);
00136     TotalShots->Text = ref new Platform::String(wsbuffer, length);
00137
00138     // High Score is not used for showing Game Statistics
00139     HighScoreTitle->Visibility = ::Visibility::Collapsed;
00140     HighScoreData->Visibility  = ::Visibility::Collapsed;
00141 }
00142
00143 //----------------------------------------------------------------------
00144
00145 void MainPage::SetGameOver(
00146     bool win,
00147     int maxLevel,
00148     int hitCount,
00149     int shotCount,
00150     int highScore
00151     )
00152 {
00153     if (win)
00154     {
00155         GameInfoOverlayTitle->Text = "You Won!";
00156         m_possiblePurchaseUpgrade = true;
00157         OptionalTrialUpgrade();
00158     }
00159     else
00160     {
00161         GameInfoOverlayTitle->Text = "Game Over";
00162         m_possiblePurchaseUpgrade = false;
00163         PurchaseUpgrade->Visibility = ::Visibility::Collapsed;
00164     }
00165     Loading->Visibility = ::Visibility::Collapsed;
00166     Stats->Visibility = ::Visibility::Visible;
00167     LevelStart->Visibility = ::Visibility::Collapsed;
00168     PauseData->Visibility = ::Visibility::Collapsed;
00169
00170     static const int bufferLength = 20;
00171     static char16 wsbuffer[bufferLength];
00172
00173     int length = swprintf_s(wsbuffer, bufferLength, L"%d", maxLevel);
00174     LevelsCompleted->Text = ref new Platform::String(wsbuffer, length);
00175
00176     length = swprintf_s(wsbuffer, bufferLength, L"%d", hitCount);
00177     TotalPoints->Text = ref new Platform::String(wsbuffer, length);
00178
00179     length = swprintf_s(wsbuffer, bufferLength, L"%d", shotCount);
00180     TotalShots->Text = ref new Platform::String(wsbuffer, length);
00181
00182     // Show High Score
00183     HighScoreTitle->Visibility = ::Visibility::Visible;
00184     HighScoreData->Visibility  = ::Visibility::Visible;
00185     length = swprintf_s(wsbuffer, bufferLength, L"%d", highScore);
00186     HighScore->Text = ref new Platform::String(wsbuffer, length);
00187 }
00188
00189 //----------------------------------------------------------------------
00190
00191 void MainPage::SetLevelStart(
00192     int level,
00193     Platform::String^ objective,
00194     float timeLimit,
00195     float bonusTime
00196     )
00197 {
00198     static const int bufferLength = 20;
00199     static char16 wsbuffer[bufferLength];
00200
00201     int length = swprintf_s(wsbuffer, bufferLength, L"Level %d", level);
00202     GameInfoOverlayTitle->Text = ref new Platform::String(wsbuffer, length);
00203
00204     Loading->Visibility = ::Visibility::Collapsed;
00205     Stats->Visibility = ::Visibility::Collapsed;
00206     LevelStart->Visibility = ::Visibility::Visible;
00207     PauseData->Visibility = ::Visibility::Collapsed;
00208
00209     Objective->Text = objective;
00210
00211     length = swprintf_s(wsbuffer, bufferLength, L"%6.1f sec", timeLimit);
00212     TimeLimit->Text = ref new Platform::String(wsbuffer, length);
00213
00214     if (bonusTime > 0.0)
00215     {
00216         BonusTimeTitle->Visibility = ::Visibility::Visible;
00217         BonusTimeData->Visibility  = ::Visibility::Visible;
00218         length = swprintf_s(wsbuffer, bufferLength, L"%6.1f sec", bonusTime);
00219         BonusTime->Text = ref new Platform::String(wsbuffer, length);
00220     }
00221     else
00222     {
00223         BonusTimeTitle->Visibility = ::Visibility::Collapsed;
00224         BonusTimeData->Visibility  = ::Visibility::Collapsed;
00225     }
00226 }
00227
00228 //----------------------------------------------------------------------
00229
00230 void MainPage::SetPause(int level, int hitCount, int shotCount, float timeRemaining)
00231 {
00232     GameInfoOverlayTitle->Text = "Paused";
00233     Loading->Visibility = ::Visibility::Collapsed;
00234     Stats->Visibility = ::Visibility::Collapsed;
00235     LevelStart->Visibility = ::Visibility::Collapsed;
00236     PauseData->Visibility = ::Visibility::Visible;
00237
00238     static const int bufferLength = 20;
00239     static char16 wsbuffer[bufferLength];
00240
00241     int length = swprintf_s(wsbuffer, bufferLength, L"%d", level);
00242     PauseLevel->Text = ref new Platform::String(wsbuffer, length);
00243
00244     length = swprintf_s(wsbuffer, bufferLength, L"%d", hitCount);
00245     PauseHits->Text = ref new Platform::String(wsbuffer, length);
00246
00247     length = swprintf_s(wsbuffer, bufferLength, L"%d", shotCount);
00248     PauseShots->Text = ref new Platform::String(wsbuffer, length);
00249
00250     length = swprintf_s(wsbuffer, bufferLength, L"%6.1f sec", timeRemaining);
00251     PauseTimeRemaining->Text = ref new Platform::String(wsbuffer, length);
00252 }
00253
00254 //----------------------------------------------------------------------
00255
00256 void MainPage::SetSnapped()
00257 {
00258     VisualStateManager::GoToState(this, "SnappedState", true);
00259 }
00260
00261 //----------------------------------------------------------------------
00262
00263 void MainPage::HideSnapped()
00264 {
00265     VisualStateManager::GoToState(this, "UnsnappedState", true);
00266 }
00267
00268 //----------------------------------------------------------------------
00269
00270 void MainPage::OnGameInfoOverlayTapped(Object^ /* sender */, TappedRoutedEventArgs^ /* args */)
00271 {
00272     m_app->PressComplete();
00273 }
00274
00275 //----------------------------------------------------------------------
00276
00277 void MainPage::OnPlayButtonClicked(Object^ /* sender */, RoutedEventArgs^ /* args */)
00278 {
00279     m_app->PressComplete();
00280 }
00281
00282 //----------------------------------------------------------------------
00283
00284 void MainPage::OnResetButtonClicked(Object^ /* sender */, RoutedEventArgs^ /* args */)
00285 {
00286     m_app->ResetGame();
00287     GameAppBar->IsOpen = false;
00288 }
00289
00290 //----------------------------------------------------------------------
00291
00292 void MainPage::LicenseChanged(
00293     ListingInformation^ listing,
00294     LicenseInformation^ license
00295     )
00296 {
00297     m_listingInformation = listing;
00298     m_licenseInformation = license;
00299
00300     // This function may be called from a different thread.
00301     // All XAML updates need to occur on the UI thread so dispatch to ensure this is true.
00302     Dispatcher->RunAsync(
00303         CoreDispatcherPriority::Normal,
00304         ref new DispatchedHandler([this]()
00305         {
00306             if (m_licenseInformation->IsActive)
00307             {
00308                 if (!m_licenseInformation->IsTrial)
00309                 {
00310                     PurchaseUpgrade->Visibility = ::Visibility::Collapsed;
00311                 }
00312             }
00313             else
00314             {
00315                 ChangeBackground->Visibility = ::Visibility::Collapsed;
00316             }
00317
00318             if (m_licenseInformation->IsActive && m_licenseInformation->IsTrial)
00319             {
00320                 if (m_listingInformation != nullptr)
00321                 {
00322                     PurchaseMessage->Text =
00323                         "You are running a trial version. Purchase the full version for: " + m_listingInformation->FormattedPrice;
00324                 }
00325                 else
00326                 {
00327                     PurchaseMessage->Text =
00328                         "You are running a trial version. Purchase the full version.";
00329                 }
00330                 if (m_possiblePurchaseUpgrade)
00331                 {
00332                     PurchaseUpgrade->Visibility = ::Visibility::Visible;
00333                 }
00334             }
00335
00336             if (m_licenseInformation != nullptr)
00337             {
00338                 auto items = dynamic_cast<Platform::Collections::Vector<Platform::Object^>^>(ProductListView->ItemsSource);
00339                 for (uint32 i = 0; i < items->Size; i++)
00340                 {
00341                     dynamic_cast<ProductItem^>(items->GetAt(i))->UpdateContent(m_licenseInformation);
00342                 }
00343             }
00344             if (m_listingInformation != nullptr)
00345             {
00346                 auto items = dynamic_cast<Platform::Collections::Vector<Platform::Object^>^>(ProductListView->ItemsSource);
00347                 for (uint32 i = 0; i < items->Size; i++)
00348                 {
00349                     dynamic_cast<ProductItem^>(items->GetAt(i))->UpdateContent(m_listingInformation);
00350                 }
00351             }
00352         })
00353         );
00354 }
00355
00356 //----------------------------------------------------------------------
00357
00358 void MainPage::OnBuyAppButtonTapped(Object^ sender, TappedRoutedEventArgs^ args)
00359 {
00360     args->Handled = true;
00361     OnBuySelectorClicked(sender, args);
00362 }
00363
00364 //----------------------------------------------------------------------
00365
00366 void MainPage::OnBuySelectorClicked(Object^ sender, RoutedEventArgs^ /* args */)
00367 {
00368     Platform::String^ tag = dynamic_cast<Platform::String^>(dynamic_cast<Button^>(sender)->CommandParameter);
00369     StoreUnavailable->Visibility = ::Visibility::Collapsed;
00370
00371     if (tag == "MainApp")
00372     {
00373         if ((m_licenseInformation != nullptr) && m_licenseInformation->IsActive)
00374         {
00375             if (m_licenseInformation->IsTrial)
00376             {
00377 #ifdef USE_STORE_SIMULATOR
00378                 task<Platform::String^> purchaseTask(CurrentAppSimulator::RequestAppPurchaseAsync(false));
00379 #else
00380                 task<Platform::String^> purchaseTask(CurrentApp::RequestAppPurchaseAsync(false));
00381 #endif
00382                 purchaseTask.then([this](task<Platform::String^> previousTask)
00383                 {
00384                     try
00385                     {
00386                         // Try getting all exceptions from the continuation chain above this point
00387                         previousTask.get();
00388                     }
00389                     catch (Platform::Exception^ exception)
00390                     {
00391                         if (exception->HResult == E_FAIL)
00392                         {
00393                             StoreUnavailable->Visibility = ::Visibility::Visible;
00394                         }
00395                     }
00396                 });
00397             }
00398         }
00399     }
00400     else
00401     {
00402         if ((m_licenseInformation != nullptr) && m_licenseInformation->IsActive && !m_licenseInformation->IsTrial)
00403         {
00404             if (!m_licenseInformation->ProductLicenses->Lookup(tag)->IsActive)
00405             {
00406 #ifdef USE_STORE_SIMULATOR
00407                 task<Platform::String^> purchaseTask(CurrentAppSimulator::RequestProductPurchaseAsync(tag, false));
00408 #else
00409                 task<Platform::String^> purchaseTask(CurrentApp::RequestProductPurchaseAsync(tag, false));
00410 #endif
00411                 purchaseTask.then([=](task<Platform::String^> previousTask)
00412                 {
00413                     try
00414                     {
00415                         // Try getting all exceptions from the continuation chain above this point
00416                         previousTask.get();
00417                     }
00418                     catch (Platform::Exception^ exception)
00419                     {
00420                         if (exception->HResult == E_FAIL)
00421                         {
00422                             StoreUnavailable->Visibility = ::Visibility::Visible;
00423                         }
00424                     }
00425                 });
00426             }
00427         }
00428     }
00429 }
00430
00431 //----------------------------------------------------------------------
00432
00433 void MainPage::OnChangeBackgroundButtonClicked(Object^ /* sender */, RoutedEventArgs^ /* args */)
00434 {
00435     if ((m_licenseInformation != nullptr) && m_licenseInformation->IsActive)
00436     {
00437         if (m_licenseInformation->IsTrial ||
00438             (!m_licenseInformation->ProductLicenses->Lookup("NightBackground")->IsActive  &&
00439             !m_licenseInformation->ProductLicenses->Lookup("DayBackground")->IsActive))
00440         {
00441             ShowStoreFlyout();
00442         }
00443         else
00444         {
00445             m_app->CycleBackground();
00446         }
00447     }
00448 }
00449
00450 //----------------------------------------------------------------------
00451
00452 void MainPage::OnResetLicenseButtonClicked(Object^ /* sender */, RoutedEventArgs^ /* args */)
00453 {
00454 #ifdef USE_STORE_SIMULATOR
00455     m_app->ResetLicense();
00456 #endif
00457     m_app->SetBackground(0);
00458 }
00459
00460 //----------------------------------------------------------------------
00461
00462 void MainPage::OptionalTrialUpgrade()
00463 {
00464     PurchaseUpgrade->Visibility = ::Visibility::Collapsed;
00465
00466     if (m_licenseInformation != nullptr)
00467     {
00468         if (m_licenseInformation->IsActive && m_licenseInformation->IsTrial)
00469         {
00470             if (m_listingInformation != nullptr)
00471             {
00472                 PurchaseMessage->Text =
00473                     "You are running a trial version. Purchase the full version for: " + m_listingInformation->FormattedPrice;
00474             }
00475             else
00476             {
00477                 PurchaseMessage->Text =
00478                     "You are running a trial version. Purchase the full version.";
00479             }
00480             PurchaseUpgrade->Visibility = ::Visibility::Visible;
00481         }
00482     }
00483 }
00484
00485 //----------------------------------------------------------------------
00486
00487 void MainPage::OnStoreReturnClicked(Object^ /* sender */, RoutedEventArgs^ /* args */)
00488 {
00489     StoreFlyout->IsOpen = false;
00490     StoreFlyout->Visibility = ::Visibility::Collapsed;
00491 }
00492
00493 //----------------------------------------------------------------------
00494
00495 void MainPage::OnLoadStoreClicked(Object^ /* sender */, RoutedEventArgs^ /* args */)
00496 {
00497     m_app->PauseRequested();
00498     ShowStoreFlyout();
00499 }
00500
00501 //----------------------------------------------------------------------
00502
00503 void MainPage::SetProductItems(
00504     ListingInformation^ listing,
00505     LicenseInformation^ license
00506     )
00507 {
00508     auto items = ref new Platform::Collections::Vector<Platform::Object^>();
00509     items->Append(ref new ProductItem(listing, license, "MainApp", true));
00510     items->Append(ref new ProductItem(listing, license, "AutoFire", false));
00511     items->Append(ref new ProductItem(listing, license, "NightBackground", false));
00512     items->Append(ref new ProductItem(listing, license, "DayBackground", false));
00513     ProductListView->ItemsSource = items;
00514     StoreUnavailable->Visibility = ::Visibility::Collapsed;
00515 }
00516
00517 //----------------------------------------------------------------------
00518
00519 void MainPage::OnWindowSizeChanged()
00520 {
00521     StoreGrid->Height = Window::Current->Bounds.Height;
00522     StoreFlyout->HorizontalOffset = Window::Current->Bounds.Width - StoreGrid->Width;
00523 }
00524
00525 //----------------------------------------------------------------------
00526
00527 void MainPage::OnAppBarOpened(Object^ /* sender */, Object^ /* args */)
00528 {
00529     m_app->PauseRequested();
00530 }
00531
00532 //----------------------------------------------------------------------
00533
00534 void MainPage::ShowStoreFlyout()
00535 {
00536     StoreGrid->Height = Window::Current->Bounds.Height;
00537     StoreUnavailable->Visibility = ::Visibility::Collapsed;
00538     StoreFlyout->HorizontalOffset = Window::Current->Bounds.Width - StoreGrid->Width;
00539     StoreFlyout->IsOpen = true;
00540     StoreFlyout->Visibility = ::Visibility::Visible;
00541     GameAppBar->IsOpen = false;
00542 }
00543
00544 //----------------------------------------------------------------------
Generated on Sat Nov 23 2024 16:07:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML Direct2D lighting effects/C++/pch.cpp Source File

  • XAML Direct2D lighting effects

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 //
00009 // Include the standard header and generate the precompiled header.
00010 //
00011
00012 #include "pch.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File picker contracts/C++/FileSavePicker_SaveToAppStorage.xaml.h Source File

  • File picker contracts

FileSavePicker_SaveToAppStorage.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 // FileSavePicker_SaveToAppStorage.xaml.h
00013 // Declaration of the FileSavePicker_SaveToAppStorage class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "FileSavePicker_SaveToAppStorage.g.h"
00020
00021 namespace SDKSample
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         [Windows::Foundation::Metadata::WebHostHidden]
00029         public ref class FileSavePicker_SaveToAppStorage sealed
00030         {
00031         public:
00032             FileSavePicker_SaveToAppStorage();
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         internal:
00039             Windows::Storage::Pickers::Provider::FileSavePickerUI^ fileSavePickerUI;
00040
00041         private:
00042             Platform::String^ fileID;
00043             Windows::Foundation::EventRegistrationToken token;
00044
00045             void OnTargetFileRequested(Windows::Storage::Pickers::Provider::FileSavePickerUI^ sender,  Windows::Storage::Pickers::Provider::TargetFileRequestedEventArgs^ e);
00046         };
00047     }
00048 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Simplified ink/C++/simpleInk.cpp Source File

  • Input Simplified ink

simpleInk.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 <ppltasks.h>
00010 #include "simpleInk.h"
00011
00012 #pragma region Helper functions
00013
00014 typedef enum
00015 {
00016     None,
00017     Ink,
00018     Select,
00019     Erase
00020 } PointerEventType;
00021
00022 bool EventIsErase(_In_ Windows::UI::Core::PointerEventArgs^ e)
00023 {
00024     auto pointerDevice = e->CurrentPoint->PointerDevice;
00025     auto pointerProperties = e->CurrentPoint->Properties;
00026
00027     bool rval = false
00028         || (pointerProperties->IsEraser)
00029         || (pointerDevice->PointerDeviceType == Windows::Devices::Input::PointerDeviceType::Pen && !pointerProperties->IsBarrelButtonPressed && pointerProperties->IsRightButtonPressed)
00030         || (pointerDevice->PointerDeviceType == Windows::Devices::Input::PointerDeviceType::Mouse && pointerProperties->IsRightButtonPressed);
00031
00032     return rval;
00033 }
00034
00035 bool EventIsInk(_In_ Windows::UI::Core::PointerEventArgs^ e)
00036 {
00037     auto pointerDevice = e->CurrentPoint->PointerDevice;
00038     auto pointerProperties = e->CurrentPoint->Properties;
00039
00040     bool rval = false
00041         || (pointerDevice->PointerDeviceType == Windows::Devices::Input::PointerDeviceType::Pen && !pointerProperties->IsBarrelButtonPressed && !pointerProperties->IsRightButtonPressed)
00042         || (pointerDevice->PointerDeviceType == Windows::Devices::Input::PointerDeviceType::Mouse && pointerProperties->IsLeftButtonPressed && e->KeyModifiers == Windows::System::VirtualKeyModifiers::None);
00043
00044     return rval;
00045 }
00046
00047 bool EventIsSelect(_In_ Windows::UI::Core::PointerEventArgs^ e)
00048 {
00049     auto pointerDevice = e->CurrentPoint->PointerDevice;
00050     auto pointerProperties = e->CurrentPoint->Properties;
00051
00052     bool rval = false
00053         || (pointerDevice->PointerDeviceType == Windows::Devices::Input::PointerDeviceType::Pen && pointerProperties->IsBarrelButtonPressed)
00054         || (pointerDevice->PointerDeviceType == Windows::Devices::Input::PointerDeviceType::Mouse && pointerProperties->IsLeftButtonPressed && e->KeyModifiers == Windows::System::VirtualKeyModifiers::Control);
00055
00056     return rval;
00057 }
00058
00059 PointerEventType GetPointerEventType(_In_ Windows::UI::Core::PointerEventArgs^ e)
00060 {
00061     PointerEventType type = PointerEventType::None;
00062
00063     if (EventIsErase(e))
00064     {
00065         type = PointerEventType::Erase;
00066     }
00067     else if (EventIsInk(e))
00068     {
00069         type = PointerEventType::Ink;
00070     }
00071     else if (EventIsSelect(e))
00072     {
00073         type = PointerEventType::Select;
00074     }
00075
00076     return type;
00077 }
00078
00079 void CreateBrush(
00080     _In_ ID2D1DeviceContext* d2dContext,
00081     _In_ Windows::UI::Color color,
00082     _Outptr_ ID2D1SolidColorBrush** brush)
00083 {
00084     D2D1::ColorF d2dColor(color.R/255.0f, color.G/255.0f, color.B/255.0f);
00085     *brush = nullptr;
00086     DX::ThrowIfFailed(
00087         d2dContext->CreateSolidColorBrush(
00088             d2dColor,
00089             brush
00090             )
00091         );
00092 }
00093
00094 bool AnySelected(_In_ Windows::Foundation::Collections::IVectorView<Windows::UI::Input::Inking::InkStroke^>^ strokes)
00095 {
00096     for (unsigned int i = 0; i < strokes->Size; i++)
00097     {
00098         if (strokes->GetAt(i)->Selected)
00099         {
00100             return true;
00101         }
00102     }
00103     return false;
00104 }
00105
00106 void SelectAll(_In_ Windows::Foundation::Collections::IVectorView<Windows::UI::Input::Inking::InkStroke^>^ strokes, _In_ bool val)
00107 {
00108     for (unsigned int i = 0; i < strokes->Size; i++)
00109     {
00110         strokes->GetAt(i)->Selected = val;
00111     }
00112 }
00113
00114 #pragma endregion
00115
00116 //-----------------------------------------------------------------------------
00117 // simpleInk implementation
00118 //-----------------------------------------------------------------------------
00119
00120 simpleInk::simpleInk() :
00121     _backgroundColor(Windows::UI::Colors::White),
00122     _backgroundBrush(nullptr),
00123     _inkBrush(nullptr),
00124     _messageBrush(nullptr),
00125     _selectionBrush(nullptr),
00126     _currentBuffer(nullptr),
00127     _previousBuffer(nullptr),
00128     _inkStyle(nullptr),
00129     _selectionStyle(nullptr),
00130     _pointerId(-1),
00131     _recognitionText(""),
00132     _recognizerId(0),
00133     _renderingMode(Bezier),
00134     _manipulationMode(Windows::UI::Input::Inking::InkManipulationMode::Inking),
00135     _statusMessage("")
00136 {
00137     // Change the number of rendering buffers (the constructor of DirectXBase sets it to 2)
00138     // to account for the special needs of apps that must support live rendering of ink.
00139     // Notice that buffers are created by CreateWindowSizeDependentResources, so it is safe
00140     // to change the number here.
00141     //
00142     // We must deviate from the recommended practice of using 2 buffers because calling
00143     // Present more than m_numBuffers-1 times within one VSync cycle will block the app.
00144     // We use 4 buffers because in live rendering mode we will be calling Present every time
00145     // we receive input updates, and we estimate the ratio between the frequency of updates
00146     // and that of VSync to be between 2 and 3.
00147     m_numBuffers = 4;
00148
00149     _manipulationPoints = ref new Platform::Collections::Vector<Windows::Foundation::Point>();
00150
00151     _strokeBuilder = ref new Windows::UI::Input::Inking::InkStrokeBuilder();
00152     _strokeContainer = ref new Windows::UI::Input::Inking::InkStrokeContainer();
00153     _recognizerContainer = ref new Windows::UI::Input::Inking::InkRecognizerContainer();
00154
00155     // take the first recognizer from the recognizer collection and set it as default
00156     _recognizer = _recognizerContainer->GetRecognizers()->GetAt(_recognizerId);
00157     _recognizerContainer->SetDefaultRecognizer(_recognizer);
00158
00159     _drawingAttributes = ref new Windows::UI::Input::Inking::InkDrawingAttributes();
00160     _drawingAttributes->Color = Windows::UI::Colors::Black;
00161     _drawingAttributes->PenTip = Windows::UI::Input::Inking::PenTipShape::Circle;
00162     _drawingAttributes->Size = Windows::Foundation::Size(3.0f, 3.0f);
00163     _drawingAttributes->IgnorePressure = true;
00164     _drawingAttributes->FitToCurve = true;
00165
00166     _strokeBuilder->SetDefaultDrawingAttributes(_drawingAttributes);
00167 }
00168
00169 #pragma region Pointer event handlers (live rendering)
00170
00171 void simpleInk::OnPointerPressed(
00172     _In_ Windows::UI::Core::CoreWindow^,
00173     _In_ Windows::UI::Core::PointerEventArgs^ args)
00174 {
00175     Windows::UI::Input::PointerPoint^ pointerPoint = args->CurrentPoint;
00176
00177     // Make sure no pointer is already inking (we allow only one 'active' pointer at a time)
00178     // Make sure pointer is in inking mode (pen and no button, or mouse and left button down)
00179     if (_pointerId == -1)
00180     {
00181         _statusMessage = "";
00182         _manipulationPoints->Clear();
00183         SelectAll(_strokeContainer->GetStrokes(), false);
00184
00185         switch (GetPointerEventType(args))
00186         {
00187         case PointerEventType::Erase:
00188             _manipulationMode = Windows::UI::Input::Inking::InkManipulationMode::Erasing;
00189             _statusMessage = "Erase mode: scribble across the ink you want to erase.";
00190             _manipulationPoints->Append(pointerPoint->Position);
00191             break;
00192         case PointerEventType::Ink:
00193              _manipulationMode = Windows::UI::Input::Inking::InkManipulationMode::Inking;
00194             _renderingMode = Live; // enter live rendering mode
00195             // this is the first point of the stroke, begin the stroke with the stroke builder
00196             _strokeBuilder->BeginStroke(pointerPoint);
00197             break;
00198         case PointerEventType::Select:
00199             _manipulationMode = Windows::UI::Input::Inking::InkManipulationMode::Selecting;
00200             _statusMessage = "Select mode: draw a contour around the ink you want to select.";
00201             _manipulationPoints->Append(pointerPoint->Position);
00202             break;
00203         default:
00204             return; // pointer is neither inking nor erasing nor selecting: do nothing
00205         }
00206
00207         Render();
00208
00209         _pointerId = pointerPoint->PointerId; // save pointer id so that no other pointer can ink until this one it is released
00210     }
00211 }
00212
00213 void simpleInk::OnPointerMoved(
00214     _In_ Windows::UI::Core::CoreWindow^,
00215     _In_ Windows::UI::Core::PointerEventArgs^ args)
00216 {
00217     Windows::UI::Input::PointerPoint^ pointerPoint = args->CurrentPoint;
00218
00219     // Make sure the event belongs to the pointer that is currently inking
00220     if (_pointerId == (int) pointerPoint->PointerId)
00221     {
00222         if (_manipulationMode == Windows::UI::Input::Inking::InkManipulationMode::Erasing)
00223         {
00224             // Erase ink that intersects line from last point to current point
00225             Windows::Foundation::Rect invalidateRect = _strokeContainer->SelectWithLine(_manipulationPoints->GetAt(0), pointerPoint->Position);
00226             if (invalidateRect.Height != 0 || invalidateRect.Width != 0)
00227             {
00228                 _strokeContainer->DeleteSelected();
00229                 Render();
00230             }
00231
00232             // Store current point: it will be the starting point at next pointer update
00233             _manipulationPoints->Clear();
00234             _manipulationPoints->Append(pointerPoint->Position);
00235         }
00236         else
00237         {
00238             Windows::Foundation::Point previousPoint;
00239             ID2D1StrokeStyle* strokeStyle;
00240             ID2D1SolidColorBrush* brush;
00241             float width;
00242
00243             if (_manipulationMode == Windows::UI::Input::Inking::InkManipulationMode::Inking)
00244             {
00245                 // Obtain intermediate points (including the last/current one)
00246                 Windows::Foundation::Collections::IVector<Windows::UI::Input::PointerPoint^>^ intermediatePoints = args->GetIntermediatePoints();
00247
00248                 // Update ink manager with all intermediate points
00249                 int i = intermediatePoints->Size - 1;
00250                 // AppendToStroke returns the last point that was added to the stroke builder.
00251                 // We need to save it because it is the initial point of the new line we want to render.
00252                 previousPoint = _strokeBuilder->AppendToStroke(intermediatePoints->GetAt(i))->Position;
00253                 for (i = i - 1; i >= 0; i--)
00254                 {
00255                     _strokeBuilder->AppendToStroke(intermediatePoints->GetAt(i));
00256                 }
00257
00258                 // Setup drawing attributes for live rendering
00259                 strokeStyle = _inkStyle.Get();
00260                 brush = _inkBrush.Get();
00261                 width = _drawingAttributes->Size.Width;
00262             }
00263             else // _manipulationMode == Windows::UI::Input::Inking::InkManipulationMode::Selecting
00264             {
00265                 previousPoint = _manipulationPoints->GetAt(_manipulationPoints->Size - 1);
00266                 _manipulationPoints->Append(pointerPoint->Position);
00267
00268                 // Setup drawing attributes for live rendering
00269                 strokeStyle = _selectionStyle.Get();
00270                 brush = _selectionBrush.Get();
00271                 width = 1.0f;
00272             }
00273
00274             // Live rendering
00275             // First we need to copy the content of the last presented buffer: it contains
00276             // the Beziers and the lines we rendered at previous pointer moves.
00277             m_d3dContext->CopyResource(_currentBuffer.Get(), _previousBuffer.Get());
00278             // Then we draw a new line, from the last position of the pointer to its current one.
00279             m_d2dContext->BeginDraw();
00280             m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00281             m_d2dContext->DrawLine(
00282                 D2D1::Point2F(previousPoint.X, previousPoint.Y),
00283                 D2D1::Point2F(pointerPoint->Position.X, pointerPoint->Position.Y),
00284                 brush,
00285                 width,
00286                 strokeStyle);
00287
00288             // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00289             // is lost. It will be handled during the next call to Present.
00290             HRESULT hr = m_d2dContext->EndDraw();
00291             if (hr != D2DERR_RECREATE_TARGET)
00292             {
00293                 DX::ThrowIfFailed(hr);
00294             }
00295
00296             Present();
00297         }
00298     }
00299 }
00300
00301 void simpleInk::OnPointerReleased(
00302     _In_ Windows::UI::Core::CoreWindow^,
00303     _In_ Windows::UI::Core::PointerEventArgs^ args)
00304 {
00305     Windows::UI::Input::Inking::InkStroke^ stroke = nullptr;
00306     Windows::UI::Input::PointerPoint^ pointerPoint = args->CurrentPoint;
00307
00308     // Make sure the event belongs to the pointer that is currently inking
00309     if (_pointerId == (int) pointerPoint->PointerId)
00310     {
00311         _renderingMode = Bezier;    // exit live rendering mode
00312         _pointerId = -1;            // release 'active' pointer so that a new pointer may start inking again
00313         _statusMessage = "";
00314
00315         switch (_manipulationMode)
00316         {
00317         case Windows::UI::Input::Inking::InkManipulationMode::Erasing:
00318             _strokeContainer->SelectWithLine(_manipulationPoints->GetAt(0), pointerPoint->Position);
00319             _strokeContainer->DeleteSelected();
00320             break;
00321         case Windows::UI::Input::Inking::InkManipulationMode::Inking:
00322             // this is the last point in the stroke
00323             stroke = _strokeBuilder->EndStroke(pointerPoint);
00324
00325             // add stroke to the stoke container
00326             _strokeContainer->AddStroke(stroke);
00327
00328             // out of curiosity we shall change the color and the width of the next stroke
00329             OnChangeDrawingAttributes();
00330             break;
00331         case Windows::UI::Input::Inking::InkManipulationMode::Selecting:
00332             _manipulationPoints->Append(pointerPoint->Position);
00333             _strokeContainer->SelectWithPolyLine(_manipulationPoints);
00334             break;
00335         }
00336
00337          _manipulationPoints->Clear();
00338
00339         // re-render the entire scene
00340         Render();
00341     }
00342 }
00343
00344 #pragma endregion
00345
00346 #pragma region Bezier rendering
00347
00348 // convert bezier control points in each segment to a bezier curve in the path geometry
00349 void simpleInk::ConvertStrokeToGeometry(_In_ Windows::UI::Input::Inking::InkStroke^ stroke, _Outptr_ ID2D1PathGeometry** geometry)
00350 {
00351     // create a geometry path
00352     DX::ThrowIfFailed(m_d2dFactory->CreatePathGeometry(geometry));
00353
00354     // create and initialize a geometry sink
00355     Microsoft::WRL::ComPtr<ID2D1GeometrySink> sink;
00356     DX::ThrowIfFailed((*geometry)->Open(&sink));
00357     sink->SetSegmentFlags(D2D1_PATH_SEGMENT_FORCE_ROUND_LINE_JOIN);
00358     sink->SetFillMode(D2D1_FILL_MODE_ALTERNATE);
00359
00360     // obtain rendering segments for this stroke
00361     Windows::Foundation::Collections::IVectorView<Windows::UI::Input::Inking::InkStrokeRenderingSegment^>^ renderingSegments = stroke->GetRenderingSegments();
00362
00363     // obtain first rendering segment, set as a starting point
00364     Windows::UI::Input::Inking::InkStrokeRenderingSegment^ firstSegment = renderingSegments->GetAt(0);
00365     Windows::Foundation::Point first = firstSegment->Position;
00366     sink->BeginFigure(D2D1::Point2F(first.X, first.Y), D2D1_FIGURE_BEGIN_FILLED);
00367
00368     // process all remaining rendering segments, add bezier segment to the geometry path sink
00369     for (unsigned int j = 1; j < renderingSegments->Size; j++)
00370     {
00371         // obtain j-th rendering segment for the given stroke
00372         Windows::UI::Input::Inking::InkStrokeRenderingSegment^ renderingSegment = renderingSegments->GetAt(j);
00373
00374         // add bezier segment to the geometry path sink
00375         sink->AddBezier(
00376             D2D1::BezierSegment(
00377                 D2D1::Point2F(renderingSegment->BezierControlPoint1.X, renderingSegment->BezierControlPoint1.Y),
00378                 D2D1::Point2F(renderingSegment->BezierControlPoint2.X, renderingSegment->BezierControlPoint2.Y),
00379                 D2D1::Point2F(renderingSegment->Position.X, renderingSegment->Position.Y)
00380                 )
00381             );
00382     }
00383
00384     // done with given stroke, end and close geometry sink
00385     // sink will be automatically released as it is a smart pointer
00386     sink->EndFigure(D2D1_FIGURE_END_OPEN);
00387     DX::ThrowIfFailed(sink->Close());
00388 }
00389
00390 // creates Bezier render, called by Render()
00391 void simpleInk::BezierRender()
00392 {
00393     // render all strokes
00394     Windows::Foundation::Collections::IVectorView<Windows::UI::Input::Inking::InkStroke^>^ inkStrokes = _strokeContainer->GetStrokes();
00395     for (unsigned int i = 0; i < inkStrokes->Size; i++)
00396     {
00397         // obtain the stroke
00398         Windows::UI::Input::Inking::InkStroke^ stroke = inkStrokes->GetAt(i);
00399
00400         // convert stroke to geometry
00401         // geometry is a smart pointer and it is released right after it is used
00402         // for performance reasons one may consider storing geometry paths instead of auto-releasing them once they are used
00403         Microsoft::WRL::ComPtr<ID2D1PathGeometry> strokeGeometry;
00404         ConvertStrokeToGeometry(stroke, &strokeGeometry);
00405
00406         // stroke's width and color are retrieved from the stroke's drawing attributes
00407         float width = stroke->DrawingAttributes->Size.Width;
00408         // create brush from current stroke
00409         Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> strokeBrush;
00410         CreateBrush(m_d2dContext.Get(), stroke->DrawingAttributes->Color, &strokeBrush);
00411
00412         // render stroke geometry
00413         // if stroke is selected, we render its contour with the stroke's color and we fill it with white
00414         if (stroke->Selected)
00415         {
00416             m_d2dContext->DrawGeometry(strokeGeometry.Get(), strokeBrush.Get(), width + 2, _inkStyle.Get());
00417             m_d2dContext->DrawGeometry(strokeGeometry.Get(), _backgroundBrush.Get(), width, _inkStyle.Get());
00418         }
00419         else
00420         {
00421             m_d2dContext->DrawGeometry(strokeGeometry.Get(), strokeBrush.Get(), width, _inkStyle.Get());
00422         }
00423     }
00424 }
00425
00426 #pragma endregion
00427
00428 #pragma region Event handlers
00429
00430 void simpleInk::OnCharacterReceived(
00431     _In_ Windows::UI::Core::CoreWindow^,
00432     _In_ Windows::UI::Core::CharacterReceivedEventArgs^ args)
00433 {
00434     if (_pointerId == -1) // While in live rendering mode everything else is disabled
00435     {
00436         Platform::String^ oldStatusMessage = _statusMessage;
00437
00438         // Reset status message, it will be updated by the functio that will be called
00439         _statusMessage = ""; // reset status message
00440         switch (args->KeyCode)
00441         {
00442         case 3: // ctrl+c, copy handler
00443             OnCopyToClipboard();
00444             break;
00445         case 20: // ctrl+t, copy text handler
00446             OnCopyTextToClipboard();
00447             break;
00448         case 22: // ctrl+v, paste handler
00449             SelectAll(_strokeContainer->GetStrokes(), false);
00450             OnPasteFromClipboard();
00451             break;
00452         case 19: // ctrl+s, save handler
00453             OnSave();
00454             break;
00455         case 15: // ctrl+o, open handler
00456             OnLoad();
00457             break;
00458         case 1: // ctrl+a, select all handler
00459             OnSelectAll();
00460             break;
00461         case 8: // backspace, delete handler
00462             OnDelete();
00463             break;
00464         case 4: // crtl+d, change drawing attributes
00465             OnChangeDrawingAttributes();
00466             break;
00467         case 18: // crtl+r, change recognizer
00468             OnChangeRecognizer();
00469             break;
00470         case 32: // space, recognize handler
00471             OnRecognize();
00472             break;
00473         default:
00474             // invalid command: ignore and restore old status message
00475             _statusMessage = oldStatusMessage;
00476         }
00477     }
00478 }
00479
00480 void simpleInk::OnCopyToClipboard()
00481 {
00482     // for most app scenarios it is sufficient to just call _strokeContainer->CopySelectedToClipboard();
00483     // for this sample we shall implement a slightly different scenario:
00484     //  - in case some strokes are selected we shall copy just the selected strokes
00485     //  - in case no strokes are selected we shall copy all strokes
00486
00487     // obtain the strokes in the stroke container
00488     Windows::Foundation::Collections::IVectorView<Windows::UI::Input::Inking::InkStroke^>^ inkStrokes = _strokeContainer->GetStrokes();
00489
00490     // check if any strokes are selected
00491     if (AnySelected(inkStrokes))
00492     {
00493         // some strokes are selected, copy only those
00494         _strokeContainer->CopySelectedToClipboard();
00495     }
00496     else
00497     {
00498         // no strokes are selected, copy all strokes to clipboard
00499
00500         // select all strokes
00501         SelectAll(inkStrokes, true);
00502
00503         // copy all selected strokes to clipboard
00504         _strokeContainer->CopySelectedToClipboard();
00505
00506         // deselect all strokes
00507         SelectAll(inkStrokes, false);
00508     }
00509 }
00510
00511 void simpleInk::OnCopyTextToClipboard()
00512 {
00513     // we use data package to set text
00514     Windows::ApplicationModel::DataTransfer::DataPackage^ dataPackage = ref new Windows::ApplicationModel::DataTransfer::DataPackage();
00515
00516     // set recognition text to data package
00517     dataPackage->SetText(_recognitionText);
00518
00519     // copy text to clipboard
00520     Windows::ApplicationModel::DataTransfer::Clipboard::SetContent(dataPackage);
00521 }
00522
00523 void simpleInk::OnPasteFromClipboard()
00524 {
00525     // make sure that clipboard object is compatible with ink
00526     bool canPaste = _strokeContainer->CanPasteFromClipboard();
00527     if (canPaste)
00528     {
00529         // clipboard does contain ink compatible object
00530
00531         // this is the position where ink will be pasted to
00532         Windows::Foundation::Point position;
00533         position.X = 100.0f;
00534         position.Y = 100.0f;
00535
00536         _strokeContainer->PasteFromClipboard(position);
00537     }
00538     else
00539     {
00540         _statusMessage = "Clipboard does not contain ink compatible objects. Cannot paste from clipboard.";
00541     }
00542
00543     Render();
00544 }
00545
00546 // how to use StrokeContainer::SaveAsync()
00547 void simpleInk::OnSave()
00548 {
00549     // NOTE: check that we have some ink to save before calling StrokeContainer::SaveAsync()
00550     if (_strokeContainer->GetStrokes()->Size > 0)
00551     {
00552         // File pickers don't work in snapped state. Make sure we are not in snapped state, or that we successfully unsnapped
00553         if (Windows::UI::ViewManagement::ApplicationView::Value != Windows::UI::ViewManagement::ApplicationViewState::Snapped || Windows::UI::ViewManagement::ApplicationView::TryUnsnap())
00554         {
00555             Windows::Storage::Pickers::FileSavePicker^ savePicker = ref new Windows::Storage::Pickers::FileSavePicker();
00556             savePicker->SuggestedStartLocation = Windows::Storage::Pickers::PickerLocationId::PicturesLibrary;
00557
00558             auto extension = ref new Platform::Collections::Vector<Platform::String^>;
00559             extension->Append(".gif");
00560             savePicker->FileTypeChoices->Insert("Gif with embedded ISF", extension);
00561
00562             savePicker->DefaultFileExtension = ".gif";
00563
00564             concurrency::task<Windows::Storage::StorageFile^> savePickerTask(savePicker->PickSaveFileAsync());
00565             savePickerTask.then([this] (Windows::Storage::StorageFile^ file)
00566             {
00567                 // file may be nullptr if end user clicked on cancel button
00568                 if (nullptr != file)
00569                 {
00570                     return file->OpenAsync(Windows::Storage::FileAccessMode::ReadWrite);
00571                 }
00572                 else
00573                 {
00574                     // user clicked cancel, cancel all value based continuations
00575                     concurrency::cancel_current_task();
00576                 }
00577
00578             }).then([this] (Windows::Storage::Streams::IRandomAccessStream^ stream)
00579             {
00580                 // IOutputStream is required by IRandomAccessStream, hence we can safely use the latter
00581                 return _strokeContainer->SaveAsync(stream);
00582
00583             });
00584         }
00585     }
00586     else
00587     {
00588         _statusMessage = "There is no ink to save.";
00589         Render();
00590     }
00591 }
00592
00593 // how to use StrokeContainer::LoadAsync()
00594 void simpleInk::OnLoad()
00595 {
00596     // File pickers don't work in snapped state. Make sure we are not in snapped state, or that we successfully unsnapped
00597     if (Windows::UI::ViewManagement::ApplicationView::Value != Windows::UI::ViewManagement::ApplicationViewState::Snapped || Windows::UI::ViewManagement::ApplicationView::TryUnsnap())
00598     {
00599         Windows::Storage::Pickers::FileOpenPicker^ openPicker = ref new Windows::Storage::Pickers::FileOpenPicker();
00600         openPicker->SuggestedStartLocation = Windows::Storage::Pickers::PickerLocationId::PicturesLibrary;
00601         openPicker->FileTypeFilter->Append(".gif");
00602
00603         concurrency::task<Windows::Storage::StorageFile^> openPickerTask(openPicker->PickSingleFileAsync());
00604         openPickerTask.then([this] (Windows::Storage::StorageFile^ file)
00605         {
00606             // file may be nullptr if end user clicked on cancel button
00607             if (nullptr != file)
00608             {
00609                 return file->OpenAsync(Windows::Storage::FileAccessMode::Read);
00610             }
00611             else
00612             {
00613                 // user clicked cancel, cancel all value based continuations
00614                 concurrency::cancel_current_task();
00615             }
00616
00617         }).then([this] (Windows::Storage::Streams::IRandomAccessStream^ stream)
00618         {
00619             return _strokeContainer->LoadAsync(stream);
00620
00621         }).then([this] ()
00622         {
00623             Render();
00624
00625         });
00626     }
00627 }
00628
00629 void simpleInk::OnSelectAll()
00630 {
00631     SelectAll(_strokeContainer->GetStrokes(), true);
00632     Render();
00633 }
00634
00635 void simpleInk::OnDelete()
00636 {
00637     // for most app scenarios it is sufficient to just call _strokeContainer->DeleteSelected();
00638     // for this sample we shall implement a slightly different scenario:
00639     //  - in case some strokes are selected we shall delete just the selected strokes
00640     //  - in case no strokes are selected we shall delete all strokes
00641
00642     // obtain the strokes in the stroke container
00643     Windows::Foundation::Collections::IVectorView<Windows::UI::Input::Inking::InkStroke^>^ inkStrokes = _strokeContainer->GetStrokes();
00644
00645     // check if any strokes are selected
00646     if (AnySelected(inkStrokes))
00647     {
00648         // some strokes are selected, delete only those
00649         _strokeContainer->DeleteSelected();
00650     }
00651     else
00652     {
00653         // no strokes are selected, delete all strokes
00654
00655         // select all strokes
00656         SelectAll(inkStrokes, true);
00657
00658         // delete all selected strokes
00659         _strokeContainer->DeleteSelected();
00660     }
00661
00662     _recognitionText = ""; // ink has been erased, reset recognition text
00663
00664     Render();
00665 }
00666
00667 void simpleInk::OnChangeDrawingAttributes()
00668 {
00669     // change color randomly
00670     // manipulate bitwise & 0xf0 to ensure we do not have entirely (or close to) white stroke
00671     _drawingAttributes->Color = Windows::UI::ColorHelper::FromArgb(255, rand() & 0xf0, rand() & 0xf0, rand() & 0xf0);
00672
00673     // change size randomly
00674     float val = (rand() & 0x07) * 1.0f + 1.0f; // make sure we do not have 0.0f stroke width/height
00675     _drawingAttributes->Size = Windows::Foundation::Size(val, val);
00676
00677     // update default drawing attributes
00678     _strokeBuilder->SetDefaultDrawingAttributes(_drawingAttributes);
00679
00680     // update _inkBrush to reflect drawing color change
00681     CreateBrush(m_d2dContext.Get(), _drawingAttributes->Color, &_inkBrush);
00682 }
00683
00684 void simpleInk::OnChangeRecognizer()
00685 {
00686     // select next recognizer
00687     _recognizerId++;
00688
00689     // make sure we are still in range
00690     if (_recognizerId >= _recognizerContainer->GetRecognizers()->Size)
00691     {
00692         _recognizerId = 0;
00693     }
00694
00695     // set as a new default recognizer
00696     _recognizerContainer->SetDefaultRecognizer(_recognizerContainer->GetRecognizers()->GetAt(_recognizerId));
00697
00698     // update the name of the recognizer on the screen
00699     // name is stored in _recognizerContainer->GetRecognizers()->GetAt(_recognizerId)->Name
00700     Render();
00701 }
00702
00703 void simpleInk::OnRecognize()
00704 {
00705     // there are three ways to do handwriting recognition, as defined
00706     // by the Windows::UI::Input::Inking::InkRecognitionTarget
00707     //  - (All) against all strokes
00708     //  - (Selected) against selected strokes
00709     //  - (Recent) against recent strokes, not recognized (InkStroke::Recognized == false)
00710     //
00711     // in this sample we shall demonstrate recognition against all and selected strokes
00712     // in case some strokes as selected we shall recognize only those
00713     // in case no strokes are selected we shall recognize against all strokes
00714
00715     // obtain the strokes in the stroke container
00716     Windows::Foundation::Collections::IVectorView<Windows::UI::Input::Inking::InkStroke^>^ inkStrokes = _strokeContainer->GetStrokes();
00717
00718     // NOTE: check that we have some ink to recognize before calling RecognizerContainer::RecognizeAsync()
00719     if (inkStrokes->Size > 0)
00720     {
00721         // loop through all strokes, check for selected flag
00722         Windows::UI::Input::Inking::InkRecognitionTarget target;
00723         if (AnySelected(inkStrokes))
00724         {
00725             _statusMessage = "Selected ink recognized as: ";
00726             target = Windows::UI::Input::Inking::InkRecognitionTarget::Selected;
00727         }
00728         else
00729         {
00730             _statusMessage = "Ink recognized as: ";
00731             target = Windows::UI::Input::Inking::InkRecognitionTarget::All;
00732         }
00733
00734         // do handwriting recognition
00735         concurrency::task<Windows::Foundation::Collections::IVectorView<Windows::UI::Input::Inking::InkRecognitionResult^>^> recognizeTask(_recognizerContainer->RecognizeAsync(_strokeContainer, target));
00736         recognizeTask.then([this] (Windows::Foundation::Collections::IVectorView<Windows::UI::Input::Inking::InkRecognitionResult^>^ recognitionResults)
00737         {
00738             // update results in stroke container
00739             _strokeContainer->UpdateRecognitionResults(recognitionResults);
00740
00741             // display recognition result
00742             _recognitionText = "";
00743             for (unsigned int i = 0; i < recognitionResults->Size; i++)
00744             {
00745                 // obtain recognition results
00746                 Windows::UI::Input::Inking::InkRecognitionResult^ recognitionResult = recognitionResults->GetAt(i);
00747
00748                 // obtain text candidates
00749                 Windows::Foundation::Collections::IVectorView<Platform::String^>^ textCandidates = recognitionResult->GetTextCandidates();
00750
00751                 // we only need top candidate
00752                 Platform::String^ topCandidate = textCandidates->GetAt(0);
00753
00754                 // update global recognition text with the top candidate
00755                 _recognitionText += topCandidate + " ";
00756             }
00757
00758             _statusMessage += _recognitionText;
00759
00760             // render everything including the updated text
00761             Render();
00762         });
00763     }
00764 }
00765
00766 void simpleInk::OnWindowSizeChanged(
00767     _In_ Windows::UI::Core::CoreWindow^ /*sender*/,
00768     _In_ Windows::UI::Core::WindowSizeChangedEventArgs^ /*args*/)
00769 {
00770     UpdateForWindowSizeChange();
00771     Render();
00772 }
00773
00774 void simpleInk::OnLogicalDpiChanged(_In_ Platform::Object^ /*sender*/)
00775 {
00776     SetDpi(static_cast<float>(Windows::Graphics::Display::DisplayProperties::LogicalDpi));
00777     Render();
00778 }
00779
00780 void simpleInk::OnDisplayContentsInvalidated(_In_ Platform::Object^ /*sender*/)
00781 {
00782     // Ensure the D3D Device is available for rendering.
00783     ValidateDevice();
00784
00785     Render();
00786 }
00787
00788 void simpleInk::OnActivated(
00789     _In_ Windows::ApplicationModel::Core::CoreApplicationView^ /*applicationView*/,
00790     _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^ /*args*/)
00791 {
00792     Windows::UI::Core::CoreWindow::GetForCurrentThread()->Activate();
00793 }
00794
00795 #pragma endregion
00796
00797 #pragma region DirectXBase overrides
00798
00799 void simpleInk::CreateDeviceIndependentResources()
00800 {
00801     DirectXBase::CreateDeviceIndependentResources();
00802
00803     DX::ThrowIfFailed(
00804         m_d2dFactory->CreateStrokeStyle(
00805             D2D1::StrokeStyleProperties(
00806                 D2D1_CAP_STYLE_ROUND,
00807                 D2D1_CAP_STYLE_ROUND,
00808                 D2D1_CAP_STYLE_ROUND,
00809                 D2D1_LINE_JOIN_ROUND,
00810                 1.0f,
00811                 D2D1_DASH_STYLE_SOLID,
00812                 0.0f),
00813             nullptr,
00814             0,
00815             &_inkStyle));
00816
00817     DX::ThrowIfFailed(
00818         m_d2dFactory->CreateStrokeStyle(
00819             D2D1::StrokeStyleProperties(
00820                 D2D1_CAP_STYLE_ROUND,
00821                 D2D1_CAP_STYLE_ROUND,
00822                 D2D1_CAP_STYLE_ROUND,
00823                 D2D1_LINE_JOIN_ROUND,
00824                 1.0f,
00825                 D2D1_DASH_STYLE_DASH,
00826                 0.0f),
00827             nullptr,
00828             0,
00829             &_selectionStyle));
00830 }
00831
00832 void simpleInk::CreateDeviceResources()
00833 {
00834     DirectXBase::CreateDeviceResources();
00835
00836     // Create a DirectWrite text format object.
00837     DX::ThrowIfFailed(
00838         m_dwriteFactory->CreateTextFormat(L"Verdana", nullptr, DWRITE_FONT_WEIGHT_NORMAL,
00839             DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, 20.0f, L"",
00840             &_eventTextFormat));
00841     // Center the text horizontally and vertically.
00842     _eventTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
00843     _eventTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
00844
00845     CreateBrush(m_d2dContext.Get(), _backgroundColor, &_backgroundBrush);
00846     CreateBrush(m_d2dContext.Get(), _drawingAttributes->Color, &_inkBrush);
00847     CreateBrush(m_d2dContext.Get(), Windows::UI::Colors::Black, &_messageBrush);
00848     CreateBrush(m_d2dContext.Get(), Windows::UI::Colors::Goldenrod, &_selectionBrush);
00849 }
00850
00851 void simpleInk::CreateWindowSizeDependentResources()
00852 {
00853     _previousBuffer = nullptr;
00854     _currentBuffer = nullptr;
00855
00856     DirectXBase::CreateWindowSizeDependentResources();
00857
00858     // Retrieve buffers 0 and m_numBuffers-1: we will need them in live rendering mode.
00859     //
00860     // In live rendering mode we need to copy the content of the last buffer we
00861     // presented into the new buffer we are going to present. This is more
00862     // efficient than redoing the whole bezier render and the previous parts
00863     // of the live render.
00864     // The next buffer that will be presented is always buffer 0, and the last
00865     // buffer presented is always buffer m_numBuffers - 1.
00866     DX::ThrowIfFailed(
00867         m_swapChain->GetBuffer(
00868             0,
00869             __uuidof(ID3D11Texture2D),
00870             &_currentBuffer
00871             )
00872         );
00873     DX::ThrowIfFailed(
00874         m_swapChain->GetBuffer(
00875             m_numBuffers - 1,
00876             __uuidof(ID3D11Texture2D),
00877             &_previousBuffer
00878             )
00879         );
00880 }
00881
00882 void simpleInk::Present()
00883 {
00884     HRESULT hr = S_OK;
00885
00886     DXGI_PRESENT_PARAMETERS parameters = {0};
00887     parameters.DirtyRectsCount = 0;
00888     parameters.pDirtyRects = nullptr;
00889     parameters.pScrollRect = nullptr;
00890     parameters.pScrollOffset = nullptr;
00891
00892     // In the interest of minimizing lagging between the rendered stroke and the
00893     // position of the inking device, we shall use immediate-mode presentation
00894     // (Present(0, ...)) while in live rendering. This way we can always present
00895     // the most up to date inking sample.
00896     // Since immediate mode presentation drains the battery we use non-immediate
00897     // mode presentation (Present(1, ...)) when we are not in live rendering mode.
00898     switch (_renderingMode)
00899     {
00900     case Bezier:
00901         hr = m_swapChain->Present(1, 0);
00902         break;
00903     case Live:
00904         hr = m_swapChain->Present(0, 0);
00905         break;
00906     }
00907
00908     // If the device was removed either by a disconnect or a driver upgrade, we
00909     // must recreate all device resources.
00910     if (hr == DXGI_ERROR_DEVICE_REMOVED)
00911     {
00912         HandleDeviceLost();
00913     }
00914     else
00915     {
00916         DX::ThrowIfFailed(hr);
00917     }
00918 }
00919
00920 void simpleInk::Render()
00921 {
00922     m_d2dContext->BeginDraw();
00923     m_d2dContext->Clear(D2D1::ColorF(_backgroundColor.R/255.0f, _backgroundColor.G/255.0f, _backgroundColor.B/255.0f));
00924     m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00925
00926     // Render recognizer name
00927     D2D1_RECT_F recoNameRect = {0, 0, 1000, 500};
00928     Platform::String^ name = _recognizerContainer->GetRecognizers()->GetAt(_recognizerId)->Name;
00929     m_d2dContext->DrawText(name->Begin(), name->Length(), _eventTextFormat.Get(), &recoNameRect, _messageBrush.Get());
00930
00931     // Render status message, if any
00932     D2D1_RECT_F statusMessageRect = {0, 50, 1000, 500};
00933     m_d2dContext->DrawText(_statusMessage->Begin(), _statusMessage->Length(), _eventTextFormat.Get(), &statusMessageRect, _messageBrush.Get());
00934
00935     // Render Beziers
00936     BezierRender();
00937
00938     // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00939     // is lost. It will be handled during the next call to Present.
00940     HRESULT hr = m_d2dContext->EndDraw();
00941     if (hr != D2DERR_RECREATE_TARGET)
00942     {
00943         DX::ThrowIfFailed(hr);
00944     }
00945
00946     Present();
00947 }
00948
00949 #pragma endregion
00950
00951 #pragma region IFrameworkView overrides
00952
00953 void simpleInk::Initialize(
00954     _In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView)
00955 {
00956     applicationView->Activated +=
00957         ref new Windows::Foundation::TypedEventHandler<
00958             Windows::ApplicationModel::Core::CoreApplicationView^,
00959             Windows::ApplicationModel::Activation::IActivatedEventArgs^>(
00960                 this, &simpleInk::OnActivated);
00961 }
00962
00963 void simpleInk::SetWindow(_In_ Windows::UI::Core::CoreWindow^ window)
00964 {
00965     // Setup event handlers
00966     Windows::Graphics::Display::DisplayProperties::LogicalDpiChanged +=
00967         ref new Windows::Graphics::Display::DisplayPropertiesEventHandler(
00968             this, &simpleInk::OnLogicalDpiChanged);
00969
00970     Windows::Graphics::Display::DisplayProperties::DisplayContentsInvalidated +=
00971         ref new Windows::Graphics::Display::DisplayPropertiesEventHandler(
00972             this, &simpleInk::OnDisplayContentsInvalidated);
00973
00974     window->SizeChanged +=
00975         ref new Windows::Foundation::TypedEventHandler<
00976             Windows::UI::Core::CoreWindow^,
00977             Windows::UI::Core::WindowSizeChangedEventArgs^>(
00978                 this, &simpleInk::OnWindowSizeChanged);
00979
00980     window->CharacterReceived +=
00981         ref new Windows::Foundation::TypedEventHandler<
00982             Windows::UI::Core::CoreWindow^,
00983             Windows::UI::Core::CharacterReceivedEventArgs^>(
00984                 this, &simpleInk::OnCharacterReceived);
00985
00986     window->PointerPressed +=
00987         ref new Windows::Foundation::TypedEventHandler<
00988             Windows::UI::Core::CoreWindow^, Windows::UI::Core::PointerEventArgs^>(
00989                 this, &simpleInk::OnPointerPressed);
00990
00991     window->PointerMoved +=
00992         ref new Windows::Foundation::TypedEventHandler<
00993             Windows::UI::Core::CoreWindow^, Windows::UI::Core::PointerEventArgs^>(
00994                 this, &simpleInk::OnPointerMoved);
00995
00996     window->PointerReleased +=
00997         ref new Windows::Foundation::TypedEventHandler<
00998             Windows::UI::Core::CoreWindow^, Windows::UI::Core::PointerEventArgs^>(
00999                 this, &simpleInk::OnPointerReleased);
01000
01001     // Set mouse cursor
01002     window->PointerCursor = ref new Windows::UI::Core::CoreCursor(
01003         Windows::UI::Core::CoreCursorType::Arrow, 0);
01004
01005     DirectXBase::Initialize(
01006         Windows::UI::Core::CoreWindow::GetForCurrentThread(),
01007         Windows::Graphics::Display::DisplayProperties::LogicalDpi);
01008 }
01009
01010 void simpleInk::Load(_In_ Platform::String^ /*entryPoint*/)
01011 {
01012 }
01013
01014 void simpleInk::Run()
01015 {
01016     Render();
01017     Windows::UI::Core::CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(
01018         Windows::UI::Core::CoreProcessEventsOption::ProcessUntilQuit);
01019 }
01020
01021 void simpleInk::Uninitialize()
01022 {
01023 }
01024
01025 #pragma endregion
01026
01027 //-----------------------------------------------------------------------------
01028 // entry point
01029 //-----------------------------------------------------------------------------
01030
01031 Windows::ApplicationModel::Core::IFrameworkView^ DirectXAppSource::CreateView()
01032 {
01033     return ref new simpleInk();
01034 }
01035
01036 // The main entry point for the sample program.
01037 [Platform::MTAThread]
01038 int main(Platform::Array<_In_ Platform::String^>^ /*args*/)
01039 {
01040     auto directXAppSource = ref new DirectXAppSource();
01041     Windows::ApplicationModel::Core::CoreApplication::Run(directXAppSource);
01042     return 0;
01043 }
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAudio2 audio stream effect/C++/DirectXBase.h Source File

  • XAudio2 audio stream effect

DirectXBase.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 "DirectXSample.h"
00011
00012 // Helper class that initializes DirectX APIs for both 2D and 3D rendering.
00013 // Some of the code in this class may be omitted if only 2D or only 3D rendering is being used.
00014 ref class DirectXBase abstract
00015 {
00016 internal:
00017     DirectXBase();
00018
00019     virtual void Initialize(Windows::UI::Core::CoreWindow^ window, float dpi);
00020     virtual void HandleDeviceLost();
00021     virtual void CreateDeviceIndependentResources();
00022     virtual void CreateDeviceResources();
00023     virtual void SetDpi(float dpi);
00024     virtual void UpdateForWindowSizeChange();
00025     virtual void CreateWindowSizeDependentResources();
00026     virtual void Render() = 0;
00027     virtual void Present();
00028     void ValidateDevice();
00029
00030 protected private:
00031     Platform::Agile<Windows::UI::Core::CoreWindow>  m_window;
00032
00033     // DirectWrite & Windows Imaging Component Objects.
00034     Microsoft::WRL::ComPtr<IDWriteFactory1>         m_dwriteFactory;
00035     Microsoft::WRL::ComPtr<IWICImagingFactory2>     m_wicFactory;
00036
00037     // DirectX Core Objects. Required for 2D and 3D.
00038     Microsoft::WRL::ComPtr<ID3D11Device1>           m_d3dDevice;
00039     Microsoft::WRL::ComPtr<ID3D11DeviceContext1>    m_d3dContext;
00040     Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00041     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00042
00043     // Direct2D Rendering Objects. Required for 2D.
00044     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00046     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00047     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmap;
00048
00049     // Direct3D Rendering Objects. Required for 3D.
00050     Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00051
00052     // Cached renderer properties.
00053     D3D_FEATURE_LEVEL                               m_featureLevel;
00054     Windows::Foundation::Size                       m_renderTargetSize;
00055     Windows::Foundation::Rect                       m_windowBounds;
00056     float                                           m_dpi;
00057     bool                                            m_windowSizeChangeInProgress;
00058 };
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DirectX::INTEndPntPair Member List

This is the complete list of members for DirectX::INTEndPntPair, including all inherited members.
A | DirectX::INTEndPntPair
B | DirectX::INTEndPntPair
Generated on Sat Nov 23 2024 16:09:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: App package information/C++/Scenario1.xaml.h Source File

  • App package information

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 SDKSample
00023 {
00024     namespace PackageSample
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 Scenario1 sealed
00031         {
00032         public:
00033             Scenario1();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039
00040             Platform::String^ VersionString(Windows::ApplicationModel::PackageVersion version);
00041             Platform::String^ ArchitectureString(Windows::System::ProcessorArchitecture architecture);
00042
00043             void GetPackage_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00044         };
00045     }
00046 }
Generated on Sat Nov 23 2024 16:07:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Display orientation/C++/Scenario3.xaml.h Source File

  • Display orientation

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 SDKSample
00023 {
00024     namespace DisplayOrientation
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             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00038
00039         private:
00040             void OnOrientationChanged(Platform::Object^ sender);
00041
00042             Windows::Foundation::EventRegistrationToken orientationChangedEventToken;
00043         };
00044     }
00045 }
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/RotateImageView.xaml.cpp Source File

  • Hilo C++
  • Hilo

RotateImageView.xaml.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 #include "RotateImageView.xaml.h"
00009 #include "ImageBrowserViewModel.h"
00010
00011 using namespace Hilo;
00012 using namespace Windows::Foundation;
00013 using namespace Windows::UI::Input;
00014 using namespace Windows::UI::Xaml::Input;
00015
00016 // See http://go.microsoft.com/fwlink/?LinkId=267278 for info on how Hilo creates pages and navigates to pages.
00017
00018 RotateImageView::RotateImageView()
00019 {
00020     InitializeComponent();
00021     m_viewModel = dynamic_cast<Hilo::RotateImageViewModel^>(DataContext);
00022 }
00023
00024 void RotateImageView::OnManipulationDelta(ManipulationDeltaRoutedEventArgs^ e)
00025 {
00026     m_viewModel->RotationAngle += e->Delta.Rotation;
00027 }
00028
00029 void RotateImageView::OnManipulationCompleted(ManipulationCompletedRoutedEventArgs^ e)
00030 {
00031     m_viewModel->EndRotation();
00032 }
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Association launching/C++/ReceiveUriOutput.xaml.cpp Source File

  • Association launching

ReceiveUriOutput.xaml.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 //
00009 // ReceiveUriOutput.xaml.cpp
00010 // Implementation of the ReceiveUriOutput class
00011 //
00012
00013 #include "pch.h"
00014 #include "ReceiveUriOutput.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace AssociationLaunching;
00018
00019 using namespace Platform;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Graphics::Display;
00023 using namespace Windows::UI::ViewManagement;
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 ReceiveUriOutput::ReceiveUriOutput()
00033 {
00034     InitializeComponent();
00035 }
00036
00037 ReceiveUriOutput::~ReceiveUriOutput()
00038 {
00039 }
00040
00041 #pragma region Template-Related Code - Do not remove
00042 void ReceiveUriOutput::OnNavigatedTo(NavigationEventArgs^ e)
00043 {
00044     // Get a pointer to our main page.
00045     rootPage = dynamic_cast<MainPage^>(e->Parameter);
00046 }
00047
00048 void ReceiveUriOutput::OnNavigatedFrom(NavigationEventArgs^ e)
00049 {
00050 }
00051
00052 #pragma endregion
Generated on Sat Nov 23 2024 16:07:57 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

ProximityCPP::sealed Member List

This is the complete list of members for ProximityCPP::sealed, including all inherited members.
__pad0__ | ProximityCPP::sealed | [protected]
App() | ProximityCPP::sealed |
autoSizeInputSectionWhenSnapped | ProximityCPP::sealed | [private]
ClearLog(Windows::UI::Xaml::Controls::TextBlock^textBlock) | ProximityCPP::sealed |
CloseSocket() | ProximityCPP::sealed | [private]
ConnectionRequestedEventHandler(Object^sender, Windows::Networking::Proximity::ConnectionRequestedEventArgs^e) | ProximityCPP::sealed | [private]
DeviceArrived(Windows::Networking::Proximity::ProximityDevice^device) | ProximityCPP::sealed |
DeviceDeparted(Windows::Networking::Proximity::ProximityDevice^device) | ProximityCPP::sealed |
Footer_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | ProximityCPP::sealed | [private]
HiddenFrame | ProximityCPP::sealed | [private]
InvalidateSize() | ProximityCPP::sealed | [private]
InvalidateViewState() | ProximityCPP::sealed | [private]
IsLaunchedByTap() | ProximityCPP::sealed |
LoadScenario(Platform::String^scenarioName) | ProximityCPP::sealed |
LogInfo(Platform::String^strMessage, Windows::UI::Xaml::Controls::TextBlock^textBlock) | ProximityCPP::sealed |
m_arrivedToken | ProximityCPP::sealed | [private]
m_browseConnectSupported | ProximityCPP::sealed | [private]
m_connectionRequestedToken | ProximityCPP::sealed | [private]
m_ConnectStateArray | ProximityCPP::sealed | [private]
m_coreDispatcher | ProximityCPP::sealed | [private]
m_dataWriter | ProximityCPP::sealed | [private]
m_departedToken | ProximityCPP::sealed | [private]
m_IsLaunchedByTap | ProximityCPP::sealed | [protected]
m_peerFinderStarted | ProximityCPP::sealed | [private]
m_peerInformationList | ProximityCPP::sealed | [private]
m_proximityDevice | ProximityCPP::sealed | [private]
m_publishedMessageId | ProximityCPP::sealed | [private]
m_requestingPeer | ProximityCPP::sealed | [private]
m_rootPage | ProximityCPP::sealed | [private]
m_socket | ProximityCPP::sealed | [private]
m_socketClosed | ProximityCPP::sealed | [private]
m_startPeerFinderImmediately | ProximityCPP::sealed | [private]
m_subscribedMessageId | ProximityCPP::sealed | [private]
m_triggeredConnectSupported | ProximityCPP::sealed | [private]
m_triggerToken | ProximityCPP::sealed | [private]
MainPage() | ProximityCPP::sealed |
MainPage_SizeChanged(Object^sender, Windows::UI::Xaml::SizeChangedEventArgs^e) | ProximityCPP::sealed | [protected]
MainPageResized | ProximityCPP::sealed |
MessageReceived(Windows::Networking::Proximity::ProximityDevice^device, Windows::Networking::Proximity::ProximityMessage^message) | ProximityCPP::sealed | [protected]
NotifyUser(Platform::String^strMessage, NotifyType type) | ProximityCPP::sealed |
OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^pArgs) override | ProximityCPP::sealed | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ProximityCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ProximityCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ProximityCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ProximityCPP::sealed | [protected, virtual]
OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^e) override | ProximityCPP::sealed | [protected, virtual]
OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^e) override | ProximityCPP::sealed | [protected, virtual]
OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^e) override | ProximityCPP::sealed | [protected, virtual]
OnSuspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^pArgs) | ProximityCPP::sealed | [virtual]
PeerFinder_Accept(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | ProximityCPP::sealed | [private]
PeerFinder_BrowsePeers(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | ProximityCPP::sealed | [private]
PeerFinder_Connect(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | ProximityCPP::sealed | [private]
PeerFinder_Send(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | ProximityCPP::sealed | [private]
PeerFinder_StartFindingPeers(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | ProximityCPP::sealed | [private]
PeerFinder_StartReader(Windows::Storage::Streams::DataReader^socketReader) | ProximityCPP::sealed | [private]
PeerFinder_StartSendReceive(Windows::Networking::Sockets::StreamSocket^socket) | ProximityCPP::sealed | [private]
PeerFinderInit() | ProximityCPP::sealed | [private]
PeerFinderReset() | ProximityCPP::sealed | [private]
PeerFinderScenario() | ProximityCPP::sealed |
PopulateScenarios() | ProximityCPP::sealed | [private]
ProximityDevice_PublishMessage(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | ProximityCPP::sealed | [protected]
ProximityDevice_SubscribeForMessage(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | ProximityCPP::sealed | [protected]
ProximityDeviceEvents() | ProximityCPP::sealed |
ProximityDeviceScenario() | ProximityCPP::sealed |
Scenario2Reset() | ProximityCPP::sealed | [private]
ScenarioList | ProximityCPP::sealed | [private]
ScenarioLoaded | ProximityCPP::sealed |
Scenarios_SelectionChanged(Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | ProximityCPP::sealed | [protected]
SetFeatureName(Platform::String^strFeature) | ProximityCPP::sealed | [private]
SetupWindowing(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^pArgs) | ProximityCPP::sealed | [private]
SocketError(Platform::String^errMessage) | ProximityCPP::sealed | [private]
TriggeredConnectionStateChangedEventHandler(Object^sender, Windows::Networking::Proximity::TriggeredConnectionStateChangedEventArgs^e) | ProximityCPP::sealed | [private]
~MainPage() | ProximityCPP::sealed | [private]
Generated on Sat Nov 23 2024 16:09:46 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text display/C++/App.xaml.h Source File

  • XAML text display

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CameraCaptureUI/C++/MainPage.xaml.h Source File

  • CameraCaptureUI

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playback Manager msAudioCategory/C++/common/suspensionmanager.h Source File

  • Playback Manager msAudioCategory
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Search contract/C++/Scenario2.xaml.cpp Source File

  • Search contract

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 SDKSample::SearchContract;
00020
00021 using namespace std;
00022 using namespace Platform;
00023 using namespace Windows::ApplicationModel::Search;
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
00029 Scenario2::Scenario2()
00030 {
00031     InitializeComponent();
00032     searchPane = SearchPane::GetForCurrentView();
00033 }
00034
00035 void Scenario2::OnNavigatedTo(NavigationEventArgs^ e)
00036 {
00037     MainPage::Current->NotifyUser("Use the search pane to submit a query", NotifyType::StatusMessage);
00038     // This event should be registered when your app first creates its main window in App::OnWindowCreated().
00039     token = searchPane->SuggestionsRequested += ref new TypedEventHandler<SearchPane^, SearchPaneSuggestionsRequestedEventArgs^>(this, &Scenario2::OnSearchPaneSuggestionsRequested);
00040 }
00041
00042 void Scenario2::OnNavigatedFrom(NavigationEventArgs^ e)
00043 {
00044     searchPane->SuggestionsRequested -= token;
00045 }
00046
00047 void Scenario2::OnSearchPaneSuggestionsRequested(SearchPane^ sender, SearchPaneSuggestionsRequestedEventArgs^ e)
00048 {
00049     static wstring suggestionList [] =
00050         {
00051             L"shanghai", L"istanbul", L"karachi", L"delhi", L"mumbai", L"moscow", L"são paulo", L"seoul", L"beijing", L"jakarta",
00052             L"tokyo", L"mexico city", L"kinshasa", L"new york city", L"lagos", L"london", L"lima", L"bogota", L"tehran", L"ho chi minh city",
00053             L"hong kong", L"bangkok", L"dhaka", L"cairo", L"hanoi", L"rio de janeiro", L"lahore", L"chonquing", L"bengaluru", L"tianjin",
00054             L"baghdad", L"riyadh", L"singapore", L"santiago", L"saint petersburg", L"surat", L"chennai", L"kolkata", L"yangon", L"guangzhou",
00055             L"alexandria", L"shenyang", L"hyderabad", L"ahmedabad", L"ankara", L"johannesburg", L"wuhan", L"los angeles", L"yokohama",
00056             L"abidjan", L"busan", L"cape town", L"durban", L"pune", L"jeddah", L"berlin", L"pyongyang", L"kanpur", L"madrid", L"jaipur",
00057             L"nairobi", L"chicago", L"houston", L"philadelphia", L"phoenix", L"san antonio", L"san diego", L"dallas", L"san jose",
00058             L"jacksonville", L"indianapolis", L"san francisco", L"austin", L"columbus", L"fort worth", L"charlotte", L"detroit",
00059             L"el paso", L"memphis", L"baltimore", L"boston", L"seattle washington", L"nashville", L"denver", L"louisville", L"milwaukee",
00060             L"portland", L"las vegas", L"oklahoma city", L"albuquerque", L"tucson", L"fresno", L"sacramento", L"long beach", L"kansas city",
00061             L"mesa", L"virginia beach", L"atlanta", L"colorado springs", L"omaha", L"raleigh", L"miami", L"cleveland", L"tulsa", L"oakland",
00062             L"minneapolis", L"wichita", L"arlington", L"bakersfield", L"new orleans", L"honolulu", L"anaheim", L"tampa", L"aurora",
00063             L"santa ana", L"st. louis", L"pittsburgh", L"corpus christi", L"riverside", L"cincinnati", L"lexington", L"anchorage",
00064             L"stockton", L"toledo", L"st. paul", L"newark", L"greensboro", L"buffalo", L"plano", L"lincoln", L"henderson", L"fort wayne",
00065             L"jersey city", L"st. petersburg", L"chula vista", L"norfolk", L"orlando", L"chandler", L"laredo", L"madison", L"winston-salem",
00066             L"lubbock", L"baton rouge", L"durham", L"garland", L"glendale", L"reno", L"hialeah", L"chesapeake", L"scottsdale",
00067             L"north las vegas", L"irving", L"fremont", L"irvine", L"birmingham", L"rochester", L"san bernardino", L"spokane",
00068             L"toronto", L"montreal", L"vancouver", L"ottawa-gatineau", L"calgary", L"edmonton", L"quebec city", L"winnipeg", L"hamilton"
00069         };
00070
00071     auto queryText = e->QueryText;
00072     wstring query = wstring(queryText->Data());
00073     // convert query string to lower case.
00074     transform(query.begin(), query.end(), query.begin(), tolower);
00075     if (queryText->Length() == 0)
00076     {
00077         MainPage::Current->NotifyUser("Use the search pane to submit a query", NotifyType::StatusMessage);
00078     }
00079     else
00080     {
00081         auto request = e->Request;
00082         for each(wstring suggestion in suggestionList)
00083         {
00084             if (suggestion.find(query) == 0)
00085             {
00086                 // if the string starts with the queryText (ignoring case), add suggestion to search pane.
00087                 request->SearchSuggestionCollection->AppendQuerySuggestion(ref new String(const_cast<wchar_t*>(suggestion.c_str())));
00088
00089                 // break since the search pane can show at most 5 suggestions.
00090                 if (request->SearchSuggestionCollection->Size >= MainPage::SearchPaneMaxSuggestions)
00091                 {
00092                     break;
00093                 }
00094             }
00095
00096         }
00097
00098         if (request->SearchSuggestionCollection->Size > 0)
00099         {
00100             MainPage::Current->NotifyUser("Suggestions provided for query: " + queryText, NotifyType::StatusMessage);
00101         }
00102         else
00103         {
00104             MainPage::Current->NotifyUser("No suggestions provided for query: " + queryText, NotifyType::StatusMessage);
00105         }
00106     }
00107 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File picker contracts/C++/FileSavePicker_SaveToCachedFile.xaml.h Source File

  • File picker contracts

FileSavePicker_SaveToCachedFile.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 // FileSavePicker_SaveToCachedFile.xaml.h
00013 // Declaration of the FileSavePicker_SaveToCachedFile class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "FileSavePicker_SaveToCachedFile.g.h"
00020
00021 namespace SDKSample
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         [Windows::Foundation::Metadata::WebHostHidden]
00029         public ref class FileSavePicker_SaveToCachedFile sealed
00030         {
00031         public:
00032             FileSavePicker_SaveToCachedFile();
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         internal:
00039             Windows::Storage::Pickers::Provider::FileSavePickerUI^ fileSavePickerUI;
00040
00041         private:
00042             Platform::String^ fileID;
00043             Windows::Foundation::EventRegistrationToken token;
00044
00045             void OnTargetFileRequested(Windows::Storage::Pickers::Provider::FileSavePickerUI^ sender,  Windows::Storage::Pickers::Provider::TargetFileRequestedEventArgs^ e);
00046         };
00047     }
00048 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Hilo::sealed Member List

This is the complete list of members for Hilo::sealed, including all inherited members.
__pad0__ | Hilo::sealed |
__pad1__ | Hilo::sealed |
App() | Hilo::sealed |
App::OnResume(Object^sender, Platform::Object^e) | Hilo::sealed | [private]
BuildDateQuery() | Hilo::sealed |
CalculateInitialCropOverlayPosition(Windows::UI::Xaml::Media::GeneralTransform^transform, float width, float height) | Hilo::sealed |
callback | Hilo::sealed |
CancelCartoonize(Platform::Object^parameter) | Hilo::sealed |
CancelCrop(Platform::Object^parameter) | Hilo::sealed |
CancelMonthAndYearQueries() | Hilo::sealed |
CancelRotate(Platform::Object^parameter) | Hilo::sealed |
CanExecute(Platform::Object^parameter) | Hilo::sealed | [virtual]
CanExecuteChanged | Hilo::sealed |
CanNavigateToPictures(Platform::Object^parameter) | Hilo::sealed |
CanProcessImage(Object^parameter) | Hilo::sealed |
CanProcessImage(Object^parameter) | Hilo::sealed |
CanProcessImage(Platform::Object^parameter) | Hilo::sealed |
CartoonizeImage(Platform::Object^parameter) | Hilo::sealed |
CartoonizeImage(Platform::Object^parameter) | Hilo::sealed |
CartoonizeImage(Platform::Object^parameter) | Hilo::sealed |
CartoonizeImage(Platform::Object^parameter) | Hilo::sealed |
CartoonizeImageAmpAsync(concurrency::cancellation_token token) | Hilo::sealed |
CartoonizeImagePPLAsync(concurrency::cancellation_token token) | Hilo::sealed |
CartoonizeImageView() | Hilo::sealed |
ChangeInProgress(bool value) | Hilo::sealed |
ChangeInProgress(bool value) | Hilo::sealed |
ChangeInProgress(bool value) | Hilo::sealed |
CheckForCancellation() | Hilo::sealed |
CheckRotationAngle(unsigned int angle) | Hilo::sealed |
ClearCachedData() | Hilo::sealed |
ClearImageData() | Hilo::sealed | [virtual]
Convert(Object^value, Windows::UI::Xaml::Interop::TypeName targetType, Object^parameter, Platform::String^language) | Hilo::sealed | [virtual]
Convert(Object^value, Windows::UI::Xaml::Interop::TypeName targetType, Object^parameter, Platform::String^language) | Hilo::sealed | [virtual]
ConvertBack(Object^value, Windows::UI::Xaml::Interop::TypeName targetType, Object^parameter, Platform::String^language) | Hilo::sealed | [virtual]
ConvertBack(Object^value, Windows::UI::Xaml::Interop::TypeName targetType, Object^parameter, Platform::String^language) | Hilo::sealed | [virtual]
CopyAmpPixelArrayToPixelData(byte *destPixels, AmpPixel *newPixels, unsigned int width, unsigned int height) | Hilo::sealed |
CopyPixelDataToAmpPixelArray(byte *sourcePixels, unsigned int width, unsigned int height, const unsigned int size) | Hilo::sealed |
CopyPixelDataToPlatformArray(Windows::Storage::Streams::IBuffer^buffer, Platform::Array< unsigned char, 1 >^pixels, unsigned int width, unsigned int height) | Hilo::sealed |
CropImage(Platform::Object^parameter) | Hilo::sealed |
CropImage(Platform::Object^parameter) | Hilo::sealed |
CropImage(Platform::Object^parameter) | Hilo::sealed |
CropImageAsync(float64 actualWidth) | Hilo::sealed |
CropImageView() | Hilo::sealed |
DelegateCommand(ExecuteDelegate^execute, CanExecuteDelegate^canExecute) | Hilo::sealed |
DesignTimeData() | Hilo::sealed |
DesignTimeMonthBlock(bool hasPhotos) | Hilo::sealed |
DesignTimePhotoGroup(Platform::String^title) | Hilo::sealed |
DesignTimeYearGroup(Platform::String^title) | Hilo::sealed |
DoCrop(uint32_t xOffset, uint32_t yOffset, uint32_t newHeight, uint32_t newWidth, uint32_t oldWidth, byte *pSrcPixels, byte *pDestPixels) | Hilo::sealed |
emptyTitle | Hilo::sealed |
EncodeImageAsync(Windows::Storage::Streams::IRandomAccessStream^sourceStream) | Hilo::sealed |
EncodeImageAsync(Windows::Storage::Streams::IRandomAccessStream^sourceStream) | Hilo::sealed |
EncodeRotateImageToStream(ImageEncodingInformation decoderInfo, float64 rotationAngle, concurrency::task_continuation_context backgroundContext) | Hilo::sealed |
EndRotation() | Hilo::sealed |
EvaluateCommands() | Hilo::sealed |
exceptionPolicy | Hilo::sealed |
exceptionPolicy | Hilo::sealed |
exceptionPolicy | Hilo::sealed |
exceptionPolicy | Hilo::sealed |
exceptionPolicy | Hilo::sealed |
Execute(Platform::Object^parameter) | Hilo::sealed | [virtual]
FileSizeConverter() | Hilo::sealed |
FileSizeConverter(IResourceLoader^loader) | Hilo::sealed |
FinishMonthAndYearQueries() | Hilo::sealed |
folderQuery | Hilo::sealed |
folderQuery | Hilo::sealed |
GetCustomProperty(Platform::String^name) | Hilo::Common::BindableBase | [virtual]
GetDecoderInfo(Windows::Storage::Streams::IRandomAccessStream^source, concurrency::task_continuation_context backgroundContext) | Hilo::sealed |
GetFileNameFromFileSavePickerAsync(Platform::String^fileType) | Hilo::ImageBase | [protected]
GetImagePhotoAsync() | Hilo::sealed |
GetImagePhotoAsync() | Hilo::sealed |
GetImagePhotoAsync() | Hilo::sealed |
GetIndexedProperty(Platform::String^name, Windows::UI::Xaml::Interop::TypeName type) | Hilo::Common::BindableBase | [virtual]
GetPhotoForYearAndMonth(unsigned int year, unsigned int month) | Hilo::sealed |
GetStateFileDate() | Hilo::sealed |
GetStateFilePath() | Hilo::sealed |
GetStateQuery() | Hilo::sealed |
GetStreamWithFailCheck() | Hilo::ImageBase | [protected]
GetString(Platform::String^value) | Hilo::sealed | [virtual]
Hilo::IResourceLoader::GetString(Platform::String^value) | Hilo::IResourceLoader |
GetStringRepresentation() | Hilo::Common::BindableBase | [virtual]
GoHome() | Hilo::ViewModelBase | [virtual]
GoToPage(PageType page, Platform::Object^parameter) | Hilo::ViewModelBase | [virtual]
ImageBrowserView() | Hilo::sealed |
ImageView() | Hilo::sealed |
Initialize(Platform::String^photoPath) | Hilo::sealed |
Initialize(Platform::String^photoPath) | Hilo::sealed |
Initialize(Platform::String^filePath, Windows::Foundation::DateTime fileDate, Platform::String^query) | Hilo::sealed |
Initialize(Platform::String^photoPath) | Hilo::sealed |
IsCartoonizing(Platform::Object^parameter) | Hilo::sealed |
LoadState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^stateMap) override | Hilo::sealed | [virtual]
LoadState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^stateMap) override | Hilo::sealed | [virtual]
LoadState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^stateMap) override | Hilo::sealed | [virtual]
m_actualHeight | Hilo::sealed |
m_actualWidth | Hilo::sealed |
m_bottom | Hilo::sealed |
m_callback | Hilo::sealed | [private]
m_callback(callback) | Hilo::sealed | [inline]
m_cancelCommand | Hilo::sealed |
m_cancellationTokenSource | Hilo::sealed |
m_canExecute | Hilo::sealed | [private]
m_canExecuteDelegate | Hilo::sealed | [private]
m_cartoonizeCommand | Hilo::sealed |
m_cartoonizeImageCommand | Hilo::sealed |
m_checkedForHardwareAcceleration | Hilo::sealed |
m_columnSpan | Hilo::sealed | [private]
m_count | Hilo::sealed |
m_count | Hilo::sealed |
m_cropImageCommand | Hilo::sealed |
m_cropImageViewModel | Hilo::sealed | [private]
m_cropOverlayHeight | Hilo::sealed |
m_cropOverlayLeft | Hilo::sealed |
m_cropOverlayTop | Hilo::sealed |
m_cropOverlayWidth | Hilo::sealed |
m_cropX | Hilo::sealed |
m_cropY | Hilo::sealed |
m_cts | Hilo::sealed |
m_currentMode | Hilo::sealed |
m_currentQueryId | Hilo::sealed |
m_dateTimeForTitle | Hilo::sealed |
m_emptyTitle | Hilo::sealed |
m_exceptionPolicy | Hilo::sealed | [private]
m_executeDelegate | Hilo::sealed | [private]
m_fileDate | Hilo::sealed |
m_fileInfo | Hilo::sealed | [private]
m_filePath | Hilo::sealed |
m_filmStripLoadedToken | Hilo::sealed | [private]
m_folderQuery | Hilo::sealed |
m_getPhotoAsyncIsRunning | Hilo::sealed |
m_groupCommand | Hilo::sealed |
m_hasCount | Hilo::sealed |
m_hasFileUpdateTask | Hilo::sealed |
m_image | Hilo::sealed |
m_image | Hilo::sealed | [private]
m_imageFailedEventToken | Hilo::sealed | [private]
m_imageMargin | Hilo::sealed |
m_initializationTask | Hilo::sealed |
m_inProgress | Hilo::sealed |
m_isAmpPixelArrayPopulated | Hilo::sealed |
Hilo::m_isAppBarEnabled | Hilo::ViewModelBase |
Hilo::ViewModelBase::m_isAppBarEnabled | Hilo::ViewModelBase |
Hilo::m_isAppBarOpen | Hilo::ViewModelBase |
Hilo::ViewModelBase::m_isAppBarOpen | Hilo::ViewModelBase |
Hilo::m_isAppBarSticky | Hilo::ViewModelBase |
Hilo::ViewModelBase::m_isAppBarSticky | Hilo::ViewModelBase |
m_isCropOverlayVisible | Hilo::sealed |
m_isInvalidThumbnail | Hilo::sealed | [private]
m_isSaving | Hilo::sealed |
m_isSourcePixelsPopulated | Hilo::sealed |
m_lastFileChangeTime | Hilo::sealed |
m_left | Hilo::sealed |
m_loader | Hilo::sealed | [private]
m_month | Hilo::sealed |
m_monthGroups | Hilo::sealed |
m_months | Hilo::sealed |
m_months | Hilo::sealed |
m_name | Hilo::sealed |
m_navigateToPicturesCommand | Hilo::sealed |
m_neighborWindow | Hilo::sealed |
m_phases | Hilo::sealed |
m_photo | Hilo::sealed |
m_photoCache | Hilo::sealed |
m_photoCts | Hilo::sealed |
m_photoPath | Hilo::sealed |
m_photos | Hilo::sealed |
m_photos | Hilo::sealed |
m_photosCts | Hilo::sealed |
m_pictureGroup | Hilo::sealed |
m_pictureGroupPropertyChangedToken | Hilo::sealed |
m_pointer | Hilo::sealed | [private]
m_pointerPressed | Hilo::sealed | [private]
m_pOriginalPixels | Hilo::sealed |
m_pSourcePixels | Hilo::sealed |
m_query | Hilo::sealed |
m_query | Hilo::sealed | [private]
m_queryPhotoImageAsyncIsRunning | Hilo::sealed | [private]
m_receivedChangeWhileRunning | Hilo::sealed |
m_repository | Hilo::sealed | [private]
m_resumeCartoonizeCommand | Hilo::sealed |
m_resumeCropCommand | Hilo::sealed |
m_resumeRotateCommand | Hilo::sealed |
m_retrievedPhotos | Hilo::sealed |
m_right | Hilo::sealed |
m_rotateCommand | Hilo::sealed |
m_rotateImageCommand | Hilo::sealed |
m_rotationAngle | Hilo::sealed |
m_rowSpan | Hilo::sealed |
m_runningMonthQuery | Hilo::sealed |
m_runningOperation | Hilo::sealed |
m_runningQuery | Hilo::sealed |
m_runningQueryPhotosAsync | Hilo::sealed |
m_runningQuerySinglePhotoAsync | Hilo::sealed |
m_runningYearQuery | Hilo::sealed |
m_runOperation | Hilo::sealed |
m_saveCommand | Hilo::sealed |
m_scaledHeight | Hilo::sealed |
m_scaledWidth | Hilo::sealed |
m_sizeChangedAttached | Hilo::sealed | [private]
m_thumbnailUpdatedEventToken | Hilo::sealed | [private]
m_tileUpdateScheduler | Hilo::sealed | [private]
m_top | Hilo::sealed |
m_useHardwareAcceleration | Hilo::sealed |
m_viewModel | Hilo::sealed | [private]
m_watchToken | Hilo::sealed | [private]
m_weakPhotoCache | Hilo::sealed |
m_weakPhotoGroup | Hilo::sealed | [private]
m_year | Hilo::sealed |
m_yearDate | Hilo::sealed |
m_yearGroups | Hilo::sealed |
MainHubView() | Hilo::sealed |
month | Hilo::sealed |
Hilo::NavigateBack | Hilo::ViewModelBase |
Hilo::ViewModelBase::NavigateBack | Hilo::ViewModelBase |
Hilo::NavigateHome | Hilo::ViewModelBase |
Hilo::ViewModelBase::NavigateHome | Hilo::ViewModelBase |
NavigateToGroup(Platform::Object^parameter) | Hilo::sealed |
Hilo::NavigateToPage | Hilo::ViewModelBase |
Hilo::ViewModelBase::NavigateToPage | Hilo::ViewModelBase |
NavigateToPictures(Platform::Object^parameter) | Hilo::sealed |
ObserveFileChange() | Hilo::sealed |
ObserveFileChange() | Hilo::sealed |
OnCropRectangleTapped(Platform::Object^sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^e) | Hilo::sealed | [private]
OnDataChanged() | Hilo::sealed |
OnDataChanged() | Hilo::sealed |
OnDataChanged() | Hilo::sealed |
OnFileQueryContentsChanged(Windows::Storage::Search::IStorageQueryResultBase^sender, Platform::Object^e) | Hilo::sealed | [inline, private]
OnFilmStripLoaded(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Hilo::sealed | [private]
OnImageFailedToOpen(Platform::Object^sender, Windows::UI::Xaml::ExceptionRoutedEventArgs^e) | Hilo::sealed | [private]
OnImagePointerMoved(Platform::Object^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^e) | Hilo::sealed | [private]
OnImagePointerPressed(Platform::Object^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^e) | Hilo::sealed | [private]
OnImagePointerReleased(Platform::Object^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^e) | Hilo::sealed | [private]
OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^args) override | Hilo::sealed | [virtual]
OnManipulationCompleted(Windows::UI::Xaml::Input::ManipulationCompletedRoutedEventArgs^e) override | Hilo::sealed | [protected, virtual]
OnManipulationDelta(Windows::UI::Xaml::Input::ManipulationDeltaRoutedEventArgs^e) override | Hilo::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | Hilo::sealed | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | Hilo::sealed | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | Hilo::sealed | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | Hilo::sealed | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | Hilo::sealed | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | Hilo::sealed | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | Hilo::sealed | [virtual]
OnPhotoItemClicked(Platform::Object^sender, Windows::UI::Xaml::Controls::ItemClickEventArgs^e) | Hilo::sealed | [private]
OnPhotoItemClicked(Platform::Object^sender, Windows::UI::Xaml::Controls::ItemClickEventArgs^e) | Hilo::sealed | [private]
OnPictureGroupPropertyChanged(Platform::Object^sender, Windows::UI::Xaml::Data::PropertyChangedEventArgs^e) | Hilo::sealed |
OnPropertyChanged(Platform::String^propertyName) | Hilo::sealed |
OnPropertyChanged(Platform::String^propertyName) | Hilo::sealed |
OnPropertyChanged(Platform::String^propertyName) | Hilo::sealed |
OnPropertyChanged(Platform::String^propertyName) | Hilo::sealed | [private]
OnPropertyChanged(Platform::String^propertyName) | Hilo::sealed |
OnSizeChanged(Platform::Object^sender, Windows::UI::Xaml::SizeChangedEventArgs^e) | Hilo::sealed | [private]
OnSuspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^e) | Hilo::sealed | [private]
OnThumbDragDelta(Platform::Object^sender, Windows::UI::Xaml::Controls::Primitives::DragDeltaEventArgs^e) | Hilo::sealed | [private]
OnThumbnailUpdated(Windows::Storage::BulkAccess::IStorageItemInformation^sender, Platform::Object^e) | Hilo::sealed | [private]
OnViewChangeCompleted(Platform::Object^sender, Windows::UI::Xaml::Controls::SemanticZoomViewChangedEventArgs^e) | Hilo::sealed | [private]
OnZoomedOutGridPointerEntered(Platform::Object^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^e) | Hilo::sealed | [private]
OpenReadAsync() | Hilo::IPhoto |
photoGroup | Hilo::sealed |
PhotoSizeChanged(Platform::Object^sender, Windows::UI::Xaml::SizeChangedEventArgs^e) | Hilo::sealed | [private]
PrepareContainerForItemOverride(Windows::UI::Xaml::DependencyObject^element, Platform::Object^item) override | Hilo::sealed | [protected, virtual]
PropertyChanged | Hilo::sealed |
QueryPhotoCount() | Hilo::sealed |
QueryPhotosAsync() | Hilo::sealed |
QueryPhotosAsync() | Hilo::sealed |
QueryPhotosAsync() | Hilo::sealed |
QuerySinglePhotoAsync() | Hilo::sealed |
repository | Hilo::sealed |
repository | Hilo::sealed |
repository | Hilo::sealed |
Rotate90(Platform::Object^parameter) | Hilo::sealed |
RotateImage(Platform::Object^parameter) | Hilo::sealed |
RotateImage(Platform::Object^parameter) | Hilo::sealed |
RotateImage(Platform::Object^parameter) | Hilo::sealed |
RotateImageView() | Hilo::sealed |
RotateImageViewModel::RotateImageAsync(Windows::Storage::Streams::IRandomAccessStream^sourceStream, float64 angle) | Hilo::sealed |
RotateImageViewModel::SetEncodingRotation(Windows::Graphics::Imaging::BitmapEncoder^encoder, std::shared_ptr< ImageEncodingInformation > decoderInfo, float64 rotationAngle, concurrency::task_continuation_context backgroundContext) | Hilo::sealed |
SaveImage(Platform::Object^parameter) | Hilo::sealed |
SaveImage(Platform::Object^parameter) | Hilo::sealed |
SaveImage(Platform::Object^parameter) | Hilo::sealed |
SaveImageAsync(Windows::Storage::StorageFile^file, Windows::Storage::Streams::IRandomAccessStream^ras) | Hilo::ImageBase | [protected]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^stateMap) override | Hilo::sealed | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^stateMap) override | Hilo::sealed | [virtual]
SaveState(Windows::Foundation::Collections::IMap< Platform::String^, Platform::Object^>^stateMap) override | Hilo::sealed | [virtual]
ScaleImageDimensions(unsigned int origWidth, unsigned int origHeight) | Hilo::sealed |
StartMonthAndYearQueries() | Hilo::sealed |
StartMonthQuery(int queryId, concurrency::cancellation_token token) | Hilo::sealed |
StartYearQuery(int queryId, concurrency::cancellation_token token) | Hilo::sealed |
ToTwoDecimalPlaces(float64 value) | Hilo::sealed | [private]
Unsnap(Platform::Object^parameter) | Hilo::sealed |
Unsnap(Platform::Object^parameter) | Hilo::sealed |
Unsnap(Platform::Object^parameter) | Hilo::sealed |
UpdateCropOverlayPostion(Windows::UI::Xaml::Controls::Primitives::Thumb^thumb, float64 verticalChange, float64 horizontalChange, float64 minWidth, float64 minHeight) | Hilo::sealed |
ViewModelLocator() | Hilo::sealed |
~CartoonizeImageViewModel() | Hilo::sealed | [virtual]
~HubPhotoGroup() | Hilo::sealed | [virtual]
~ImageBrowserViewModel() | Hilo::sealed | [virtual]
~ImageView() | Hilo::sealed | [virtual]
~ImageViewModel() | Hilo::sealed | [virtual]
~MainHubViewModel() | Hilo::sealed | [virtual]
~Photo() | Hilo::sealed | [virtual]
~QueryChange() | Hilo::sealed | [inline, virtual]
Generated on Sat Nov 23 2024 16:09:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Animation metrics/C++/common/suspensionmanager.h Source File

  • Animation metrics
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML WebView control/C++/pch.h Source File

  • XAML WebView control

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D stereoscopic 3D/C++/DirectXBase.cpp Source File

  • Direct3D stereoscopic 3D

DirectXBase.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 "DirectXBase.h"
00010
00011 using namespace Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::Graphics::Display;
00015 using namespace D2D1;
00016 using namespace DirectX;
00017
00018 DirectXBase::DirectXBase() :
00019     m_windowSizeChangeInProgress(false),
00020     m_dpi(-1.0f)
00021 {
00022 }
00023
00024 // Initialize the DirectX resources required to run.
00025 void DirectXBase::Initialize(CoreWindow^ window, float dpi)
00026 {
00027     m_window = window;
00028
00029     CreateDeviceIndependentResources();
00030     CreateDeviceResources();
00031     SetDpi(dpi);
00032
00033     DisplayProperties::StereoEnabledChanged +=
00034         ref new DisplayPropertiesEventHandler(this, &DirectXBase::OnStereoEnabledChanged);
00035 }
00036
00037 // Recreate all device resources and set them back to the current state.
00038 void DirectXBase::HandleDeviceLost()
00039 {
00040     // Reset these member variables to ensure that SetDpi recreates all resources.
00041     float dpi = m_dpi;
00042     m_dpi = -1.0f;
00043     m_windowBounds.Width = 0;
00044     m_windowBounds.Height = 0;
00045     m_swapChain = nullptr;
00046
00047     // Make sure the rendering state has been released.
00048     m_d3dContext->OMSetRenderTargets(0, nullptr, nullptr);
00049     m_d3dDepthStencilView = nullptr;
00050     m_d3dRenderTargetView = nullptr;
00051     m_d3dRenderTargetViewRight = nullptr;
00052
00053     m_d2dContext->SetTarget(nullptr);
00054     m_d2dTargetBitmap = nullptr;
00055     m_d2dTargetBitmapRight = nullptr;
00056     m_d2dContext = nullptr;
00057     m_d2dDevice = nullptr;
00058
00059     m_d3dContext->Flush();
00060
00061     CreateDeviceResources();
00062     SetDpi(dpi);
00063 }
00064
00065 // These are the resources required independent of the device.
00066 void DirectXBase::CreateDeviceIndependentResources()
00067 {
00068     D2D1_FACTORY_OPTIONS options;
00069     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00070
00071 #if defined(_DEBUG)
00072     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00073     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00074 #endif
00075
00076     DX::ThrowIfFailed(
00077         D2D1CreateFactory(
00078             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00079             __uuidof(ID2D1Factory1),
00080             &options,
00081             &m_d2dFactory
00082             )
00083         );
00084
00085     DX::ThrowIfFailed(
00086         DWriteCreateFactory(
00087             DWRITE_FACTORY_TYPE_SHARED,
00088             __uuidof(IDWriteFactory),
00089             &m_dwriteFactory
00090             )
00091         );
00092
00093     DX::ThrowIfFailed(
00094         CoCreateInstance(
00095             CLSID_WICImagingFactory,
00096             nullptr,
00097             CLSCTX_INPROC_SERVER,
00098             IID_PPV_ARGS(&m_wicFactory)
00099             )
00100         );
00101 }
00102
00103 // These are the resources that depend on the device.
00104 void DirectXBase::CreateDeviceResources()
00105 {
00106     // This flag adds support for surfaces with a different color channel ordering
00107     // than the API default. It is required for compatibility with Direct2D.
00108     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00109     ComPtr<IDXGIDevice> dxgiDevice;
00110
00111 #if defined(_DEBUG)
00112     // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00113     creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00114 #endif
00115
00116     // This array defines the set of DirectX hardware feature levels this app will support.
00117     // Note the ordering should be preserved.
00118     // Don't forget to declare your application's minimum required feature level in its
00119     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00120     D3D_FEATURE_LEVEL featureLevels[] =
00121     {
00122         D3D_FEATURE_LEVEL_11_1,
00123         D3D_FEATURE_LEVEL_11_0,
00124         D3D_FEATURE_LEVEL_10_1,
00125         D3D_FEATURE_LEVEL_10_0,
00126         D3D_FEATURE_LEVEL_9_3,
00127         D3D_FEATURE_LEVEL_9_2,
00128         D3D_FEATURE_LEVEL_9_1
00129     };
00130
00131     // Create the Direct3D 11 API device object and a corresponding context.
00132     ComPtr<ID3D11Device> device;
00133     ComPtr<ID3D11DeviceContext> context;
00134     DX::ThrowIfFailed(
00135         D3D11CreateDevice(
00136             nullptr,                    // Specify nullptr to use the default adapter.
00137             D3D_DRIVER_TYPE_HARDWARE,
00138             0,
00139             creationFlags,              // Set debug and Direct2D compatibility flags.
00140             featureLevels,              // List of feature levels this app can support.
00141             ARRAYSIZE(featureLevels),
00142             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Metro style apps.
00143             &device,                    // Returns the Direct3D device created.
00144             &m_featureLevel,            // Returns feature level of device created.
00145             &context                    // Returns the device immediate context.
00146             )
00147         );
00148
00149     // Get the Direct3D 11.1 API device and context interfaces.
00150     DX::ThrowIfFailed(
00151         device.As(&m_d3dDevice)
00152         );
00153
00154     DX::ThrowIfFailed(
00155         context.As(&m_d3dContext)
00156         );
00157
00158     // Get the underlying DXGI device of the Direct3D device.
00159     DX::ThrowIfFailed(
00160         m_d3dDevice.As(&dxgiDevice)
00161         );
00162
00163     // Create the Direct2D device object and a corresponding context.
00164     DX::ThrowIfFailed(
00165         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00166         );
00167
00168     DX::ThrowIfFailed(
00169         m_d2dDevice->CreateDeviceContext(
00170             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00171             &m_d2dContext
00172             )
00173         );
00174 }
00175
00176 // Event handler for StereoEnabled changes.
00177 void DirectXBase::OnStereoEnabledChanged(
00178     _In_ Platform::Object^ /* sender */
00179     )
00180 {
00181     UpdateForWindowSizeChange();
00182 }
00183
00184 // Helps track the DPI in the helper class.
00185 void DirectXBase::SetDpi(float dpi)
00186 {
00187     if (dpi != m_dpi)
00188     {
00189         // Save the DPI of this display in our class.
00190         m_dpi = dpi;
00191
00192         // Update Direct2D's stored DPI.
00193         m_d2dContext->SetDpi(m_dpi, m_dpi);
00194
00195         // Often a DPI change implies a window size change. In some cases Windows will issue
00196         // both a size changed event and a DPI changed event. In this case, the resulting bounds
00197         // will not change, and the window resize code will only be executed once.
00198         UpdateForWindowSizeChange();
00199     }
00200 }
00201
00202 bool DirectXBase::GetStereoEnabledStatus()
00203 {
00204     return m_stereoEnabled;
00205 }
00206
00207 void DirectXBase::UpdateStereoEnabledStatus()
00208 {
00209     // First, retrieve the underlying DXGI Device from the Direct3D Device.
00210     ComPtr<IDXGIDevice1> dxgiDevice;
00211     DX::ThrowIfFailed(
00212         m_d3dDevice.As(&dxgiDevice)
00213         );
00214
00215     // Next, get the associated adapter from the DXGI Device.
00216     ComPtr<IDXGIAdapter> dxgiAdapter;
00217     DX::ThrowIfFailed(
00218         dxgiDevice->GetAdapter(&dxgiAdapter)
00219         );
00220
00221     // Next, get the parent factory from the DXGI adapter.
00222     ComPtr<IDXGIFactory2> dxgiFactory;
00223     DX::ThrowIfFailed(
00224         dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00225         );
00226
00227     m_stereoEnabled = dxgiFactory->IsWindowedStereoEnabled() ? true : false;
00228 }
00229
00230 // This routine is called in the event handler for the view SizeChanged event.
00231 void DirectXBase::UpdateForWindowSizeChange()
00232 {
00233     // Only handle window size changed if there is no pending DPI change.
00234     if (m_dpi != DisplayProperties::LogicalDpi)
00235     {
00236         return;
00237     }
00238
00239     bool previousStereoState = m_stereoEnabled;
00240     UpdateStereoEnabledStatus();
00241     if (previousStereoState != m_stereoEnabled)
00242     {
00243         // Swap chain needs to be recreated so release the existing one.
00244         // The rest of the dependent resources with be released in CreateWindowSizeDependentResources.
00245         m_swapChain = nullptr;
00246         m_windowSizeChangeInProgress = true;
00247         CreateWindowSizeDependentResources();
00248     }
00249     else if (m_window->Bounds.Width != m_windowBounds.Width ||
00250         m_window->Bounds.Height != m_windowBounds.Height)
00251     {
00252         m_windowSizeChangeInProgress = true;
00253         CreateWindowSizeDependentResources();
00254     }
00255 }
00256
00257 // Allocate all memory resources that change on a window SizeChanged event.
00258 void DirectXBase::CreateWindowSizeDependentResources()
00259 {
00260     // Store the window bounds so the next time we get a SizeChanged event we can
00261     // avoid rebuilding everything if the size is identical.
00262     m_windowBounds = m_window->Bounds;
00263
00264     // If the swap chain already exists, resize it.
00265     if (m_swapChain != nullptr)
00266     {
00267         // Existing swap chain needs to be resized.
00268         // Make sure that the dependent objects have been released.
00269         m_d3dContext->OMSetRenderTargets(0, nullptr, nullptr);
00270         m_d3dRenderTargetView = nullptr;
00271         m_d3dDepthStencilView = nullptr;
00272         m_d2dContext->SetTarget(nullptr);
00273         m_d2dTargetBitmap = nullptr;
00274         m_d2dTargetBitmapRight = nullptr;
00275         m_d3dRenderTargetViewRight = nullptr;
00276
00277         HRESULT hr = m_swapChain->ResizeBuffers(2, 0, 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0);
00278
00279         if (hr == DXGI_ERROR_DEVICE_REMOVED)
00280         {
00281             // If the device was removed for any reason, a new device and swapchain will need to be created.
00282             HandleDeviceLost();
00283
00284             // Everything is set up now. Do not continue execution of this method.
00285             return;
00286         }
00287         else
00288         {
00289             DX::ThrowIfFailed(hr);
00290         }
00291     }
00292     else    // Otherwise, create a new one.
00293     {
00294         // m_swapChain is nullptr either because it has never been created or because it has been
00295         // invalidated. Make sure that the dependent objects are also released.
00296         m_d3dContext->OMSetRenderTargets(0, nullptr, nullptr);
00297         m_d3dRenderTargetView = nullptr;
00298         m_d3dDepthStencilView = nullptr;
00299         m_d2dContext->SetTarget(nullptr);
00300         m_d2dTargetBitmap = nullptr;
00301         m_d3dRenderTargetViewRight = nullptr;
00302         m_d2dTargetBitmapRight = nullptr;
00303         m_d3dContext->Flush();
00304
00305         // Allocate a descriptor.
00306         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00307         swapChainDesc.Width = 0;                                     // Use automatic sizing.
00308         swapChainDesc.Height = 0;
00309         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;           // This is the most common swap chain format.
00310         swapChainDesc.Stereo = m_stereoEnabled;
00311         swapChainDesc.SampleDesc.Count = 1;                          // Don't use multi-sampling.
00312         swapChainDesc.SampleDesc.Quality = 0;
00313         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00314         swapChainDesc.BufferCount = 2;                               // Use double buffering to minimize latency.
00315         swapChainDesc.Scaling = DXGI_SCALING_NONE;
00316         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Metro style apps must use this SwapEffect.
00317         swapChainDesc.Flags = 0;
00318
00319         // Once the desired swap chain description is configured, it must be created on the same adapter as our D3D Device.
00320
00321         // First, retrieve the underlying DXGI Device from the D3D Device.
00322         ComPtr<IDXGIDevice1> dxgiDevice;
00323         DX::ThrowIfFailed(
00324             m_d3dDevice.As(&dxgiDevice)
00325             );
00326
00327         // Identify the physical adapter (GPU or card) this device is running on.
00328         ComPtr<IDXGIAdapter> dxgiAdapter;
00329         DX::ThrowIfFailed(
00330             dxgiDevice->GetAdapter(&dxgiAdapter)
00331             );
00332
00333         // And obtain the factory object that created it.
00334         ComPtr<IDXGIFactory2> dxgiFactory;
00335         DX::ThrowIfFailed(
00336             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00337             );
00338
00339         // Obtain the final swap chain for this window from the DXGI factory.
00340         CoreWindow^ window = m_window.Get();
00341         DX::ThrowIfFailed(
00342             dxgiFactory->CreateSwapChainForCoreWindow(
00343                 m_d3dDevice.Get(),
00344                 reinterpret_cast<IUnknown*>(window),
00345                 &swapChainDesc,
00346                 nullptr,    // allow on all displays
00347                 &m_swapChain
00348                 )
00349             );
00350
00351         // Ensure that DXGI does not queue more than one frame at a time. This both reduces
00352         // latency and ensures that the application will only render after each VSync, minimizing
00353         // power consumption.
00354         DX::ThrowIfFailed(
00355             dxgiDevice->SetMaximumFrameLatency(1)
00356             );
00357     }
00358
00359     // Obtain the backbuffer for this window which will be the final 3D rendertarget.
00360     ComPtr<ID3D11Texture2D> backBuffer;
00361     DX::ThrowIfFailed(
00362         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00363         );
00364
00365     // Create a descriptor for the RenderTargetView.
00366     CD3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc(
00367         D3D11_RTV_DIMENSION_TEXTURE2DARRAY,
00368         DXGI_FORMAT_B8G8R8A8_UNORM,
00369         0,
00370         0,
00371         1
00372         );
00373
00374     // Create a view interface on the rendertarget to use on bind for mono or left eye view.
00375     DX::ThrowIfFailed(
00376         m_d3dDevice->CreateRenderTargetView(
00377             backBuffer.Get(),
00378             &renderTargetViewDesc,
00379             &m_d3dRenderTargetView
00380             )
00381         );
00382
00383     // Stereo swapchains have an arrayed resource, so create a second Render Target
00384     // for the right eye buffer.
00385     if (m_stereoEnabled)
00386     {
00387         CD3D11_RENDER_TARGET_VIEW_DESC renderTargetViewRightDesc(
00388             D3D11_RTV_DIMENSION_TEXTURE2DARRAY,
00389             DXGI_FORMAT_B8G8R8A8_UNORM,
00390             0,
00391             1,
00392             1
00393             );
00394
00395         DX::ThrowIfFailed(
00396             m_d3dDevice->CreateRenderTargetView(
00397                 backBuffer.Get(),
00398                 &renderTargetViewRightDesc,
00399                 &m_d3dRenderTargetViewRight
00400                 )
00401             );
00402     }
00403
00404     // Cache the rendertarget dimensions in our helper class for convenient use.
00405     D3D11_TEXTURE2D_DESC backBufferDesc = {0};
00406     backBuffer->GetDesc(&backBufferDesc);
00407     m_renderTargetSize.Width  = static_cast<float>(backBufferDesc.Width);
00408     m_renderTargetSize.Height = static_cast<float>(backBufferDesc.Height);
00409
00410     // Create a descriptor for the depth/stencil buffer.
00411     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00412         DXGI_FORMAT_D24_UNORM_S8_UINT,
00413         backBufferDesc.Width,
00414         backBufferDesc.Height,
00415         1,
00416         1,
00417         D3D11_BIND_DEPTH_STENCIL
00418         );
00419
00420     // Allocate a 2-D surface as the depth/stencil buffer.
00421     ComPtr<ID3D11Texture2D> depthStencil;
00422     DX::ThrowIfFailed(
00423         m_d3dDevice->CreateTexture2D(
00424             &depthStencilDesc,
00425             nullptr,
00426             &depthStencil
00427             )
00428         );
00429
00430     // Create a DepthStencil view on this surface to use on bind.
00431     auto viewDesc = CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D);
00432     DX::ThrowIfFailed(
00433         m_d3dDevice->CreateDepthStencilView(
00434             depthStencil.Get(),
00435             &viewDesc,
00436             &m_d3dDepthStencilView
00437             )
00438         );
00439
00440     // Create a viewport descriptor of the full window size.
00441     CD3D11_VIEWPORT viewport(
00442         0.0f,
00443         0.0f,
00444         static_cast<float>(backBufferDesc.Width),
00445         static_cast<float>(backBufferDesc.Height)
00446         );
00447
00448     // Set the current viewport using the descriptor.
00449     m_d3dContext->RSSetViewports(1, &viewport);
00450
00451     // Now we set up the Direct2D render target bitmap linked to the swapchain.
00452     // Whenever we render to this bitmap, it will be directly rendered to the
00453     // swapchain associated with the window.
00454     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00455         BitmapProperties1(
00456             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00457             PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00458             m_dpi,
00459             m_dpi
00460             );
00461
00462     // Direct2D needs the dxgi version of the backbuffer surface pointer.
00463     ComPtr<IDXGIResource1> dxgiBackBuffer;
00464     DX::ThrowIfFailed(
00465         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00466         );
00467
00468     ComPtr<IDXGISurface2> dxgiSurface;
00469     DX::ThrowIfFailed(
00470         dxgiBackBuffer->CreateSubresourceSurface(0, &dxgiSurface)
00471         );
00472
00473     // Get a D2D surface from the DXGI back buffer to use as the D2D render target.
00474     DX::ThrowIfFailed(
00475         m_d2dContext->CreateBitmapFromDxgiSurface(
00476             dxgiSurface.Get(),
00477             &bitmapProperties,
00478             &m_d2dTargetBitmap
00479             )
00480         );
00481
00482     // Stereo swapchains have an arrayed resource, so create a second Target Bitmap
00483     // for the right eye buffer.
00484     if (m_stereoEnabled)
00485     {
00486         DX::ThrowIfFailed(
00487             dxgiBackBuffer->CreateSubresourceSurface(1, &dxgiSurface)
00488             );
00489         DX::ThrowIfFailed(
00490             m_d2dContext->CreateBitmapFromDxgiSurface(
00491                 dxgiSurface.Get(),
00492                 &bitmapProperties,
00493                 &m_d2dTargetBitmapRight
00494             )
00495         );
00496     }
00497
00498     // So now we can set the Direct2D render target.
00499     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00500
00501     // Set D2D text anti-alias mode to Grayscale to ensure proper rendering of text on intermediate surfaces.
00502     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00503 }
00504
00505 // Method to deliver the final image to the display.
00506 void DirectXBase::Present()
00507 {
00508     // The application may optionally specify "dirty" or "scroll" rects to improve efficiency
00509     // in certain scenarios.  In this sample, however, we do not utilize those features.
00510     DXGI_PRESENT_PARAMETERS parameters = {0};
00511     parameters.DirtyRectsCount = 0;
00512     parameters.pDirtyRects = nullptr;
00513     parameters.pScrollRect = nullptr;
00514     parameters.pScrollOffset = nullptr;
00515
00516     // The first argument instructs DXGI to block until VSync, putting the application
00517     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00518     // frames that will never be displayed to the screen.
00519     HRESULT hr = m_swapChain->Present1(1, 0, &parameters);
00520
00521     // If the device was removed either by a disconnect or a driver upgrade, we
00522     // must recreate all device resources.
00523     if (hr == DXGI_ERROR_DEVICE_REMOVED)
00524     {
00525         // Recreate the Device Resources.
00526         HandleDeviceLost();
00527     }
00528     else
00529     {
00530         DX::ThrowIfFailed(hr);
00531     }
00532
00533     if (m_windowSizeChangeInProgress)
00534     {
00535         // A window size change has been initiated and the app has just completed presenting
00536         // the first frame with the new size. Notify the resize manager so we can short
00537         // circuit any resize animation and prevent unnecessary delays.
00538         CoreWindowResizeManager::GetForCurrentView()->NotifyLayoutCompleted();
00539         m_windowSizeChangeInProgress = false;
00540     }
00541 }
Generated on Sat Nov 23 2024 16:08:02 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playback Manager Companion/C++/StreamTypeCommunications.xaml.cpp Source File

  • Playback Manager Companion

StreamTypeCommunications.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 // StreamTypeCommunications.xaml.cpp
00013 // Implementation of the StreamTypeCommunications class
00014 //
00015
00016 #include "pch.h"
00017 #include "StreamTypeCommunications.xaml.h"
00018
00019 using namespace SDKSample::PlaybackManager2;
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::UI::Xaml::Media;
00025
00026 StreamTypeCommunications::StreamTypeCommunications()
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 StreamTypeCommunications::OnNavigatedTo(NavigationEventArgs^ e)
00037 {
00038     // Get a pointer to our main page.
00039     rootPage = MainPage::Current;
00040 }
00041
00042
00043 void StreamTypeCommunications::Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00044 {
00045     Playback->SetAudioCategory(AudioCategory::Communications);
00046     Playback->SetAudioDeviceType(AudioDeviceType::Communications);
00047     Playback->SelectFile();
00048 }
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML FlipView control/C++/MainPage.xaml.cpp Source File

  • XAML FlipView control

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML high contrast style/C++/MainPage.xaml.h Source File

  • XAML high contrast style

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX touch input/C++/SampleOverlay.cpp Source File

  • DirectX touch input

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 Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::UI::ViewManagement;
00015 using namespace Windows::Graphics::Display;
00016 using namespace D2D1;
00017
00018 SampleOverlay::SampleOverlay() :
00019     m_drawOverlay(true)
00020 {
00021 }
00022
00023 void SampleOverlay::Initialize(
00024     _In_ ID2D1Device*         d2dDevice,
00025     _In_ ID2D1DeviceContext*  d2dContext,
00026     _In_ IWICImagingFactory*  wicFactory,
00027     _In_ IDWriteFactory*      dwriteFactory,
00028     _In_ Platform::String^    caption
00029     )
00030 {
00031     m_wicFactory = wicFactory;
00032     m_dwriteFactory = dwriteFactory;
00033     m_sampleName = caption;
00034     m_d2dDevice = d2dDevice;
00035     m_d2dContext = d2dContext;
00036     m_padding = 3.0f;
00037     m_textVerticalOffset = 5.0f;
00038     m_logoSize = D2D1::SizeF(0.0f, 0.0f);
00039     m_overlayWidth = 0.0f;
00040
00041     ComPtr<ID2D1Factory> factory;
00042     d2dDevice->GetFactory(&factory);
00043
00044     DX::ThrowIfFailed(
00045         factory.As(&m_d2dFactory)
00046         );
00047
00048     ResetDirectXResources();
00049 }
00050
00051 void SampleOverlay::ResetDirectXResources()
00052 {
00053     DX::ThrowIfFailed(
00054         m_d2dContext->CreateSolidColorBrush(ColorF(ColorF::White), &m_whiteBrush)
00055         );
00056
00057     ComPtr<IWICBitmapDecoder> wicBitmapDecoder;
00058     DX::ThrowIfFailed(
00059         m_wicFactory->CreateDecoderFromFilename(
00060             L"windowsbig-sdk.png",
00061             nullptr,
00062             GENERIC_READ,
00063             WICDecodeMetadataCacheOnDemand,
00064             &wicBitmapDecoder
00065             )
00066         );
00067
00068     ComPtr<IWICBitmapFrameDecode> wicBitmapFrame;
00069     DX::ThrowIfFailed(
00070         wicBitmapDecoder->GetFrame(0, &wicBitmapFrame)
00071         );
00072
00073     ComPtr<IWICFormatConverter> wicFormatConverter;
00074     DX::ThrowIfFailed(
00075         m_wicFactory->CreateFormatConverter(&wicFormatConverter)
00076         );
00077
00078     DX::ThrowIfFailed(
00079         wicFormatConverter->Initialize(
00080             wicBitmapFrame.Get(),
00081             GUID_WICPixelFormat32bppPBGRA,
00082             WICBitmapDitherTypeNone,
00083             nullptr,
00084             0.0,
00085             WICBitmapPaletteTypeCustom  // the BGRA format has no palette so this value is ignored
00086             )
00087         );
00088
00089     double dpiX = 96.0f;
00090     double dpiY = 96.0f;
00091     DX::ThrowIfFailed(
00092         wicFormatConverter->GetResolution(&dpiX, &dpiY)
00093         );
00094
00095     DX::ThrowIfFailed(
00096         m_d2dContext->CreateBitmapFromWicBitmap(
00097             wicFormatConverter.Get(),
00098             BitmapProperties(
00099                 PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00100                 static_cast<float>(dpiX),
00101                 static_cast<float>(dpiY)
00102                 ),
00103             &m_logoBitmap
00104             )
00105         );
00106
00107     m_logoSize = m_logoBitmap->GetSize();
00108
00109     ComPtr<IDWriteTextFormat> nameTextFormat;
00110     DX::ThrowIfFailed(
00111         m_dwriteFactory->CreateTextFormat(
00112             L"Segoe UI",
00113             nullptr,
00114             DWRITE_FONT_WEIGHT_LIGHT,
00115             DWRITE_FONT_STYLE_NORMAL,
00116             DWRITE_FONT_STRETCH_NORMAL,
00117             36.0f,
00118             L"en-US",
00119             &nameTextFormat
00120             )
00121         );
00122
00123     DX::ThrowIfFailed(
00124         nameTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)
00125         );
00126
00127     DX::ThrowIfFailed(
00128         nameTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)
00129         );
00130
00131     DX::ThrowIfFailed(
00132         m_dwriteFactory->CreateTextLayout(
00133             m_sampleName->Data(),
00134             m_sampleName->Length(),
00135             nameTextFormat.Get(),
00136             4096.0f,
00137             4096.0f,
00138             &m_textLayout
00139             )
00140         );
00141
00142     DWRITE_TEXT_METRICS metrics = {0};
00143     DX::ThrowIfFailed(
00144         m_textLayout->GetMetrics(&metrics)
00145         );
00146
00147     m_overlayWidth = m_padding * 3.0f + m_logoSize.width + metrics.width;
00148
00149     DX::ThrowIfFailed(
00150         m_d2dFactory->CreateDrawingStateBlock(&m_stateBlock)
00151         );
00152
00153     UpdateForWindowSizeChange();
00154 }
00155
00156 void SampleOverlay::UpdateForWindowSizeChange()
00157 {
00158     if (CoreWindow::GetForCurrentThread()->Bounds.Width < m_overlayWidth)
00159     {
00160         m_drawOverlay = false;
00161     }
00162     else
00163     {
00164         m_drawOverlay = true;
00165     }
00166 }
00167
00168 void SampleOverlay::Render()
00169 {
00170     if (m_drawOverlay)
00171     {
00172         m_d2dContext->SaveDrawingState(m_stateBlock.Get());
00173
00174         m_d2dContext->BeginDraw();
00175         m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00176         m_d2dContext->DrawBitmap(
00177             m_logoBitmap.Get(),
00178             D2D1::RectF(m_padding, 0.0f, m_logoSize.width + m_padding, m_logoSize.height)
00179             );
00180
00181         m_d2dContext->DrawTextLayout(
00182             Point2F(m_logoSize.width + 2.0f * m_padding, m_textVerticalOffset),
00183             m_textLayout.Get(),
00184             m_whiteBrush.Get()
00185             );
00186
00187         // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00188         // is lost. It will be handled during the next call to Present.
00189         HRESULT hr = m_d2dContext->EndDraw();
00190         if (hr != D2DERR_RECREATE_TARGET)
00191         {
00192             DX::ThrowIfFailed(hr);
00193         }
00194
00195         m_d2dContext->RestoreDrawingState(m_stateBlock.Get());
00196     }
00197 }
00198
00199 float SampleOverlay::GetTitleHeightInDips()
00200 {
00201     return m_logoSize.height;
00202 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Device capabilities/C++/common/suspensionmanager.h Source File

  • Input Device capabilities
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: SimpleOrientationSensor/C++/common/suspensionmanager.cpp Source File

  • SimpleOrientationSensor
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:37 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D basic image effects/C++/DirectXBase.cpp Source File

  • Direct2D basic image effects

DirectXBase.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 "DirectXBase.h"
00010
00011 using namespace Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::Graphics::Display;
00015 using namespace D2D1;
00016
00017 // Constructor.
00018 DirectXBase::DirectXBase() :
00019     m_windowSizeChangeInProgress(false),
00020     m_dpi(-1.0f)
00021 {
00022 }
00023
00024 // Initialize the DirectX resources required to run.
00025 void DirectXBase::Initialize(CoreWindow^ window, float dpi)
00026 {
00027     m_window = window;
00028
00029     CreateDeviceIndependentResources();
00030     CreateDeviceResources();
00031     SetDpi(dpi);
00032 }
00033
00034 // Recreate all device resources and set them back to the current state.
00035 void DirectXBase::HandleDeviceLost()
00036 {
00037     // Reset these member variables to ensure that SetDpi recreates all resources.
00038     float dpi = m_dpi;
00039     m_dpi = -1.0f;
00040     m_windowBounds.Width = 0;
00041     m_windowBounds.Height = 0;
00042     m_swapChain = nullptr;
00043
00044     CreateDeviceResources();
00045     SetDpi(dpi);
00046 }
00047
00048 // These are the resources required independent of the device.
00049 void DirectXBase::CreateDeviceIndependentResources()
00050 {
00051     D2D1_FACTORY_OPTIONS options;
00052     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00053
00054 #if defined(_DEBUG)
00055     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00056     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00057 #endif
00058
00059     DX::ThrowIfFailed(
00060         D2D1CreateFactory(
00061             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00062             __uuidof(ID2D1Factory1),
00063             &options,
00064             &m_d2dFactory
00065             )
00066         );
00067
00068     DX::ThrowIfFailed(
00069         DWriteCreateFactory(
00070             DWRITE_FACTORY_TYPE_SHARED,
00071             __uuidof(IDWriteFactory),
00072             &m_dwriteFactory
00073             )
00074         );
00075
00076     DX::ThrowIfFailed(
00077         CoCreateInstance(
00078             CLSID_WICImagingFactory,
00079             nullptr,
00080             CLSCTX_INPROC_SERVER,
00081             IID_PPV_ARGS(&m_wicFactory)
00082             )
00083         );
00084 }
00085
00086 // These are the resources that depend on the device.
00087 void DirectXBase::CreateDeviceResources()
00088 {
00089     // This flag adds support for surfaces with a different color channel ordering
00090     // than the API default. It is required for compatibility with Direct2D.
00091     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00092     ComPtr<IDXGIDevice> dxgiDevice;
00093
00094 #if defined(_DEBUG)
00095     // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00096     creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00097 #endif
00098
00099     // This array defines the set of DirectX hardware feature levels this app will support.
00100     // Note the ordering should be preserved.
00101     // Don't forget to declare your application's minimum required feature level in its
00102     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00103     D3D_FEATURE_LEVEL featureLevels[] =
00104     {
00105         D3D_FEATURE_LEVEL_11_1,
00106         D3D_FEATURE_LEVEL_11_0,
00107         D3D_FEATURE_LEVEL_10_1,
00108         D3D_FEATURE_LEVEL_10_0,
00109         D3D_FEATURE_LEVEL_9_3,
00110         D3D_FEATURE_LEVEL_9_2,
00111         D3D_FEATURE_LEVEL_9_1
00112     };
00113
00114     // Create the Direct3D 11 API device object and a corresponding context.
00115     ComPtr<ID3D11Device> device;
00116     ComPtr<ID3D11DeviceContext> context;
00117     DX::ThrowIfFailed(
00118         D3D11CreateDevice(
00119             nullptr,                    // Specify nullptr to use the default adapter.
00120             D3D_DRIVER_TYPE_HARDWARE,
00121             0,
00122             creationFlags,              // Set debug and Direct2D compatibility flags.
00123             featureLevels,              // List of feature levels this app can support.
00124             ARRAYSIZE(featureLevels),
00125             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Metro style apps.
00126             &device,                    // Returns the Direct3D device created.
00127             &m_featureLevel,            // Returns feature level of device created.
00128             &context                    // Returns the device immediate context.
00129             )
00130         );
00131
00132     // Get the Direct3D 11.1 API device and context interfaces.
00133     DX::ThrowIfFailed(
00134         device.As(&m_d3dDevice)
00135         );
00136
00137     DX::ThrowIfFailed(
00138         context.As(&m_d3dContext)
00139         );
00140
00141     // Get the underlying DXGI device of the Direct3D device.
00142     DX::ThrowIfFailed(
00143         m_d3dDevice.As(&dxgiDevice)
00144         );
00145
00146     // Create the Direct2D device object and a corresponding context.
00147     DX::ThrowIfFailed(
00148         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00149         );
00150
00151     DX::ThrowIfFailed(
00152         m_d2dDevice->CreateDeviceContext(
00153             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00154             &m_d2dContext
00155             )
00156         );
00157 }
00158
00159 // Helps track the DPI in the helper class.
00160 // This is called in the dpiChanged event handler in the view class.
00161 void DirectXBase::SetDpi(float dpi)
00162 {
00163     if (dpi != m_dpi)
00164     {
00165         // Save the DPI of this display in our class.
00166         m_dpi = dpi;
00167
00168         // Update Direct2D's stored DPI.
00169         m_d2dContext->SetDpi(m_dpi, m_dpi);
00170
00171         // Often a DPI change implies a window size change. In some cases Windows will issue
00172         // both a size changed event and a DPI changed event. In this case, the resulting bounds
00173         // will not change, and the window resize code will only be executed once.
00174         UpdateForWindowSizeChange();
00175     }
00176 }
00177
00178 // This routine is called in the event handler for the view SizeChanged event.
00179 void DirectXBase::UpdateForWindowSizeChange()
00180 {
00181     // Only handle window size changed if there is no pending DPI change.
00182     if (m_dpi != DisplayProperties::LogicalDpi)
00183     {
00184         return;
00185     }
00186
00187     if (m_window->Bounds.Width  != m_windowBounds.Width ||
00188         m_window->Bounds.Height != m_windowBounds.Height)
00189     {
00190         m_d2dContext->SetTarget(nullptr);
00191         m_d2dTargetBitmap = nullptr;
00192         m_d3dRenderTargetView = nullptr;
00193         m_d3dDepthStencilView = nullptr;
00194         m_windowSizeChangeInProgress = true;
00195         CreateWindowSizeDependentResources();
00196     }
00197 }
00198
00199 // Allocate all memory resources that change on a window SizeChanged event.
00200 void DirectXBase::CreateWindowSizeDependentResources()
00201 {
00202     // Store the window bounds so the next time we get a SizeChanged event we can
00203     // avoid rebuilding everything if the size is identical.
00204     m_windowBounds = m_window->Bounds;
00205
00206     if (m_swapChain != nullptr)
00207     {
00208         // If the swap chain already exists, resize it.
00209         HRESULT hr = m_swapChain->ResizeBuffers(2, 0, 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0);
00210
00211         if (hr == DXGI_ERROR_DEVICE_REMOVED)
00212         {
00213             // If the device was removed for any reason, a new device and swapchain will need to be created.
00214             HandleDeviceLost();
00215
00216             // Everything is set up now. Do not continue execution of this method.
00217             return;
00218         }
00219         else
00220         {
00221             DX::ThrowIfFailed(hr);
00222         }
00223     }
00224     else
00225     {
00226         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00227         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00228         swapChainDesc.Width = 0;                                     // Use automatic sizing.
00229         swapChainDesc.Height = 0;
00230         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;           // This is the most common swap chain format.
00231         swapChainDesc.Stereo = false;
00232         swapChainDesc.SampleDesc.Count = 1;                          // Don't use multi-sampling.
00233         swapChainDesc.SampleDesc.Quality = 0;
00234         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00235         swapChainDesc.BufferCount = 2;                               // Use double-buffering to minimize latency.
00236         swapChainDesc.Scaling = DXGI_SCALING_NONE;
00237         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Metro style apps must use this SwapEffect.
00238         swapChainDesc.Flags = 0;
00239
00240         ComPtr<IDXGIDevice1> dxgiDevice;
00241         DX::ThrowIfFailed(
00242             m_d3dDevice.As(&dxgiDevice)
00243             );
00244
00245         ComPtr<IDXGIAdapter> dxgiAdapter;
00246         DX::ThrowIfFailed(
00247             dxgiDevice->GetAdapter(&dxgiAdapter)
00248             );
00249
00250         ComPtr<IDXGIFactory2> dxgiFactory;
00251         DX::ThrowIfFailed(
00252             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00253             );
00254
00255         CoreWindow^ window = m_window.Get();
00256         DX::ThrowIfFailed(
00257             dxgiFactory->CreateSwapChainForCoreWindow(
00258                 m_d3dDevice.Get(),
00259                 reinterpret_cast<IUnknown*>(window),
00260                 &swapChainDesc,
00261                 nullptr,
00262                 &m_swapChain
00263                 )
00264             );
00265
00266         // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
00267         // ensures that the application will only render after each VSync, minimizing power consumption.
00268         DX::ThrowIfFailed(
00269             dxgiDevice->SetMaximumFrameLatency(1)
00270             );
00271     }
00272
00273     // Create a Direct3D render target view of the swap chain back buffer.
00274     ComPtr<ID3D11Texture2D> backBuffer;
00275     DX::ThrowIfFailed(
00276         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00277         );
00278
00279     DX::ThrowIfFailed(
00280         m_d3dDevice->CreateRenderTargetView(
00281             backBuffer.Get(),
00282             nullptr,
00283             &m_d3dRenderTargetView
00284             )
00285         );
00286
00287     // Cache the rendertarget dimensions in our helper class for convenient use.
00288     D3D11_TEXTURE2D_DESC backBufferDesc = {0};
00289     backBuffer->GetDesc(&backBufferDesc);
00290     m_renderTargetSize.Width  = static_cast<float>(backBufferDesc.Width);
00291     m_renderTargetSize.Height = static_cast<float>(backBufferDesc.Height);
00292
00293     // Create a depth stencil view for use with 3D rendering if needed.
00294     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00295         DXGI_FORMAT_D24_UNORM_S8_UINT,
00296         backBufferDesc.Width,
00297         backBufferDesc.Height,
00298         1,
00299         1,
00300         D3D11_BIND_DEPTH_STENCIL
00301         );
00302
00303     ComPtr<ID3D11Texture2D> depthStencil;
00304     DX::ThrowIfFailed(
00305         m_d3dDevice->CreateTexture2D(
00306             &depthStencilDesc,
00307             nullptr,
00308             &depthStencil
00309             )
00310         );
00311
00312     auto viewDesc = CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D);
00313     DX::ThrowIfFailed(
00314         m_d3dDevice->CreateDepthStencilView(
00315             depthStencil.Get(),
00316             &viewDesc,
00317             &m_d3dDepthStencilView
00318             )
00319         );
00320
00321     // Set the 3D rendering viewport to target the entire window.
00322     CD3D11_VIEWPORT viewport(
00323         0.0f,
00324         0.0f,
00325         static_cast<float>(backBufferDesc.Width),
00326         static_cast<float>(backBufferDesc.Height)
00327         );
00328
00329     m_d3dContext->RSSetViewports(1, &viewport);
00330
00331     // Create a Direct2D target bitmap associated with the
00332     // swap chain back buffer and set it as the current target.
00333     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00334         BitmapProperties1(
00335             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00336             PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00337             m_dpi,
00338             m_dpi
00339             );
00340
00341     ComPtr<IDXGISurface> dxgiBackBuffer;
00342     DX::ThrowIfFailed(
00343         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00344         );
00345
00346     DX::ThrowIfFailed(
00347         m_d2dContext->CreateBitmapFromDxgiSurface(
00348             dxgiBackBuffer.Get(),
00349             &bitmapProperties,
00350             &m_d2dTargetBitmap
00351             )
00352         );
00353
00354     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00355
00356     // Grayscale text anti-aliasing is recommended for all Metro style apps.
00357     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00358 }
00359
00360 // Method to deliver the final image to the display.
00361 void DirectXBase::Present()
00362 {
00363     // The application may optionally specify "dirty" or "scroll" rects to improve efficiency
00364     // in certain scenarios.  In this sample, however, we do not utilize those features.
00365     DXGI_PRESENT_PARAMETERS parameters = {0};
00366     parameters.DirtyRectsCount = 0;
00367     parameters.pDirtyRects = nullptr;
00368     parameters.pScrollRect = nullptr;
00369     parameters.pScrollOffset = nullptr;
00370
00371     // The first argument instructs DXGI to block until VSync, putting the application
00372     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00373     // frames that will never be displayed to the screen.
00374     HRESULT hr = m_swapChain->Present1(1, 0, &parameters);
00375
00376     // Discard the contents of the render target.
00377     // This is a valid operation only when the existing contents will be entirely
00378     // overwritten. If dirty or scroll rects are used, this call should be removed.
00379     m_d3dContext->DiscardView(m_d3dRenderTargetView.Get());
00380
00381     // Discard the contents of the depth stencil.
00382     m_d3dContext->DiscardView(m_d3dDepthStencilView.Get());
00383
00384     // If the device was removed either by a disconnect or a driver upgrade, we
00385     // must recreate all device resources.
00386     if (hr == DXGI_ERROR_DEVICE_REMOVED)
00387     {
00388         HandleDeviceLost();
00389     }
00390     else
00391     {
00392         DX::ThrowIfFailed(hr);
00393     }
00394
00395     if (m_windowSizeChangeInProgress)
00396     {
00397         // A window size change has been initiated and the app has just completed presenting
00398         // the first frame with the new size. Notify the resize manager so we can short
00399         // circuit any resize animation and prevent unnecessary delays.
00400         CoreWindowResizeManager::GetForCurrentView()->NotifyLayoutCompleted();
00401         m_windowSizeChangeInProgress = false;
00402     }
00403 }
00404
00405 void DirectXBase::ValidateDevice()
00406 {
00407     // The D3D Device is no longer valid if the default adapter changes or if
00408     // the device has been removed.
00409
00410     // First, get the information for the adapter related to the current device.
00411
00412     ComPtr<IDXGIDevice1> dxgiDevice;
00413     ComPtr<IDXGIAdapter> deviceAdapter;
00414     DXGI_ADAPTER_DESC deviceDesc;
00415     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00416     DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter));
00417     DX::ThrowIfFailed(deviceAdapter->GetDesc(&deviceDesc));
00418
00419     // Next, get the information for the default adapter.
00420
00421     ComPtr<IDXGIFactory2> dxgiFactory;
00422     ComPtr<IDXGIAdapter1> currentAdapter;
00423     DXGI_ADAPTER_DESC currentDesc;
00424     DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)));
00425     DX::ThrowIfFailed(dxgiFactory->EnumAdapters1(0, &currentAdapter));
00426     DX::ThrowIfFailed(currentAdapter->GetDesc(&currentDesc));
00427
00428     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00429     // a new D3D device must be created.
00430
00431     if ((deviceDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart) ||
00432         (deviceDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart) ||
00433         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00434     {
00435         // Release references to resources related to the old device.
00436         dxgiDevice = nullptr;
00437         deviceAdapter = nullptr;
00438
00439         // Create a new device and swap chain.
00440         HandleDeviceLost();
00441     }
00442 }
Generated on Sat Nov 23 2024 16:08:02 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playlist/C++/Create.xaml.cpp Source File

  • Playlist

Create.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 // Create.xaml.cpp
00013 // Implementation of the Create class
00014 //
00015
00016 #include "pch.h"
00017 #include "Create.xaml.h"
00018
00019 using namespace SDKSample::Playlists;
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::Navigation;
00024
00025 Create::Create()
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 Create::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 Create::PickAudioButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00043 {
00044     // Make sure app is unsnapped before invoking the file picker
00045     if(!MainPage::EnsureUnsnapped())
00046     {
00047         OutputStatus->Text = "Unable to unsnap the app.";
00048         return;
00049     }
00050
00051     // Pick multiple files, then create the playlist.
00052     FileOpenPicker^ picker = MainPage::CreateFilePicker(MainPage::audioExtensions);
00053
00054     task<IVectorView<StorageFile^>^>(picker->PickMultipleFilesAsync()).then([this](IVectorView<StorageFile^>^ files)
00055     {
00056         if(files->Size > 0)
00057         {
00058             MainPage::playlist = ref new Playlist();
00059
00060             for each (StorageFile^ file in files)
00061             {
00062                 MainPage::playlist->Files->Append(file);
00063             }
00064
00065             StorageFolder^ folder = KnownFolders::MusicLibrary;
00066             String^ name = "Sample";
00067             NameCollisionOption collisionOption = NameCollisionOption::ReplaceExisting;
00068             PlaylistFormat format = PlaylistFormat::WindowsMedia;
00069
00070             task<StorageFile^>(MainPage::playlist->SaveAsAsync(folder, name, collisionOption, format)).then([this](StorageFile^ file)
00071             {
00072                 OutputStatus->Text = "The playlist " + file->Name + " was created and saved.";
00073
00074                 // Reset playlist so subsequent SaveAsync calls don't fail
00075                 MainPage::playlist = nullptr;
00076             });
00077         }
00078         else
00079         {
00080             OutputStatus->Text = "No files picked.";
00081         }
00082     });
00083 }
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Reading and writing data/C++/common/LayoutAwarePage.cpp Source File

  • Reading and writing data
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:32 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Lock screen apps/C#,C++/ScenarioInput3.xaml.cpp Source File

  • Lock screen apps
  • C#,C++

ScenarioInput3.xaml.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 //
00009 // Scenario2Input.xaml.cpp
00010 // Implementation of the Scenario2Input class.
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioInput3.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace LockScreenAppsCPP;
00018
00019 using namespace Concurrency;
00020 using namespace NotificationsExtensions::BadgeContent;
00021 using namespace NotificationsExtensions::TileContent;
00022 using namespace Platform;
00023 using namespace Windows::Foundation;
00024 using namespace Windows::ApplicationModel::Background;
00025 using namespace Windows::UI::Notifications;
00026 using namespace Windows::UI::Popups;
00027 using namespace Windows::UI::StartScreen;
00028 using namespace Windows::UI::Xaml;
00029 using namespace Windows::UI::Xaml::Controls;
00030 using namespace Windows::UI::Xaml::Navigation;
00031
00032 #define BADGE_TILE_ID "ST_BADGE"
00033 #define TEXT_TILE_ID "ST_BADGE_AND_TEXT"
00034
00035 ScenarioInput3::ScenarioInput3()
00036 {
00037     InitializeComponent();
00038     CreateBadgeTile->Click += ref new RoutedEventHandler(this, &ScenarioInput3::CreateBadgeTile_Click);
00039     CreateBadgeAndTextTile->Click += ref new RoutedEventHandler(this, &ScenarioInput3::CreateBadgeAndTextTile_Click);
00040 }
00041
00042 ScenarioInput3::~ScenarioInput3()
00043 {
00044 }
00045
00046 void ScenarioInput3::CreateBadgeTile_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00047 {
00048    if (!SecondaryTile::Exists(BADGE_TILE_ID)) {
00049         auto secondTile = ref new SecondaryTile(
00050             BADGE_TILE_ID,
00051             "LockBadge",
00052             "LockScreen CPP - Badge only",
00053             "BADGE_ARGS",
00054             TileOptions::ShowNameOnLogo,
00055             ref new Uri("ms-appx:///images/squareTile-sdk.png")
00056         );
00057         secondTile->LockScreenBadgeLogo = ref new Uri("ms-appx:///images/badgelogo-sdk.png");
00058
00059         create_task(secondTile->RequestCreateForSelectionAsync(GetElementRect(dynamic_cast<FrameworkElement^>(sender)), Placement::Above)).then([this] (bool isPinned) {
00060       if (isPinned)
00061       {
00062         auto badgeContent = ref new BadgeNumericNotificationContent(2);
00063         BadgeUpdateManager::CreateBadgeUpdaterForSecondaryTile(BADGE_TILE_ID)->Update(badgeContent->CreateNotification());
00064         rootPage->NotifyUser("Secondary tile created and badge updated. Go to PC settings to add it to the lock screen.", NotifyType::StatusMessage);
00065       }
00066       else
00067       {
00068         rootPage->NotifyUser("Tile not created.", NotifyType::ErrorMessage);
00069       }
00070     });
00071
00072     } else {
00073         rootPage->NotifyUser("Badge secondary tile already exists.", NotifyType::ErrorMessage);
00074     }
00075 }
00076
00077
00078 void ScenarioInput3::CreateBadgeAndTextTile_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00079 {
00080     if (!SecondaryTile::Exists(TEXT_TILE_ID))
00081     {
00082         auto secondTile = ref new SecondaryTile(
00083             TEXT_TILE_ID,
00084             "LockText",
00085             "LockScreen CPP - Badge and tile text",
00086             "TEXT_ARGS",
00087             TileOptions::ShowNameOnLogo | TileOptions::ShowNameOnWideLogo,
00088             ref new Uri("ms-appx:///images/squareTile-sdk.png"),
00089             ref new Uri("ms-appx:///images/tile-sdk.png")
00090         );
00091         secondTile->LockScreenBadgeLogo = ref new Uri("ms-appx:///images/badgelogo-sdk.png");
00092         secondTile->LockScreenDisplayBadgeAndTileText = true;
00093
00094         create_task(secondTile->RequestCreateForSelectionAsync(GetElementRect(dynamic_cast<FrameworkElement^>(sender)), Placement::Above)).then([this] (bool isPinned) {
00095       if (isPinned)
00096       {
00097         auto tileContent = TileContentFactory::CreateTileWideText03();
00098         tileContent->TextHeadingWrap->Text = "Text for the lock screen";
00099         tileContent->RequireSquareContent = false;
00100         TileUpdateManager::CreateTileUpdaterForSecondaryTile(TEXT_TILE_ID)->Update(tileContent->CreateNotification());
00101         rootPage->NotifyUser("Secondary tile created and updated. Go to PC settings to add it to the lock screen.", NotifyType::StatusMessage);
00102       }
00103       else
00104       {
00105         rootPage->NotifyUser("Tile not created.", NotifyType::ErrorMessage);
00106       }
00107     });
00108
00109     }
00110     else
00111     {
00112         rootPage->NotifyUser("Badge and text secondary tile already exists.", NotifyType::ErrorMessage);
00113     }
00114 }
00115
00116 Rect ScenarioInput3::GetElementRect(FrameworkElement^ element)
00117 {
00118   Windows::UI::Xaml::Media::GeneralTransform^ buttonTransform = element->TransformToVisual(nullptr);
00119   const Point pointOrig(0, 0);
00120   const Point pointTransformed = buttonTransform->TransformPoint(pointOrig);
00121   const Rect rect(pointTransformed.X,
00122           pointTransformed.Y,
00123           safe_cast<float>(element->ActualWidth),
00124           safe_cast<float>(element->ActualHeight));
00125   return rect;
00126 }
00127
00128 void ScenarioInput3::OnNavigatedTo(NavigationEventArgs^ e)
00129 {
00130     // Get a pointer to our main page.
00131     rootPage = dynamic_cast<MainPage^>(e->Parameter);
00132 }
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Raw notifications/C++/SampleBackgroundTask/BackgroundTask.h Source File

  • Raw notifications
  • SampleBackgroundTask

BackgroundTask.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 BackgroundTasks
00011 {
00012     // You must use a sealed class, and make sure the output is a WINMD.
00013     public ref class SampleBackgroundTask sealed : Windows::ApplicationModel::Background::IBackgroundTask
00014     {
00015     public:
00016         virtual void Run(Windows::ApplicationModel::Background::IBackgroundTaskInstance^ taskInstance);
00017     };
00018 }
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D geometry realization/C++/DirectXBase.h Source File

  • Direct2D geometry realization

DirectXBase.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 "DirectXSample.h"
00011
00012 // Helper class that initializes DirectX APIs for both 2D and 3D rendering.
00013 // Some of the code in this class may be omitted if only 2D or only 3D rendering is being used.
00014 ref class DirectXBase abstract
00015 {
00016 internal:
00017     DirectXBase();
00018
00019     virtual void Initialize(Windows::UI::Core::CoreWindow^ window, float dpi);
00020     virtual void HandleDeviceLost();
00021     virtual void CreateDeviceIndependentResources();
00022     virtual void CreateDeviceResources();
00023     virtual void SetDpi(float dpi);
00024     virtual void UpdateForWindowSizeChange();
00025     virtual void CreateWindowSizeDependentResources();
00026     virtual void Render() = 0;
00027     virtual void Present();
00028     void ValidateDevice();
00029
00030 protected private:
00031     Platform::Agile<Windows::UI::Core::CoreWindow>  m_window;
00032
00033     // DirectWrite & Windows Imaging Component Objects.
00034     Microsoft::WRL::ComPtr<IDWriteFactory1>         m_dwriteFactory;
00035     Microsoft::WRL::ComPtr<IWICImagingFactory2>     m_wicFactory;
00036
00037     // DirectX Core Objects. Required for 2D and 3D.
00038     Microsoft::WRL::ComPtr<ID3D11Device1>           m_d3dDevice;
00039     Microsoft::WRL::ComPtr<ID3D11DeviceContext1>    m_d3dContext;
00040     Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00041     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00042
00043     // Direct2D Rendering Objects. Required for 2D.
00044     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00046     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00047     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmap;
00048
00049     // Direct3D Rendering Objects. Required for 3D.
00050     Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00051
00052     // Cached renderer properties.
00053     D3D_FEATURE_LEVEL                               m_featureLevel;
00054     Windows::Foundation::Size                       m_renderTargetSize;
00055     Windows::Foundation::Rect                       m_windowBounds;
00056     float                                           m_dpi;
00057     bool                                            m_windowSizeChangeInProgress;
00058 };
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/MainHubViewModel.h Source File

  • Hilo C++
  • Hilo

MainHubViewModel.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
00009 #include "ViewModelBase.h"
00010
00011 namespace Hilo
00012 {
00013     ref class HubPhotoGroup;
00014     interface class IPhoto;
00015     class ExceptionPolicy;
00016
00017     // See http://go.microsoft.com/fwlink/?LinkId=267276 for info on how view model classes interact
00018     // with view classes (pages) and model classes (the state and operations of business objects).
00019
00020     // The MainHubViewModel class contains the presentation logic for the main hub page (MainHubView.xaml).
00021     [Windows::UI::Xaml::Data::Bindable]
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class MainHubViewModel sealed : public ViewModelBase
00024     {
00025     internal:
00026         MainHubViewModel(Windows::Foundation::Collections::IObservableVector<HubPhotoGroup^>^ photoGroups, std::shared_ptr<ExceptionPolicy> exceptionPolicy);
00027
00028     public:
00029         virtual ~MainHubViewModel();
00030
00031         property Windows::Foundation::Collections::IObservableVector<HubPhotoGroup^>^ PhotoGroups
00032         {
00033             Windows::Foundation::Collections::IObservableVector<HubPhotoGroup^>^ get();
00034         }
00035
00036         property Windows::UI::Xaml::Input::ICommand^ NavigateToPicturesCommand
00037         {
00038             Windows::UI::Xaml::Input::ICommand^ get();
00039         }
00040
00041         property Windows::UI::Xaml::Input::ICommand^ CropImageCommand
00042         {
00043             Windows::UI::Xaml::Input::ICommand^ get();
00044         }
00045
00046         property Windows::UI::Xaml::Input::ICommand^ RotateImageCommand
00047         {
00048             Windows::UI::Xaml::Input::ICommand^ get();
00049         }
00050
00051         property Windows::UI::Xaml::Input::ICommand^ CartoonizeImageCommand
00052         {
00053             Windows::UI::Xaml::Input::ICommand^ get();
00054         }
00055
00056         // These are really IPhoto^ but XAML cannot convert any underlying
00057         // real object (e.g. Photo) back to IPhoto which results in strange
00058         // side effects (such as the AppBar not working).
00059         property Platform::Object^ SelectedItem
00060         {
00061             Platform::Object^ get();
00062             void set(Platform::Object^ value);
00063         }
00064
00065     private:
00066         Windows::Foundation::Collections::IObservableVector<HubPhotoGroup^>^ m_photoGroups;
00067         Windows::UI::Xaml::Input::ICommand^ m_navigateToPicturesCommand;
00068         Windows::UI::Xaml::Input::ICommand^ m_cropImageCommand;
00069         Windows::UI::Xaml::Input::ICommand^ m_rotateImageCommand;
00070         Windows::UI::Xaml::Input::ICommand^ m_cartoonizeImageCommand;
00071         IPhoto^ m_photo;
00072         HubPhotoGroup^ m_pictureGroup;
00073         Windows::Foundation::EventRegistrationToken m_pictureGroupPropertyChangedToken;
00074
00075         void NavigateToPictures(Platform::Object^ parameter);
00076         bool CanNavigateToPictures(Platform::Object^ parameter);
00077         void CropImage(Platform::Object^ parameter);
00078         void RotateImage(Platform::Object^ parameter);
00079         void CartoonizeImage(Platform::Object^ parameter);
00080         bool CanProcessImage(Platform::Object^ parameter);
00081         void OnPictureGroupPropertyChanged(Platform::Object^ sender, Windows::UI::Xaml::Data::PropertyChangedEventArgs^ e);
00082     };
00083 }
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application resources and localization/C++/pch.h Source File

  • Application resources and localization

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX postcard app/C++/DirectXBase.h Source File

  • DirectX postcard app

DirectXBase.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 "DirectXSample.h"
00011
00012 // Helper class that initializes DirectX APIs for both 2D and 3D rendering.
00013 // Some of the code in this class may be omitted if only 2D or only 3D rendering is being used.
00014 ref class DirectXBase abstract
00015 {
00016 internal:
00017     DirectXBase();
00018
00019     virtual void Initialize(
00020         Windows::UI::Core::CoreWindow^ window,
00021         Windows::UI::Xaml::Controls::SwapChainBackgroundPanel^ swapChainPanel,
00022         float dpi
00023         );
00024
00025     virtual void HandleDeviceLost();
00026     virtual void CreateDeviceIndependentResources();
00027     virtual void CreateDeviceResources();
00028     virtual void SetDpi(float dpi);
00029     virtual void UpdateForWindowSizeChange();
00030     virtual void CreateWindowSizeDependentResources();
00031     virtual void Render() = 0;
00032     virtual void Present();
00033     void ValidateDevice();
00034
00035 protected private:
00036     Windows::UI::Xaml::Controls::SwapChainBackgroundPanel^  m_swapChainPanel;
00037     Platform::Agile<Windows::UI::Core::CoreWindow>          m_window;
00038
00039     // DirectWrite & Windows Imaging Component Objects.
00040     Microsoft::WRL::ComPtr<IDWriteFactory1>         m_dwriteFactory;
00041     Microsoft::WRL::ComPtr<IWICImagingFactory2>     m_wicFactory;
00042
00043     // DirectX Core Objects. Required for 2D and 3D.
00044     Microsoft::WRL::ComPtr<ID3D11Device1>           m_d3dDevice;
00045     Microsoft::WRL::ComPtr<ID3D11DeviceContext1>    m_d3dContext;
00046     Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00047     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00048
00049     // Direct2D Rendering Objects. Required for 2D.
00050     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00051     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00052     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00053     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmap;
00054
00055     // Direct3D Rendering Objects. Required for 3D.
00056     Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00057
00058     // Cached renderer properties.
00059     D3D_FEATURE_LEVEL                               m_featureLevel;
00060     Windows::Foundation::Size                       m_renderTargetSize;
00061     Windows::Foundation::Rect                       m_windowBounds;
00062     float                                           m_dpi;
00063 };
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML user and custom controls/C++/Scenario3.xaml.cpp Source File

  • XAML user and custom controls

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 SDKSample::UserAndCustomControls;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 Scenario3::Scenario3()
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 Scenario3::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
00043 void SDKSample::UserAndCustomControls::Scenario3::Go_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00044 {
00045     Button^ b = safe_cast<Button^>(sender);
00046     if (b != nullptr)
00047     {
00048         rootPage->NotifyUser("You clicked the " + b->Name + " button", NotifyType::StatusMessage);
00049     }
00050 }
00051
00052 void SDKSample::UserAndCustomControls::Scenario3::NavigateDPHelp(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00053 {
00054   auto uri = ref new Windows::Foundation::Uri("http://go.microsoft.com/fwlink/?LinkID=236356");
00055
00056   Windows::System::Launcher::LaunchUriAsync(uri);
00057 }
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Custom driver access/C++/DLL/fx2device.h Source File

  • Custom driver access
  • DLL

fx2device.h

Go to the documentation of this file.
00001 ﻿#pragma once
00002
00003 #include <specstrings.h>
00004 #include <deviceaccess.h>
00005 #include <winioctl.h>
00006 #include <strsafe.h>
00007
00008 #include <wrl\client.h>
00009
00010 // #include "ppltasks_mod2.h"
00011 #include <ppltasks.h>
00012
00013 #include <functional>
00014
00015 #include "public.h"
00016 #include "support.h"
00017 #include "repeater.h"
00018
00019 using namespace Windows::Foundation;
00020 using namespace Platform;
00021 using namespace Microsoft::WRL;
00022 using namespace concurrency;
00023
00024 const BYTE c_NumBarsInGraph = 8;
00025 const BYTE c_NumSwitches = 8;
00026 const BYTE c_SegmentMask[] = {
00027     0xD7, // 0
00028     0x06, // 1
00029     0xB3, // 2
00030     0xA7, // 3
00031     0x66, // 4
00032     0xE5, // 5
00033     0xF4, // 6
00034     0x07, // 7
00035     0xF7, // 8
00036     0x67, // 9
00037 };
00038 const unsigned int c_SegmentMaskCe = _countof(c_SegmentMask);
00039
00040 inline void THROW_HR(HRESULT hr)
00041 {
00042     if (hr != 0) {
00043         throw Platform::Exception::ReCreateException(hr);
00044     }
00045 }
00046
00047 namespace Samples {
00048     namespace Devices {
00049         namespace Fx2 {
00050
00051             ref class Fx2Device;
00052             ref class SwitchStateChangedEventArgs;
00053             ref class BarGraphDisplayResult;
00054
00055             public delegate void SwitchStateChangedHandler(Fx2Device^ Sender, SwitchStateChangedEventArgs^ EventArgs);
00056
00057             /// <summary>
00058             /// The device projection for an OSR Fx2 device
00059             /// </summary>
00060             public ref class Fx2Device sealed
00061             {
00062
00063             private:
00064                 String^ m_Id;
00065
00066                 ComPtr<IDeviceIoControl> m_DeviceIoControl;
00067
00068                 //
00069                 // Fields to track the switch state of the fx2 board.
00070                 //
00071                 struct {
00072                     LONG ListenerCount;
00073                     Repeater Repeater;
00074
00075                     SWITCH_STATE Buffer;
00076                     ULONG_PTR CancelContext;
00077                     ULONG FailureCount;
00078                 } m_SwitchState;
00079                 event SwitchStateChangedHandler^ m_SwitchStateChangedEvent;
00080
00081                 Fx2Device(__in IDeviceIoControl* DeviceControl, __in String^ Id);
00082                 ~Fx2Device ();
00083
00084                 void StartEventLoop();
00085                 void StopEventLoop();
00086
00087             public:
00088
00089                 /// <summary>Returns the device selector that an app should use to locate Fx2 devices</summary>
00090                 /// <returns>The selector string for the Fx2 device interface</returns>
00091                 static String^ GetDeviceSelector();
00092
00093                 static Fx2Device^ FromId(__in String^ InterfacePath);
00094
00095                 property String^ Id {String^ get();}
00096                 property BYTE SevenSegmentDisplay {BYTE get(); void set(__in BYTE value);}
00097
00098                 void SetBarGraphDisplay(__in const Array<bool>^ Values);
00099                 IAsyncOperation<BarGraphDisplayResult^>^ GetBarGraphDisplayAsync(void);
00100
00101                 property Array<bool>^ SwitchState {Array<bool>^ get();}
00102
00103                 event SwitchStateChangedHandler^ SwitchStateChanged {
00104                     EventRegistrationToken add(__in SwitchStateChangedHandler^ h);
00105                     void remove(__in EventRegistrationToken cookie);
00106                     void raise(__in Fx2Device^ Sender, __in SwitchStateChangedEventArgs^ args) {m_SwitchStateChangedEvent::raise(Sender, args);}
00107                 };
00108             };
00109
00110             public ref class SwitchStateChangedEventArgs sealed {
00111                 friend ref class Fx2Device;
00112
00113             private:
00114                 HRESULT m_Hr;
00115                 Array<bool>^ m_Switches;
00116                 SWITCH_STATE m_State;
00117
00118                 SwitchStateChangedEventArgs(__in HRESULT Hr) {
00119                     m_Hr = Hr;
00120                     m_Switches = nullptr;
00121                     ZeroMemory(&m_State, sizeof(m_State));
00122                 }
00123
00124                 SwitchStateChangedEventArgs(__in SWITCH_STATE State) {
00125                     m_Hr = S_OK;
00126                     m_Switches = ref new Array<bool>(c_NumSwitches);
00127                     m_State = State;
00128                     for(int i = 0; i < c_NumSwitches; i += 1) {
00129                         m_Switches[i] = ((State.SwitchesAsUChar & (1 << i)) != 0);
00130                     }
00131                 }
00132
00133                 void CheckResult(void) {
00134                     if (m_Hr != S_OK) {
00135                         throw Platform::Exception::CreateException(m_Hr, "Error requesting switch state");
00136                     }
00137                 }
00138
00139             public:
00140
00141                 property BYTE AsByte {BYTE get() {CheckResult(); return m_State.SwitchesAsUChar;}};
00142                 property Array<bool>^ SwitchState {Array<bool>^ get() {CheckResult(); return m_Switches;}};
00143             };
00144
00145             public ref class BarGraphDisplayResult sealed {
00146                 friend ref class Fx2Device;
00147
00148             private:
00149                 Array<bool>^ m_Bars;
00150                 BAR_GRAPH_STATE m_State;
00151                 ULONG_PTR m_CancelToken;
00152
00153                 void UpdateBars() {
00154                     for(int i = 0; i < c_NumBarsInGraph; i += 1) {
00155                         m_Bars[i] = ((m_State.BarsAsUChar & (1 << i)) != 0);
00156                     }
00157                 }
00158
00159             public:
00160                 BarGraphDisplayResult() : m_CancelToken(0) {
00161                     m_Bars = ref new Array<bool>(c_NumBarsInGraph);
00162                     ZeroMemory(&m_State, sizeof(m_State));
00163                 }
00164
00165                 property BYTE AsByte {BYTE get() {return m_State.BarsAsUChar;}};
00166                 property Array<bool>^ BarGraphDisplay {Array<bool>^ get() {return m_Bars;}}
00167
00168             internal:
00169                 ULONG_PTR* GetCancelToken(void) {return &m_CancelToken;}
00170             };
00171         }
00172     }
00173 }
00174 using namespace Samples::Devices;
00175 using namespace Samples::Devices::Fx2;
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D animation/C++/SampleOverlay.h Source File

  • Direct2D animation

SampleOverlay.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 "DirectXSample.h"
00011
00012 // This class is responsible for initializing and rendering the title overlay visible
00013 // at the top of the DirectX SDK samples.
00014 ref class SampleOverlay
00015 {
00016 internal:
00017     SampleOverlay();
00018
00019     void Initialize(
00020         _In_ ID2D1Device*         d2dDevice,
00021         _In_ ID2D1DeviceContext*  d2dContext,
00022         _In_ IWICImagingFactory*  wicFactory,
00023         _In_ IDWriteFactory*      dwriteFactory,
00024         _In_ Platform::String^    caption
00025         );
00026
00027     void ResetDirectXResources();
00028
00029     void UpdateForWindowSizeChange();
00030
00031     void Render();
00032
00033     float GetTitleHeightInDips();
00034
00035 private:
00036
00037     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00038     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00039     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00040     Microsoft::WRL::ComPtr<IDWriteFactory>          m_dwriteFactory;
00041     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_whiteBrush;
00042     Microsoft::WRL::ComPtr<ID2D1DrawingStateBlock>  m_stateBlock;
00043
00044     Microsoft::WRL::ComPtr<IWICImagingFactory>      m_wicFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Bitmap>             m_logoBitmap;
00046     Microsoft::WRL::ComPtr<IDWriteTextLayout>       m_textLayout;
00047
00048     UINT                                            m_idIncrement;
00049     bool                                            m_drawOverlay;
00050     Platform::String^                               m_sampleName;
00051     float                                           m_padding;
00052     float                                           m_textVerticalOffset;
00053     D2D1_SIZE_F                                     m_logoSize;
00054     float                                           m_overlayWidth;
00055 };
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: SMS message send, receive, and SIM management/C++/App.xaml.cpp Source File

  • SMS message send, receive, and SIM management

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:28 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Credential locker/C++/Scenario1.xaml.h Source File

  • Credential locker

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 SDKSample
00023 {
00024     namespace PasswordVaultCPP
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 Scenario1 sealed
00031         {
00032
00033         public:
00034             Scenario1();
00035
00036         protected:
00037             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00038
00039         private:
00040             MainPage^ rootPage;
00041             void Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00042             void Other_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00043             void WelcomeMessage_TextChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::TextChangedEventArgs^ e);
00044             void Launch_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00045             void Signin_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00046             void ChangeUser_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void Reset_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             Windows::Foundation::IAsyncAction^ InitializeVaultAsync();
00049         };
00050     }
00051 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/MainHubView.xaml.h Source File

  • Hilo C++
  • Hilo

MainHubView.xaml.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
00009 #include "pch.h"
00010 #include "VariableGridView.h" // Required by generated header
00011 #include "MainHubView.g.h"
00012
00013 namespace Hilo
00014 {
00015     // See http://go.microsoft.com/fwlink/?LinkId=267278 for info on how Hilo creates pages and navigates to pages.
00016
00017     // See http://go.microsoft.com/fwlink/?LinkId=267276 for info on how view classes interact
00018     // with corresponding view model classes that encapsulate the app’s state, actions, and operations.
00019
00020     // See http://go.microsoft.com/fwlink/?LinkId=267279 for info on how Hilo pages use XAML controls.
00021
00022     // The MainHubView class implements the main hub page.
00023     public ref class MainHubView sealed
00024     {
00025     public:
00026         MainHubView();
00027
00028     private:
00029         void OnPhotoItemClicked(Platform::Object^ sender, Windows::UI::Xaml::Controls::ItemClickEventArgs^ e);
00030     };
00031 }
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Snap/C++/pch.h Source File

  • Snap

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML images/C++/MainPage.xaml.cpp Source File

  • XAML images

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Context menu/C++/App.xaml.cpp Source File

  • Context menu

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Context menu/C++/common/LayoutAwarePage.h Source File

  • Context menu
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: UI Automation core window provider/C++/TriColorWindow.cpp Source File

  • UI Automation core window provider

TriColorWindow.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 //
00009 // Main window for the TriColor sample provider
00010
00011 #include "pch.h"
00012 #include "TriColorWindow.h"
00013 #include "TriColorValue.h"
00014 #include <UIAutomationCore.h>
00015 #include <UIAutomationCoreApi.h>
00016
00017 using namespace Microsoft::WRL;
00018 using namespace Windows::ApplicationModel;
00019 using namespace Windows::ApplicationModel::Core;
00020 using namespace Windows::ApplicationModel::Activation;
00021 using namespace Windows::UI::Core;
00022 using namespace Windows::UI::ViewManagement;
00023 using namespace Windows::System;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Graphics::Display;
00026 using namespace UiaCoreWindowProvider;
00027
00028 // Factory methods for providers
00029 HRESULT CAppWindowProvider_CreateInstance(IInspectable **retVal);
00030 HRESULT CTriColorControlProvider_CreateInstance(IInspectable **retVal);
00031 HRESULT CTriColorFragmentProvider_CreateInstance(IInspectable **retVal);
00032
00033 // Utility method to convert Foundation Rects to D2D RectFs
00034 D2D1_RECT_F RectToRectF(_In_ Rect rect)
00035 {
00036     return D2D1::RectF(
00037         rect.X,
00038         rect.Y,
00039         rect.X + rect.Width,
00040         rect.Y + rect.Height
00041         );
00042 }
00043
00044 // Utility method to convert Object^ to IRawElementProviderSimple
00045 // to assist in calling UIA methods
00046 ComPtr<IRawElementProviderSimple> AsSimpleProvider(Platform::Object^ object)
00047 {
00048     ComPtr<IRawElementProviderSimple> spSimple;
00049     DX::ThrowIfFailed(
00050         ((IUnknown*)reinterpret_cast<__abi_IUnknown*>(object))->QueryInterface(IID_PPV_ARGS(&spSimple))
00051     );
00052     return spSimple;
00053 }
00054
00055 //
00056 // CTriColorWindow methods
00057 //
00058
00059 CTriColorWindow::CTriColorWindow() :
00060     m_value(TriColorValue::Red)
00061 {
00062 }
00063
00064 CTriColorWindow::~CTriColorWindow()
00065 {
00066 }
00067
00068 // Basic initialization procedure for this window object.
00069 void CTriColorWindow::Initialize(
00070     _In_ Windows::ApplicationModel::Core::CoreApplicationView^ view
00071 )
00072 {
00073     view->Activated +=
00074         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &CTriColorWindow::OnActivated);
00075
00076     CoreApplication::Suspending +=
00077         ref new EventHandler<SuspendingEventArgs^>(this, &CTriColorWindow::OnSuspending);
00078
00079     CoreApplication::Resuming +=
00080         ref new EventHandler<Platform::Object^>(this, &CTriColorWindow::OnResuming);
00081 }
00082
00083 void CTriColorWindow::SetWindow(
00084     _In_ Windows::UI::Core::CoreWindow^ window
00085 )
00086 {
00087     // Create helper settings objects
00088     m_accSettings = ref new AccessibilitySettings();
00089     m_uiSettings = ref new UISettings();
00090
00091     DirectXBase::Initialize(window, DisplayProperties::LogicalDpi);
00092
00093     // Set cursor for the window
00094     m_window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
00095
00096     // Register all the delegates
00097     m_window->KeyDown +=
00098         ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &CTriColorWindow::OnKeyDown);
00099     m_window->PointerReleased +=
00100         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &CTriColorWindow::OnPointerReleased);
00101     m_window->Activated +=
00102         ref new TypedEventHandler<CoreWindow^, WindowActivatedEventArgs^>(this, &CTriColorWindow::OnWindowActivated);
00103     m_window->SizeChanged +=
00104         ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &CTriColorWindow::OnWindowSizeChanged);
00105     m_window->Closed +=
00106         ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &CTriColorWindow::OnWindowClosed);
00107     m_window->AutomationProviderRequested +=
00108         ref new TypedEventHandler<CoreWindow^, AutomationProviderRequestedEventArgs^>(this, &CTriColorWindow::OnAutomationProviderRequested);
00109     m_accSettings->HighContrastChanged +=
00110         ref new TypedEventHandler<AccessibilitySettings^, Platform::Object^>(this, &CTriColorWindow::OnHighContrastChanged);
00111     DisplayProperties::LogicalDpiChanged +=
00112         ref new DisplayPropertiesEventHandler(this, &CTriColorWindow::OnLogicalDpiChanged);
00113     DisplayProperties::DisplayContentsInvalidated +=
00114         ref new DisplayPropertiesEventHandler(this, &CTriColorWindow::OnDisplayContentsInvalidated);
00115 }
00116
00117 // Load all appropriate resources based on the entry point.
00118 // This sample does not make use of the entry point argument.
00119 void CTriColorWindow::Load(_In_ Platform::String^ /*entryPoint*/)
00120 {
00121 }
00122
00123 // Run the window's event processing loop.
00124 void CTriColorWindow::Run()
00125 {
00126     m_window->Activate();
00127
00128     Render();
00129     Present();
00130
00131     m_window->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessUntilQuit);
00132 }
00133
00134 // Clean up resources for this window.
00135 void CTriColorWindow::Uninitialize()
00136 {
00137 }
00138
00139 TriColorValue CTriColorWindow::ControlValue::get()
00140 {
00141     return m_value;
00142 }
00143
00144 void CTriColorWindow::ControlValue::set(_In_ TriColorValue value)
00145 {
00146     SetValue(value);
00147 }
00148
00149 short CTriColorWindow::HasFocus::get()
00150 {
00151     return (m_activated) ? VARIANT_TRUE : VARIANT_FALSE;
00152 }
00153
00154 Rect CTriColorWindow::ControlRect::get()
00155 {
00156     return m_controlRect;
00157 }
00158
00159 Windows::Foundation::Rect CTriColorWindow::RectFromValue(_In_ UiaCoreWindowProvider::TriColorValue value)
00160 {
00161     Rect rect(0,0,0,0);
00162     switch (value)
00163     {
00164     case TriColorValue::Red: rect = GetRedRect(); break;
00165     case TriColorValue::Yellow: rect = GetYellowRect(); break;
00166     case TriColorValue::Green: rect = GetGreenRect(); break;
00167     }
00168     return rect;
00169 }
00170
00171 UiaCoreWindowProvider::TriColorValue CTriColorWindow::ValueFromPoint(_In_ Windows::Foundation::Point pt)
00172 {
00173     TriColorValue value;
00174     DX::ThrowIfFailed(ValueFromPoint(pt, &value));
00175     return value;
00176 }
00177
00178 Platform::Object ^CTriColorWindow::GetAppWindowProvider()
00179 {
00180     EnsureAppWindowProviderCreated();
00181     return m_appWindowProvider;
00182 }
00183
00184 Platform::Object ^CTriColorWindow::GetTriColorControlProvider()
00185 {
00186     EnsureControlProviderCreated();
00187     return m_controlProvider;
00188 }
00189
00190 Platform::Object ^CTriColorWindow::GetTriColorFragmentProvider(_In_ UiaCoreWindowProvider::TriColorValue value)
00191 {
00192     EnsureFragmentProviderCreated(value);
00193     switch (value)
00194     {
00195     case TriColorValue::Red: return m_redProvider;
00196     case TriColorValue::Yellow: return m_yellowProvider;
00197     case TriColorValue::Green: return m_greenProvider;
00198     default: DX::ThrowIfFailed(E_INVALIDARG);
00199     }
00200     return nullptr;
00201 }
00202
00203 //
00204 // Event handlers for CoreWindow events
00205 //
00206
00207 void CTriColorWindow::OnWindowSizeChanged(
00208     _In_ CoreWindow^ /*sender*/,
00209     _In_ WindowSizeChangedEventArgs^ /*args*/
00210     )
00211 {
00212     UpdateForWindowSizeChange();
00213     Render();
00214     Present();
00215 }
00216
00217 void CTriColorWindow::OnLogicalDpiChanged(
00218     _In_ Platform::Object^ /*sender*/
00219     )
00220 {
00221     SetDpi(DisplayProperties::LogicalDpi);
00222     Render();
00223     Present();
00224 }
00225
00226 void CTriColorWindow::OnDisplayContentsInvalidated(
00227     _In_ Platform::Object^ /*sender*/
00228     )
00229 {
00230     // Ensure the D3D Device is available for rendering.
00231     ValidateDevice();
00232
00233     Render();
00234     Present();
00235 }
00236
00237 void CTriColorWindow::OnActivated(
00238     _In_ CoreApplicationView^ /*applicationView*/,
00239     _In_ IActivatedEventArgs^ /*args*/
00240     )
00241 {
00242     m_window->Activate();
00243 }
00244
00245 void CTriColorWindow::OnSuspending(
00246     _In_ Platform::Object^ /*sender*/,
00247     _In_ SuspendingEventArgs^ /*args*/
00248     )
00249 {
00250     // This sample has no interesting state,
00251     // so there is no work to do on suspension.
00252 }
00253
00254 void CTriColorWindow::OnResuming(
00255     _In_ Platform::Object^ /*sender*/,
00256     _In_ Platform::Object^ /*args*/
00257     )
00258 {
00259     // This sample has no interesting state,
00260     // so there is no work to do on resume.
00261 }
00262
00263 void CTriColorWindow::OnKeyDown(
00264     _In_ Windows::UI::Core::CoreWindow^ /*sender*/,
00265     _In_ Windows::UI::Core::KeyEventArgs^ e
00266     )
00267 {
00268     VirtualKey vkey = e->VirtualKey;
00269
00270     TriColorValue newValue = m_value;
00271     if (vkey == VirtualKey::Up)
00272     {
00273         if (!TriColorValueHelper::IsFirst(newValue))
00274         {
00275             newValue = TriColorValueHelper::PreviousValue(newValue);
00276             SetValue(newValue);
00277         }
00278     }
00279     else if (vkey == VirtualKey::Down)
00280     {
00281         if (!TriColorValueHelper::IsLast(newValue))
00282         {
00283             newValue = TriColorValueHelper::NextValue(newValue);
00284             SetValue(newValue);
00285         }
00286     }
00287 }
00288
00289 void CTriColorWindow::OnPointerReleased(
00290     _In_ Windows::UI::Core::CoreWindow^ /*sender*/,
00291     _In_ Windows::UI::Core::PointerEventArgs^ e
00292     )
00293 {
00294     SetValue(ValueFromPoint(e->CurrentPoint->RawPosition));
00295 }
00296
00297 void CTriColorWindow::OnWindowActivated(
00298     _In_ Windows::UI::Core::CoreWindow^ /*sender*/,
00299     _In_ Windows::UI::Core::WindowActivatedEventArgs^ e
00300     )
00301 {
00302     CoreWindowActivationState state = e->WindowActivationState;
00303
00304     if (state == CoreWindowActivationState::CodeActivated ||
00305         state == CoreWindowActivationState::PointerActivated)
00306     {
00307         m_activated = true;
00308
00309         // Render for the first time when window is activated.
00310         Render();
00311         Present();
00312
00313         // Fire a focus changed event, after converting control provider to an IRawElementProviderSimple
00314         EnsureControlProviderCreated();
00315         UiaRaiseAutomationEvent(AsSimpleProvider(m_controlProvider).Get(), UIA_AutomationFocusChangedEventId);
00316     }
00317     else if (state == CoreWindowActivationState::Deactivated)
00318     {
00319         m_activated = false;
00320     }
00321 }
00322
00323 void CTriColorWindow::OnWindowClosed(
00324     _In_ Windows::UI::Core::CoreWindow^ /*sender*/,
00325     _In_ Windows::UI::Core::CoreWindowEventArgs^ /*e*/
00326     )
00327 {
00328     // Disconnect our provider.
00329     if (m_appWindowProvider)
00330     {
00331         // Tell the provider it is now disconnected
00332         IDisconnectableProvider^ disconnectableProvider = dynamic_cast<IDisconnectableProvider^>(m_appWindowProvider);
00333         disconnectableProvider->Disconnect();
00334     }
00335 }
00336
00337 // Respond to a request for an automation provider.
00338 // We create one if we haven't yet, and then return it.
00339 void CTriColorWindow::OnAutomationProviderRequested(
00340     _In_ Windows::UI::Core::CoreWindow^ /*sender*/,
00341     _In_ Windows::UI::Core::AutomationProviderRequestedEventArgs ^e
00342     )
00343 {
00344     EnsureAppWindowProviderCreated();
00345     e->AutomationProvider = m_appWindowProvider;
00346     e->Handled = true;
00347 }
00348
00349 // Handle a high contrast change
00350 void CTriColorWindow::OnHighContrastChanged(
00351     _In_ Windows::UI::ViewManagement::AccessibilitySettings^ /*sender*/,
00352     _In_ Object^ /*e*/
00353     )
00354 {
00355     DiscardThemeSpecificResources();
00356     CreateThemeSpecificResources();
00357
00358     Render();
00359     Present();
00360 }
00361
00362 // Create an automation provider if we don't already have one
00363 void CTriColorWindow::EnsureAppWindowProviderCreated()
00364 {
00365     if (!m_appWindowProvider)
00366     {
00367         // This unusual code sequence creates a new non-ref class
00368         // through a factory method, and then converts from IInspectable*
00369         // to Object^.
00370         ComPtr<IInspectable> spAppWindowProvider;
00371         DX::ThrowIfFailed(
00372             CAppWindowProvider_CreateInstance(&spAppWindowProvider)
00373             );
00374
00375         IAppWindowProvider^ appWindowProviderInit = nullptr;
00376         DX::ThrowIfFailed(
00377             spAppWindowProvider.Get()->QueryInterface(__uuidof(IAppWindowProvider^), (void**)&appWindowProviderInit)
00378             );
00379         appWindowProviderInit->Initialize(this, m_window.Get());
00380         m_appWindowProvider = appWindowProviderInit;
00381     }
00382 }
00383
00384 // Create a control provider if we don't already have one
00385 void CTriColorWindow::EnsureControlProviderCreated()
00386 {
00387     if (!m_controlProvider)
00388     {
00389         // This unusual code sequence creates a new non-ref class
00390         // through a factory method, and then converts from IInspectable*
00391         // to Object^.
00392         ComPtr<IInspectable> spControlProvider;
00393         DX::ThrowIfFailed(
00394             CTriColorControlProvider_CreateInstance(&spControlProvider)
00395             );
00396
00397         ITriColorControlProvider^ controlProviderInit = nullptr;
00398         DX::ThrowIfFailed(
00399             spControlProvider.Get()->QueryInterface(__uuidof(ITriColorControlProvider^), (void**)&controlProviderInit)
00400             );
00401         controlProviderInit->Initialize(this);
00402         m_controlProvider = controlProviderInit;
00403     }
00404 }
00405
00406 // Create a fragment provider if we don't already have one
00407 void CTriColorWindow::EnsureFragmentProviderCreated(_In_ TriColorValue value)
00408 {
00409     // Get the right pointer to update
00410     Platform::Object ^* pspProvider = nullptr;
00411     switch (value)
00412     {
00413     case TriColorValue::Red: pspProvider = &m_redProvider; break;
00414     case TriColorValue::Yellow: pspProvider = &m_yellowProvider; break;
00415     case TriColorValue::Green: pspProvider = &m_greenProvider; break;
00416     }
00417
00418     if (pspProvider && !(*pspProvider))
00419     {
00420         // This unusual code sequence creates a new non-ref class
00421         // through a factory method, and then converts from IInspectable*
00422         // to Object^.
00423         ComPtr<IInspectable> spFragmentProvider;
00424         DX::ThrowIfFailed(
00425             CTriColorFragmentProvider_CreateInstance(&spFragmentProvider)
00426             );
00427
00428         ITriColorFragmentProvider^ fragmentProviderInit = nullptr;
00429         DX::ThrowIfFailed(
00430             spFragmentProvider.Get()->QueryInterface(__uuidof(ITriColorFragmentProvider^), (void**)&fragmentProviderInit)
00431             );
00432         fragmentProviderInit->Initialize(this, value);
00433         *pspProvider = fragmentProviderInit;
00434     }
00435 }
00436
00437 // Create resources which are not bound to any device.
00438 // Their lifetime effectively extends for the duration of the app.
00439 // These resources include the Direct2D and DirectWrite factories,
00440 // and a DirectWrite Text Format object.
00441 void CTriColorWindow::CreateDeviceIndependentResources()
00442 {
00443     DirectXBase::CreateDeviceIndependentResources();
00444
00445     // Create a DirectWrite text format object.
00446     DX::ThrowIfFailed(
00447         m_dwriteFactory->CreateTextFormat(
00448             L"Segoe UI",
00449             nullptr,
00450             DWRITE_FONT_WEIGHT_NORMAL,
00451             DWRITE_FONT_STYLE_NORMAL,
00452             DWRITE_FONT_STRETCH_NORMAL,
00453             24.0f,
00454             L"en-US",
00455             &m_titleFormat
00456             )
00457     );
00458     DX::ThrowIfFailed(
00459         m_dwriteFactory->CreateTextFormat(
00460             L"Segoe UI",
00461             nullptr,
00462             DWRITE_FONT_WEIGHT_NORMAL,
00463             DWRITE_FONT_STYLE_NORMAL,
00464             DWRITE_FONT_STRETCH_NORMAL,
00465             14.0f,
00466             L"en-US",
00467             &m_labelFormat
00468             )
00469     );
00470 }
00471
00472 //  This method creates resources which are bound to a particular
00473 //  Direct3D device. It's all centralized here, in case the resources
00474 //  need to be recreated in case of Direct3D device loss (eg. display
00475 //  change, remoting, removal of video card, etc).
00476 void CTriColorWindow::CreateDeviceResources()
00477 {
00478     DirectXBase::CreateDeviceResources();
00479
00480     // Create brushes.
00481     DX::ThrowIfFailed(
00482         m_d2dContext->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &m_blackBrush)
00483     );
00484     DX::ThrowIfFailed(
00485         m_d2dContext->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &m_whiteBrush)
00486     );
00487     DX::ThrowIfFailed(
00488         m_d2dContext->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Red), &m_redBrush)
00489     );
00490     DX::ThrowIfFailed(
00491         m_d2dContext->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Yellow), &m_yellowBrush)
00492     );
00493     DX::ThrowIfFailed(
00494         m_d2dContext->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Green), &m_greenBrush)
00495     );
00496
00497     CreateThemeSpecificResources();
00498 }
00499
00500 void CTriColorWindow::CreateWindowSizeDependentResources()
00501 {
00502     DirectXBase::CreateWindowSizeDependentResources();
00503 }
00504
00505 void CTriColorWindow::CreateThemeSpecificResources()
00506 {
00507     Windows::UI::Color color = m_uiSettings->UIElementColor(UIElementType::WindowText);
00508     DX::ThrowIfFailed(
00509         m_d2dContext->CreateSolidColorBrush(D2D1::ColorF(RGB(color.R, color.G, color.B)), &m_windowTextBrush)
00510     );
00511 }
00512
00513 void CTriColorWindow::DiscardThemeSpecificResources()
00514 {
00515     m_windowTextBrush = nullptr;
00516 }
00517
00518 // Re-render the contents of the window
00519 void CTriColorWindow::Render()
00520 {
00521     m_d2dContext->BeginDraw();
00522
00523     // Retrieve the size of the render target.
00524     D2D1_SIZE_F renderTargetSize = m_d2dContext->GetSize();
00525
00526     Windows::UI::Color color = m_uiSettings->UIElementColor(UIElementType::Window);
00527     m_d2dContext->Clear(D2D1::ColorF(RGB(color.R, color.G, color.B)));
00528
00529     // Define the control coordinates - control is at (100, 200) and extends
00530     // out to a 100-pixel border, unless total window is too narrow for that.
00531     m_controlRect.X = 100;
00532     m_controlRect.Y = 200;
00533     m_controlRect.Width = max(renderTargetSize.width - 200, 0);
00534     m_controlRect.Height = max(renderTargetSize.height - 300, 0);
00535
00536     // Draw the title
00537     static const WCHAR sc_title[] = L"UIA CoreWindow Sample";
00538     m_d2dContext->DrawText(
00539         sc_title,
00540         ARRAYSIZE(sc_title) - 1,
00541         m_titleFormat.Get(),
00542         D2D1::RectF(10, 10, renderTargetSize.width - 10, renderTargetSize.height - 10),
00543         m_windowTextBrush.Get()
00544         );
00545
00546     static const WCHAR sc_description[] = L"Demonstrates techniques for creating Accessible applications using the CoreWindow " \
00547         L"and Direct2D APIs.  This application has a simple UI Automation (UIA) tree which includes the custom control below and " \
00548         L"demonstrates the basic techniques for making the control programmatically accessible.  This application also follows " \
00549         L"the High Contrast themes and is keyboard-accessible (arrow keys move the control selection).";
00550     m_d2dContext->DrawText(
00551         sc_description,
00552         ARRAYSIZE(sc_description) - 1,
00553         m_labelFormat.Get(),
00554         D2D1::RectF(10, 60, renderTargetSize.width - 10, renderTargetSize.height - 60),
00555         m_windowTextBrush.Get()
00556         );
00557
00558     // Paint rectangles and labels
00559     D2D1_RECT_F rectRed = RectToRectF(GetRedRect());
00560     D2D1_RECT_F rectYellow = RectToRectF(GetYellowRect());
00561     D2D1_RECT_F rectGreen = RectToRectF(GetGreenRect());
00562     D2D1_RECT_F rectControl = RectToRectF(m_controlRect);
00563
00564     m_d2dContext->FillRectangle(
00565         &rectRed,
00566         m_redBrush.Get()
00567         );
00568
00569     m_d2dContext->FillRectangle(
00570         &rectYellow,
00571         m_yellowBrush.Get()
00572         );
00573
00574     m_d2dContext->FillRectangle(
00575         &rectGreen,
00576         m_greenBrush.Get()
00577         );
00578
00579     m_d2dContext->DrawRectangle(
00580         &rectControl,
00581         m_blackBrush.Get()
00582         );
00583
00584     m_d2dContext->DrawText(
00585         L"Red",
00586         3,
00587         m_labelFormat.Get(),
00588         rectRed,
00589         m_whiteBrush.Get()
00590         );
00591
00592     m_d2dContext->DrawText(
00593         L"Yellow",
00594         6,
00595         m_labelFormat.Get(),
00596         rectYellow,
00597         m_blackBrush.Get()
00598         );
00599
00600     m_d2dContext->DrawText(
00601         L"Green",
00602         5,
00603         m_labelFormat.Get(),
00604         rectGreen,
00605         m_whiteBrush.Get()
00606         );
00607
00608     // Paint the selection circle.
00609     ComPtr<ID2D1SolidColorBrush> selectionBrush =
00610         (this->m_value == TriColorValue::Yellow) ?
00611         m_blackBrush :
00612         m_whiteBrush;
00613
00614     Rect selectionRect = RectFromValue(m_value);
00615     m_d2dContext->FillEllipse(
00616         D2D1::Ellipse(
00617             D2D1::Point2F(
00618                 selectionRect.X + (selectionRect.Width / 2),
00619                 selectionRect.Y + (selectionRect.Height / 2)
00620                 ),
00621             10.0,
00622             10.0
00623             ),
00624         selectionBrush.Get());
00625
00626     // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00627     // is lost. It will be handled during the next call to Present.
00628     HRESULT hr = m_d2dContext->EndDraw();
00629     if (hr != D2DERR_RECREATE_TARGET)
00630     {
00631         DX::ThrowIfFailed(hr);
00632     }
00633 }
00634
00635 Rect CTriColorWindow::GetRedRect()
00636 {
00637     Rect redRect = m_controlRect;
00638     redRect.Height = m_controlRect.Height / 3;
00639     return redRect;
00640 }
00641
00642 Rect CTriColorWindow::GetYellowRect()
00643 {
00644     Rect yellowRect = m_controlRect;
00645     yellowRect.Y = m_controlRect.Y + (m_controlRect.Height / 3);
00646     yellowRect.Height = m_controlRect.Height / 3;
00647     return yellowRect;
00648 }
00649
00650 Rect CTriColorWindow::GetGreenRect()
00651 {
00652     Rect greenRect = m_controlRect;
00653     greenRect.Y = m_controlRect.Y + (m_controlRect.Height / 3) + (m_controlRect.Height / 3);
00654     greenRect.Height = m_controlRect.Height / 3;
00655     return greenRect;
00656 }
00657
00658 HRESULT CTriColorWindow::ValueFromPoint(_In_ Point pt, _Out_ TriColorValue * pValue)
00659 {
00660     HRESULT hr = E_INVALIDARG;
00661     *pValue = TriColorValue::Red;
00662
00663     // This could be optimized by caching the rectangles,
00664     // if this is called often.
00665     Rect redRect = GetRedRect();
00666     Rect yellowRect = GetYellowRect();
00667     Rect greenRect = GetGreenRect();
00668     if (PointInRect(redRect, pt))
00669     {
00670         *pValue = TriColorValue::Red;
00671         hr = S_OK;
00672     }
00673     else if (PointInRect(yellowRect, pt))
00674     {
00675         *pValue = TriColorValue::Yellow;
00676         hr = S_OK;
00677     }
00678     else if (PointInRect(greenRect, pt))
00679     {
00680         *pValue = TriColorValue::Green;
00681         hr = S_OK;
00682     }
00683     return hr;
00684 }
00685
00686 /* static */
00687 bool CTriColorWindow::PointInRect(_In_ Rect rect, _In_ Point pt)
00688 {
00689     return (pt.X >= rect.X &&
00690             pt.X < (rect.X + rect.Width) &&
00691             pt.Y >= rect.Y &&
00692             pt.Y < (rect.Y + rect.Height));
00693 }
00694
00695 void CTriColorWindow::SetValue(_In_ TriColorValue newValue)
00696 {
00697     TriColorValue oldValue = m_value;
00698
00699     m_value = newValue;
00700     Render();
00701     Present();
00702
00703     if (oldValue != newValue)
00704     {
00705         VARIANT varOldValue;
00706         VARIANT varNewValue;
00707         VariantInit(&varOldValue);
00708         VariantInit(&varNewValue);
00709
00710         // Query for string representations of the old and new values
00711         HRESULT hr = TriColorValueHelper::ValueToString(oldValue, &varOldValue.bstrVal);
00712         if (SUCCEEDED(hr))
00713         {
00714             varOldValue.vt = VT_BSTR;
00715             hr = TriColorValueHelper::ValueToString(newValue, &varNewValue.bstrVal);
00716             if (SUCCEEDED(hr))
00717             {
00718                 varNewValue.vt = VT_BSTR;
00719
00720                 EnsureControlProviderCreated();
00721                 // Notify the property change
00722                 UiaRaiseAutomationPropertyChangedEvent(AsSimpleProvider(m_controlProvider).Get(), UIA_ValueValuePropertyId, varOldValue, varNewValue);
00723             }
00724         }
00725
00726         // Notify the selection changed
00727         Platform::Object^ selectedFragment = GetTriColorFragmentProvider(newValue);
00728         UiaRaiseAutomationEvent(AsSimpleProvider(selectedFragment).Get(), UIA_SelectionItem_ElementSelectedEventId);
00729
00730         VariantClear(&varOldValue);
00731         VariantClear(&varNewValue);
00732     }
00733 }
00734
00735 //
00736 // CTriColorWindowFactory methods
00737 //
00738
00739 // Create an instance of the TriColorWindow
00740 Windows::ApplicationModel::Core::IFrameworkView^ CTriColorWindowFactory::CreateView()
00741 {
00742     return ref new CTriColorWindow();
00743 }
00744
00745 // The main entry point for the sample program.
00746 [Platform::MTAThread]
00747 int main(Platform::Array<Platform::String^>^)
00748 {
00749     auto frameworkViewSource = ref new CTriColorWindowFactory();
00750     Windows::ApplicationModel::Core::CoreApplication::Run(frameworkViewSource);
00751     return 0;
00752 }
00753
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C#,C++/MediaExtensions/Grayscale/Grayscale.cpp Source File

  • Media extensions
  • C#,C++
  • MediaExtensions
  • Grayscale

Grayscale.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 "Grayscale.h"
00009 #include "bufferlock.h"
00010
00011 #pragma comment(lib, "d2d1")
00012
00013 using namespace Microsoft::WRL;
00014
00015 /*
00016
00017 This sample implements a video effect as a Media Foundation transform (MFT).
00018
00019 The video effect manipulates chroma values in a YUV image. In the default setting,
00020 the entire image is converted to grayscale. Optionally, the application may set any
00021 of the following attributes:
00022
00023 MFT_GRAYSCALE_DESTINATION_RECT (type = blob, UINT32[4] array)
00024
00025     Sets the destination rectangle for the effect. Pixels outside the destination
00026     rectangle are not altered.
00027
00028 MFT_GRAYSCALE_SATURATION (type = double)
00029
00030     Sets the saturation level. The nominal range is [0...1]. Values beyond 1.0f
00031     result in supersaturated colors. Values below 0.0f create inverted colors.
00032
00033 MFT_GRAYSCALE_CHROMA_ROTATION (type = double)
00034
00035     Rotates the chroma values of each pixel. The attribue value is the angle of
00036     rotation in degrees. The result is a shift in hue.
00037
00038 The effect is implemented by treating the chroma value of each pixel as a vector [u,v],
00039 and applying a transformation matrix to the vector. The saturation parameter is applied
00040 as a scaling transform.
00041
00042
00043 NOTES ON THE MFT IMPLEMENTATION
00044
00045 1. The MFT has fixed streams: One input stream and one output stream.
00046
00047 2. The MFT supports the following formats: UYVY, YUY2, NV12.
00048
00049 3. If the MFT is holding an input sample, SetInputType and SetOutputType both fail.
00050
00051 4. The input and output types must be identical.
00052
00053 5. If both types are set, no type can be set until the current type is cleared.
00054
00055 6. Preferred input types:
00056
00057      (a) If the output type is set, that's the preferred type.
00058      (b) Otherwise, the preferred types are partial types, constructed from the
00059          list of supported subtypes.
00060
00061 7. Preferred output types: As above.
00062
00063 8. Streaming:
00064
00065     The private BeingStreaming() method is called in response to the
00066     MFT_MESSAGE_NOTIFY_BEGIN_STREAMING message.
00067
00068     If the client does not send MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, the MFT calls
00069     BeginStreaming inside the first call to ProcessInput or ProcessOutput.
00070
00071     This is a good approach for allocating resources that your MFT requires for
00072     streaming.
00073
00074 9. The configuration attributes are applied in the BeginStreaming method. If the
00075    client changes the attributes during streaming, the change is ignored until
00076    streaming is stopped (either by changing the media types or by sending the
00077    MFT_MESSAGE_NOTIFY_END_STREAMING message) and then restarted.
00078
00079 */
00080
00081
00082 // Video FOURCC codes.
00083 const DWORD FOURCC_YUY2 = '2YUY';
00084 const DWORD FOURCC_UYVY = 'YVYU';
00085 const DWORD FOURCC_NV12 = '21VN';
00086
00087 // Static array of media types (preferred and accepted).
00088 const GUID g_MediaSubtypes[] =
00089 {
00090     MFVideoFormat_NV12,
00091     MFVideoFormat_YUY2,
00092     MFVideoFormat_UYVY
00093 };
00094
00095 HRESULT GetImageSize(DWORD fcc, UINT32 width, UINT32 height, DWORD* pcbImage);
00096 HRESULT GetDefaultStride(IMFMediaType *pType, LONG *plStride);
00097 bool ValidateRect(const RECT& rc);
00098
00099 template <typename T>
00100 inline T clamp(const T& val, const T& minVal, const T& maxVal)
00101 {
00102     return (val < minVal ? minVal : (val > maxVal ? maxVal : val));
00103 }
00104
00105
00106 // TransformChroma:
00107 // Apply the transforms to calculate the output chroma values.
00108
00109 void TransformChroma(const D2D1::Matrix3x2F& mat, BYTE *pu, BYTE *pv)
00110 {
00111     // Normalize the chroma values to [-112, 112] range
00112
00113     D2D1_POINT_2F pt = { static_cast<float>(*pu) - 128, static_cast<float>(*pv) - 128 };
00114
00115     pt = mat.TransformPoint(pt);
00116
00117     // Clamp to valid range.
00118     clamp(pt.x, -112.0f, 112.0f);
00119     clamp(pt.y, -112.0f, 112.0f);
00120
00121     // Map back to [16...240] range.
00122     *pu = static_cast<BYTE>(pt.x + 128.0f);
00123     *pv = static_cast<BYTE>(pt.y + 128.0f);
00124 }
00125
00126 //-------------------------------------------------------------------
00127 // Functions to convert a YUV images to grayscale.
00128 //
00129 // In all cases, the same transformation is applied to the 8-bit
00130 // chroma values, but the pixel layout in memory differs.
00131 //
00132 // The image conversion functions take the following parameters:
00133 //
00134 // mat               Transfomation matrix for chroma values.
00135 // rcDest            Destination rectangle.
00136 // pDest             Pointer to the destination buffer.
00137 // lDestStride       Stride of the destination buffer, in bytes.
00138 // pSrc              Pointer to the source buffer.
00139 // lSrcStride        Stride of the source buffer, in bytes.
00140 // dwWidthInPixels   Frame width in pixels.
00141 // dwHeightInPixels  Frame height, in pixels.
00142 //-------------------------------------------------------------------
00143
00144 // Convert UYVY image.
00145
00146 void TransformImage_UYVY(
00147     const D2D1::Matrix3x2F& mat,
00148     const D2D_RECT_U& rcDest,
00149     _Inout_updates_(_Inexpressible_(lDestStride * dwHeightInPixels)) BYTE *pDest,
00150     _In_ LONG lDestStride,
00151     _In_reads_(_Inexpressible_(lSrcStride * dwHeightInPixels)) const BYTE* pSrc,
00152     _In_ LONG lSrcStride,
00153     _In_ DWORD dwWidthInPixels,
00154     _In_ DWORD dwHeightInPixels)
00155 {
00156     DWORD y = 0;
00157     const DWORD y0 = min(rcDest.bottom, dwHeightInPixels);
00158
00159     // Lines above the destination rectangle.
00160     for ( ; y < rcDest.top; y++)
00161     {
00162         memcpy(pDest, pSrc, dwWidthInPixels * 2);
00163         pSrc += lSrcStride;
00164         pDest += lDestStride;
00165     }
00166
00167     // Lines within the destination rectangle.
00168     for ( ; y < y0; y++)
00169     {
00170         WORD *pSrc_Pixel = (WORD*)pSrc;
00171         WORD *pDest_Pixel = (WORD*)pDest;
00172
00173         for (DWORD x = 0; (x + 1) < dwWidthInPixels; x += 2)
00174         {
00175             // Byte order is U0 Y0 V0 Y1
00176             // Each WORD is a byte pair (U/V, Y)
00177             // Windows is little-endian so the order appears reversed.
00178
00179             if (x >= rcDest.left && x < rcDest.right)
00180             {
00181                 BYTE u = pSrc_Pixel[x] & 0x00FF;
00182                 BYTE v = pSrc_Pixel[x+1] & 0x00FF;
00183
00184                 TransformChroma(mat, &u, &v);
00185
00186                 pDest_Pixel[x] = (pSrc_Pixel[x] & 0xFF00) | u;
00187                 pDest_Pixel[x+1] = (pSrc_Pixel[x+1] & 0xFF00) | v;
00188             }
00189             else
00190             {
00191 #pragma warning(push)
00192 #pragma warning(disable: 6385)
00193 #pragma warning(disable: 6386)
00194                 pDest_Pixel[x] = pSrc_Pixel[x];
00195                 pDest_Pixel[x+1] = pSrc_Pixel[x+1];
00196 #pragma warning(pop)
00197             }
00198         }
00199
00200         pDest += lDestStride;
00201         pSrc += lSrcStride;
00202     }
00203
00204     // Lines below the destination rectangle.
00205     for ( ; y < dwHeightInPixels; y++)
00206     {
00207         memcpy(pDest, pSrc, dwWidthInPixels * 2);
00208         pSrc += lSrcStride;
00209         pDest += lDestStride;
00210     }
00211 }
00212
00213
00214 // Convert YUY2 image.
00215
00216 void TransformImage_YUY2(
00217     const D2D1::Matrix3x2F& mat,
00218     const D2D_RECT_U& rcDest,
00219     _Inout_updates_(_Inexpressible_(lDestStride * dwHeightInPixels)) BYTE *pDest,
00220     _In_ LONG lDestStride,
00221     _In_reads_(_Inexpressible_(lSrcStride * dwHeightInPixels)) const BYTE* pSrc,
00222     _In_ LONG lSrcStride,
00223     _In_ DWORD dwWidthInPixels,
00224     _In_ DWORD dwHeightInPixels)
00225 {
00226     DWORD y = 0;
00227     const DWORD y0 = min(rcDest.bottom, dwHeightInPixels);
00228
00229     // Lines above the destination rectangle.
00230     for ( ; y < rcDest.top; y++)
00231     {
00232         memcpy(pDest, pSrc, dwWidthInPixels * 2);
00233         pSrc += lSrcStride;
00234         pDest += lDestStride;
00235     }
00236
00237     // Lines within the destination rectangle.
00238     for ( ; y < y0; y++)
00239     {
00240         WORD *pSrc_Pixel = (WORD*)pSrc;
00241         WORD *pDest_Pixel = (WORD*)pDest;
00242
00243         for (DWORD x = 0; (x + 1) < dwWidthInPixels; x += 2)
00244         {
00245             // Byte order is Y0 U0 Y1 V0
00246             // Each WORD is a byte pair (Y, U/V)
00247             // Windows is little-endian so the order appears reversed.
00248
00249             if (x >= rcDest.left && x < rcDest.right)
00250             {
00251                 BYTE u = pSrc_Pixel[x] >> 8;
00252                 BYTE v = pSrc_Pixel[x+1] >> 8;
00253
00254                 TransformChroma(mat, &u, &v);
00255
00256                 pDest_Pixel[x] = (pSrc_Pixel[x] & 0x00FF) | (u<<8);
00257                 pDest_Pixel[x+1] = (pSrc_Pixel[x+1] & 0x00FF) | (v<<8);
00258             }
00259             else
00260             {
00261 #pragma warning(push)
00262 #pragma warning(disable: 6385)
00263 #pragma warning(disable: 6386)
00264                 pDest_Pixel[x] = pSrc_Pixel[x];
00265                 pDest_Pixel[x+1] = pSrc_Pixel[x+1];
00266 #pragma warning(pop)
00267             }
00268         }
00269         pDest += lDestStride;
00270         pSrc += lSrcStride;
00271     }
00272
00273     // Lines below the destination rectangle.
00274     for ( ; y < dwHeightInPixels; y++)
00275     {
00276         memcpy(pDest, pSrc, dwWidthInPixels * 2);
00277         pSrc += lSrcStride;
00278         pDest += lDestStride;
00279     }
00280 }
00281
00282 // Convert NV12 image
00283
00284 void TransformImage_NV12(
00285     const D2D1::Matrix3x2F& mat,
00286     const D2D_RECT_U& rcDest,
00287     _Inout_updates_(_Inexpressible_(2 * lDestStride * dwHeightInPixels)) BYTE *pDest,
00288     _In_ LONG lDestStride,
00289     _In_reads_(_Inexpressible_(2 * lSrcStride * dwHeightInPixels)) const BYTE* pSrc,
00290     _In_ LONG lSrcStride,
00291     _In_ DWORD dwWidthInPixels,
00292     _In_ DWORD dwHeightInPixels)
00293 {
00294     // NV12 is planar: Y plane, followed by packed U-V plane.
00295
00296     // Y plane
00297     for (DWORD y = 0; y < dwHeightInPixels; y++)
00298     {
00299         CopyMemory(pDest, pSrc, dwWidthInPixels);
00300         pDest += lDestStride;
00301         pSrc += lSrcStride;
00302     }
00303
00304     // U-V plane
00305
00306     // NOTE: The U-V plane has 1/2 the number of lines as the Y plane.
00307
00308     // Lines above the destination rectangle.
00309     DWORD y = 0;
00310     const DWORD y0 = min(rcDest.bottom, dwHeightInPixels);
00311
00312     for ( ; y < rcDest.top/2; y++)
00313     {
00314         memcpy(pDest, pSrc, dwWidthInPixels);
00315         pSrc += lSrcStride;
00316         pDest += lDestStride;
00317     }
00318
00319     // Lines within the destination rectangle.
00320     for ( ; y < y0/2; y++)
00321     {
00322         for (DWORD x = 0; (x + 1) < dwWidthInPixels; x += 2)
00323         {
00324             if (x >= rcDest.left && x < rcDest.right)
00325             {
00326                 BYTE u = pSrc[x];
00327                 BYTE v = pSrc[x+1];
00328
00329                 TransformChroma(mat, &u, &v);
00330
00331                 pDest[x] = u;
00332                 pDest[x+1] = v;
00333             }
00334             else
00335             {
00336                 pDest[x] = pSrc[x];
00337                 pDest[x+1] = pSrc[x+1];
00338             }
00339         }
00340         pDest += lDestStride;
00341         pSrc += lSrcStride;
00342     }
00343
00344     // Lines below the destination rectangle.
00345     for ( ; y < dwHeightInPixels/2; y++)
00346     {
00347         memcpy(pDest, pSrc, dwWidthInPixels);
00348         pSrc += lSrcStride;
00349         pDest += lDestStride;
00350     }
00351 }
00352
00353 CGrayscale::CGrayscale() :
00354     m_pSample(NULL), m_pInputType(NULL), m_pOutputType(NULL), m_pTransformFn(NULL),
00355     m_imageWidthInPixels(0), m_imageHeightInPixels(0), m_cbImageSize(0),
00356     m_transform(D2D1::Matrix3x2F::Identity()), m_rcDest(D2D1::RectU()), m_bStreamingInitialized(false),
00357     m_pAttributes(NULL)
00358 {
00359     InitializeCriticalSectionEx(&m_critSec, 3000, 0);
00360 }
00361
00362 CGrayscale::~CGrayscale()
00363 {
00364     SafeRelease(&m_pInputType);
00365     SafeRelease(&m_pOutputType);
00366     SafeRelease(&m_pSample);
00367     SafeRelease(&m_pAttributes);
00368     DeleteCriticalSection(&m_critSec);
00369 }
00370
00371 // Initialize the instance.
00372 STDMETHODIMP CGrayscale::RuntimeClassInitialize()
00373 {
00374     // Create the attribute store.
00375     return MFCreateAttributes(&m_pAttributes, 3);
00376 }
00377
00378 // IMediaExtension methods
00379
00380 //-------------------------------------------------------------------
00381 // SetProperties
00382 // Sets the configuration of the effect
00383 //-------------------------------------------------------------------
00384 HRESULT CGrayscale::SetProperties(ABI::Windows::Foundation::Collections::IPropertySet *pConfiguration)
00385 {
00386     return S_OK;
00387 }
00388
00389 // IMFTransform methods. Refer to the Media Foundation SDK documentation for details.
00390
00391 //-------------------------------------------------------------------
00392 // GetStreamLimits
00393 // Returns the minimum and maximum number of streams.
00394 //-------------------------------------------------------------------
00395
00396 HRESULT CGrayscale::GetStreamLimits(
00397     DWORD   *pdwInputMinimum,
00398     DWORD   *pdwInputMaximum,
00399     DWORD   *pdwOutputMinimum,
00400     DWORD   *pdwOutputMaximum
00401 )
00402 {
00403     if ((pdwInputMinimum == NULL) ||
00404         (pdwInputMaximum == NULL) ||
00405         (pdwOutputMinimum == NULL) ||
00406         (pdwOutputMaximum == NULL))
00407     {
00408         return E_POINTER;
00409     }
00410
00411     // This MFT has a fixed number of streams.
00412     *pdwInputMinimum = 1;
00413     *pdwInputMaximum = 1;
00414     *pdwOutputMinimum = 1;
00415     *pdwOutputMaximum = 1;
00416     return S_OK;
00417 }
00418
00419
00420 //-------------------------------------------------------------------
00421 // GetStreamCount
00422 // Returns the actual number of streams.
00423 //-------------------------------------------------------------------
00424
00425 HRESULT CGrayscale::GetStreamCount(
00426     DWORD   *pcInputStreams,
00427     DWORD   *pcOutputStreams
00428 )
00429 {
00430     if ((pcInputStreams == NULL) || (pcOutputStreams == NULL))
00431
00432     {
00433         return E_POINTER;
00434     }
00435
00436     // This MFT has a fixed number of streams.
00437     *pcInputStreams = 1;
00438     *pcOutputStreams = 1;
00439     return S_OK;
00440 }
00441
00442
00443
00444 //-------------------------------------------------------------------
00445 // GetStreamIDs
00446 // Returns stream IDs for the input and output streams.
00447 //-------------------------------------------------------------------
00448
00449 HRESULT CGrayscale::GetStreamIDs(
00450     DWORD   dwInputIDArraySize,
00451     DWORD   *pdwInputIDs,
00452     DWORD   dwOutputIDArraySize,
00453     DWORD   *pdwOutputIDs
00454 )
00455 {
00456     // It is not required to implement this method if the MFT has a fixed number of
00457     // streams AND the stream IDs are numbered sequentially from zero (that is, the
00458     // stream IDs match the stream indexes).
00459
00460     // In that case, it is OK to return E_NOTIMPL.
00461     return E_NOTIMPL;
00462 }
00463
00464
00465 //-------------------------------------------------------------------
00466 // GetInputStreamInfo
00467 // Returns information about an input stream.
00468 //-------------------------------------------------------------------
00469
00470 HRESULT CGrayscale::GetInputStreamInfo(
00471     DWORD                     dwInputStreamID,
00472     MFT_INPUT_STREAM_INFO *   pStreamInfo
00473 )
00474 {
00475     if (pStreamInfo == NULL)
00476     {
00477         return E_POINTER;
00478     }
00479
00480     EnterCriticalSection(&m_critSec);
00481
00482     if (!IsValidInputStream(dwInputStreamID))
00483     {
00484         LeaveCriticalSection(&m_critSec);
00485         return MF_E_INVALIDSTREAMNUMBER;
00486     }
00487
00488     // NOTE: This method should succeed even when there is no media type on the
00489     //       stream. If there is no media type, we only need to fill in the dwFlags
00490     //       member of MFT_INPUT_STREAM_INFO. The other members depend on having a
00491     //       a valid media type.
00492
00493     pStreamInfo->hnsMaxLatency = 0;
00494     pStreamInfo->dwFlags = MFT_INPUT_STREAM_WHOLE_SAMPLES | MFT_INPUT_STREAM_SINGLE_SAMPLE_PER_BUFFER;
00495
00496     if (m_pInputType == NULL)
00497     {
00498         pStreamInfo->cbSize = 0;
00499     }
00500     else
00501     {
00502         pStreamInfo->cbSize = m_cbImageSize;
00503     }
00504
00505     pStreamInfo->cbMaxLookahead = 0;
00506     pStreamInfo->cbAlignment = 0;
00507
00508     LeaveCriticalSection(&m_critSec);
00509     return S_OK;
00510 }
00511
00512 //-------------------------------------------------------------------
00513 // GetOutputStreamInfo
00514 // Returns information about an output stream.
00515 //-------------------------------------------------------------------
00516
00517 HRESULT CGrayscale::GetOutputStreamInfo(
00518     DWORD                     dwOutputStreamID,
00519     MFT_OUTPUT_STREAM_INFO *  pStreamInfo
00520 )
00521 {
00522     if (pStreamInfo == NULL)
00523     {
00524         return E_POINTER;
00525     }
00526
00527     EnterCriticalSection(&m_critSec);
00528
00529     if (!IsValidOutputStream(dwOutputStreamID))
00530     {
00531         LeaveCriticalSection(&m_critSec);
00532         return MF_E_INVALIDSTREAMNUMBER;
00533     }
00534
00535     // NOTE: This method should succeed even when there is no media type on the
00536     //       stream. If there is no media type, we only need to fill in the dwFlags
00537     //       member of MFT_OUTPUT_STREAM_INFO. The other members depend on having a
00538     //       a valid media type.
00539
00540     pStreamInfo->dwFlags =
00541         MFT_OUTPUT_STREAM_WHOLE_SAMPLES |
00542         MFT_OUTPUT_STREAM_SINGLE_SAMPLE_PER_BUFFER |
00543         MFT_OUTPUT_STREAM_FIXED_SAMPLE_SIZE ;
00544
00545     if (m_pOutputType == NULL)
00546     {
00547         pStreamInfo->cbSize = 0;
00548     }
00549     else
00550     {
00551         pStreamInfo->cbSize = m_cbImageSize;
00552     }
00553
00554     pStreamInfo->cbAlignment = 0;
00555
00556     LeaveCriticalSection(&m_critSec);
00557     return S_OK;
00558 }
00559
00560
00561 //-------------------------------------------------------------------
00562 // GetAttributes
00563 // Returns the attributes for the MFT.
00564 //-------------------------------------------------------------------
00565
00566 HRESULT CGrayscale::GetAttributes(IMFAttributes** ppAttributes)
00567 {
00568     if (ppAttributes == NULL)
00569     {
00570         return E_POINTER;
00571     }
00572
00573     EnterCriticalSection(&m_critSec);
00574
00575     *ppAttributes = m_pAttributes;
00576     (*ppAttributes)->AddRef();
00577
00578     LeaveCriticalSection(&m_critSec);
00579     return S_OK;
00580 }
00581
00582
00583 //-------------------------------------------------------------------
00584 // GetInputStreamAttributes
00585 // Returns stream-level attributes for an input stream.
00586 //-------------------------------------------------------------------
00587
00588 HRESULT CGrayscale::GetInputStreamAttributes(
00589     DWORD           dwInputStreamID,
00590     IMFAttributes   **ppAttributes
00591 )
00592 {
00593     // This MFT does not support any stream-level attributes, so the method is not implemented.
00594     return E_NOTIMPL;
00595 }
00596
00597
00598 //-------------------------------------------------------------------
00599 // GetOutputStreamAttributes
00600 // Returns stream-level attributes for an output stream.
00601 //-------------------------------------------------------------------
00602
00603 HRESULT CGrayscale::GetOutputStreamAttributes(
00604     DWORD           dwOutputStreamID,
00605     IMFAttributes   **ppAttributes
00606 )
00607 {
00608     // This MFT does not support any stream-level attributes, so the method is not implemented.
00609     return E_NOTIMPL;
00610 }
00611
00612
00613 //-------------------------------------------------------------------
00614 // DeleteInputStream
00615 //-------------------------------------------------------------------
00616
00617 HRESULT CGrayscale::DeleteInputStream(DWORD dwStreamID)
00618 {
00619     // This MFT has a fixed number of input streams, so the method is not supported.
00620     return E_NOTIMPL;
00621 }
00622
00623
00624 //-------------------------------------------------------------------
00625 // AddInputStreams
00626 //-------------------------------------------------------------------
00627
00628 HRESULT CGrayscale::AddInputStreams(
00629     DWORD   cStreams,
00630     DWORD   *adwStreamIDs
00631 )
00632 {
00633     // This MFT has a fixed number of output streams, so the method is not supported.
00634     return E_NOTIMPL;
00635 }
00636
00637
00638 //-------------------------------------------------------------------
00639 // GetInputAvailableType
00640 // Returns a preferred input type.
00641 //-------------------------------------------------------------------
00642
00643 HRESULT CGrayscale::GetInputAvailableType(
00644     DWORD           dwInputStreamID,
00645     DWORD           dwTypeIndex, // 0-based
00646     IMFMediaType    **ppType
00647 )
00648 {
00649     if (ppType == NULL)
00650     {
00651         return E_INVALIDARG;
00652     }
00653
00654     EnterCriticalSection(&m_critSec);
00655
00656     if (!IsValidInputStream(dwInputStreamID))
00657     {
00658         LeaveCriticalSection(&m_critSec);
00659         return MF_E_INVALIDSTREAMNUMBER;
00660     }
00661
00662     HRESULT hr = S_OK;
00663
00664     // If the output type is set, return that type as our preferred input type.
00665     if (m_pOutputType == NULL)
00666     {
00667         // The output type is not set. Create a partial media type.
00668         hr = OnGetPartialType(dwTypeIndex, ppType);
00669     }
00670     else if (dwTypeIndex > 0)
00671     {
00672         hr = MF_E_NO_MORE_TYPES;
00673     }
00674     else
00675     {
00676         *ppType = m_pOutputType;
00677         (*ppType)->AddRef();
00678     }
00679
00680     LeaveCriticalSection(&m_critSec);
00681     return hr;
00682 }
00683
00684
00685
00686 //-------------------------------------------------------------------
00687 // GetOutputAvailableType
00688 // Returns a preferred output type.
00689 //-------------------------------------------------------------------
00690
00691 HRESULT CGrayscale::GetOutputAvailableType(
00692     DWORD           dwOutputStreamID,
00693     DWORD           dwTypeIndex, // 0-based
00694     IMFMediaType    **ppType
00695 )
00696 {
00697     if (ppType == NULL)
00698     {
00699         return E_INVALIDARG;
00700     }
00701
00702     EnterCriticalSection(&m_critSec);
00703
00704     if (!IsValidOutputStream(dwOutputStreamID))
00705     {
00706         LeaveCriticalSection(&m_critSec);
00707         return MF_E_INVALIDSTREAMNUMBER;
00708     }
00709
00710     HRESULT hr = S_OK;
00711
00712     if (m_pInputType == NULL)
00713     {
00714         // The input type is not set. Create a partial media type.
00715         hr = OnGetPartialType(dwTypeIndex, ppType);
00716     }
00717     else if (dwTypeIndex > 0)
00718     {
00719         hr = MF_E_NO_MORE_TYPES;
00720     }
00721     else
00722     {
00723         *ppType = m_pInputType;
00724         (*ppType)->AddRef();
00725     }
00726
00727     LeaveCriticalSection(&m_critSec);
00728     return hr;
00729 }
00730
00731
00732 //-------------------------------------------------------------------
00733 // SetInputType
00734 //-------------------------------------------------------------------
00735
00736 HRESULT CGrayscale::SetInputType(
00737     DWORD           dwInputStreamID,
00738     IMFMediaType    *pType, // Can be NULL to clear the input type.
00739     DWORD           dwFlags
00740 )
00741 {
00742     // Validate flags.
00743     if (dwFlags & ~MFT_SET_TYPE_TEST_ONLY)
00744     {
00745         return E_INVALIDARG;
00746     }
00747
00748     EnterCriticalSection(&m_critSec);
00749
00750     if (!IsValidInputStream(dwInputStreamID))
00751     {
00752         LeaveCriticalSection(&m_critSec);
00753         return MF_E_INVALIDSTREAMNUMBER;
00754     }
00755
00756     HRESULT hr = S_OK;
00757
00758     // Does the caller want us to set the type, or just test it?
00759     BOOL bReallySet = ((dwFlags & MFT_SET_TYPE_TEST_ONLY) == 0);
00760
00761     // If we have an input sample, the client cannot change the type now.
00762     if (HasPendingOutput())
00763     {
00764         hr = MF_E_TRANSFORM_CANNOT_CHANGE_MEDIATYPE_WHILE_PROCESSING;
00765         goto done;
00766     }
00767
00768     // Validate the type, if non-NULL.
00769     if (pType)
00770     {
00771         hr = OnCheckInputType(pType);
00772         if (FAILED(hr))
00773         {
00774             goto done;
00775         }
00776     }
00777
00778     // The type is OK. Set the type, unless the caller was just testing.
00779     if (bReallySet)
00780     {
00781         OnSetInputType(pType);
00782
00783         // When the type changes, end streaming.
00784         hr = EndStreaming();
00785     }
00786
00787 done:
00788     LeaveCriticalSection(&m_critSec);
00789     return hr;
00790 }
00791
00792
00793
00794 //-------------------------------------------------------------------
00795 // SetOutputType
00796 //-------------------------------------------------------------------
00797
00798 HRESULT CGrayscale::SetOutputType(
00799     DWORD           dwOutputStreamID,
00800     IMFMediaType    *pType, // Can be NULL to clear the output type.
00801     DWORD           dwFlags
00802 )
00803 {
00804     // Validate flags.
00805     if (dwFlags & ~MFT_SET_TYPE_TEST_ONLY)
00806     {
00807         return E_INVALIDARG;
00808     }
00809
00810     EnterCriticalSection(&m_critSec);
00811
00812     if (!IsValidOutputStream(dwOutputStreamID))
00813     {
00814         LeaveCriticalSection(&m_critSec);
00815         return MF_E_INVALIDSTREAMNUMBER;
00816     }
00817
00818     HRESULT hr = S_OK;
00819
00820     // Does the caller want us to set the type, or just test it?
00821     BOOL bReallySet = ((dwFlags & MFT_SET_TYPE_TEST_ONLY) == 0);
00822
00823     // If we have an input sample, the client cannot change the type now.
00824     if (HasPendingOutput())
00825     {
00826         hr = MF_E_TRANSFORM_CANNOT_CHANGE_MEDIATYPE_WHILE_PROCESSING;
00827         goto done;
00828     }
00829
00830     // Validate the type, if non-NULL.
00831     if (pType)
00832     {
00833         hr = OnCheckOutputType(pType);
00834         if (FAILED(hr))
00835         {
00836             goto done;
00837         }
00838     }
00839
00840     // The type is OK. Set the type, unless the caller was just testing.
00841     if (bReallySet)
00842     {
00843         OnSetOutputType(pType);
00844
00845         // When the type changes, end streaming.
00846         hr = EndStreaming();
00847     }
00848
00849 done:
00850     LeaveCriticalSection(&m_critSec);
00851     return hr;
00852 }
00853
00854
00855 //-------------------------------------------------------------------
00856 // GetInputCurrentType
00857 // Returns the current input type.
00858 //-------------------------------------------------------------------
00859
00860 HRESULT CGrayscale::GetInputCurrentType(
00861     DWORD           dwInputStreamID,
00862     IMFMediaType    **ppType
00863 )
00864 {
00865     if (ppType == NULL)
00866     {
00867         return E_POINTER;
00868     }
00869
00870     HRESULT hr = S_OK;
00871
00872     EnterCriticalSection(&m_critSec);
00873
00874     if (!IsValidInputStream(dwInputStreamID))
00875     {
00876         hr = MF_E_INVALIDSTREAMNUMBER;
00877     }
00878     else if (!m_pInputType)
00879     {
00880         hr = MF_E_TRANSFORM_TYPE_NOT_SET;
00881     }
00882     else
00883     {
00884         *ppType = m_pInputType;
00885         (*ppType)->AddRef();
00886     }
00887     LeaveCriticalSection(&m_critSec);
00888     return hr;
00889 }
00890
00891
00892 //-------------------------------------------------------------------
00893 // GetOutputCurrentType
00894 // Returns the current output type.
00895 //-------------------------------------------------------------------
00896
00897 HRESULT CGrayscale::GetOutputCurrentType(
00898     DWORD           dwOutputStreamID,
00899     IMFMediaType    **ppType
00900 )
00901 {
00902     if (ppType == NULL)
00903     {
00904         return E_POINTER;
00905     }
00906
00907     HRESULT hr = S_OK;
00908
00909     EnterCriticalSection(&m_critSec);
00910
00911     if (!IsValidOutputStream(dwOutputStreamID))
00912     {
00913         hr = MF_E_INVALIDSTREAMNUMBER;
00914     }
00915     else if (!m_pOutputType)
00916     {
00917         hr = MF_E_TRANSFORM_TYPE_NOT_SET;
00918     }
00919     else
00920     {
00921         *ppType = m_pOutputType;
00922         (*ppType)->AddRef();
00923     }
00924
00925     LeaveCriticalSection(&m_critSec);
00926     return hr;
00927 }
00928
00929
00930 //-------------------------------------------------------------------
00931 // GetInputStatus
00932 // Query if the MFT is accepting more input.
00933 //-------------------------------------------------------------------
00934
00935 HRESULT CGrayscale::GetInputStatus(
00936     DWORD           dwInputStreamID,
00937     DWORD           *pdwFlags
00938 )
00939 {
00940     if (pdwFlags == NULL)
00941     {
00942         return E_POINTER;
00943     }
00944
00945     EnterCriticalSection(&m_critSec);
00946
00947     if (!IsValidInputStream(dwInputStreamID))
00948     {
00949         LeaveCriticalSection(&m_critSec);
00950         return MF_E_INVALIDSTREAMNUMBER;
00951     }
00952
00953     // If an input sample is already queued, do not accept another sample until the
00954     // client calls ProcessOutput or Flush.
00955
00956     // NOTE: It is possible for an MFT to accept more than one input sample. For
00957     // example, this might be required in a video decoder if the frames do not
00958     // arrive in temporal order. In the case, the decoder must hold a queue of
00959     // samples. For the video effect, each sample is transformed independently, so
00960     // there is no reason to queue multiple input samples.
00961
00962     if (m_pSample == NULL)
00963     {
00964         *pdwFlags = MFT_INPUT_STATUS_ACCEPT_DATA;
00965     }
00966     else
00967     {
00968         *pdwFlags = 0;
00969     }
00970
00971     LeaveCriticalSection(&m_critSec);
00972     return S_OK;
00973 }
00974
00975
00976
00977 //-------------------------------------------------------------------
00978 // GetOutputStatus
00979 // Query if the MFT can produce output.
00980 //-------------------------------------------------------------------
00981
00982 HRESULT CGrayscale::GetOutputStatus(DWORD *pdwFlags)
00983 {
00984     if (pdwFlags == NULL)
00985     {
00986         return E_POINTER;
00987     }
00988
00989     EnterCriticalSection(&m_critSec);
00990
00991     // The MFT can produce an output sample if (and only if) there an input sample.
00992     if (m_pSample != NULL)
00993     {
00994         *pdwFlags = MFT_OUTPUT_STATUS_SAMPLE_READY;
00995     }
00996     else
00997     {
00998         *pdwFlags = 0;
00999     }
01000
01001     LeaveCriticalSection(&m_critSec);
01002     return S_OK;
01003 }
01004
01005
01006 //-------------------------------------------------------------------
01007 // SetOutputBounds
01008 // Sets the range of time stamps that the MFT will output.
01009 //-------------------------------------------------------------------
01010
01011 HRESULT CGrayscale::SetOutputBounds(
01012     LONGLONG        hnsLowerBound,
01013     LONGLONG        hnsUpperBound
01014 )
01015 {
01016     // Implementation of this method is optional.
01017     return E_NOTIMPL;
01018 }
01019
01020
01021 //-------------------------------------------------------------------
01022 // ProcessEvent
01023 // Sends an event to an input stream.
01024 //-------------------------------------------------------------------
01025
01026 HRESULT CGrayscale::ProcessEvent(
01027     DWORD              dwInputStreamID,
01028     IMFMediaEvent      *pEvent
01029 )
01030 {
01031     // This MFT does not handle any stream events, so the method can
01032     // return E_NOTIMPL. This tells the pipeline that it can stop
01033     // sending any more events to this MFT.
01034     return E_NOTIMPL;
01035 }
01036
01037
01038 //-------------------------------------------------------------------
01039 // ProcessMessage
01040 //-------------------------------------------------------------------
01041
01042 HRESULT CGrayscale::ProcessMessage(
01043     MFT_MESSAGE_TYPE    eMessage,
01044     ULONG_PTR           ulParam
01045 )
01046 {
01047     EnterCriticalSection(&m_critSec);
01048
01049     HRESULT hr = S_OK;
01050
01051     switch (eMessage)
01052     {
01053     case MFT_MESSAGE_COMMAND_FLUSH:
01054         // Flush the MFT.
01055         hr = OnFlush();
01056         break;
01057
01058     case MFT_MESSAGE_COMMAND_DRAIN:
01059         // Drain: Tells the MFT to reject further input until all pending samples are
01060         // processed. That is our default behavior already, so there is nothing to do.
01061         //
01062         // For a decoder that accepts a queue of samples, the MFT might need to drain
01063         // the queue in response to this command.
01064     break;
01065
01066     case MFT_MESSAGE_SET_D3D_MANAGER:
01067         // Sets a pointer to the IDirect3DDeviceManager9 interface.
01068
01069         // The pipeline should never send this message unless the MFT sets the MF_SA_D3D_AWARE
01070         // attribute set to TRUE. Because this MFT does not set MF_SA_D3D_AWARE, it is an error
01071         // to send the MFT_MESSAGE_SET_D3D_MANAGER message to the MFT. Return an error code in
01072         // this case.
01073
01074         // NOTE: If this MFT were D3D-enabled, it would cache the IDirect3DDeviceManager9
01075         // pointer for use during streaming.
01076
01077         hr = E_NOTIMPL;
01078         break;
01079
01080     case MFT_MESSAGE_NOTIFY_BEGIN_STREAMING:
01081         hr = BeginStreaming();
01082         break;
01083
01084     case MFT_MESSAGE_NOTIFY_END_STREAMING:
01085         hr = EndStreaming();
01086         break;
01087
01088     // The next two messages do not require any action from this MFT.
01089
01090     case MFT_MESSAGE_NOTIFY_END_OF_STREAM:
01091         break;
01092
01093     case MFT_MESSAGE_NOTIFY_START_OF_STREAM:
01094         break;
01095     }
01096
01097     LeaveCriticalSection(&m_critSec);
01098     return hr;
01099 }
01100
01101
01102 //-------------------------------------------------------------------
01103 // ProcessInput
01104 // Process an input sample.
01105 //-------------------------------------------------------------------
01106
01107 HRESULT CGrayscale::ProcessInput(
01108     DWORD               dwInputStreamID,
01109     IMFSample           *pSample,
01110     DWORD               dwFlags
01111 )
01112 {
01113     // Check input parameters.
01114     if (pSample == NULL)
01115     {
01116         return E_POINTER;
01117     }
01118
01119     if (dwFlags != 0)
01120     {
01121         return E_INVALIDARG; // dwFlags is reserved and must be zero.
01122     }
01123
01124     HRESULT hr = S_OK;
01125
01126     EnterCriticalSection(&m_critSec);
01127
01128     // Validate the input stream number.
01129     if (!IsValidInputStream(dwInputStreamID))
01130     {
01131         hr = MF_E_INVALIDSTREAMNUMBER;
01132         goto done;
01133     }
01134
01135     // Check for valid media types.
01136     // The client must set input and output types before calling ProcessInput.
01137     if (!m_pInputType || !m_pOutputType)
01138     {
01139         hr = MF_E_NOTACCEPTING;
01140         goto done;
01141     }
01142
01143     // Check if an input sample is already queued.
01144     if (m_pSample != NULL)
01145     {
01146         hr = MF_E_NOTACCEPTING;   // We already have an input sample.
01147         goto done;
01148     }
01149
01150     // Initialize streaming.
01151     hr = BeginStreaming();
01152     if (FAILED(hr))
01153     {
01154         goto done;
01155     }
01156
01157     // Cache the sample. We do the actual work in ProcessOutput.
01158     m_pSample = pSample;
01159     pSample->AddRef();  // Hold a reference count on the sample.
01160
01161 done:
01162     LeaveCriticalSection(&m_critSec);
01163     return hr;
01164 }
01165
01166
01167 //-------------------------------------------------------------------
01168 // ProcessOutput
01169 // Process an output sample.
01170 //-------------------------------------------------------------------
01171
01172 HRESULT CGrayscale::ProcessOutput(
01173     DWORD                   dwFlags,
01174     DWORD                   cOutputBufferCount,
01175     MFT_OUTPUT_DATA_BUFFER  *pOutputSamples, // one per stream
01176     DWORD                   *pdwStatus
01177 )
01178 {
01179     // Check input parameters...
01180
01181     // This MFT does not accept any flags for the dwFlags parameter.
01182
01183     // The only defined flag is MFT_PROCESS_OUTPUT_DISCARD_WHEN_NO_BUFFER. This flag
01184     // applies only when the MFT marks an output stream as lazy or optional. But this
01185     // MFT has no lazy or optional streams, so the flag is not valid.
01186
01187     if (dwFlags != 0)
01188     {
01189         return E_INVALIDARG;
01190     }
01191
01192     if (pOutputSamples == NULL || pdwStatus == NULL)
01193     {
01194         return E_POINTER;
01195     }
01196
01197     // There must be exactly one output buffer.
01198     if (cOutputBufferCount != 1)
01199     {
01200         return E_INVALIDARG;
01201     }
01202
01203     // It must contain a sample.
01204     if (pOutputSamples[0].pSample == NULL)
01205     {
01206         return E_INVALIDARG;
01207     }
01208
01209     HRESULT hr = S_OK;
01210
01211     IMFMediaBuffer *pInput = NULL;
01212     IMFMediaBuffer *pOutput = NULL;
01213
01214     EnterCriticalSection(&m_critSec);
01215
01216     // There must be an input sample available for processing.
01217     if (m_pSample == NULL)
01218     {
01219         hr = MF_E_TRANSFORM_NEED_MORE_INPUT;
01220         goto done;
01221     }
01222
01223     // Initialize streaming.
01224
01225     hr = BeginStreaming();
01226     if (FAILED(hr))
01227     {
01228         goto done;
01229     }
01230
01231     // Get the input buffer.
01232     hr = m_pSample->ConvertToContiguousBuffer(&pInput);
01233     if (FAILED(hr))
01234     {
01235         goto done;
01236     }
01237
01238     // Get the output buffer.
01239     hr = pOutputSamples[0].pSample->ConvertToContiguousBuffer(&pOutput);
01240     if (FAILED(hr))
01241     {
01242         goto done;
01243     }
01244
01245     hr = OnProcessOutput(pInput, pOutput);
01246     if (FAILED(hr))
01247     {
01248         goto done;
01249     }
01250
01251     // Set status flags.
01252     pOutputSamples[0].dwStatus = 0;
01253     *pdwStatus = 0;
01254
01255
01256     // Copy the duration and time stamp from the input sample, if present.
01257
01258     LONGLONG hnsDuration = 0;
01259     LONGLONG hnsTime = 0;
01260
01261     if (SUCCEEDED(m_pSample->GetSampleDuration(&hnsDuration)))
01262     {
01263         hr = pOutputSamples[0].pSample->SetSampleDuration(hnsDuration);
01264         if (FAILED(hr))
01265         {
01266             goto done;
01267         }
01268     }
01269
01270     if (SUCCEEDED(m_pSample->GetSampleTime(&hnsTime)))
01271     {
01272         hr = pOutputSamples[0].pSample->SetSampleTime(hnsTime);
01273     }
01274
01275 done:
01276     SafeRelease(&m_pSample);   // Release our input sample.
01277     SafeRelease(&pInput);
01278     SafeRelease(&pOutput);
01279     LeaveCriticalSection(&m_critSec);
01280     return hr;
01281 }
01282
01283 // PRIVATE METHODS
01284
01285 // All methods that follow are private to this MFT and are not part of the IMFTransform interface.
01286
01287 // Create a partial media type from our list.
01288 //
01289 // dwTypeIndex: Index into the list of peferred media types.
01290 // ppmt:        Receives a pointer to the media type.
01291
01292 HRESULT CGrayscale::OnGetPartialType(DWORD dwTypeIndex, IMFMediaType **ppmt)
01293 {
01294     if (dwTypeIndex >= ARRAYSIZE(g_MediaSubtypes))
01295     {
01296         return MF_E_NO_MORE_TYPES;
01297     }
01298
01299     IMFMediaType *pmt = NULL;
01300
01301     HRESULT hr = MFCreateMediaType(&pmt);
01302     if (FAILED(hr))
01303     {
01304         goto done;
01305     }
01306
01307     hr = pmt->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video);
01308     if (FAILED(hr))
01309     {
01310         goto done;
01311     }
01312
01313     hr = pmt->SetGUID(MF_MT_SUBTYPE, g_MediaSubtypes[dwTypeIndex]);
01314     if (FAILED(hr))
01315     {
01316         goto done;
01317     }
01318
01319     *ppmt = pmt;
01320     (*ppmt)->AddRef();
01321
01322 done:
01323     SafeRelease(&pmt);
01324     return hr;
01325 }
01326
01327
01328 // Validate an input media type.
01329
01330 HRESULT CGrayscale::OnCheckInputType(IMFMediaType *pmt)
01331 {
01332     assert(pmt != NULL);
01333
01334     HRESULT hr = S_OK;
01335
01336     // If the output type is set, see if they match.
01337     if (m_pOutputType != NULL)
01338     {
01339         DWORD flags = 0;
01340         hr = pmt->IsEqual(m_pOutputType, &flags);
01341
01342         // IsEqual can return S_FALSE. Treat this as failure.
01343         if (hr != S_OK)
01344         {
01345             hr = MF_E_INVALIDMEDIATYPE;
01346         }
01347     }
01348     else
01349     {
01350         // Output type is not set. Just check this type.
01351         hr = OnCheckMediaType(pmt);
01352     }
01353     return hr;
01354 }
01355
01356
01357 // Validate an output media type.
01358
01359 HRESULT CGrayscale::OnCheckOutputType(IMFMediaType *pmt)
01360 {
01361     assert(pmt != NULL);
01362
01363     HRESULT hr = S_OK;
01364
01365     // If the input type is set, see if they match.
01366     if (m_pInputType != NULL)
01367     {
01368         DWORD flags = 0;
01369         hr = pmt->IsEqual(m_pInputType, &flags);
01370
01371         // IsEqual can return S_FALSE. Treat this as failure.
01372         if (hr != S_OK)
01373         {
01374             hr = MF_E_INVALIDMEDIATYPE;
01375         }
01376
01377     }
01378     else
01379     {
01380         // Input type is not set. Just check this type.
01381         hr = OnCheckMediaType(pmt);
01382     }
01383     return hr;
01384 }
01385
01386
01387 // Validate a media type (input or output)
01388
01389 HRESULT CGrayscale::OnCheckMediaType(IMFMediaType *pmt)
01390 {
01391     BOOL bFoundMatchingSubtype = FALSE;
01392
01393     // Major type must be video.
01394     GUID major_type;
01395     HRESULT hr = pmt->GetGUID(MF_MT_MAJOR_TYPE, &major_type);
01396     if (FAILED(hr))
01397     {
01398         goto done;
01399     }
01400
01401     if (major_type != MFMediaType_Video)
01402     {
01403         hr = MF_E_INVALIDMEDIATYPE;
01404         goto done;
01405     }
01406
01407     // Subtype must be one of the subtypes in our global list.
01408
01409     // Get the subtype GUID.
01410     GUID subtype;
01411     hr = pmt->GetGUID(MF_MT_SUBTYPE, &subtype);
01412     if (FAILED(hr))
01413     {
01414         goto done;
01415     }
01416
01417     // Look for the subtype in our list of accepted types.
01418     for (DWORD i = 0; i < ARRAYSIZE(g_MediaSubtypes); i++)
01419     {
01420         if (subtype == g_MediaSubtypes[i])
01421         {
01422             bFoundMatchingSubtype = TRUE;
01423             break;
01424         }
01425     }
01426
01427     if (!bFoundMatchingSubtype)
01428     {
01429         hr = MF_E_INVALIDMEDIATYPE; // The MFT does not support this subtype.
01430         goto done;
01431     }
01432
01433     // Reject single-field media types.
01434     UINT32 interlace = MFGetAttributeUINT32(pmt, MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive);
01435     if (interlace == MFVideoInterlace_FieldSingleUpper  || interlace == MFVideoInterlace_FieldSingleLower)
01436     {
01437         hr = MF_E_INVALIDMEDIATYPE;
01438     }
01439
01440 done:
01441     return hr;
01442 }
01443
01444
01445 // Set or clear the input media type.
01446 //
01447 // Prerequisite: The input type was already validated.
01448
01449 void CGrayscale::OnSetInputType(IMFMediaType *pmt)
01450 {
01451     // if pmt is NULL, clear the type.
01452     // if pmt is non-NULL, set the type.
01453
01454     SafeRelease(&m_pInputType);
01455     m_pInputType = pmt;
01456     if (m_pInputType)
01457     {
01458         m_pInputType->AddRef();
01459     }
01460
01461     // Update the format information.
01462     UpdateFormatInfo();
01463 }
01464
01465
01466 // Set or clears the output media type.
01467 //
01468 // Prerequisite: The output type was already validated.
01469
01470 void CGrayscale::OnSetOutputType(IMFMediaType *pmt)
01471 {
01472     // If pmt is NULL, clear the type. Otherwise, set the type.
01473
01474     SafeRelease(&m_pOutputType);
01475     m_pOutputType = pmt;
01476     if (m_pOutputType)
01477     {
01478         m_pOutputType->AddRef();
01479     }
01480 }
01481
01482
01483 // Initialize streaming parameters.
01484 //
01485 // This method is called if the client sends the MFT_MESSAGE_NOTIFY_BEGIN_STREAMING
01486 // message, or when the client processes a sample, whichever happens first.
01487
01488 HRESULT CGrayscale::BeginStreaming()
01489 {
01490     HRESULT hr = S_OK;
01491
01492     if (!m_bStreamingInitialized)
01493     {
01494         // Get the configuration attributes.
01495
01496         // Get the destination rectangle.
01497
01498         RECT rcDest;
01499         hr = m_pAttributes->GetBlob(MFT_GRAYSCALE_DESTINATION_RECT, (UINT8*)&rcDest, sizeof(rcDest), NULL);
01500         if (hr == MF_E_ATTRIBUTENOTFOUND || !ValidateRect(rcDest))
01501         {
01502             // The client did not set this attribute, or the client provided an invalid rectangle.
01503             // Default to the entire image.
01504
01505             m_rcDest = D2D1::RectU(0, 0, m_imageWidthInPixels, m_imageHeightInPixels);
01506             hr = S_OK;
01507         }
01508         else if (SUCCEEDED(hr))
01509         {
01510             m_rcDest = D2D1::RectU(rcDest.left, rcDest.top, rcDest.right, rcDest.bottom);
01511         }
01512         else
01513         {
01514             goto done;
01515         }
01516
01517         // Get the chroma transformations.
01518
01519         float scale = (float)MFGetAttributeDouble(m_pAttributes, MFT_GRAYSCALE_SATURATION, 0.0f);
01520         float angle = (float)MFGetAttributeDouble(m_pAttributes, MFT_GRAYSCALE_CHROMA_ROTATION, 0.0f);
01521
01522         m_transform = D2D1::Matrix3x2F::Scale(scale, scale) * D2D1::Matrix3x2F::Rotation(angle);
01523
01524         m_bStreamingInitialized = true;
01525     }
01526
01527 done:
01528     return hr;
01529 }
01530
01531
01532 // End streaming.
01533
01534 // This method is called if the client sends an MFT_MESSAGE_NOTIFY_END_STREAMING
01535 // message, or when the media type changes. In general, it should be called whenever
01536 // the streaming parameters need to be reset.
01537
01538 HRESULT CGrayscale::EndStreaming()
01539 {
01540     m_bStreamingInitialized = false;
01541     return S_OK;
01542 }
01543
01544
01545
01546 // Generate output data.
01547
01548 HRESULT CGrayscale::OnProcessOutput(IMFMediaBuffer *pIn, IMFMediaBuffer *pOut)
01549 {
01550     BYTE *pDest = NULL;         // Destination buffer.
01551     LONG lDestStride = 0;       // Destination stride.
01552
01553     BYTE *pSrc = NULL;          // Source buffer.
01554     LONG lSrcStride = 0;        // Source stride.
01555
01556     // Helper objects to lock the buffers.
01557     VideoBufferLock inputLock(pIn);
01558     VideoBufferLock outputLock(pOut);
01559
01560     // Stride if the buffer does not support IMF2DBuffer
01561     LONG lDefaultStride = 0;
01562
01563     HRESULT hr = GetDefaultStride(m_pInputType, &lDefaultStride);
01564     if (FAILED(hr))
01565     {
01566         goto done;
01567     }
01568
01569     // Lock the input buffer.
01570     hr = inputLock.LockBuffer(lDefaultStride, m_imageHeightInPixels, &pSrc, &lSrcStride);
01571     if (FAILED(hr))
01572     {
01573         goto done;
01574     }
01575
01576     // Lock the output buffer.
01577     hr = outputLock.LockBuffer(lDefaultStride, m_imageHeightInPixels, &pDest, &lDestStride);
01578     if (FAILED(hr))
01579     {
01580         goto done;
01581     }
01582
01583     // Invoke the image transform function.
01584     assert (m_pTransformFn != NULL);
01585     if (m_pTransformFn)
01586     {
01587         (*m_pTransformFn)(m_transform, m_rcDest, pDest, lDestStride, pSrc, lSrcStride,
01588             m_imageWidthInPixels, m_imageHeightInPixels);
01589     }
01590     else
01591     {
01592         hr = E_UNEXPECTED;
01593         goto done;
01594     }
01595
01596
01597     // Set the data size on the output buffer.
01598     hr = pOut->SetCurrentLength(m_cbImageSize);
01599
01600     // The VideoBufferLock class automatically unlocks the buffers.
01601 done:
01602     return hr;
01603 }
01604
01605
01606 // Flush the MFT.
01607
01608 HRESULT CGrayscale::OnFlush()
01609 {
01610     // For this MFT, flushing just means releasing the input sample.
01611     SafeRelease(&m_pSample);
01612     return S_OK;
01613 }
01614
01615
01616 // Update the format information. This method is called whenever the
01617 // input type is set.
01618
01619 HRESULT CGrayscale::UpdateFormatInfo()
01620 {
01621     HRESULT hr = S_OK;
01622
01623     GUID subtype = GUID_NULL;
01624
01625     m_imageWidthInPixels = 0;
01626     m_imageHeightInPixels = 0;
01627     m_cbImageSize = 0;
01628
01629     m_pTransformFn = NULL;
01630
01631     if (m_pInputType != NULL)
01632     {
01633         hr = m_pInputType->GetGUID(MF_MT_SUBTYPE, &subtype);
01634         if (FAILED(hr))
01635         {
01636             goto done;
01637         }
01638         if (subtype == MFVideoFormat_YUY2)
01639         {
01640             m_pTransformFn = TransformImage_YUY2;
01641         }
01642         else if (subtype == MFVideoFormat_UYVY)
01643         {
01644             m_pTransformFn = TransformImage_UYVY;
01645         }
01646         else if (subtype == MFVideoFormat_NV12)
01647         {
01648             m_pTransformFn = TransformImage_NV12;
01649         }
01650         else
01651         {
01652             hr = E_UNEXPECTED;
01653             goto done;
01654         }
01655
01656         hr = MFGetAttributeSize(m_pInputType, MF_MT_FRAME_SIZE, &m_imageWidthInPixels, &m_imageHeightInPixels);
01657         if (FAILED(hr))
01658         {
01659             goto done;
01660         }
01661
01662         // Calculate the image size (not including padding)
01663         hr = GetImageSize(subtype.Data1, m_imageWidthInPixels, m_imageHeightInPixels, &m_cbImageSize);
01664     }
01665
01666 done:
01667     return hr;
01668 }
01669
01670
01671 // Calculate the size of the buffer needed to store the image.
01672
01673 // fcc: The FOURCC code of the video format.
01674
01675 HRESULT GetImageSize(DWORD fcc, UINT32 width, UINT32 height, DWORD* pcbImage)
01676 {
01677     HRESULT hr = S_OK;
01678
01679     switch (fcc)
01680     {
01681     case FOURCC_YUY2:
01682     case FOURCC_UYVY:
01683         // check overflow
01684         if ((width > MAXDWORD / 2) || (width * 2 > MAXDWORD / height))
01685         {
01686             hr = E_INVALIDARG;
01687         }
01688         else
01689         {
01690             // 16 bpp
01691             *pcbImage = width * height * 2;
01692         }
01693         break;
01694
01695     case FOURCC_NV12:
01696         // check overflow
01697         if ((height/2 > MAXDWORD - height) || ((height + height/2) > MAXDWORD / width))
01698         {
01699             hr = E_INVALIDARG;
01700         }
01701         else
01702         {
01703             // 12 bpp
01704             *pcbImage = width * (height + (height/2));
01705         }
01706         break;
01707
01708     default:
01709         hr = E_FAIL;    // Unsupported type.
01710     }
01711     return hr;
01712 }
01713
01714 // Get the default stride for a video format.
01715 HRESULT GetDefaultStride(IMFMediaType *pType, LONG *plStride)
01716 {
01717     LONG lStride = 0;
01718
01719     // Try to get the default stride from the media type.
01720     HRESULT hr = pType->GetUINT32(MF_MT_DEFAULT_STRIDE, (UINT32*)&lStride);
01721     if (FAILED(hr))
01722     {
01723         // Attribute not set. Try to calculate the default stride.
01724         GUID subtype = GUID_NULL;
01725
01726         UINT32 width = 0;
01727         UINT32 height = 0;
01728
01729         // Get the subtype and the image size.
01730         hr = pType->GetGUID(MF_MT_SUBTYPE, &subtype);
01731         if (SUCCEEDED(hr))
01732         {
01733             hr = MFGetAttributeSize(pType, MF_MT_FRAME_SIZE, &width, &height);
01734         }
01735         if (SUCCEEDED(hr))
01736         {
01737             if (subtype == MFVideoFormat_NV12)
01738             {
01739                 lStride = width;
01740             }
01741             else if (subtype == MFVideoFormat_YUY2 || subtype == MFVideoFormat_UYVY)
01742             {
01743                 lStride = ((width * 2) + 3) & ~3;
01744             }
01745             else
01746             {
01747                 hr = E_INVALIDARG;
01748             }
01749         }
01750
01751         // Set the attribute for later reference.
01752         if (SUCCEEDED(hr))
01753         {
01754             (void)pType->SetUINT32(MF_MT_DEFAULT_STRIDE, UINT32(lStride));
01755         }
01756     }
01757     if (SUCCEEDED(hr))
01758     {
01759         *plStride = lStride;
01760     }
01761     return hr;
01762 }
01763
01764
01765 // Validate that a rectangle meets the following criteria:
01766 //
01767 //  - All coordinates are non-negative.
01768 //  - The rectangle is not flipped (top > bottom, left > right)
01769 //
01770 // These are the requirements for the destination rectangle.
01771
01772 bool ValidateRect(const RECT& rc)
01773 {
01774     if (rc.left < 0 || rc.top < 0)
01775     {
01776         return false;
01777     }
01778     if (rc.left > rc.right || rc.top > rc.bottom)
01779     {
01780         return false;
01781     }
01782     return true;
01783 }
Generated on Sat Nov 23 2024 16:08:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/CalendarExtensions.cpp Source File

  • Hilo C++
  • Hilo

CalendarExtensions.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 #include "CalendarExtensions.h"
00009
00010 using namespace Hilo;
00011 using namespace Platform;
00012 using namespace Platform::Collections;
00013 using namespace std;
00014 using namespace Windows::Foundation;
00015 using namespace Windows::Globalization;
00016 using namespace Windows::Globalization::DateTimeFormatting;
00017 using namespace Windows::System::UserProfile;
00018
00019 const int DATE_BUFFER_SIZE = 128;
00020
00021 // Creates a formatted date string that will be compatible with Advanced Query Syntax (AQS).
00022 wstring CalendarExtensions::GetAqsFormattedDate(const DateTime date)
00023 {
00024     auto utime = date.UniversalTime;
00025
00026     FILETIME time;
00027     time.dwHighDateTime = (DWORD)(utime >> 32);
00028     time.dwLowDateTime = (DWORD)(utime & 0xFFFFFFFF);
00029
00030     BOOL result;
00031     SYSTEMTIME systime;
00032
00033     result = FileTimeToSystemTime(
00034         /* __in   const FILETIME *lpFileTime */ &time,
00035         /* __out  LPSYSTEMTIME lpSystemTime */  &systime
00036         );
00037     if (!result)
00038     {
00039         throw Exception::CreateException(HRESULT_FROM_WIN32(GetLastError()));
00040     }
00041
00042     SYSTEMTIME localSystime;
00043     TIME_ZONE_INFORMATION timeZoneInfo;
00044     GetTimeZoneInformation(&timeZoneInfo);
00045     result = SystemTimeToTzSpecificLocalTime(
00046         /* _In_opt_  LPTIME_ZONE_INFORMATION lpTimeZone */ &timeZoneInfo,
00047         /* _In_      LPSYSTEMTIME lpUniversalTime*/        &systime,
00048         /* _Out_     LPSYSTEMTIME lpLocalTime */           &localSystime
00049         );
00050     if (!result)
00051     {
00052         throw Exception::CreateException(HRESULT_FROM_WIN32(GetLastError()));
00053     }
00054
00055     WCHAR dateStr[DATE_BUFFER_SIZE];
00056     result = GetDateFormatEx(
00057         /* __in_opt   LPCWSTR lpLocaleName */     LOCALE_NAME_USER_DEFAULT,
00058         /* __in       DWORD dwFlags */            DATE_SHORTDATE,
00059         /* __in_opt   const SYSTEMTIME *lpDate */ &localSystime,
00060         /* __in_opt   LPCWSTR lpFormat */         NULL,
00061         /* __out_opt  LPWSTR lpDateStr */         dateStr,
00062         /* __in       int cchDate */              DATE_BUFFER_SIZE,
00063         /* __in_opt   LPCWSTR lpCalendar */       NULL
00064         );
00065     if (!result)
00066     {
00067         throw Exception::CreateException(HRESULT_FROM_WIN32(GetLastError()));
00068     }
00069
00070     return wstring(dateStr);
00071 }
00072
00073 // private helper-- creates an AQS date-range expression that spans the month that contains the given date in the given calendar system.
00074 String^ CalendarExtensions::CreateMonthRangeFromDate(Calendar^ cal)
00075 {
00076     wstringstream dateRange;
00077     dateRange << L"System.ItemDate:" ;
00078
00079     cal->Day = cal->FirstDayInThisMonth;
00080     cal->Period = cal->FirstPeriodInThisDay;
00081     cal->Hour = cal->FirstHourInThisPeriod;
00082     cal->Minute = cal->FirstMinuteInThisHour;
00083     cal->Second = cal->FirstSecondInThisMinute;
00084     cal->Nanosecond = 0;
00085     dateRange << GetAqsFormattedDate(cal->GetDateTime());
00086
00087     dateRange << "..";
00088
00089     cal->Day = cal->LastDayInThisMonth;
00090     cal->Period = cal->LastPeriodInThisDay;
00091     cal->Hour = cal->LastHourInThisPeriod;
00092     cal->Minute = cal->LastMinuteInThisHour;
00093     cal->Second = cal->LastSecondInThisMinute;
00094     cal->Nanosecond = 999999;
00095     dateRange << GetAqsFormattedDate(cal->GetDateTime());
00096
00097     return ref new String(dateRange.str().c_str());
00098 }
00099
00100 Calendar^ CalendarExtensions::GetCalendar()
00101 {
00102     return ref new Calendar();
00103 }
00104
00105 // Uses the appropriate calendar to return an Advanced Query Syntax (AQS) date range
00106 // expression that includes all dates in this month.
00107 String^ CalendarExtensions::CreateMonthRangeFromYearAndMonth(int year, int month)
00108 {
00109     auto cal = GetCalendar();
00110
00111     cal->Year = year;
00112     cal->Month = month;
00113     cal->Day = cal->FirstDayInThisMonth;
00114     return CreateMonthRangeFromDate(cal);
00115 }
00116
00117 // Uses the appropriate calendar to create an Advanced Query Syntax (AQS) date range
00118 // expression that spans the month that contains the given date.
00119 String^ CalendarExtensions::CreateMonthRangeFromDate(const DateTime date)
00120 {
00121     auto cal = GetCalendar();
00122
00123     cal->SetDateTime(date);
00124     return CreateMonthRangeFromDate(cal);
00125 }
00126
00127 // Returns the number of months in a given year according to the appropriate calendar
00128 int CalendarExtensions::GetNumberOfMonthsInYear(DateTime yearDate)
00129 {
00130     auto cal = GetCalendar();
00131
00132     cal->SetDateTime(yearDate);
00133     return cal->NumberOfMonthsInThisYear;
00134 }
00135
00136 // Returns the short name of given month for the app's resolved language. For example, "Jan" for January in English.
00137 String^ CalendarExtensions::GetLocalizedAbbreviatedMonthName(int year, int month)
00138 {
00139     auto cal = GetCalendar();
00140     cal->Year = year;
00141     cal->Month = month;
00142     cal->Day = cal->FirstDayInThisMonth;
00143
00144     auto lang = ref new Vector<String^>();
00145     lang->Append(ResolvedLanguage());
00146     auto dtf = ref new DateTimeFormatter(
00147         YearFormat::None,
00148         MonthFormat::Abbreviated,
00149         DayFormat::None,
00150         DayOfWeekFormat::None,
00151         HourFormat::None,
00152         MinuteFormat::None,
00153         SecondFormat::None,
00154         lang, ResolvedGeographicRegion(), cal->GetCalendarSystem(), cal->GetClock());
00155
00156     return dtf->Format(cal->GetDateTime());
00157 }
00158
00159 // Returns a localized month and year string for a given date in the app's resolved language.
00160 String^ CalendarExtensions::GetLocalizedMonthAndYear(const DateTime date)
00161 {
00162     auto cal = GetCalendar();
00163     auto lang = ref new Vector<String^>();
00164     lang->Append(ResolvedLanguage());
00165     auto dtf = ref new DateTimeFormatter(
00166         YearFormat::Full,
00167         MonthFormat::Full,
00168         DayFormat::None,
00169         DayOfWeekFormat::None,
00170         HourFormat::None,
00171         MinuteFormat::None,
00172         SecondFormat::None,
00173         lang, ResolvedGeographicRegion(), cal->GetCalendarSystem(), cal->GetClock());
00174
00175     cal->SetDateTime(date);
00176     return dtf->Format(cal->GetDateTime());
00177 }
00178
00179 // Returns a localized year string for a given date using the app's resolved language.
00180 String^ CalendarExtensions::GetLocalizedYear(DateTime yearDate)
00181 {
00182     auto cal = GetCalendar();
00183
00184     cal->SetDateTime(yearDate);
00185
00186     auto lang = ref new Vector<String^>();
00187     lang->Append(ResolvedLanguage());
00188     auto dtf = ref new DateTimeFormatter(
00189         YearFormat::Full,
00190         MonthFormat::None,
00191         DayFormat::None,
00192         DayOfWeekFormat::None,
00193         HourFormat::None,
00194         MinuteFormat::None,
00195         SecondFormat::None,
00196         lang, ResolvedGeographicRegion(), cal->GetCalendarSystem(), cal->GetClock());
00197
00198     return dtf->Format(cal->GetDateTime());
00199 }
00200
00201 int CalendarExtensions::GetNumericYear(const Windows::Foundation::DateTime yearDate)
00202 {
00203     auto cal = GetCalendar();
00204
00205     cal->SetDateTime(yearDate);
00206     return cal->Year;
00207 }
00208
00209 // Sets year and month to localized values (based on the appropriate calendar) for a given date
00210 void CalendarExtensions::WriteLocalizedYearAndMonth(const Windows::Foundation::DateTime date, int& yearResult, int& monthResult)
00211 {
00212     auto cal = GetCalendar();
00213
00214     cal->SetDateTime(date);
00215     yearResult = cal->Year;
00216     monthResult = cal->Month;
00217 }
00218
00219 Platform::String^ CalendarExtensions::ResolvedLanguage()
00220 {
00221     return (ref new DateTimeFormatter("shortdate"))->ResolvedLanguage;
00222 }
00223
00224 Platform::String^ CalendarExtensions::ResolvedGeographicRegion()
00225 {
00226    return (ref new DateTimeFormatter("shortdate"))->ResolvedGeographicRegion;
00227 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Portable device API/C++/App.xaml.cpp Source File

  • Portable device API

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:28 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XInput game controller/C++/DirectXBase.h Source File

  • XInput game controller

DirectXBase.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 "DirectXSample.h"
00011
00012 // Helper class that initializes DirectX APIs for both 2D and 3D rendering.
00013 // Some of the code in this class may be omitted if only 2D or only 3D rendering is being used.
00014 ref class DirectXBase abstract
00015 {
00016 internal:
00017     DirectXBase();
00018
00019     virtual void Initialize(Windows::UI::Core::CoreWindow^ window, float dpi);
00020     virtual void HandleDeviceLost();
00021     virtual void CreateDeviceIndependentResources();
00022     virtual void CreateDeviceResources();
00023     virtual void SetDpi(float dpi);
00024     virtual void UpdateForWindowSizeChange();
00025     virtual void CreateWindowSizeDependentResources();
00026     virtual void Render() = 0;
00027     virtual void Present();
00028     void ValidateDevice();
00029
00030 protected private:
00031     Platform::Agile<Windows::UI::Core::CoreWindow>  m_window;
00032
00033     // DirectWrite & Windows Imaging Component Objects.
00034     Microsoft::WRL::ComPtr<IDWriteFactory1>         m_dwriteFactory;
00035     Microsoft::WRL::ComPtr<IWICImagingFactory2>     m_wicFactory;
00036
00037     // DirectX Core Objects. Required for 2D and 3D.
00038     Microsoft::WRL::ComPtr<ID3D11Device1>           m_d3dDevice;
00039     Microsoft::WRL::ComPtr<ID3D11DeviceContext1>    m_d3dContext;
00040     Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00041     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00042
00043     // Direct2D Rendering Objects. Required for 2D.
00044     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00046     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00047     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmap;
00048
00049     // Direct3D Rendering Objects. Required for 3D.
00050     Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00051
00052     // Cached renderer properties.
00053     D3D_FEATURE_LEVEL                               m_featureLevel;
00054     Windows::Foundation::Size                       m_renderTargetSize;
00055     Windows::Foundation::Rect                       m_windowBounds;
00056     float                                           m_dpi;
00057     bool                                            m_windowSizeChangeInProgress;
00058 };
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Clipboard app/C++/constants.cpp Source File

  • Clipboard app

constants.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 "Constants.h"
00014
00015 using namespace Clipboard;
00016 using namespace Windows::UI::ViewManagement;
00017
00018 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00019 {
00020     { "Copy and paste text", "Clipboard.CopyText" },
00021     { "Copy and paste an image", "Clipboard.CopyImage" },
00022     { "Copy and paste files", "Clipboard.CopyFiles" },
00023     { "Other Clipboard operations", "Clipboard.Others" }
00024 };
00025
00026 bool MainPage::EnsureUnsnapped()
00027 {
00028     // FilePicker APIs will not work if the application is in a snapped state.
00029     // If an app wants to show a FilePicker while snapped, it must attempt to unsnap first
00030     bool unsnapped = ((ApplicationView::Value != ApplicationViewState::Snapped) || ApplicationView::TryUnsnap());
00031     if (!unsnapped)
00032     {
00033         NotifyUser("Cannot unsnap the sample application", NotifyType::StatusMessage);
00034     }
00035
00036     return unsnapped;
00037 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D tutorial/C++/Lesson5.Components/Direct3DTutorial.h Source File

  • Direct3D tutorial
  • Lesson5.Components

Direct3DTutorial.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 "DirectXBase.h"
00011 #include "BasicCamera.h"
00012 #include "SampleOverlay.h"
00013
00014 // describes the constant buffer that will be used to draw the cube
00015 struct ConstantBuffer
00016 {
00017     float4x4 model;
00018     float4x4 view;
00019     float4x4 projection;
00020 };
00021
00022 ref class Direct3DTutorial : public DirectXBase
00023 {
00024 internal :
00025     Direct3DTutorial();
00026
00027     virtual void CreateDeviceIndependentResources() override;
00028     virtual void CreateDeviceResources() override;
00029     virtual void CreateWindowSizeDependentResources() override;
00030     virtual void Render() override;
00031     void Update(float timeTotal, float timeDelta);
00032
00033 private:
00034     SampleOverlay^ m_sampleOverlay;
00035     Microsoft::WRL::ComPtr<ID3D11InputLayout>           m_inputLayout;                // cube vertex input layout
00036     Microsoft::WRL::ComPtr<ID3D11Buffer>                m_vertexBuffer;               // cube vertex buffer
00037     Microsoft::WRL::ComPtr<ID3D11Buffer>                m_indexBuffer;                // cube index buffer
00038     Microsoft::WRL::ComPtr<ID3D11VertexShader>          m_vertexShader;               // cube vertex shader
00039     Microsoft::WRL::ComPtr<ID3D11PixelShader>           m_pixelShader;                // cube pixel shader
00040     Microsoft::WRL::ComPtr<ID3D11Texture2D>             m_texture;                    // cube texture
00041     Microsoft::WRL::ComPtr<ID3D11ShaderResourceView>    m_textureSRV;                 // cube texture view
00042     Microsoft::WRL::ComPtr<ID3D11SamplerState>          m_sampler;                    // cube texture sampler
00043     Microsoft::WRL::ComPtr<ID3D11Buffer>                m_constantBuffer;             // constant buffer resource
00044
00045     unsigned int             m_indexCount;                  // cube index count
00046     ConstantBuffer           m_constantBufferData;          // constant buffer resource data
00047     BasicCamera^             m_camera;                      // scene camera
00048 };
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Compression/C++/App.xaml.h Source File

  • Compression

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Edge gesture invocation/C++/ScenarioList.xaml.cpp Source File

  • Edge gesture invocation

ScenarioList.xaml.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 //
00009 // ScenarioList.xaml.cpp
00010 // Implementation of the ScenarioList class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioList.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace EdgeGestureSample;
00018
00019 using namespace Platform;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Graphics::Display;
00023 using namespace Windows::UI::ViewManagement;
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 using namespace Windows::UI::Xaml::Interop;
00032
00033 ScenarioList::ScenarioList()
00034 {
00035     InitializeComponent();
00036 }
00037
00038 ScenarioList::~ScenarioList()
00039 {
00040 }
00041
00042 void ScenarioList::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00043 {
00044     if (Scenarios->SelectedItem != nullptr)
00045     {
00046         rootPage->NotifyUser("", NotifyType::StatusMessage);
00047
00048         ListBoxItem^ selectedListBoxItem = dynamic_cast<ListBoxItem^>(Scenarios->SelectedItem);
00049         SuspensionManager::SessionState()->Insert("SelectedScenario", selectedListBoxItem->Name);
00050
00051         if (rootPage->InputFrame != nullptr && rootPage->OutputFrame != nullptr)
00052         {
00053             //Load the input and output pages for the current scenario into their respective frames.
00054             TypeName inputPage = { "EdgeGestureSample" + "." + "ScenarioInput" + ((Scenarios->SelectedIndex + 1).ToString()), TypeKind::Custom };
00055             TypeName outputPage = { "EdgeGestureSample" + "." + "ScenarioOutput" + ((Scenarios->SelectedIndex + 1).ToString()), TypeKind::Custom };
00056             rootPage->DoNavigation(inputPage, rootPage->InputFrame);
00057             rootPage->DoNavigation(outputPage, rootPage->OutputFrame);
00058         }
00059     }
00060 }
00061
00062 void ScenarioList::OnNavigatedTo(NavigationEventArgs^ e)
00063 {
00064     rootPage = dynamic_cast<MainPage^>(e->Parameter);
00065
00066     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &ScenarioList::Scenarios_SelectionChanged);
00067     ListBoxItem^ startingScenario = nullptr;
00068
00069     auto ps = SuspensionManager::SessionState();
00070     if (ps->HasKey("SelectedScenario"))
00071     {
00072         PropertyValue^ pv;
00073         String^ item = dynamic_cast<String^>(ps->Lookup("SelectedScenario"));
00074         startingScenario = dynamic_cast<ListBoxItem^>(this->FindName(item));
00075     }
00076
00077     Scenarios->SelectedItem = startingScenario != nullptr ? startingScenario : Scenario1;
00078 }
Generated on Sat Nov 23 2024 16:07:57 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D magazine app/C++/Document.cpp Source File

  • Direct2D magazine app

Document.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
00010 using namespace Microsoft::WRL;
00011 using namespace concurrency;
00012 using namespace Windows::Storage;
00013 using namespace Windows::Storage::Search;
00014 using namespace Windows::Storage::Streams;
00015 using namespace Windows::Storage::FileProperties;
00016 using namespace Windows::Data::Xml::Dom;
00017
00018 Document::Document(
00019     _In_ StorageFolder^ location,
00020     _In_ Platform::String^ fileName,
00021     _In_ Renderer^ renderer
00022     ) :
00023     m_location(location),
00024     m_fileName(fileName),
00025     m_rootXml(nullptr),
00026     m_rootElement(nullptr),
00027     m_design(nullptr),
00028     m_renderer(renderer),
00029     m_fontCollection(),
00030     m_fontLoader(),
00031     m_dwriteFactory()
00032 {
00033     // Create DirectWrite isolated factory.
00034     //
00035     // Unlike a typical shared factory, the isolated factory does not send miss report
00036     // to the cross-process font cache, and therefore does not interact with DirectWrite's
00037     // state in other component in the same process. It's designed to be used when the
00038     // usage of font data within one component is meant to be isolated from the rest of
00039     // the application.
00040     //
00041     DX::ThrowIfFailed(
00042         DWriteCreateFactory(
00043             DWRITE_FACTORY_TYPE_ISOLATED,
00044             __uuidof(IDWriteFactory),
00045             &m_dwriteFactory
00046             )
00047         );
00048 }
00049
00050 Document::~Document()
00051 {
00052     if (m_fontLoader != nullptr)
00053     {
00054         // Unregister the font loader from DirectWrite factory
00055         DX::ThrowIfFailed(
00056             m_dwriteFactory->UnregisterFontCollectionLoader(m_fontLoader.Get())
00057             );
00058
00059         DX::ThrowIfFailed(
00060             m_dwriteFactory->UnregisterFontFileLoader(m_fontLoader.Get())
00061             );
00062     }
00063 }
00064
00065 task<void> Document::LoadAsync()
00066 {
00067     // Get the document file from the storage location
00068     return task<StorageFile^>(m_location->GetFileAsync(m_fileName)).then([=](StorageFile^ file)
00069     {
00070         auto xmlDocument = ref new XmlDocument();
00071         return xmlDocument->LoadFromFileAsync(file);
00072
00073     }).then([=](XmlDocument^ loadedXml)
00074     {
00075         m_rootXml = loadedXml->SelectSingleNode("story");
00076
00077         // Create a font loader and start loading all the font files in the document location.
00078         m_fontLoader = new FontLoader(m_location, m_dwriteFactory.Get());
00079         return m_fontLoader->LoadAsync();
00080
00081     }).then([=]()
00082     {
00083         // Register the font loader to DirectWrite factory
00084         // The loaders are needed to load custom fonts used within the document.
00085         DX::ThrowIfFailed(
00086             m_dwriteFactory->RegisterFontCollectionLoader(m_fontLoader.Get())
00087             );
00088
00089         DX::ThrowIfFailed(
00090             m_dwriteFactory->RegisterFontFileLoader(m_fontLoader.Get())
00091             );
00092     });
00093 }
00094
00095 void Document::GetFontCollection(_Outptr_result_maybenull_ IDWriteFontCollection** fontCollection)
00096 {
00097     if (m_fontCollection != nullptr)
00098     {
00099         *fontCollection = ComPtr<IDWriteFontCollection>(m_fontCollection).Detach();
00100     }
00101     else if (m_fontLoader != nullptr)
00102     {
00103         // The font collection key is simply set to zero because the loader only
00104         // represents a single collection of fonts used in this document.
00105         size_t fontCollectionKey = 0;
00106
00107         DX::ThrowIfFailed(
00108             m_dwriteFactory->CreateCustomFontCollection(
00109                 m_fontLoader.Get(),
00110                 &fontCollectionKey,
00111                 sizeof(size_t),
00112                 &m_fontCollection
00113                 )
00114             );
00115
00116         *fontCollection = ComPtr<IDWriteFontCollection>(m_fontCollection).Detach();
00117     }
00118     else
00119     {
00120         *fontCollection = nullptr;
00121     }
00122 }
00123
00124 void Document::GetDWriteFactory(_Outptr_ IDWriteFactory** dwriteFactory)
00125 {
00126     *dwriteFactory = ComPtr<IDWriteFactory>(m_dwriteFactory).Detach();
00127 }
00128
00129 //  Parse the XML document to an element tree, then traverse the tree
00130 //  to bind resources to the element requiring them.
00131 void Document::Parse()
00132 {
00133     if (m_rootXml != nullptr)
00134     {
00135         Story^ rootElement = Element::Create<Story>(this, m_rootXml);
00136
00137         if (rootElement != nullptr)
00138         {
00139             TreeIterator<Element> it(rootElement);
00140             do
00141             {
00142                 if (!(it.GetCurrentNode())->BindResource(rootElement))
00143                     return;
00144
00145             } while (++it);
00146
00147             m_rootElement = rootElement;
00148         }
00149     }
00150 }
00151
00152 Element^ Document::GetContentRoot()
00153 {
00154     // Content root is the direct child of the design element.
00155     return UpdateDesign()->GetFirstChild();
00156 }
00157
00158 Element^ Document::UpdateDesign()
00159 {
00160     // Get the design most appropriate for the current display size.
00161     m_design = m_rootElement->GetDesign(GetRenderer()->GetDisplaySize());
00162
00163     return m_design;
00164 }
00165
00166 D2D1_SIZE_F Document::GetPageSize()
00167 {
00168     return m_design != nullptr ? m_design->GetPageSize() : D2D1::SizeF();
00169 }
00170
00171 // Convert a page design width to display width
00172 float Document::DesignToDisplayWidth(float designWidth)
00173 {
00174     return designWidth / GetPageSize().width * m_renderer->GetDisplayWidth();
00175 }
00176
00177 // Convert a page design height to display height
00178 float Document::DesignToDisplayHeight(float designHeight)
00179 {
00180     return designHeight / GetPageSize().height * m_renderer->GetDisplayHeight();
00181 }
00182
00183 // Convert a display width to page design width
00184 float Document::DisplayToDesignWidth(float displayWidth)
00185 {
00186     return displayWidth / m_renderer->GetDisplayWidth() * GetPageSize().width;
00187 }
00188
00189 // Convert a display height to page design height
00190 float Document::DisplayToDesignHeight(float displayHeight)
00191 {
00192     return displayHeight / m_renderer->GetDisplayHeight() * GetPageSize().height;
00193 }
Generated on Sat Nov 23 2024 16:08:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D composite effect modes/C++/DirectXSample.h Source File

  • Direct2D composite effect modes

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
00010 // This header defines helper utilities to make DirectX APIs work with exceptions.
00011 namespace DX
00012 {
00013     inline void ThrowIfFailed(HRESULT hr)
00014     {
00015         if (FAILED(hr))
00016         {
00017             // Set a breakpoint on this line to catch DX API errors.
00018             throw Platform::Exception::CreateException(hr);
00019         }
00020     }
00021 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::DataReaderWriter::sealed Member List

This is the complete list of members for SDKSample::DataReaderWriter::sealed, including all inherited members.
bytesPerRow | SDKSample::DataReaderWriter::sealed | [private, static]
bytesPerSegment | SDKSample::DataReaderWriter::sealed | [private, static]
chunkSize | SDKSample::DataReaderWriter::sealed | [private, static]
currChunk | SDKSample::DataReaderWriter::sealed | [private]
GetAddress(int i) | SDKSample::DataReaderWriter::sealed | [private]
HexDump(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::DataReaderWriter::sealed | [private]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::DataReaderWriter::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::DataReaderWriter::sealed | [protected, virtual]
PrintRow(Platform::Array< byte >^bytes, int i) | SDKSample::DataReaderWriter::sealed | [private]
ReadBytes() | SDKSample::DataReaderWriter::sealed |
ReadLoop(Windows::Storage::Streams::DataReader^dataReader) | SDKSample::DataReaderWriter::sealed | [private]
rootPage | SDKSample::DataReaderWriter::sealed | [private]
ToHex(byte value) | SDKSample::DataReaderWriter::sealed | [private]
TransferData(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::DataReaderWriter::sealed | [private]
WriteReadStream() | SDKSample::DataReaderWriter::sealed |
Generated on Sat Nov 23 2024 16:09:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File picker/C++/Scenario1.xaml.h Source File

  • File picker

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 SDKSample
00023 {
00024     namespace FilePicker
00025     {
00026         /// <summary>
00027         /// An empty page that can be used on its own or navigated to within a Frame.
00028         /// </summary>
00029         public ref class Scenario1 sealed
00030         {
00031         public:
00032             Scenario1();
00033
00034         private:
00035             MainPage^ rootPage;
00036
00037             void PickAFileButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038         };
00039     }
00040 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::TileContent::TileWideSmallImageAndText05 Member List

This is the complete list of members for NotificationsExtensions::TileContent::TileWideSmallImageAndText05, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
Branding | NotificationsExtensions::TileContent::TileNotificationBase |
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Image | NotificationsExtensions::TileContent::TileWideSmallImageAndText05 |
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
RequireSquareContent | NotificationsExtensions::TileContent::TileWideBase |
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SquareContent | NotificationsExtensions::TileContent::TileWideBase |
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextBodyWrap | NotificationsExtensions::TileContent::TileWideSmallImageAndText05 |
TextFields | NotificationsExtensions::NotificationBase |
TextHeading | NotificationsExtensions::TileContent::TileWideSmallImageAndText05 |
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWideSmallImageAndText05() | NotificationsExtensions::TileContent::TileWideSmallImageAndText05 | [inline]
TileWideSmallImageAndText05() | NotificationsExtensions::TileContent::TileWideSmallImageAndText05 | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:44 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML vector-based drawing/C++/Scenario4.xaml.h Source File

  • XAML vector-based drawing

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
00022 namespace SDKSample
00023 {
00024     namespace Drawing
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 Scenario4 sealed
00031         {
00032         public:
00033             Scenario4();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039         };
00040     }
00041 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX postcard app/C++/BasicMath.h Source File

  • DirectX postcard app

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 Sat Nov 23 2024 16:08:08 for Win8-Examples by doxygen 1.7.1


Win8-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 Sat Nov 23 2024 16:09:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Audio Session (WASAPI)/C++/ToneSampleGenerator.cpp Source File

  • Windows Audio Session (WASAPI)
  • C++

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 //
00039 //  ToneSampleGenerator()
00040 //
00041 ToneSampleGenerator::ToneSampleGenerator()
00042 {
00043     m_SampleQueue = nullptr;
00044     m_SampleQueueTail = &m_SampleQueue;
00045 }
00046
00047 //
00048 //  ~ToneSampleGenerator()
00049 //
00050 ToneSampleGenerator::~ToneSampleGenerator()
00051 {
00052     // Flush unused samples
00053     Flush();
00054 }
00055
00056 //
00057 //  GenerateSampleBuffer()
00058 //
00059 //  Create a linked list of sample buffers
00060 //
00061 HRESULT ToneSampleGenerator::GenerateSampleBuffer( DWORD Frequency, UINT32 FramesPerPeriod, WAVEFORMATEX *wfx )
00062 {
00063     HRESULT hr = S_OK;
00064
00065     UINT32 renderBufferSizeInBytes = FramesPerPeriod * wfx->nBlockAlign;
00066     UINT64 renderDataLength = ( wfx->nSamplesPerSec * TONE_DURATION_SEC * wfx->nBlockAlign ) + ( renderBufferSizeInBytes - 1 );
00067     UINT64 renderBufferCount = renderDataLength / renderBufferSizeInBytes;
00068
00069     double theta = 0;
00070
00071     for( UINT64 i = 0; i < renderBufferCount; i++ )
00072     {
00073         RenderBuffer *SampleBuffer = new (std::nothrow) RenderBuffer();
00074         if (nullptr == SampleBuffer)
00075         {
00076             return E_OUTOFMEMORY;
00077         }
00078
00079         SampleBuffer->BufferSize = renderBufferSizeInBytes;
00080         SampleBuffer->BytesFilled = renderBufferSizeInBytes;
00081         SampleBuffer->Buffer = new (std::nothrow) BYTE[ renderBufferSizeInBytes ];
00082         if (nullptr == SampleBuffer->Buffer)
00083         {
00084             return E_OUTOFMEMORY;
00085         }
00086
00087         switch( CalculateMixFormatType( wfx ) )
00088         {
00089         case RenderSampleType::SampleType16BitPCM:
00090             GenerateSineSamples<short>( SampleBuffer->Buffer, SampleBuffer->BufferSize, Frequency, wfx->nChannels, wfx->nSamplesPerSec, TONE_AMPLITUDE, &theta);
00091             break;
00092
00093         case RenderSampleType::SampleTypeFloat:
00094             GenerateSineSamples<float>( SampleBuffer->Buffer, SampleBuffer->BufferSize, Frequency, wfx->nChannels, wfx->nSamplesPerSec, TONE_AMPLITUDE, &theta);
00095             break;
00096
00097         default:
00098             return E_UNEXPECTED;
00099             break;
00100         }
00101
00102         *m_SampleQueueTail = SampleBuffer;
00103         m_SampleQueueTail = &SampleBuffer->Next;
00104     }
00105     return hr;
00106 }
00107
00108 //
00109 // GenerateSineSamples()
00110 //
00111 //  Generate samples which represent a sine wave that fits into the specified buffer.
00112 //
00113 //  T:  Type of data holding the sample (short, int, byte, float)
00114 //  Buffer - Buffer to hold the samples
00115 //  BufferLength - Length of the buffer.
00116 //  ChannelCount - Number of channels per audio frame.
00117 //  SamplesPerSecond - Samples/Second for the output data.
00118 //  InitialTheta - Initial theta value - start at 0, modified in this function.
00119 //
00120 template <typename T>
00121 void ToneSampleGenerator::GenerateSineSamples(BYTE *Buffer, size_t BufferLength, DWORD Frequency, WORD ChannelCount, DWORD SamplesPerSecond, double Amplitude, double *InitialTheta)
00122 {
00123     double sampleIncrement = (Frequency * (M_PI*2)) / (double)SamplesPerSecond;
00124     T *dataBuffer = reinterpret_cast<T *>(Buffer);
00125     double theta = (InitialTheta != NULL ? *InitialTheta : 0);
00126
00127     for (size_t i = 0 ; i < BufferLength / sizeof(T) ; i += ChannelCount)
00128     {
00129         double sinValue = Amplitude * sin( theta );
00130         for(size_t j = 0 ;j < ChannelCount; j++)
00131         {
00132             dataBuffer[i+j] = Convert<T>(sinValue);
00133         }
00134         theta += sampleIncrement;
00135     }
00136
00137     if (InitialTheta != NULL)
00138     {
00139         *InitialTheta = theta;
00140     }
00141 }
00142
00143 //
00144 //  FillSampleBuffer()
00145 //
00146 //  File the Data buffer of size BytesToRead with the first item in the queue.  Caller is responsible for allocating and freeing buffer
00147 //
00148 HRESULT ToneSampleGenerator::FillSampleBuffer( UINT32 BytesToRead, BYTE *Data )
00149 {
00150     if (nullptr == Data)
00151     {
00152         return E_POINTER;
00153     }
00154
00155     RenderBuffer *SampleBuffer = m_SampleQueue;
00156
00157     if (BytesToRead > SampleBuffer->BufferSize)
00158     {
00159         return E_INVALIDARG;
00160     }
00161
00162     CopyMemory( Data, SampleBuffer->Buffer, BytesToRead );
00163
00164     m_SampleQueue = m_SampleQueue->Next;
00165
00166     return S_OK;
00167 }
00168
00169 //
00170 //  Flush()
00171 //
00172 //  Remove and free unused samples from the queue
00173 //
00174 void ToneSampleGenerator::Flush()
00175 {
00176     while( m_SampleQueue != nullptr )
00177     {
00178         RenderBuffer *SampleBuffer = m_SampleQueue;
00179         m_SampleQueue = SampleBuffer->Next;
00180         SAFE_DELETE( SampleBuffer );
00181     }
00182 }
00183
Generated on Sat Nov 23 2024 16:08:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Accelerometer sensor/C++/Scenario3.xaml.h Source File

  • Accelerometer sensor

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 SDKSample
00023 {
00024     namespace AccelerometerCPP
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             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00038
00039         private:
00040             MainPage^ rootPage;
00041             Windows::UI::Core::CoreDispatcher^ dispatcher;
00042             Windows::Devices::Sensors::Accelerometer^ accelerometer;
00043             Windows::Foundation::EventRegistrationToken visibilityToken;
00044             uint32 desiredReportInterval;
00045             Windows::UI::Xaml::DispatcherTimer^ dispatcherTimer;
00046
00047             void VisibilityChanged(Platform::Object^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ e);
00048             void DisplayCurrentReading(Platform::Object^ sender, Platform::Object^ e);
00049             void ScenarioEnable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00050             void ScenarioDisable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00051         };
00052     }
00053 }
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D stereoscopic 3D/C++/Stereo3DMatrixHelper.h Source File

  • Direct3D stereoscopic 3D

Stereo3DMatrixHelper.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 // Stereo parameters are in the same units as the world.
00011 struct StereoParameters
00012 {
00013     float viewportWidth;        // viewport width
00014     float viewportHeight;       // viewport height
00015     float viewerDistance;       // distance from viewer
00016     float interocularDistance;  // interocular distance
00017 };
00018
00019 StereoParameters CreateDefaultStereoParameters(
00020     float viewportWidthInches,
00021     float viewportHeightInches,
00022     float worldScaleInInches,
00023     float stereoExaggeration
00024     );
00025
00026 DirectX::XMMATRIX StereoProjectionFieldOfViewRightHand(
00027     const StereoParameters& parameters,
00028     float nearZ,
00029     float farZ,
00030     bool rightChannel
00031     );
Generated on Sat Nov 23 2024 16:08:12 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Search contract/C++/Constants.cpp Source File

  • Search contract

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 using namespace std;
00018 using namespace Platform;
00019 using namespace Windows::ApplicationModel::Search;
00020
00021 Array<Scenario>^ MainPage::scenariosInner = ref new Array<Scenario>
00022 {
00023     { "Using the Search contract",                "SDKSample.SearchContract.Scenario1" },
00024     { "Suggestions from an app-defined list",     "SDKSample.SearchContract.Scenario2" },
00025     { "Suggestions in East Asian languages",      "SDKSample.SearchContract.Scenario3" },
00026     { "Suggestions provided by Windows",          "SDKSample.SearchContract.Scenario4" },
00027     { "Suggestions from Open Search",             "SDKSample.SearchContract.Scenario5" },
00028     { "Suggestions from a service returning XML", "SDKSample.SearchContract.Scenario6" },
00029     { "Open Search charm by typing",              "SDKSample.SearchContract.Scenario7" },
00030 };
00031
00032 void MainPage::ProcessQueryText(Platform::String^ queryText)
00033 {
00034     NotifyUser("Query submitted: " + queryText, NotifyType::StatusMessage);
00035 }
00036
00037 // Replace "{searchTerms}" part of the Open Search URL with the query text user typed into the search box.
00038 String^ MainPage::ReplaceUrlSearchTerms(String^ strUrl, String^ queryText)
00039 {
00040     wstring url = wstring(strUrl->Data());
00041     const wstring fixed = L"{searchTerms}";
00042     size_t start = url.find(fixed);
00043     if (start != std::string::npos)
00044     {
00045         url.replace(start, fixed.length(), wstring(queryText->Data()));
00046     }
00047
00048     return ref new String(url.c_str());
00049 }
00050
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/ConstantBuffers.h Source File

  • DirectX 3D shooting game

ConstantBuffers.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 struct PNTVertex
00011 {
00012     DirectX::XMFLOAT3 position;
00013     DirectX::XMFLOAT3 normal;
00014     DirectX::XMFLOAT2 textureCoordinate;
00015 };
00016
00017 static D3D11_INPUT_ELEMENT_DESC PNTVertexLayout[] =
00018 {
00019     {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0,  0, D3D11_INPUT_PER_VERTEX_DATA, 0},
00020     {"NORMAL",   0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0},
00021     {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT,    0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0},
00022 };
00023
00024 struct ConstantBufferNeverChanges
00025 {
00026     DirectX::XMFLOAT4 lightPosition[4];
00027     DirectX::XMFLOAT4 lightColor;
00028 };
00029
00030 struct ConstantBufferChangeOnResize
00031 {
00032     DirectX::XMFLOAT4X4 projection;
00033 };
00034
00035 struct ConstantBufferChangesEveryFrame
00036 {
00037     DirectX::XMFLOAT4X4 view;
00038 };
00039
00040 struct ConstantBufferChangesEveryPrim
00041 {
00042     DirectX::XMFLOAT4X4 worldMatrix;
00043     DirectX::XMFLOAT4 meshColor;
00044     DirectX::XMFLOAT4 diffuseColor;
00045     DirectX::XMFLOAT4 specularColor;
00046     float specularPower;
00047 };
00048
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Sharing content source app/C++/SetErrorMessage.xaml.cpp Source File

  • Sharing content source app

SetErrorMessage.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 // FailWithError.xaml.cpp
00013 // Implementation of the FailWithError class
00014 //
00015
00016 #include "pch.h"
00017 #include "SharePage.h"
00018 #include "SetErrorMessage.xaml.h"
00019 #include "MainPage.xaml.h"
00020
00021 using namespace SDKSample::ShareSource;
00022 using namespace SDKSample::Common;
00023
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel::DataTransfer;
00026
00027 SetErrorMessage::SetErrorMessage()
00028 {
00029     InitializeComponent();
00030 }
00031
00032 bool SetErrorMessage::GetShareContent(DataRequest^ request)
00033 {
00034     auto errorMessage = CustomErrorText->Text;
00035     if (errorMessage == nullptr)
00036     {
00037         errorMessage = ref new String(L"Enter a failure display text and try again.");
00038     }
00039     request->FailWithDisplayText(errorMessage);
00040     return false;
00041 }
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

ExtrudedTextRenderer Member List

This is the complete list of members for ExtrudedTextRenderer, including all inherited members.
__pad0__ | ExtrudedTextRenderer |
CreateBuffers(uint32 numVertices, uint32 numIndices, BasicVertex *vertexData, unsigned short *indexData, ID3D11Buffer **vertexBuffer, ID3D11Buffer **indexBuffer) | ExtrudedTextRenderer | [private]
CreateDeviceIndependentResources(Microsoft::WRL::ComPtr< ID2D1Factory1 > d2dFactory, Microsoft::WRL::ComPtr< IDWriteFactory1 > dwriteFactory) | ExtrudedTextRenderer |
CreateDeviceResources(Microsoft::WRL::ComPtr< ID3D11Device1 > d3dDevice, Microsoft::WRL::ComPtr< ID3D11DeviceContext1 > d3dContext) | ExtrudedTextRenderer |
CreateWindowSizeDependentResources(float dpi, Microsoft::WRL::ComPtr< ID3D11RenderTargetView > renderTargetView, Microsoft::WRL::ComPtr< ID3D11DepthStencilView > depthStencilView, Windows::Foundation::Size renderTargetSize) | ExtrudedTextRenderer |
DrawExtrudedText() | ExtrudedTextRenderer |
GenerateTextOutline(ID2D1Geometry **ppGeometry) | ExtrudedTextRenderer | [private]
m_camera | ExtrudedTextRenderer | [private]
m_characters | ExtrudedTextRenderer | [private]
m_constantBuffer | ExtrudedTextRenderer | [private]
m_constantBufferData | ExtrudedTextRenderer | [private]
m_d2dFactory | ExtrudedTextRenderer | [private]
m_d3dContext | ExtrudedTextRenderer | [private]
m_d3dDepthStencilView | ExtrudedTextRenderer | [private]
m_d3dDevice | ExtrudedTextRenderer | [private]
m_d3dRenderTargetView | ExtrudedTextRenderer | [private]
m_dpi | ExtrudedTextRenderer | [private]
m_dwriteFactory | ExtrudedTextRenderer | [private]
m_indexBuffer | ExtrudedTextRenderer | [private]
m_indexCount | ExtrudedTextRenderer | [private]
m_inputLayout | ExtrudedTextRenderer | [private]
m_panPosition | ExtrudedTextRenderer | [private]
m_pixelShader | ExtrudedTextRenderer | [private]
m_renderTargetSize | ExtrudedTextRenderer | [private]
m_textGeometry | ExtrudedTextRenderer | [private]
m_textLayout | ExtrudedTextRenderer | [private]
m_vertexBuffer | ExtrudedTextRenderer | [private]
m_vertexShader | ExtrudedTextRenderer | [private]
m_zoom | ExtrudedTextRenderer | [private]
OnManipulationDelta(Windows::Foundation::Point position, Windows::Foundation::Point positionDelta, float zoomDelta, float rotation) | ExtrudedTextRenderer |
ReleaseBufferResources() | ExtrudedTextRenderer |
Reset() | ExtrudedTextRenderer |
SetExtrudedText(Platform::String^text) | ExtrudedTextRenderer |
UpdateModelAndCamera() | ExtrudedTextRenderer | [private]
UpdateTextGeometry() | ExtrudedTextRenderer | [private]
Generated on Sat Nov 23 2024 16:09:12 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Display orientation/C++/Constants.cpp Source File

  • Display orientation

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     { "Adjust for Rotation", "SDKSample.DisplayOrientation.Scenario1" },
00020     { "Set a Rotation Preference", "SDKSample.DisplayOrientation.Scenario2" },
00021     { "Screen Orientation", "SDKSample.DisplayOrientation.Scenario3" }
00022 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CryptoWinRT/C++/Scenario2.xaml.h Source File

  • CryptoWinRT

Scenario2.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.xaml.h
00013 // Declaration of the Scenario2 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario2.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace CryptoWinRT
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 sealed
00031         {
00032         public:
00033             Scenario2();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void RunSample_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D magazine app/C++/Resource.h Source File

  • Direct2D magazine app

Resource.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 "Element.h"
00011
00012 //  <resource> is the base definition of content element which may be used in multiple
00013 //  drawings. Resource neither measures nor draws as it is only the drawing state not
00014 //  the drawing itself. Resource may be media content such as image or text, or it may
00015 //  be types of brush.
00016 //
00017 ref class Resource : public Element
00018 {
00019 internal:
00020     virtual bool AcceptChildNode(
00021         _In_ Document^ document,
00022         _In_ Windows::Data::Xml::Dom::IXmlNode^ childXmlNode
00023         ) override;
00024
00025     virtual void Measure(
00026         _In_ Document^ document,
00027         D2D1_SIZE_F const& parentSize,
00028         _Out_ D2D1_RECT_F* bounds
00029         ) override;
00030
00031     virtual bool PrepareToDraw(
00032         _In_ Document^ document,
00033         D2D1::Matrix3x2F const& transform
00034         ) override;
00035
00036     virtual bool Draw(
00037         _In_ Document^ document,
00038         D2D1::Matrix3x2F const& transform
00039         ) override;
00040 };
00041
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text display/C++/Scenario1.xaml.cpp Source File

  • XAML text display

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::TextDisplay;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 Scenario1::Scenario1()
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 Scenario1::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 SDKSample::TextDisplay::Scenario1::Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00043 {
00044     Button^ b = safe_cast<Button^>(sender);
00045     if (b != nullptr)
00046     {
00047         rootPage->NotifyUser("You clicked the " + b->Name + " button", NotifyType::StatusMessage);
00048     }
00049 }
00050
00051 void SDKSample::TextDisplay::Scenario1::Other_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00052 {
00053     Button^ b = safe_cast<Button^>(sender);
00054     if (b != nullptr)
00055     {
00056         rootPage->NotifyUser("You clicked the " + b->Name + " button", NotifyType::StatusMessage);
00057     }
00058 }
Generated on Sat Nov 23 2024 16:07:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D printing images and effects/C++/DirectXSample.h Source File

  • Direct2D printing images and effects

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
00010 // This header defines helper utilities to make DirectX APIs work with exceptions.
00011 namespace DX
00012 {
00013     inline void ThrowIfFailed(HRESULT hr)
00014     {
00015         if (FAILED(hr))
00016         {
00017             // Set a breakpoint on this line to catch DX API errors.
00018             throw Platform::Exception::CreateException(hr);
00019         }
00020     }
00021 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX touch input/C++/BasicLoader.cpp Source File

  • DirectX touch input

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 Sat Nov 23 2024 16:08:07 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Date and time formatting/C++/App.xaml.h Source File

  • Date and time formatting

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playback Manager Companion/C++/MainPage.xaml.cpp Source File

  • Playback Manager Companion

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:43 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D custom image effects/C++/VertexShader/WaveEffect.h Source File

  • Direct2D custom image effects
  • VertexShader

WaveEffect.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 // GUIDs for the shader, vertex buffers, and effect itself.
00009 DEFINE_GUID(GUID_WaveTransformVertexShader,
00010             0x65fa2492, 0x9478, 0x4c4d, 0x95, 0x67, 0xf6, 0x96, 0x72, 0x6a, 0x83, 0xa4
00011             );
00012 DEFINE_GUID(GUID_WaveTransformVertexBuffer,
00013             0xa9149e76, 0xc708, 0x4b3a, 0xad, 0x59, 0x56, 0x72, 0x3b, 0x65, 0x33, 0x44
00014             );
00015 DEFINE_GUID(CLSID_CustomWaveEffect,
00016             0x7b4c948b, 0xfcf2, 0x4c6b, 0xa0, 0x93, 0xdb, 0x4e, 0x59, 0x99, 0x42, 0x43
00017             );
00018
00019 typedef enum WAVE_PROP
00020 {
00021     WAVE_PROP_OFFSET      = 0,
00022     WAVE_PROP_SKEW_X     = 1,
00023     WAVE_PROP_SKEW_Y     = 2,
00024     WAVE_PROP_FORCE_DWORD = 0xFFFFFFFF
00025 };
00026
00027 // Our effect contains one transform, which is simply a wrapper around a vertex shader.
00028 // As such, we can simply make the effect itself act as the transform.
00029 class WaveEffect : public ID2D1EffectImpl, public ID2D1DrawTransform
00030 {
00031 public:
00032     // Declare effect registration methods.
00033     static HRESULT Register(_In_ ID2D1Factory1* pFactory);
00034     static HRESULT __stdcall CreateWaveImpl(_Outptr_ IUnknown** ppEffectImpl);
00035
00036     // Declare property getter/setter methods.
00037     float GetWaveOffset() const;
00038     HRESULT SetWaveOffset(float waveOffset);
00039
00040     float GetSkewX() const;
00041     HRESULT SetSkewX(float skew);
00042
00043     float GetSkewY() const;
00044     HRESULT SetSkewY(float skew);
00045
00046     // Declare ID2D1EffectImpl implementation methods.
00047     IFACEMETHODIMP Initialize(
00048         _In_ ID2D1EffectContext* pEffectContext,
00049         _In_ ID2D1TransformGraph* pTransformGraph
00050         );
00051
00052     IFACEMETHODIMP PrepareForRender(D2D1_CHANGE_TYPE changeType);
00053
00054     IFACEMETHODIMP SetGraph(_In_ ID2D1TransformGraph* pTransformGraph)
00055     {
00056         return E_NOTIMPL; // There's no need to implement this on effects with static input counts.
00057     }
00058
00059     // Declare ID2D1DrawTransform implementation methods.
00060     IFACEMETHODIMP SetDrawInfo(_In_ ID2D1DrawInfo* pDrawInfo);
00061
00062     // Declare ID2D1Transform implementation methods.
00063     IFACEMETHODIMP MapOutputRectToInputRects(
00064         _In_ const D2D1_RECT_L* pOutputRect,
00065         _Out_writes_(inputRectCount) D2D1_RECT_L* pInputRects,
00066         UINT32 inputRectCount
00067         ) const;
00068
00069     IFACEMETHODIMP MapInputRectsToOutputRect(
00070         _In_reads_(inputRectCount) CONST D2D1_RECT_L *pInputRects,
00071         _In_reads_(inputRectCount) CONST D2D1_RECT_L *pInputOpaqueSubRects,
00072         UINT32 inputRectCount,
00073         _Out_ D2D1_RECT_L *pOutputRect,
00074         _Out_ D2D1_RECT_L *pOutputOpaqueSubRect
00075         );
00076
00077     IFACEMETHODIMP MapInvalidRect(
00078         UINT32 inputIndex,
00079         D2D1_RECT_L invalidInputRect,
00080         _Out_ D2D1_RECT_L *pInvalidOutputRect
00081         ) const;
00082
00083
00084     // Declare ID2D1TransformNode implementation methods.
00085     IFACEMETHODIMP_(UINT32) GetInputCount() const { return 1; }
00086
00087     // Declare IUnknown implementation methods.
00088     IFACEMETHODIMP_(ULONG) AddRef();
00089     IFACEMETHODIMP_(ULONG) Release();
00090     IFACEMETHODIMP QueryInterface(_In_ REFIID riid, _Outptr_ void** ppOutput);
00091
00092 private:
00093     WaveEffect();
00094
00095     inline static float Clamp(float v, float low, float high)
00096     {
00097         return (v < low) ? low : (v > high) ? high : v;
00098     }
00099
00100     typedef struct Vertex
00101     {
00102         float x;
00103         float y;
00104     };
00105
00106     // This is a grid mesh in unit space, 0 to 1, with texture coordinates.
00107     // Deformations of this geometry will be performed in the vertex shader.
00108     HRESULT GenerateMesh(_Outptr_ Vertex** ppMesh);
00109
00110     // Updates the constant buffer when effect properties are changed.
00111     HRESULT UpdateConstants();
00112
00113     float                                       m_waveOffset;
00114     float                                       m_sizeX;
00115     float                                       m_sizeY;
00116     float                                       m_skewX;
00117     float                                       m_skewY;
00118
00119     Microsoft::WRL::ComPtr<ID2D1VertexBuffer>   m_vertexBuffer;
00120     Microsoft::WRL::ComPtr<ID2D1DrawInfo>       m_drawInfo;
00121     UINT                                        m_numVertices;
00122     D2D_RECT_L                                  m_inputRect;
00123
00124     LONG                                        m_refCount;
00125
00126     // Used to update the constant buffer for the vertex shader.
00127     struct
00128     {
00129         D2D_MATRIX_4X4_F matrix;
00130         float sizeX;
00131         float sizeY;
00132         float waveOffset;
00133         float skewX;
00134         float skewY;
00135     } m_constants;
00136 };
Generated on Sat Nov 23 2024 16:08:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D save to image file/C++/DirectXBase.h Source File

  • Direct2D save to image file

DirectXBase.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 "DirectXSample.h"
00011
00012 // Helper class that initializes DirectX APIs for both 2D and 3D rendering.
00013 // Some of the code in this class may be omitted if only 2D or only 3D rendering is being used.
00014 ref class DirectXBase abstract
00015 {
00016 internal:
00017     DirectXBase();
00018
00019     virtual void Initialize(Windows::UI::Core::CoreWindow^ window, float dpi);
00020     virtual void HandleDeviceLost();
00021     virtual void CreateDeviceIndependentResources();
00022     virtual void CreateDeviceResources();
00023     virtual void SetDpi(float dpi);
00024     virtual void UpdateForWindowSizeChange();
00025     virtual void CreateWindowSizeDependentResources();
00026     virtual void Render() = 0;
00027     virtual void Present();
00028     void ValidateDevice();
00029
00030 protected private:
00031     Platform::Agile<Windows::UI::Core::CoreWindow>  m_window;
00032
00033     // DirectWrite & Windows Imaging Component Objects.
00034     Microsoft::WRL::ComPtr<IDWriteFactory1>         m_dwriteFactory;
00035     Microsoft::WRL::ComPtr<IWICImagingFactory2>     m_wicFactory;
00036
00037     // DirectX Core Objects. Required for 2D and 3D.
00038     Microsoft::WRL::ComPtr<ID3D11Device1>           m_d3dDevice;
00039     Microsoft::WRL::ComPtr<ID3D11DeviceContext1>    m_d3dContext;
00040     Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00041     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00042
00043     // Direct2D Rendering Objects. Required for 2D.
00044     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00046     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00047     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmap;
00048
00049     // Direct3D Rendering Objects. Required for 3D.
00050     Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00051
00052     // Cached renderer properties.
00053     D3D_FEATURE_LEVEL                               m_featureLevel;
00054     Windows::Foundation::Size                       m_renderTargetSize;
00055     Windows::Foundation::Rect                       m_windowBounds;
00056     float                                           m_dpi;
00057     bool                                            m_windowSizeChangeInProgress;
00058 };
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/texconv/DirectXTexD3D11.cpp Source File

  • Direct3D resource loading
  • texconv

DirectXTexD3D11.cpp

Go to the documentation of this file.
00001 //-------------------------------------------------------------------------------------
00002 // DirectXTexD3D11.cpp
00003 //
00004 // DirectX Texture Library - Direct3D 11 helpers
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 #include "directxtexp.h"
00015
00016 #include <d3dcommon.h>
00017 #include <d3d10.h>
00018
00019 namespace DirectX
00020 {
00021
00022 static HRESULT _Capture( _In_ ID3D11DeviceContext* pContext, _In_ ID3D11Resource* pSource, _In_ const TexMetadata& metadata,
00023                          _In_ const ScratchImage& result )
00024 {
00025     if ( !pContext || !pSource || !result.GetPixels() )
00026         return E_POINTER;
00027
00028     if ( metadata.dimension == TEX_DIMENSION_TEXTURE3D )
00029     {
00030         //--- Volume texture ----------------------------------------------------------
00031         assert( metadata.arraySize == 1 );
00032
00033         size_t height = metadata.height;
00034         size_t depth = metadata.depth;
00035
00036         for( size_t level = 0; level < metadata.mipLevels; ++level )
00037         {
00038             UINT dindex = D3D11CalcSubresource( static_cast<UINT>( level ), 0, static_cast<UINT>( metadata.mipLevels ) );
00039
00040             D3D11_MAPPED_SUBRESOURCE mapped;
00041             HRESULT hr = pContext->Map( pSource, dindex, D3D11_MAP_READ, 0, &mapped );
00042             if ( FAILED(hr) )
00043                 return hr;
00044
00045             const uint8_t* pslice = reinterpret_cast<const uint8_t*>( mapped.pData );
00046             if ( !pslice )
00047             {
00048                 pContext->Unmap( pSource, dindex );
00049                 return E_POINTER;
00050             }
00051
00052             size_t lines = ComputeScanlines( metadata.format, height );
00053
00054             for( size_t slice = 0; slice < depth; ++slice )
00055             {
00056                 const Image* img = result.GetImage( level, 0, slice );
00057                 if ( !img )
00058                 {
00059                     pContext->Unmap( pSource, dindex );
00060                     return E_FAIL;
00061                 }
00062
00063                 if ( !img->pixels )
00064                 {
00065                     pContext->Unmap( pSource, dindex );
00066                     return E_POINTER;
00067                 }
00068
00069                 const uint8_t* sptr = pslice;
00070                 uint8_t* dptr = img->pixels;
00071                 for( size_t h = 0; h < lines; ++h )
00072                 {
00073                     size_t msize = std::min<size_t>( img->rowPitch, mapped.RowPitch );
00074                     memcpy_s( dptr, img->rowPitch, sptr, msize );
00075                     sptr += mapped.RowPitch;
00076                     dptr += img->rowPitch;
00077                 }
00078
00079                 pslice += mapped.DepthPitch;
00080             }
00081
00082             pContext->Unmap( pSource, dindex );
00083
00084             if ( height > 1 )
00085                 height >>= 1;
00086             if ( depth > 1 )
00087                 depth >>= 1;
00088         }
00089     }
00090     else
00091     {
00092         //--- 1D or 2D texture --------------------------------------------------------
00093         assert( metadata.depth == 1 );
00094
00095         for( size_t item = 0; item < metadata.arraySize; ++item )
00096         {
00097             size_t height = metadata.height;
00098
00099             for( size_t level = 0; level < metadata.mipLevels; ++level )
00100             {
00101                 UINT dindex = D3D11CalcSubresource( static_cast<UINT>( level ), static_cast<UINT>( item ), static_cast<UINT>( metadata.mipLevels ) );
00102
00103                 D3D11_MAPPED_SUBRESOURCE mapped;
00104                 HRESULT hr = pContext->Map( pSource, dindex, D3D11_MAP_READ, 0, &mapped );
00105                 if ( FAILED(hr) )
00106                     return hr;
00107
00108                 const Image* img = result.GetImage( level, item, 0 );
00109                 if ( !img )
00110                 {
00111                     pContext->Unmap( pSource, dindex );
00112                     return E_FAIL;
00113                 }
00114
00115                 if ( !img->pixels )
00116                 {
00117                     pContext->Unmap( pSource, dindex );
00118                     return E_POINTER;
00119                 }
00120
00121                 size_t lines = ComputeScanlines( metadata.format, height );
00122
00123                 const uint8_t* sptr = reinterpret_cast<const uint8_t*>( mapped.pData );
00124                 uint8_t* dptr = img->pixels;
00125                 for( size_t h = 0; h < lines; ++h )
00126                 {
00127                     size_t msize = std::min<size_t>( img->rowPitch, mapped.RowPitch );
00128                     memcpy_s( dptr, img->rowPitch, sptr, msize );
00129                     sptr += mapped.RowPitch;
00130                     dptr += img->rowPitch;
00131                 }
00132
00133                 pContext->Unmap( pSource, dindex );
00134
00135                 if ( height > 1 )
00136                     height >>= 1;
00137             }
00138         }
00139     }
00140
00141     return S_OK;
00142 }
00143
00144
00145 //=====================================================================================
00146 // Entry-points
00147 //=====================================================================================
00148
00149 //-------------------------------------------------------------------------------------
00150 // Determine if given texture metadata is supported on the given device
00151 //-------------------------------------------------------------------------------------
00152 _Use_decl_annotations_
00153 bool IsSupportedTexture( ID3D11Device* pDevice, const TexMetadata& metadata )
00154 {
00155     if ( !pDevice )
00156         return false;
00157
00158     D3D_FEATURE_LEVEL fl = pDevice->GetFeatureLevel();
00159
00160     // Validate format
00161     DXGI_FORMAT fmt = metadata.format;
00162
00163     if ( !IsValid( fmt ) )
00164         return false;
00165
00166     if ( IsVideo(fmt) )
00167         return false;
00168
00169     switch( fmt )
00170     {
00171     case DXGI_FORMAT_BC4_TYPELESS:
00172     case DXGI_FORMAT_BC4_UNORM:
00173     case DXGI_FORMAT_BC4_SNORM:
00174     case DXGI_FORMAT_BC5_TYPELESS:
00175     case DXGI_FORMAT_BC5_UNORM:
00176     case DXGI_FORMAT_BC5_SNORM:
00177         if ( fl < D3D_FEATURE_LEVEL_10_0 )
00178             return false;
00179         break;
00180
00181     case DXGI_FORMAT_BC6H_TYPELESS:
00182     case DXGI_FORMAT_BC6H_UF16:
00183     case DXGI_FORMAT_BC6H_SF16:
00184     case DXGI_FORMAT_BC7_TYPELESS:
00185     case DXGI_FORMAT_BC7_UNORM:
00186     case DXGI_FORMAT_BC7_UNORM_SRGB:
00187         if ( fl < D3D_FEATURE_LEVEL_11_0 )
00188             return false;
00189         break;
00190     }
00191
00192     // Validate miplevel count
00193     if ( metadata.mipLevels > D3D11_REQ_MIP_LEVELS )
00194         return false;
00195
00196     // Validate array size, dimension, and width/height
00197     size_t arraySize = metadata.arraySize;
00198     size_t iWidth = metadata.width;
00199     size_t iHeight = metadata.height;
00200     size_t iDepth = metadata.depth;
00201
00202     // Most cases are known apriori based on feature level, but we use this for robustness to handle the few optional cases
00203     UINT formatSupport = 0;
00204     pDevice->CheckFormatSupport( fmt, &formatSupport );
00205
00206     switch ( metadata.dimension )
00207     {
00208     case TEX_DIMENSION_TEXTURE1D:
00209         if ( !(formatSupport & D3D11_FORMAT_SUPPORT_TEXTURE1D) )
00210             return false;
00211
00212         if ( (arraySize > D3D11_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION)
00213              || (iWidth > D3D11_REQ_TEXTURE1D_U_DIMENSION) )
00214             return false;
00215
00216         if ( fl < D3D_FEATURE_LEVEL_11_0 )
00217         {
00218             if ( (arraySize > D3D10_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION)
00219                  || (iWidth > D3D10_REQ_TEXTURE1D_U_DIMENSION) )
00220                 return false;
00221
00222             if ( fl < D3D_FEATURE_LEVEL_10_0 )
00223             {
00224                 if ( (arraySize > 1) || (iWidth > D3D_FL9_3_REQ_TEXTURE1D_U_DIMENSION) )
00225                     return false;
00226
00227                 if ( (fl < D3D_FEATURE_LEVEL_9_3) && (iWidth > D3D_FL9_1_REQ_TEXTURE1D_U_DIMENSION ) )
00228                     return false;
00229             }
00230         }
00231         break;
00232
00233     case TEX_DIMENSION_TEXTURE2D:
00234         if ( metadata.miscFlags & TEX_MISC_TEXTURECUBE )
00235         {
00236             if ( !(formatSupport & D3D11_FORMAT_SUPPORT_TEXTURECUBE) )
00237                 return false;
00238
00239             if ( (arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION)
00240                  || (iWidth > D3D11_REQ_TEXTURECUBE_DIMENSION)
00241                  || (iHeight > D3D11_REQ_TEXTURECUBE_DIMENSION))
00242                 return false;
00243
00244             if ( fl < D3D_FEATURE_LEVEL_11_0 )
00245             {
00246                 if ( (arraySize > D3D10_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION)
00247                      || (iWidth > D3D10_REQ_TEXTURECUBE_DIMENSION)
00248                      || (iHeight > D3D10_REQ_TEXTURECUBE_DIMENSION))
00249                     return false;
00250
00251                 if ( (fl < D3D_FEATURE_LEVEL_10_1) && (arraySize != 6) )
00252                     return false;
00253
00254                 if ( fl < D3D_FEATURE_LEVEL_10_0 )
00255                 {
00256                     if ( (iWidth > D3D_FL9_3_REQ_TEXTURECUBE_DIMENSION )
00257                          || (iHeight > D3D_FL9_3_REQ_TEXTURECUBE_DIMENSION ) )
00258                         return false;
00259
00260                     if ( (fl < D3D_FEATURE_LEVEL_9_3)
00261                          && ( (iWidth > D3D_FL9_1_REQ_TEXTURECUBE_DIMENSION)
00262                               || (iHeight > D3D_FL9_1_REQ_TEXTURECUBE_DIMENSION) ) )
00263                         return false;
00264                 }
00265             }
00266         }
00267         else // Not a cube map
00268         {
00269             if ( !(formatSupport & D3D11_FORMAT_SUPPORT_TEXTURE2D) )
00270                 return false;
00271
00272             if ( (arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION)
00273                  || (iWidth > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION)
00274                  || (iHeight > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION))
00275                 return false;
00276
00277             if ( fl < D3D_FEATURE_LEVEL_11_0 )
00278             {
00279                 if ( (arraySize > D3D10_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION)
00280                      || (iWidth > D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION)
00281                      || (iHeight > D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION))
00282                     return false;
00283
00284                 if ( fl < D3D_FEATURE_LEVEL_10_0 )
00285                 {
00286                     if ( (arraySize > 1)
00287                          || (iWidth > D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION)
00288                          || (iHeight > D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION) )
00289                         return false;
00290
00291                     if ( (fl < D3D_FEATURE_LEVEL_9_3)
00292                          && ( (iWidth > D3D_FL9_1_REQ_TEXTURE2D_U_OR_V_DIMENSION)
00293                               || (iHeight > D3D_FL9_1_REQ_TEXTURE2D_U_OR_V_DIMENSION) ) )
00294                         return false;
00295                 }
00296             }
00297         }
00298         break;
00299
00300     case TEX_DIMENSION_TEXTURE3D:
00301         if ( !(formatSupport & D3D11_FORMAT_SUPPORT_TEXTURE3D) )
00302             return false;
00303
00304         if ( (arraySize > 1)
00305              || (iWidth > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION)
00306              || (iHeight > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION)
00307              || (iDepth > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) )
00308             return false;
00309
00310         if ( fl < D3D_FEATURE_LEVEL_11_0 )
00311         {
00312             if ( (iWidth > D3D10_REQ_TEXTURE3D_U_V_OR_W_DIMENSION)
00313                  || (iHeight > D3D10_REQ_TEXTURE3D_U_V_OR_W_DIMENSION)
00314                  || (iDepth > D3D10_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) )
00315                 return false;
00316
00317             if ( fl < D3D_FEATURE_LEVEL_10_0 )
00318             {
00319                 if ( (iWidth > D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION)
00320                      || (iHeight > D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION)
00321                      || (iDepth > D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) )
00322                     return false;
00323             }
00324         }
00325         break;
00326
00327     default:
00328         // Not a supported dimension
00329         return false;
00330     }
00331
00332     return true;
00333 }
00334
00335
00336 //-------------------------------------------------------------------------------------
00337 // Create a texture resource
00338 //-------------------------------------------------------------------------------------
00339 _Use_decl_annotations_
00340 HRESULT CreateTexture( ID3D11Device* pDevice, const Image* srcImages, size_t nimages, const TexMetadata& metadata,
00341                        ID3D11Resource** ppResource )
00342 {
00343     if ( !pDevice || !srcImages || !nimages || !ppResource )
00344         return E_INVALIDARG;
00345
00346     if ( !metadata.mipLevels || !metadata.arraySize )
00347         return E_INVALIDARG;
00348
00349 #ifdef _AMD64_
00350     if ( (metadata.width > 0xFFFFFFFF) || (metadata.height > 0xFFFFFFFF)
00351          || (metadata.mipLevels > 0xFFFFFFFF) || (metadata.arraySize > 0xFFFFFFFF) )
00352         return E_INVALIDARG;
00353 #endif
00354
00355     std::unique_ptr<D3D11_SUBRESOURCE_DATA[]> initData( new D3D11_SUBRESOURCE_DATA[ metadata.mipLevels * metadata.arraySize ] );
00356     if ( !initData )
00357         return E_OUTOFMEMORY;
00358
00359     // Fill out subresource array
00360     if ( metadata.dimension == TEX_DIMENSION_TEXTURE3D )
00361     {
00362         //--- Volume case -------------------------------------------------------------
00363         if ( !metadata.depth )
00364             return E_INVALIDARG;
00365
00366 #ifdef _AMD64_
00367         if ( metadata.depth > 0xFFFFFFFF )
00368             return E_INVALIDARG;
00369 #endif
00370
00371         if ( metadata.arraySize > 1 )
00372             // Direct3D 11 doesn't support arrays of 3D textures
00373             return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
00374
00375         size_t depth = metadata.depth;
00376
00377         size_t idx = 0;
00378         for( size_t level = 0; level < metadata.mipLevels; ++level )
00379         {
00380             size_t index = metadata.ComputeIndex( level, 0, 0 );
00381             if ( index >= nimages )
00382                 return E_FAIL;
00383
00384             const Image& img = srcImages[ index ];
00385
00386             if ( img.format != metadata.format )
00387                 return E_FAIL;
00388
00389             if ( !img.pixels )
00390                 return E_POINTER;
00391
00392             // Verify pixels in image 1 .. (depth-1) are exactly image->slicePitch apart
00393             // For 3D textures, this relies on all slices of the same miplevel being continous in memory
00394             // (this is how ScratchImage lays them out), which is why we just give the 0th slice to Direct3D 11
00395             const uint8_t* pSlice = img.pixels + img.slicePitch;
00396             for( size_t slice = 1; slice < depth; ++slice )
00397             {
00398                 size_t tindex = metadata.ComputeIndex( level, 0, slice );
00399                 if ( tindex >= nimages )
00400                     return E_FAIL;
00401
00402                 const Image& timg = srcImages[ tindex ];
00403
00404                 if ( !timg.pixels )
00405                     return E_POINTER;
00406
00407                 if ( timg.pixels != pSlice
00408                      || timg.format != metadata.format
00409                      || timg.rowPitch != img.rowPitch
00410                      || timg.slicePitch != img.slicePitch )
00411                     return E_FAIL;
00412
00413                 pSlice = timg.pixels + img.slicePitch;
00414             }
00415
00416             assert( idx < (metadata.mipLevels * metadata.arraySize) );
00417
00418             initData[idx].pSysMem = img.pixels;
00419             initData[idx].SysMemPitch = static_cast<DWORD>( img.rowPitch );
00420             initData[idx].SysMemSlicePitch = static_cast<DWORD>( img.slicePitch );
00421             ++idx;
00422
00423             if ( depth > 1 )
00424                 depth >>= 1;
00425         }
00426     }
00427     else
00428     {
00429         //--- 1D or 2D texture case ---------------------------------------------------
00430         size_t idx = 0;
00431         for( size_t item = 0; item < metadata.arraySize; ++item )
00432         {
00433             for( size_t level = 0; level < metadata.mipLevels; ++level )
00434             {
00435                 size_t index = metadata.ComputeIndex( level, item, 0 );
00436                 if ( index >= nimages )
00437                     return E_FAIL;
00438
00439                 const Image& img = srcImages[ index ];
00440
00441                 if ( img.format != metadata.format )
00442                     return E_FAIL;
00443
00444                 if ( !img.pixels )
00445                     return E_POINTER;
00446
00447                 assert( idx < (metadata.mipLevels * metadata.arraySize) );
00448
00449                 initData[idx].pSysMem = img.pixels;
00450                 initData[idx].SysMemPitch = static_cast<DWORD>( img.rowPitch );
00451                 initData[idx].SysMemSlicePitch = static_cast<DWORD>( img.slicePitch );
00452                 ++idx;
00453             }
00454         }
00455     }
00456
00457     // Create texture using static initialization data
00458     HRESULT hr = E_FAIL;
00459
00460     switch ( metadata.dimension )
00461     {
00462     case TEX_DIMENSION_TEXTURE1D:
00463         {
00464             D3D11_TEXTURE1D_DESC desc;
00465             desc.Width = static_cast<UINT>( metadata.width );
00466             desc.MipLevels = static_cast<UINT>( metadata.mipLevels );
00467             desc.ArraySize = static_cast<UINT>( metadata.arraySize );
00468             desc.Format = metadata.format;
00469             desc.Usage = D3D11_USAGE_DEFAULT;
00470             desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
00471             desc.CPUAccessFlags = 0;
00472             desc.MiscFlags = 0;
00473
00474             hr = pDevice->CreateTexture1D( &desc, initData.get(), reinterpret_cast<ID3D11Texture1D**>(ppResource) );
00475         }
00476         break;
00477
00478     case TEX_DIMENSION_TEXTURE2D:
00479         {
00480             D3D11_TEXTURE2D_DESC desc;
00481             desc.Width = static_cast<UINT>( metadata.width );
00482             desc.Height = static_cast<UINT>( metadata.height );
00483             desc.MipLevels = static_cast<UINT>( metadata.mipLevels );
00484             desc.ArraySize = static_cast<UINT>( metadata.arraySize );
00485             desc.Format = metadata.format;
00486             desc.SampleDesc.Count = 1;
00487             desc.SampleDesc.Quality = 0;
00488             desc.Usage = D3D11_USAGE_DEFAULT;
00489             desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
00490             desc.CPUAccessFlags = 0;
00491             desc.MiscFlags = (metadata.miscFlags & TEX_MISC_TEXTURECUBE) ? D3D11_RESOURCE_MISC_TEXTURECUBE : 0;
00492
00493             hr = pDevice->CreateTexture2D( &desc, initData.get(), reinterpret_cast<ID3D11Texture2D**>(ppResource) );
00494         }
00495         break;
00496
00497     case TEX_DIMENSION_TEXTURE3D:
00498         {
00499             D3D11_TEXTURE3D_DESC desc;
00500             desc.Width = static_cast<UINT>( metadata.width );
00501             desc.Height = static_cast<UINT>( metadata.height );
00502             desc.Depth = static_cast<UINT>( metadata.depth );
00503             desc.MipLevels = static_cast<UINT>( metadata.mipLevels );
00504             desc.Format = metadata.format;
00505             desc.Usage = D3D11_USAGE_DEFAULT;
00506             desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
00507             desc.CPUAccessFlags = 0;
00508             desc.MiscFlags = 0;
00509
00510             hr = pDevice->CreateTexture3D( &desc, initData.get(), reinterpret_cast<ID3D11Texture3D**>(ppResource) );
00511         }
00512         break;
00513     }
00514
00515     return hr;
00516 }
00517
00518
00519 //-------------------------------------------------------------------------------------
00520 // Create a shader resource view and associated texture
00521 //-------------------------------------------------------------------------------------
00522 _Use_decl_annotations_
00523 HRESULT CreateShaderResourceView( ID3D11Device* pDevice, const Image* srcImages, size_t nimages, const TexMetadata& metadata,
00524                                   ID3D11ShaderResourceView** ppSRV )
00525 {
00526     if ( !ppSRV )
00527         return E_INVALIDARG;
00528
00529     ScopedObject<ID3D11Resource> resource;
00530     HRESULT hr = CreateTexture( pDevice, srcImages, nimages, metadata, &resource );
00531     if ( FAILED(hr) )
00532         return hr;
00533
00534     assert( !resource.IsNull() );
00535
00536     D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
00537     memset( &SRVDesc, 0, sizeof(SRVDesc) );
00538     SRVDesc.Format = metadata.format;
00539
00540     switch ( metadata.dimension )
00541     {
00542     case TEX_DIMENSION_TEXTURE1D:
00543         if ( metadata.arraySize > 1 )
00544         {
00545             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE1DARRAY;
00546             SRVDesc.Texture1DArray.MipLevels = static_cast<UINT>( metadata.mipLevels );
00547             SRVDesc.Texture1DArray.ArraySize = static_cast<UINT>( metadata.arraySize );
00548         }
00549         else
00550         {
00551             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE1D;
00552             SRVDesc.Texture1D.MipLevels = static_cast<UINT>( metadata.mipLevels );
00553         }
00554         break;
00555
00556     case TEX_DIMENSION_TEXTURE2D:
00557         if ( metadata.miscFlags & TEX_MISC_TEXTURECUBE )
00558         {
00559             if (metadata.arraySize > 6)
00560             {
00561                 assert( (metadata.arraySize % 6) == 0 );
00562                 SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURECUBEARRAY;
00563                 SRVDesc.TextureCubeArray.MipLevels = static_cast<UINT>( metadata.mipLevels );
00564                 SRVDesc.TextureCubeArray.NumCubes = static_cast<UINT>( metadata.arraySize / 6 );
00565             }
00566             else
00567             {
00568                 SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURECUBE;
00569                 SRVDesc.TextureCube.MipLevels = static_cast<UINT>( metadata.mipLevels );
00570             }
00571         }
00572         else if ( metadata.arraySize > 1 )
00573         {
00574             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE2DARRAY;
00575             SRVDesc.Texture2DArray.MipLevels = static_cast<UINT>( metadata.mipLevels );
00576             SRVDesc.Texture2DArray.ArraySize = static_cast<UINT>( metadata.arraySize );
00577         }
00578         else
00579         {
00580             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE2D;
00581             SRVDesc.Texture2D.MipLevels = static_cast<UINT>( metadata.mipLevels );
00582         }
00583         break;
00584
00585     case TEX_DIMENSION_TEXTURE3D:
00586         assert( metadata.arraySize == 1 );
00587         SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE3D;
00588         SRVDesc.Texture3D.MipLevels = static_cast<UINT>( metadata.mipLevels );
00589         break;
00590
00591     default:
00592         return E_FAIL;
00593     }
00594
00595     hr = pDevice->CreateShaderResourceView( resource.Get(), &SRVDesc, ppSRV );
00596     if ( FAILED(hr) )
00597         return hr;
00598
00599     assert( *ppSRV );
00600
00601     return S_OK;
00602 }
00603
00604
00605 //-------------------------------------------------------------------------------------
00606 // Save a texture resource to a DDS file in memory/on disk
00607 //-------------------------------------------------------------------------------------
00608 _Use_decl_annotations_
00609 HRESULT CaptureTexture( ID3D11Device* pDevice, ID3D11DeviceContext* pContext, ID3D11Resource* pSource, ScratchImage& result )
00610 {
00611     if ( !pDevice || !pContext || !pSource )
00612         return E_INVALIDARG;
00613
00614     D3D11_RESOURCE_DIMENSION resType = D3D11_RESOURCE_DIMENSION_UNKNOWN;
00615     pSource->GetType( &resType );
00616
00617     HRESULT hr;
00618
00619     switch( resType )
00620     {
00621     case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
00622         {
00623             ScopedObject<ID3D11Texture1D> pTexture;
00624             hr = pSource->QueryInterface( __uuidof(ID3D11Texture1D), (void**) &pTexture );
00625             if ( FAILED(hr) )
00626                 break;
00627
00628             assert( pTexture.Get() );
00629
00630             D3D11_TEXTURE1D_DESC desc;
00631             pTexture->GetDesc( &desc );
00632
00633             desc.BindFlags = 0;
00634             desc.MiscFlags = 0;
00635             desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
00636             desc.Usage = D3D11_USAGE_STAGING;
00637
00638             ScopedObject<ID3D11Texture1D> pStaging;
00639             hr = pDevice->CreateTexture1D( &desc, 0, &pStaging );
00640             if ( FAILED(hr) )
00641                 break;
00642
00643             assert( pStaging.Get() );
00644
00645             pContext->CopyResource( pStaging.Get(), pSource );
00646
00647             TexMetadata mdata;
00648             mdata.width = desc.Width;
00649             mdata.height = mdata.depth = 1;
00650             mdata.arraySize = desc.ArraySize;
00651             mdata.mipLevels = desc.MipLevels;
00652             mdata.miscFlags = 0;
00653             mdata.format = desc.Format;
00654             mdata.dimension = TEX_DIMENSION_TEXTURE1D;
00655
00656             hr = result.Initialize( mdata );
00657             if ( FAILED(hr) )
00658                 break;
00659
00660             hr = _Capture( pContext, pStaging.Get(), mdata, result );
00661         }
00662         break;
00663
00664     case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
00665         {
00666             ScopedObject<ID3D11Texture2D> pTexture;
00667             hr = pSource->QueryInterface( __uuidof(ID3D11Texture2D), (void**) &pTexture );
00668             if ( FAILED(hr) )
00669                 break;
00670
00671             assert( pTexture.Get() );
00672
00673             D3D11_TEXTURE2D_DESC desc;
00674             pTexture->GetDesc( &desc );
00675
00676             ScopedObject<ID3D11Texture2D> pStaging;
00677             if ( desc.SampleDesc.Count > 1 )
00678             {
00679                 desc.SampleDesc.Count = 1;
00680                 desc.SampleDesc.Quality = 0;
00681
00682                 ScopedObject<ID3D11Texture2D> pTemp;
00683                 hr = pDevice->CreateTexture2D( &desc, 0, &pTemp );
00684                 if ( FAILED(hr) )
00685                     break;
00686
00687                 assert( pTemp.Get() );
00688
00689                 for( UINT item = 0; item < desc.ArraySize; ++item )
00690                 {
00691                     for( UINT level = 0; level < desc.MipLevels; ++level )
00692                     {
00693                         UINT index = D3D11CalcSubresource( level, item, desc.MipLevels );
00694                         pContext->ResolveSubresource( pTemp.Get(), index, pSource, index, desc.Format );
00695                     }
00696                 }
00697
00698                 desc.BindFlags = 0;
00699                 desc.MiscFlags &= D3D11_RESOURCE_MISC_TEXTURECUBE;
00700                 desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
00701                 desc.Usage = D3D11_USAGE_STAGING;
00702
00703                 hr = pDevice->CreateTexture2D( &desc, 0, &pStaging );
00704                 if ( FAILED(hr) )
00705                     break;
00706
00707                 assert( pStaging.Get() );
00708
00709                 pContext->CopyResource( pStaging.Get(), pTemp.Get() );
00710             }
00711             else
00712             {
00713                 desc.BindFlags = 0;
00714                 desc.MiscFlags &= D3D11_RESOURCE_MISC_TEXTURECUBE;
00715                 desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
00716                 desc.Usage = D3D11_USAGE_STAGING;
00717
00718                 hr = pDevice->CreateTexture2D( &desc, 0, &pStaging );
00719                 if ( FAILED(hr) )
00720                     break;
00721
00722                 assert( pStaging.Get() );
00723
00724                 pContext->CopyResource( pStaging.Get(), pSource );
00725             }
00726
00727             TexMetadata mdata;
00728             mdata.width = desc.Width;
00729             mdata.height = desc.Height;
00730             mdata.depth = 1;
00731             mdata.arraySize = desc.ArraySize;
00732             mdata.mipLevels = desc.MipLevels;
00733             mdata.miscFlags = (desc.MiscFlags & D3D11_RESOURCE_MISC_TEXTURECUBE) ? TEX_MISC_TEXTURECUBE : 0;
00734             mdata.format = desc.Format;
00735             mdata.dimension = TEX_DIMENSION_TEXTURE2D;
00736
00737             hr = result.Initialize( mdata );
00738             if ( FAILED(hr) )
00739                 break;
00740
00741             hr = _Capture( pContext, pStaging.Get(), mdata, result );
00742         }
00743         break;
00744
00745     case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
00746         {
00747             ScopedObject<ID3D11Texture3D> pTexture;
00748             hr = pSource->QueryInterface( __uuidof(ID3D11Texture3D), (void**) &pTexture );
00749             if ( FAILED(hr) )
00750                 break;
00751
00752             assert( pTexture.Get() );
00753
00754             D3D11_TEXTURE3D_DESC desc;
00755             pTexture->GetDesc( &desc );
00756
00757             desc.BindFlags = 0;
00758             desc.MiscFlags = 0;
00759             desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
00760             desc.Usage = D3D11_USAGE_STAGING;
00761
00762             ScopedObject<ID3D11Texture3D> pStaging;
00763             hr = pDevice->CreateTexture3D( &desc, 0, &pStaging );
00764             if ( FAILED(hr) )
00765                 break;
00766
00767             assert( pStaging.Get() );
00768
00769             pContext->CopyResource( pStaging.Get(), pSource );
00770
00771             TexMetadata mdata;
00772             mdata.width = desc.Width;
00773             mdata.height = desc.Height;
00774             mdata.depth = desc.Depth;
00775             mdata.arraySize = 1;
00776             mdata.mipLevels = desc.MipLevels;
00777             mdata.miscFlags = 0;
00778             mdata.format = desc.Format;
00779             mdata.dimension = TEX_DIMENSION_TEXTURE3D;
00780
00781             hr = result.Initialize( mdata );
00782             if ( FAILED(hr) )
00783                 break;
00784
00785             hr = _Capture( pContext, pStaging.Get(), mdata, result );
00786         }
00787         break;
00788
00789     default:
00790         hr = E_FAIL;
00791         break;
00792     }
00793
00794     if ( FAILED(hr) )
00795     {
00796         result.Release();
00797         return hr;
00798     }
00799
00800     return S_OK;
00801 }
00802
00803 }; // namespace
Generated on Sat Nov 23 2024 16:08:12 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Network information/C++/common/suspensionmanager.cpp Source File

  • Network information
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:37 for Win8-Examples by doxygen 1.7.1


Win8-Examples: HttpClient/C++/Scenario3.xaml.cpp Source File

  • HttpClient

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 SDKSample::HttpClientSample;
00020
00021 using namespace concurrency;
00022 using namespace Platform;
00023 using namespace Windows::Data::Xml::Dom;
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
00029 Scenario3::Scenario3()
00030 {
00031     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 void Scenario3::OnNavigatedTo(NavigationEventArgs^ e)
00040 {
00041     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00042     // as NotifyUser()
00043     rootPage = MainPage::Current;
00044 }
00045
00046
00047 void SDKSample::HttpClientSample::Scenario3::Start_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00048 {
00049     Helpers::ScenarioStarted(StartButton, CancelButton);
00050     rootPage->NotifyUser("In progress", NotifyType::StatusMessage);
00051     OutputField->Text = "";
00052
00053     // 'AddressField' is a disabled text box, so the value is considered trusted input. When enabling the
00054     // text box make sure to validate user input (e.g., by catching exceptions with TryGetUri as shown in scenario 1).
00055     Uri^ resourceAddress = ref new Uri(AddressField->Text);
00056
00057     cancellationTokenSource = cancellation_token_source();
00058
00059     // Do an asynchronous GET.  We need to use use_current() with the continuations since the tasks are completed on
00060     // background threads and we need to run on the UI thread to update the UI.
00061     httpRequest.GetAsync(resourceAddress, cancellationTokenSource.get_token()).then([this](std::wstring str)
00062     {
00063         DisplayTextResult(str, OutputField);
00064
00065         // Create and load the XML document from the response.
00066         XmlDocument^ xmlDocument = ref new XmlDocument();
00067         xmlDocument->LoadXml(ref new String(str.c_str()));
00068
00069         if (httpRequest.GetStatusCode() == 200)
00070         {
00071             // Create a collection to bind to the view.
00072             auto items = ref new Platform::Collections::Vector<Platform::Object^>();
00073             auto elements = xmlDocument->GetElementsByTagName("item");
00074             for (auto c = elements->First(); c->HasCurrent; c->MoveNext())
00075             {
00076                 XmlElement^ element = safe_cast<XmlElement^>(c->Current);
00077                 items->Append(element->GetAttribute("name"));
00078             }
00079
00080             OutputList->ItemsSource = items;
00081         }
00082
00083         rootPage->NotifyUser("Completed", NotifyType::StatusMessage);
00084     }, task_continuation_context::use_current()).then([this](task<void> previousTask)
00085     {
00086         Helpers::ScenarioCompleted(StartButton, CancelButton);
00087
00088         try
00089         {
00090             previousTask.get();
00091         }
00092         catch (const task_canceled&)
00093         {
00094             rootPage->NotifyUser("Request canceled.", NotifyType::ErrorMessage);
00095         }
00096         catch (Exception^ ex)
00097         {
00098             rootPage->NotifyUser(ex->Message, NotifyType::ErrorMessage);
00099         }
00100     }, task_continuation_context::use_current());
00101
00102 }
00103
00104 void SDKSample::HttpClientSample::Scenario3::Cancel_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00105 {
00106     cancellationTokenSource.cancel();
00107 }
00108
00109 void SDKSample::HttpClientSample::Scenario3::DisplayTextResult(const std::wstring& response, TextBox^ output)
00110 {
00111     output->Text += httpRequest.GetStatusCode() + " " + ref new String(httpRequest.GetReasonPhrase().c_str()) + "\n";
00112
00113     // Convert all instances of <br> to newline.
00114     std::wstring ws = response;
00115     Helpers::ReplaceAll(ws, L"<br>", L"\n");
00116
00117     output->Text += ref new String(ws.c_str());
00118 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Credential picker/C++/ScenarioList.xaml.cpp Source File

  • Credential picker

ScenarioList.xaml.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 //
00009 // ScenarioList.xaml.cpp
00010 // Implementation of the ScenarioList class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioList.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace CredentialPickerCPP;
00018
00019 using namespace Platform;
00020 using namespace CppSamplesUtils;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Foundation::Collections;
00023 using namespace Windows::Graphics::Display;
00024 using namespace Windows::UI::ViewManagement;
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 using namespace Windows::UI::Xaml::Interop;
00033
00034 ScenarioList::ScenarioList()
00035 {
00036     InitializeComponent();
00037 }
00038
00039 ScenarioList::~ScenarioList()
00040 {
00041 }
00042
00043 void ScenarioList::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00044 {
00045     if(Scenarios->SelectedItem != nullptr)
00046     {
00047         rootPage->NotifyUser("", NotifyType::StatusMessage);
00048
00049         ListBoxItem^ selectedListBoxItem = dynamic_cast<ListBoxItem^>(Scenarios->SelectedItem);
00050         SuspensionManager::SessionState()->Insert("SelectedScenario", selectedListBoxItem->Name);
00051
00052         if (rootPage->InputFrame != nullptr && rootPage->OutputFrame != nullptr)
00053         {
00054              //Load the input and output pages for the current scenario into their respective frames
00055             TypeName inputPage = { "CredentialPickerCPP" + "." + "ScenarioInput" + ((Scenarios->SelectedIndex + 1).ToString()), TypeKind::Custom };
00056             TypeName outputPage = { "CredentialPickerCPP" + "." + "ScenarioOutput" + ((Scenarios->SelectedIndex + 1).ToString()), TypeKind::Custom };
00057             rootPage->DoNavigation(inputPage, rootPage->InputFrame, outputPage, rootPage->OutputFrame);
00058         }
00059     }
00060 }
00061
00062 void ScenarioList::OnNavigatedTo(NavigationEventArgs^ e)
00063 {
00064     rootPage = dynamic_cast<MainPage^>(e->Parameter);
00065
00066     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &ScenarioList::Scenarios_SelectionChanged);
00067     ListBoxItem^ startingScenario = nullptr;
00068
00069     auto ps = SuspensionManager::SessionState();
00070     if (ps->HasKey("SelectedScenario"))
00071     {
00072         PropertyValue^ pv;
00073         String^ item = dynamic_cast<String^>(ps->Lookup("SelectedScenario"));
00074         startingScenario = dynamic_cast<ListBoxItem^>(this->FindName(item));
00075     }
00076
00077     Scenarios->SelectedItem = startingScenario != nullptr ? startingScenario : Scenario1;
00078 }
Generated on Sat Nov 23 2024 16:07:57 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application resources and localization/C++/Scenario2.xaml.cpp Source File

  • Application resources and localization

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 SDKSample::ApplicationResources;
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 Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playback Manager msAudioCategory/C++/pch.h Source File

  • Playback Manager msAudioCategory

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX marble maze game/C++/Collision.cpp Source File

  • DirectX marble maze game

Collision.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
00010 using namespace Microsoft::WRL;
00011 using namespace DirectX;
00012
00013 #include "Primitives.h"
00014 #include "Collision.h"
00015 #include "Physics.h"
00016
00017 #pragma region Inline math functions
00018
00019 // Return the point on the line segment (S1, S2) nearest the point P.
00020 static inline XMVECTOR PointOnLineSegmentNearestPoint(FXMVECTOR S1, FXMVECTOR S2, FXMVECTOR P)
00021 {
00022     XMVECTOR dir = S2 - S1;
00023     XMVECTOR projection = (XMVector3Dot(P, dir) - XMVector3Dot(S1, dir));
00024     XMVECTOR lengthSq = XMVector3Dot(dir, dir);
00025
00026     XMVECTOR t = projection * XMVectorReciprocal(lengthSq);
00027     XMVECTOR point = S1 + t * dir;
00028
00029     // t < 0
00030     XMVECTOR selectS1 = XMVectorLess(projection, XMVectorZero());
00031     point = XMVectorSelect(point, S1, selectS1);
00032
00033     // t > 1
00034     XMVECTOR selectS2 = XMVectorGreater(projection, lengthSq);
00035     point = XMVectorSelect(point, S2, selectS2);
00036
00037     return point;
00038 }
00039
00040 // Test if the point (P) on the plane of the triangle is inside the triangle
00041 // (V0, V1, V2).
00042 static inline XMVECTOR PointOnPlaneInsideTriangle(FXMVECTOR P, FXMVECTOR V0, FXMVECTOR V1, CXMVECTOR V2)
00043 {
00044     // Compute the triangle normal.
00045     XMVECTOR N = XMVector3Cross(V2 - V0, V1 - V0);
00046
00047     // Compute the cross products of the vector from the base of each edge to
00048     // the point with each edge vector.
00049     XMVECTOR C0 = XMVector3Cross(P - V0, V1 - V0);
00050     XMVECTOR C1 = XMVector3Cross(P - V1, V2 - V1);
00051     XMVECTOR C2 = XMVector3Cross(P - V2, V0 - V2);
00052
00053     // If the cross product points in the same direction as the normal the the
00054     // point is inside the edge (it is zero if is on the edge).
00055     XMVECTOR zero = XMVectorZero();
00056     XMVECTOR inside0 = XMVectorGreaterOrEqual(XMVector3Dot(C0, N), zero);
00057     XMVECTOR inside1 = XMVectorGreaterOrEqual(XMVector3Dot(C1, N), zero);
00058     XMVECTOR inside2 = XMVectorGreaterOrEqual(XMVector3Dot(C2, N), zero);
00059
00060     // If the point inside all of the edges it is inside.
00061     return XMVectorAndInt(XMVectorAndInt(inside0, inside1), inside2);
00062 }
00063
00064 #pragma endregion
00065
00066 BOOL Collision::AccumulateSphereTriangleIntersections(
00067     FXMVECTOR sphere,
00068     FXMVECTOR radius,
00069     FXMVECTOR path,
00070     MeshID mesh,
00071     const std::vector<Triangle>& triList
00072     )
00073 {
00074     size_t triCount = triList.size();
00075
00076     BOOL found = FALSE;
00077     for (size_t i = 0; i < triCount; ++i)
00078     {
00079         Contact f(triList[i], i, mesh);
00080
00081         if (f.CalculateContact(sphere, radius, path))
00082         {
00083             m_collisions.push_back(f);
00084             found = TRUE;
00085         }
00086     }
00087
00088     return found;
00089 }
00090
00091 // Builds a list of triangles which are fully or partially enclosed by the sphere.
00092 BOOL Collision::BuildCollisionListForSphere(const Sphere& meshLocalSpace, FXMVECTOR path)
00093 {
00094     m_collisions.clear();
00095     XMVECTOR sphere = XMLoadFloat4(&meshLocalSpace.center);
00096     XMVECTOR radius = XMVectorSplatW(sphere);
00097
00098     m_intersectsGround = AccumulateSphereTriangleIntersections(sphere, radius, path, MeshID::Ground, m_groundTriList);
00099
00100     BOOL intersected = m_intersectsGround;
00101     intersected |= AccumulateSphereTriangleIntersections(sphere, radius, path, MeshID::Wall, m_wallTriList);
00102
00103     // NOTE: We don't collide against the floor, as the mesh has some edges which interfere with normal rolling.
00104
00105     // intersected |= AccumulateSphereTriangleIntersections(sphere, radius, path, MeshID::Floor, m_floorTriList);
00106
00107     MergeSharedEdgeCoplanarContacts(sphere, radius, path);
00108
00109     return intersected;
00110 }
00111
00112 // After the worst interpenetration has been handled, recalculate the distances.
00113 void Collision::UpdateInterpenetrations(FXMVECTOR newPosition, FXMVECTOR radius, FXMVECTOR path)
00114 {
00115     const size_t contacts = m_collisions.size();
00116     for (size_t i = 0; i < contacts; ++i)
00117     {
00118         Contact& c = m_collisions[i];
00119
00120         if (!c.CalculateContact(newPosition, radius, path))
00121         {
00122             c.Invalidate();
00123         }
00124     }
00125
00126     MergeSharedEdgeCoplanarContacts(newPosition, radius, path);
00127 }
00128
00129 // Finds the contact which exhibits the worst inclusion with the sphere with a velocity that is moving the sphere
00130 // into that triangle. If none match, returns nullptr.
00131 Contact* Collision::FindWorstInterpenetration()
00132 {
00133     Contact* worst = nullptr;
00134     float worstDistance = FLT_MAX;
00135
00136     for (size_t i = 0; i < m_collisions.size(); ++i)
00137     {
00138         Contact& c = m_collisions[i];
00139
00140         if (c.IsColliding() && c.penetrationDistance < worstDistance && c.closingVelocity <= 0.0f)
00141         {
00142             worst = &c;
00143             worstDistance = c.penetrationDistance;
00144         }
00145     }
00146
00147     return worst;
00148 }
00149
00150 // Merges any collisions we find together, depending on if they're coplanar or not (face vs. edge contacts), and
00151 // whether or not they share edges.
00152 void Collision::MergeSharedEdgeCoplanarContacts(FXMVECTOR sphere, FXMVECTOR radius, FXMVECTOR path)
00153 {
00154     size_t count = m_collisions.size();
00155     for (size_t j = 0; j < count; ++j)
00156     {
00157         Contact& c1 = m_collisions[j];
00158         if (!c1.IsColliding())
00159             continue;
00160
00161         XMVECTOR A = XMLoadFloat3(&c1.triangle.A);
00162         XMVECTOR B = XMLoadFloat3(&c1.triangle.B);
00163         XMVECTOR C = XMLoadFloat3(&c1.triangle.C);
00164         XMVECTOR N = c1.triangle.Normal();
00165
00166         XMVECTOR c1Contact = XMLoadFloat3(&c1.contactPosition);
00167
00168         for (size_t i = j + 1; i < count; ++i)
00169         {
00170             Contact& c2 = m_collisions[i];
00171             if (!c2.IsColliding())
00172                 continue;
00173
00174             BOOL coplanar, sharesverts;
00175             c2.triangle.CheckSharesVertsOrCoplanar(A, B, C, N, sharesverts, coplanar);
00176
00177             if (sharesverts)
00178             {
00179                 if (coplanar)
00180                 {
00181                     // If we share vertices with the other tri, and we're coplanar, then
00182                     // we're on a larger "plane" stretch, so we should use that.
00183
00184                     c2.Invalidate();
00185
00186                     // Update normal
00187                     XMStoreFloat3((XMFLOAT3*)&c1.plane, N);
00188
00189                     // Update closing velocity.
00190                     XMStoreFloat(&c1.closingVelocity, XMVector3Dot(path, N));
00191
00192                     XMVECTOR dist = XMVector3Dot(sphere - A, N);
00193                     XMVECTOR newContact = sphere - (dist * N);
00194                     XMVECTOR penetration = dist - radius;
00195
00196                     // Find new contact point - project sphere center down onto plane.
00197                     XMStoreFloat3(&c1.contactPosition, newContact);
00198                     c1.contactIsEdge = FALSE;
00199                     XMStoreFloat(&c1.penetrationDistance, penetration);
00200
00201                 }
00202                 else if (c1.contactIsEdge || c2.contactIsEdge)
00203                 {
00204                     // We've got a contact position that's most likely on a corner.
00205                     const XMVECTOR epsilon = XMVectorSet(1E-4f, 1E-4f, 1E-4f, 1E-4f);
00206                     const XMVECTOR contactPos1 = XMLoadFloat3(&c1.contactPosition);
00207                     const XMVECTOR contactPos2 = XMLoadFloat3(&c2.contactPosition);
00208
00209                     // If they're nearly equal, recalculate normal as average of two tris.
00210                     if (XMVector3NearEqual(contactPos1, contactPos2, epsilon))
00211                     {
00212                         c1.contactIsEdge = FALSE;
00213                         XMVECTOR C1Normal = c1.triangle.Normal();
00214                         XMVECTOR C2Normal = c2.triangle.Normal();
00215                         XMVECTOR newNormal = XMVector3Normalize(C1Normal + C2Normal);
00216                         XMStoreFloat3((XMFLOAT3*)&c1.plane, newNormal);
00217
00218                         XMStoreFloat(&c1.closingVelocity, XMVector3Dot(path, newNormal));
00219
00220                         // Calculate new penetration...
00221                         XMVECTOR dist = XMVector3Dot(sphere - contactPos1, newNormal);
00222                         XMVECTOR penetration = dist - radius;
00223                         XMStoreFloat(&c1.penetrationDistance, penetration);
00224                         c2.Invalidate();
00225                     }
00226                 }
00227             }
00228             else
00229             {
00230                 // If we don't share an edge, but we're coplanar, check if we're the same distance... If
00231                 // we are, we're probably on a flat plane, and can merge the two.
00232                 if (coplanar)
00233                 {
00234                     const float PENETRATION_DIST_TOLERANCE = 1E-4f;
00235                     if (fabs(c1.penetrationDistance - c2.penetrationDistance) <= PENETRATION_DIST_TOLERANCE)
00236                     {
00237                         // Same plane!
00238                         c2.Invalidate();
00239                     }
00240                 }
00241             }
00242         }
00243     }
00244 }
00245
00246 // Push the sphere out of the surface along its surface normal until it is just touching.
00247 XMVECTOR Contact::Resolve(FXMVECTOR position, FXMVECTOR radius)
00248 {
00249     XMVECTOR N = XMLoadFloat3((XMFLOAT3*) &plane);
00250     return position - (penetrationDistance * N);
00251 }
00252
00253 // Calculates the penetration distance of the sphere into the triangle.
00254 BOOL Contact::CalculateContact(FXMVECTOR position, FXMVECTOR radiusIn, FXMVECTOR path)
00255 {
00256     XMVECTOR V0 = XMLoadFloat3(&triangle.A);
00257     XMVECTOR V1 = XMLoadFloat3(&triangle.B);
00258     XMVECTOR V2 = XMLoadFloat3(&triangle.C);
00259
00260     // Load the sphere.
00261     XMVECTOR center = position;
00262     XMVECTOR radius = radiusIn;
00263
00264     // Compute the plane of the triangle (has to be normalized).
00265     XMVECTOR N = XMVector3Normalize(XMVector3Cross(V1 - V0, V2 - V0));
00266
00267     // Is velocity in
00268     XMVECTOR VDotN = XMVector3Dot(path, N);
00269     XMStoreFloat(&closingVelocity, VDotN);
00270
00271     // Find the nearest feature on the triangle to the sphere.
00272     XMVECTOR dist = XMVector3Dot(center - V0, N);
00273
00274     // If the center of the sphere is farther from the plane of the triangle than
00275     // the radius of the sphere, then there cannot be an intersection.
00276     XMVECTOR noIntersection = XMVectorLess(dist, -radius);
00277     noIntersection = XMVectorOrInt(noIntersection, XMVectorGreater(dist, radius));
00278
00279     // Project the center of the sphere onto the plane of the triangle.
00280     XMVECTOR pointOnPlane = center - (N * dist);
00281
00282     // Is it inside all the edges? If so we intersect because the distance
00283     // to the plane is less than the radius.
00284     XMVECTOR isOnPlaneInsideTriangle = PointOnPlaneInsideTriangle(pointOnPlane, V0, V1, V2);
00285
00286     // Find the nearest point on each edge.
00287     XMVECTOR radiusSq = radius * radius;
00288
00289     // Edge 0, 1
00290     XMVECTOR pointEdge01 = PointOnLineSegmentNearestPoint(V0, V1, center);
00291
00292     XMVECTOR distEdge01 = XMVector3LengthSq(center - pointEdge01);
00293
00294     // If the distance to the center of the sphere to the point is less than
00295     // the radius of the sphere then it must intersect.
00296     XMVECTOR intersection = XMVectorOrInt(isOnPlaneInsideTriangle, XMVectorLessOrEqual(distEdge01, radiusSq));
00297
00298     // Edge 1, 2
00299     XMVECTOR pointEdge12 = PointOnLineSegmentNearestPoint(V1, V2, center);
00300     XMVECTOR distEdge12 = XMVector3LengthSq(center - pointEdge12);
00301
00302     // If the distance to the center of the sphere to the point is less than
00303     // the radius of the sphere then it must intersect.
00304     intersection = XMVectorOrInt(intersection, XMVectorLessOrEqual(distEdge12, radiusSq));
00305
00306     // Edge 2, 0
00307     XMVECTOR pointEdge20 = PointOnLineSegmentNearestPoint(V2, V0, center);
00308     XMVECTOR distEdge20 = XMVector3LengthSq(center - pointEdge20);
00309
00310     // If the distance to the center of the sphere to the point is less than
00311     // the radius of the sphere then it must intersect.
00312     intersection = XMVectorOrInt(intersection, XMVectorLessOrEqual(distEdge20, radiusSq));
00313
00314     XMVECTOR pointOnPlaneDist = XMVector3LengthSq(center - pointOnPlane);
00315     XMVECTOR contactPointDist = XMVectorSet(FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX);
00316     XMVECTOR contactPoint = pointOnPlane;
00317     XMVECTOR isEdge = XMVectorFalseInt();
00318     // if intersects plane, start with point on plane distance
00319     contactPointDist = XMVectorSelect(contactPointDist, pointOnPlaneDist, isOnPlaneInsideTriangle);
00320
00321     XMVECTOR select = XMVectorLessOrEqual(distEdge01, contactPointDist);
00322     contactPointDist = XMVectorSelect(contactPointDist, distEdge01, select);
00323     contactPoint = XMVectorSelect(contactPoint, pointEdge01, select);
00324     isEdge = XMVectorOrInt(isEdge, select);
00325
00326     select = XMVectorLessOrEqual(distEdge12, contactPointDist);
00327     contactPointDist = XMVectorSelect(contactPointDist, distEdge12, select);
00328     contactPoint = XMVectorSelect(contactPoint, pointEdge12, select);
00329     isEdge = XMVectorOrInt(isEdge, select);
00330
00331     select = XMVectorLessOrEqual(distEdge20, contactPointDist);
00332     contactPointDist = XMVectorSelect(contactPointDist, distEdge20, select);
00333     contactPoint = XMVectorSelect(contactPoint, pointEdge20, select);
00334     isEdge = XMVectorOrInt(isEdge, select);
00335
00336     contactPointDist = XMVectorSqrt(contactPointDist);
00337
00338     // Store the contact point, and the contact edge.
00339     XMStoreFloat3(&contactPosition, contactPoint);
00340     contactIsEdge = XMVector4EqualInt(isEdge, XMVectorTrueInt());
00341
00342     // Is the sphere at the contact point? In which case we just use the surface normal.
00343     XMVECTOR isContactAtSphereCenter = XMVectorInBounds(contactPointDist, XMVectorSplatEpsilon());
00344     XMVECTOR contactToCenterNormal = (center - contactPoint) / contactPointDist;
00345     XMVECTOR contactNormal = XMVectorSelect(contactToCenterNormal, N, isContactAtSphereCenter);
00346
00347     // Store the contact normal
00348     XMStoreFloat3((XMFLOAT3*)&plane, contactNormal);
00349
00350     // Figure out the penetration distance...
00351
00352     XMVECTOR penetrationDistTemp = XMVector3Dot(center - contactPoint, contactNormal) - radius;
00353
00354     XMStoreFloat(&penetrationDistance, penetrationDistTemp);
00355
00356     return XMVector4EqualInt(XMVectorAndCInt(intersection, noIntersection), XMVectorTrueInt());
00357 }
Generated on Sat Nov 23 2024 16:08:15 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C#,C++/MediaExtensions/Invert/InvertModule.cpp Source File

  • Media extensions
  • C#,C++
  • MediaExtensions
  • Invert

InvertModule.cpp

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include "InvertModule.h"
00004
00005 struct ScreenVertex
00006 {
00007     FLOAT pos[4];
00008     FLOAT tex[2];
00009 };
00010
00011 CInvertModule::~CInvertModule()
00012 {
00013     Invalidate();
00014 }
00015
00016 void CInvertModule::Invalidate()
00017 {
00018     m_pScreenQuadVB = nullptr;
00019     m_pSampleStateLinear = nullptr;
00020     m_spQuadLayout = nullptr;
00021     m_pVertexShader = nullptr;
00022     m_pPixelShader = nullptr;
00023 }
00024
00025 HRESULT CInvertModule::Initialize(ID3D11Device *pDevice, UINT uiWidth, UINT uiHeight)
00026 {
00027     HRESULT hr = S_OK;
00028
00029     m_uiWidth = uiWidth;
00030     m_uiHeight = uiHeight;
00031
00032     if(m_pScreenQuadVB == nullptr)
00033     {
00034         // Vertex Buffer Layout
00035         D3D11_BUFFER_DESC vbdesc;
00036
00037         // 2 vertices (Triangles), covering the whole Viewport, with the input video mapped as a texture
00038         const ScreenVertex svDefault[4] = {
00039             //   x      y     z     w         u     v
00040             { { -1.0f,  1.0f, 0.5f, 1.0f }, { 0.0f, 0.0f } }, // 0
00041             { {  1.0f,  1.0f, 0.5f, 1.0f }, { 1.0f, 0.0f } }, // 1
00042             { { -1.0f, -1.0f, 0.5f, 1.0f }, { 0.0f, 1.0f } }, // 2
00043             { {  1.0f, -1.0f, 0.5f, 1.0f }, { 1.0f, 1.0f } }  // 3
00044         };
00045
00046         ZeroMemory(&vbdesc, sizeof(vbdesc));
00047
00048         vbdesc.Usage = D3D11_USAGE_DYNAMIC;
00049         vbdesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
00050         vbdesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
00051         vbdesc.MiscFlags = 0;
00052         vbdesc.ByteWidth = sizeof( svDefault );
00053
00054         D3D11_SUBRESOURCE_DATA InitData;
00055         InitData.pSysMem = svDefault;
00056         InitData.SysMemPitch = 0;
00057         InitData.SysMemSlicePitch = 0;
00058         hr = pDevice->CreateBuffer( &vbdesc, &InitData, &m_pScreenQuadVB );
00059         if( FAILED(hr) )
00060         {
00061             goto done;
00062         }
00063     }
00064
00065     // Pixel Shader
00066     {
00067         static
00068 #       include "PixelShader.hps"
00069         if(m_pPixelShader == nullptr)
00070         {
00071             hr = pDevice->CreatePixelShader(g_psshader, sizeof(g_psshader), NULL, &m_pPixelShader);
00072       if(FAILED(hr))
00073       {
00074         goto done;
00075       }
00076         }
00077     }
00078
00079     // Vertex Shader
00080     {
00081         static
00082 #       include "VertexShader.hvs"
00083         if( m_pVertexShader == nullptr )
00084         {
00085             const D3D11_INPUT_ELEMENT_DESC quadlayout[] =
00086             {
00087                 { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0,  0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
00088                 { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT,       0, 16, D3D11_INPUT_PER_VERTEX_DATA, 0 },
00089             };
00090             hr = pDevice->CreateVertexShader(g_vsshader, sizeof(g_vsshader), NULL, &m_pVertexShader);
00091       if(FAILED(hr))
00092       {
00093         goto done;
00094       }
00095
00096             hr = pDevice->CreateInputLayout(quadlayout, 2, g_vsshader, sizeof(g_vsshader), &m_spQuadLayout);
00097       if(FAILED(hr))
00098       {
00099         goto done;
00100       }
00101         }
00102     }
00103
00104     if( m_pSampleStateLinear == NULL )
00105     {
00106         // Sampler
00107         D3D11_SAMPLER_DESC SamplerDesc;
00108         ZeroMemory(&SamplerDesc, sizeof(SamplerDesc));
00109
00110         SamplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
00111         SamplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
00112         SamplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
00113         SamplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
00114         SamplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
00115
00116         hr = pDevice->CreateSamplerState( &SamplerDesc, &m_pSampleStateLinear);
00117         if( FAILED(hr) )
00118         {
00119             goto done;
00120         }
00121     }
00122
00123     return hr;
00124
00125 done:
00126     m_pScreenQuadVB = nullptr;
00127     m_pSampleStateLinear = nullptr;
00128     m_spQuadLayout = nullptr;
00129     m_pVertexShader = nullptr;
00130     m_pPixelShader = nullptr;
00131     return hr;
00132
00133 }
00134
00135 HRESULT CreateShaderInputView(ID3D11Texture2D *pTexture, UINT uiIndex, ID3D11Device *pDevice, ID3D11ShaderResourceView **ppSRV)
00136 {
00137     D3D11_TEXTURE2D_DESC textureDesc;
00138     D3D11_SHADER_RESOURCE_VIEW_DESC viewDesc;
00139
00140     ZeroMemory( &viewDesc, sizeof( viewDesc ) );
00141
00142     pTexture->GetDesc( &textureDesc );
00143
00144     viewDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
00145
00146     if ( textureDesc.ArraySize > 1 )
00147     {
00148         // Texture array, use the subresource index
00149         viewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY;
00150         viewDesc.Texture2DArray.FirstArraySlice = uiIndex;
00151         viewDesc.Texture2DArray.ArraySize = 1;
00152         viewDesc.Texture2DArray.MipLevels = 1;
00153         viewDesc.Texture2DArray.MostDetailedMip = 0;
00154     }
00155     else
00156     {
00157         viewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
00158         viewDesc.Texture2D.MostDetailedMip = 0;
00159         viewDesc.Texture2D.MipLevels = 1;
00160     }
00161
00162     return pDevice->CreateShaderResourceView(pTexture,
00163                                              &viewDesc,
00164                                              ppSRV);
00165 }
00166
00167 HRESULT CreateShaderOutputView(ID3D11Texture2D *pTexture, UINT uiIndex, ID3D11Device *pDevice, ID3D11RenderTargetView **ppRTV)
00168 {
00169     D3D11_TEXTURE2D_DESC textureDesc;
00170     D3D11_RENDER_TARGET_VIEW_DESC viewDesc;
00171
00172     ZeroMemory( &viewDesc, sizeof( viewDesc ) );
00173
00174     pTexture->GetDesc( &textureDesc );
00175
00176     viewDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
00177
00178     if ( textureDesc.ArraySize > 1 )
00179     {
00180         // Texture array, use the subresource index
00181         viewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY;
00182         viewDesc.Texture2DArray.FirstArraySlice = uiIndex;
00183         viewDesc.Texture2DArray.ArraySize = 1;
00184         viewDesc.Texture2DArray.MipSlice = 0;
00185     }
00186     else
00187     {
00188         viewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
00189         viewDesc.Texture2D.MipSlice = 0;
00190     }
00191
00192     return pDevice->CreateRenderTargetView(pTexture,
00193                                            &viewDesc,
00194                                            ppRTV );
00195
00196 }
00197
00198 HRESULT CInvertModule::ProcessFrame(ID3D11Device *pDevice, ID3D11Texture2D *pInput, UINT uiInIndex, ID3D11Texture2D *pOutput, UINT uiOutIndex)
00199 {
00200
00201     HRESULT hr = S_OK;
00202     ComPtr<ID3D11DeviceContext> pd3dImmediateContext;
00203
00204     // Render targets
00205     ComPtr<ID3D11RenderTargetView> rgpOrigRTV;
00206     ComPtr<ID3D11DepthStencilView> pOrigDSV;
00207     ID3D11RenderTargetView *pRTVs[1] = { nullptr };
00208
00209     // Shader resources
00210     ComPtr<ID3D11ShaderResourceView> rgpOrigSRV;
00211     ID3D11ShaderResourceView *pSRVs[1] = { nullptr };
00212
00213     // Vertex buffers
00214     ID3D11Buffer *pBuffers[1] = { m_pScreenQuadVB.Get() };
00215     UINT vbStrides = sizeof( ScreenVertex );
00216     UINT vbOffsets = 0;
00217
00218     // Samplers
00219     ID3D11SamplerState *pSamplers[1] = { m_pSampleStateLinear.Get() };
00220
00221     // View port
00222     D3D11_VIEWPORT vpOld[D3D11_VIEWPORT_AND_SCISSORRECT_MAX_INDEX];
00223     UINT nViewPorts = 1;
00224     D3D11_VIEWPORT vp;
00225
00226     // Get the context
00227     pDevice->GetImmediateContext(&pd3dImmediateContext);
00228
00229     // Get the resource views
00230     hr = CreateShaderInputView(pInput, uiInIndex, pDevice, &(pSRVs[0]));
00231     if( FAILED(hr) )
00232     {
00233         goto done;
00234     }
00235
00236     hr = CreateShaderOutputView(pOutput, uiOutIndex, pDevice, &(pRTVs[0]));
00237     if( FAILED(hr) )
00238     {
00239         goto done;
00240     }
00241
00242     // Setup the Draw call
00243     pd3dImmediateContext->IASetInputLayout(m_spQuadLayout.Get());
00244
00245     pd3dImmediateContext->IASetVertexBuffers(0, 1, pBuffers, &vbStrides, &vbOffsets);
00246
00247     pd3dImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
00248
00249     pd3dImmediateContext->PSSetSamplers(0, 1, pSamplers);
00250
00251     pd3dImmediateContext->OMGetRenderTargets(1, &rgpOrigRTV, &pOrigDSV);
00252
00253     pd3dImmediateContext->OMSetRenderTargets(1, pRTVs, NULL);
00254
00255     pd3dImmediateContext->PSGetShaderResources(0, 1, &rgpOrigSRV);
00256
00257     pd3dImmediateContext->PSSetShaderResources(0, 1, pSRVs);
00258
00259     pd3dImmediateContext->RSGetViewports( &nViewPorts, vpOld );
00260
00261     // Setup the viewport to match the backbuffer
00262     vp.Width = (float)m_uiWidth;
00263     vp.Height = (float)m_uiHeight;
00264     vp.MinDepth = 0.0f;
00265     vp.MaxDepth = 1.0f;
00266     vp.TopLeftX = 0.0f;
00267     vp.TopLeftY = 0.0f;
00268
00269     pd3dImmediateContext->RSSetViewports( 1, &vp );
00270
00271     pd3dImmediateContext->VSSetShader( m_pVertexShader.Get(), NULL, 0 );
00272
00273     pd3dImmediateContext->PSSetShader( m_pPixelShader.Get(), NULL, 0 );
00274
00275     pd3dImmediateContext->Draw( 4, 0 );
00276
00277     // Restore the Old
00278     pd3dImmediateContext->RSSetViewports( nViewPorts, vpOld );
00279     pd3dImmediateContext->PSSetShaderResources(0, 1, rgpOrigSRV.GetAddressOf());
00280     pd3dImmediateContext->OMSetRenderTargets( 1, rgpOrigRTV.GetAddressOf(), pOrigDSV.Get() );
00281
00282 done:
00283     if(nullptr != pSRVs[0])
00284     {
00285         pSRVs[0]->Release();
00286     }
00287     if(nullptr != pRTVs[0])
00288     {
00289         pRTVs[0]->Release();
00290     }
00291     return hr;
00292
00293 }
Generated on Sat Nov 23 2024 16:08:21 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML ListView and GridView essentials/C++/App.xaml.cpp Source File

  • XAML ListView and GridView essentials

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML FlipView control/C++/App.xaml.h Source File

  • XAML FlipView control

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playlist/C++/common/LayoutAwarePage.cpp Source File

  • Playlist
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:32 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D post-processing effects/C++/BasicLoader.cpp Source File

  • Direct3D post-processing effects

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 Sat Nov 23 2024 16:08:07 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::TileContent::TileSquareText04 Member List

This is the complete list of members for NotificationsExtensions::TileContent::TileSquareText04, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
Branding | NotificationsExtensions::TileContent::TileNotificationBase |
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
NotificationsExtensions::GetContent() | NotificationsExtensions::TileContent::TileSquareBase | [inline]
NotificationsExtensions::GetContent() | NotificationsExtensions::TileContent::TileSquareBase | [inline]
NotificationsExtensions::TileContent::TileNotificationBase::GetContent() | NotificationsExtensions::NotificationBase | [pure virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeBinding(string globalLang, string globalBaseUri, TileBranding globalBranding, bool globalAddImageQuery) | NotificationsExtensions::TileContent::TileSquareBase | [inline]
SerializeBinding(string globalLang, string globalBaseUri, TileBranding globalBranding, bool globalAddImageQuery) | NotificationsExtensions::TileContent::TileSquareBase | [inline]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextBodyWrap | NotificationsExtensions::TileContent::TileSquareText04 |
TextFields | NotificationsExtensions::NotificationBase |
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileSquareBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileSquareBase | [inline]
TileSquareBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileSquareBase | [inline]
TileSquareText04() | NotificationsExtensions::TileContent::TileSquareText04 | [inline]
TileSquareText04() | NotificationsExtensions::TileContent::TileSquareText04 | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:43 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Lock screen apps/C#,C++/App.xaml.h Source File

  • Lock screen apps
  • C#,C++

App.xaml.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 //
00009 // App.xaml.h
00010 // Declaration of the App.xaml class.
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "App.g.h"
00017
00018 namespace LockScreenAppsCPP
00019 {
00020     ref class App sealed
00021     {
00022     public:
00023         App();
00024         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00025         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00026     };
00027 }
00028
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite hello world/C++/SampleOverlay.cpp Source File

  • DirectWrite hello world

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 Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::UI::ViewManagement;
00015 using namespace Windows::Graphics::Display;
00016 using namespace D2D1;
00017
00018 SampleOverlay::SampleOverlay() :
00019     m_drawOverlay(true)
00020 {
00021 }
00022
00023 void SampleOverlay::Initialize(
00024     _In_ ID2D1Device*         d2dDevice,
00025     _In_ ID2D1DeviceContext*  d2dContext,
00026     _In_ IWICImagingFactory*  wicFactory,
00027     _In_ IDWriteFactory*      dwriteFactory,
00028     _In_ Platform::String^    caption
00029     )
00030 {
00031     m_wicFactory = wicFactory;
00032     m_dwriteFactory = dwriteFactory;
00033     m_sampleName = caption;
00034     m_d2dDevice = d2dDevice;
00035     m_d2dContext = d2dContext;
00036     m_padding = 3.0f;
00037     m_textVerticalOffset = 5.0f;
00038     m_logoSize = D2D1::SizeF(0.0f, 0.0f);
00039     m_overlayWidth = 0.0f;
00040
00041     ComPtr<ID2D1Factory> factory;
00042     d2dDevice->GetFactory(&factory);
00043
00044     DX::ThrowIfFailed(
00045         factory.As(&m_d2dFactory)
00046         );
00047
00048     ResetDirectXResources();
00049 }
00050
00051 void SampleOverlay::ResetDirectXResources()
00052 {
00053     DX::ThrowIfFailed(
00054         m_d2dContext->CreateSolidColorBrush(ColorF(ColorF::White), &m_whiteBrush)
00055         );
00056
00057     ComPtr<IWICBitmapDecoder> wicBitmapDecoder;
00058     DX::ThrowIfFailed(
00059         m_wicFactory->CreateDecoderFromFilename(
00060             L"windowsbig-sdk.png",
00061             nullptr,
00062             GENERIC_READ,
00063             WICDecodeMetadataCacheOnDemand,
00064             &wicBitmapDecoder
00065             )
00066         );
00067
00068     ComPtr<IWICBitmapFrameDecode> wicBitmapFrame;
00069     DX::ThrowIfFailed(
00070         wicBitmapDecoder->GetFrame(0, &wicBitmapFrame)
00071         );
00072
00073     ComPtr<IWICFormatConverter> wicFormatConverter;
00074     DX::ThrowIfFailed(
00075         m_wicFactory->CreateFormatConverter(&wicFormatConverter)
00076         );
00077
00078     DX::ThrowIfFailed(
00079         wicFormatConverter->Initialize(
00080             wicBitmapFrame.Get(),
00081             GUID_WICPixelFormat32bppPBGRA,
00082             WICBitmapDitherTypeNone,
00083             nullptr,
00084             0.0,
00085             WICBitmapPaletteTypeCustom  // the BGRA format has no palette so this value is ignored
00086             )
00087         );
00088
00089     double dpiX = 96.0f;
00090     double dpiY = 96.0f;
00091     DX::ThrowIfFailed(
00092         wicFormatConverter->GetResolution(&dpiX, &dpiY)
00093         );
00094
00095     DX::ThrowIfFailed(
00096         m_d2dContext->CreateBitmapFromWicBitmap(
00097             wicFormatConverter.Get(),
00098             BitmapProperties(
00099                 PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00100                 static_cast<float>(dpiX),
00101                 static_cast<float>(dpiY)
00102                 ),
00103             &m_logoBitmap
00104             )
00105         );
00106
00107     m_logoSize = m_logoBitmap->GetSize();
00108
00109     ComPtr<IDWriteTextFormat> nameTextFormat;
00110     DX::ThrowIfFailed(
00111         m_dwriteFactory->CreateTextFormat(
00112             L"Segoe UI",
00113             nullptr,
00114             DWRITE_FONT_WEIGHT_LIGHT,
00115             DWRITE_FONT_STYLE_NORMAL,
00116             DWRITE_FONT_STRETCH_NORMAL,
00117             36.0f,
00118             L"en-US",
00119             &nameTextFormat
00120             )
00121         );
00122
00123     DX::ThrowIfFailed(
00124         nameTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)
00125         );
00126
00127     DX::ThrowIfFailed(
00128         nameTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)
00129         );
00130
00131     DX::ThrowIfFailed(
00132         m_dwriteFactory->CreateTextLayout(
00133             m_sampleName->Data(),
00134             m_sampleName->Length(),
00135             nameTextFormat.Get(),
00136             4096.0f,
00137             4096.0f,
00138             &m_textLayout
00139             )
00140         );
00141
00142     DWRITE_TEXT_METRICS metrics = {0};
00143     DX::ThrowIfFailed(
00144         m_textLayout->GetMetrics(&metrics)
00145         );
00146
00147     m_overlayWidth = m_padding * 3.0f + m_logoSize.width + metrics.width;
00148
00149     DX::ThrowIfFailed(
00150         m_d2dFactory->CreateDrawingStateBlock(&m_stateBlock)
00151         );
00152
00153     UpdateForWindowSizeChange();
00154 }
00155
00156 void SampleOverlay::UpdateForWindowSizeChange()
00157 {
00158     if (CoreWindow::GetForCurrentThread()->Bounds.Width < m_overlayWidth)
00159     {
00160         m_drawOverlay = false;
00161     }
00162     else
00163     {
00164         m_drawOverlay = true;
00165     }
00166 }
00167
00168 void SampleOverlay::Render()
00169 {
00170     if (m_drawOverlay)
00171     {
00172         m_d2dContext->SaveDrawingState(m_stateBlock.Get());
00173
00174         m_d2dContext->BeginDraw();
00175         m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00176         m_d2dContext->DrawBitmap(
00177             m_logoBitmap.Get(),
00178             D2D1::RectF(m_padding, 0.0f, m_logoSize.width + m_padding, m_logoSize.height)
00179             );
00180
00181         m_d2dContext->DrawTextLayout(
00182             Point2F(m_logoSize.width + 2.0f * m_padding, m_textVerticalOffset),
00183             m_textLayout.Get(),
00184             m_whiteBrush.Get()
00185             );
00186
00187         // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00188         // is lost. It will be handled during the next call to Present.
00189         HRESULT hr = m_d2dContext->EndDraw();
00190         if (hr != D2DERR_RECREATE_TARGET)
00191         {
00192             DX::ThrowIfFailed(hr);
00193         }
00194
00195         m_d2dContext->RestoreDrawingState(m_stateBlock.Get());
00196     }
00197 }
00198
00199 float SampleOverlay::GetTitleHeightInDips()
00200 {
00201     return m_logoSize.height;
00202 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: App settings/C++/App.xaml.h Source File

  • App settings

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032         virtual void OnWindowCreated(Windows::UI::Xaml::WindowCreatedEventArgs^ pArgs) override;
00033     private:
00034         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00035     };
00036 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XInput audio controller playback/C++/DirectXBase.h Source File

  • XInput audio controller playback

DirectXBase.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 "DirectXSample.h"
00011
00012 // Helper class that initializes DirectX APIs for both 2D and 3D rendering.
00013 // Some of the code in this class may be omitted if only 2D or only 3D rendering is being used.
00014 ref class DirectXBase abstract
00015 {
00016 internal:
00017     DirectXBase();
00018
00019     virtual void Initialize(Windows::UI::Core::CoreWindow^ window, float dpi);
00020     virtual void HandleDeviceLost();
00021     virtual void CreateDeviceIndependentResources();
00022     virtual void CreateDeviceResources();
00023     virtual void SetDpi(float dpi);
00024     virtual void UpdateForWindowSizeChange();
00025     virtual void CreateWindowSizeDependentResources();
00026     virtual void Render() = 0;
00027     virtual void Present();
00028     void ValidateDevice();
00029
00030 protected private:
00031     Platform::Agile<Windows::UI::Core::CoreWindow>  m_window;
00032
00033     // DirectWrite & Windows Imaging Component Objects.
00034     Microsoft::WRL::ComPtr<IDWriteFactory1>         m_dwriteFactory;
00035     Microsoft::WRL::ComPtr<IWICImagingFactory2>     m_wicFactory;
00036
00037     // DirectX Core Objects. Required for 2D and 3D.
00038     Microsoft::WRL::ComPtr<ID3D11Device1>           m_d3dDevice;
00039     Microsoft::WRL::ComPtr<ID3D11DeviceContext1>    m_d3dContext;
00040     Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00041     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00042
00043     // Direct2D Rendering Objects. Required for 2D.
00044     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00046     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00047     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmap;
00048
00049     // Direct3D Rendering Objects. Required for 3D.
00050     Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00051
00052     // Cached renderer properties.
00053     D3D_FEATURE_LEVEL                               m_featureLevel;
00054     Windows::Foundation::Size                       m_renderTargetSize;
00055     Windows::Foundation::Rect                       m_windowBounds;
00056     float                                           m_dpi;
00057     bool                                            m_windowSizeChangeInProgress;
00058 };
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: HttpClient/C++/common/LayoutAwarePage.h Source File

  • HttpClient
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media Play To/C++/pch.cpp Source File

  • Media Play To

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML user and custom controls/C++/BasicCustomControl.cpp Source File

  • XAML user and custom controls

BasicCustomControl.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // BasicCustomControl.cpp
00003 // Implementation of the BasicCustomControl class.
00004 //
00005
00006 #include "pch.h"
00007 #include "BasicCustomControl.h"
00008
00009 using namespace SDKSample::UserAndCustomControls;
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::Data;
00017 using namespace Windows::UI::Xaml::Documents;
00018 using namespace Windows::UI::Xaml::Input;
00019 using namespace Windows::UI::Xaml::Interop;
00020 using namespace Windows::UI::Xaml::Media;
00021
00022 // The Templated Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234235
00023
00024 BasicCustomControl::BasicCustomControl()
00025 {
00026   DefaultStyleKey = "SDKSample.UserAndCustomControls.BasicCustomControl";
00027 }
Generated on Sat Nov 23 2024 16:08:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite paragraph text/C++/DirectXBase.h Source File

  • DirectWrite paragraph text

DirectXBase.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 "DirectXSample.h"
00011
00012 // Helper class that initializes DirectX APIs for both 2D and 3D rendering.
00013 // Some of the code in this class may be omitted if only 2D or only 3D rendering is being used.
00014 ref class DirectXBase abstract
00015 {
00016 internal:
00017     DirectXBase();
00018
00019     virtual void Initialize(Windows::UI::Core::CoreWindow^ window, float dpi);
00020     virtual void HandleDeviceLost();
00021     virtual void CreateDeviceIndependentResources();
00022     virtual void CreateDeviceResources();
00023     virtual void SetDpi(float dpi);
00024     virtual void UpdateForWindowSizeChange();
00025     virtual void CreateWindowSizeDependentResources();
00026     virtual void Render() = 0;
00027     virtual void Present();
00028     void ValidateDevice();
00029
00030 protected private:
00031     Platform::Agile<Windows::UI::Core::CoreWindow>  m_window;
00032
00033     // DirectWrite & Windows Imaging Component Objects.
00034     Microsoft::WRL::ComPtr<IDWriteFactory1>         m_dwriteFactory;
00035     Microsoft::WRL::ComPtr<IWICImagingFactory2>     m_wicFactory;
00036
00037     // DirectX Core Objects. Required for 2D and 3D.
00038     Microsoft::WRL::ComPtr<ID3D11Device1>           m_d3dDevice;
00039     Microsoft::WRL::ComPtr<ID3D11DeviceContext1>    m_d3dContext;
00040     Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00041     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00042
00043     // Direct2D Rendering Objects. Required for 2D.
00044     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00046     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00047     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmap;
00048
00049     // Direct3D Rendering Objects. Required for 3D.
00050     Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00051
00052     // Cached renderer properties.
00053     D3D_FEATURE_LEVEL                               m_featureLevel;
00054     Windows::Foundation::Size                       m_renderTargetSize;
00055     Windows::Foundation::Rect                       m_windowBounds;
00056     float                                           m_dpi;
00057     bool                                            m_windowSizeChangeInProgress;
00058 };
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/MediaExtensions/Mpeg1Source/Parse.h Source File

  • Media extensions
  • MediaExtensions
  • Mpeg1Source

Parse.h

Go to the documentation of this file.
00001 //////////////////////////////////////////////////////////////////////////
00002 //
00003 // Parse.h
00004 // MPEG-1 parsing code.
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
00018 // Note: The structs, enums, and constants defined in this header are not taken from
00019 // Media Foundation or DirectShow headers. The parser code is written to be API-agnostic.
00020 // The only exceptions are:
00021 //    - Use of the MFRatio structure to describe ratios.
00022 //    - The MPEG1AudioFlags enum defined here maps directly to the equivalent DirectShow flags.
00023
00024 // Sizes
00025 const DWORD MPEG1_MAX_PACKET_SIZE = 65535 + 6;          // Maximum packet size.
00026 const DWORD MPEG1_PACK_HEADER_SIZE = 12;                // Pack header.
00027
00028 const DWORD MPEG1_SYSTEM_HEADER_MIN_SIZE = 12;          // System header, excluding the stream info.
00029 const DWORD MPEG1_SYSTEM_HEADER_PREFIX = 6;             // This value + header length = total size of the system header.
00030 const DWORD MPEG1_SYSTEM_HEADER_STREAM = 3;             // Size of each stream info in the system header.
00031
00032 const DWORD MPEG1_PACKET_HEADER_MIN_SIZE = 6;           // Minimum amount to read in the packet header. (Up to the variable-sized padding bytes)
00033 const DWORD MPEG1_PACKET_HEADER_MAX_STUFFING_BYTE = 16; // Maximum number of stuffing bytes in a packet header.
00034 const DWORD MPEG1_PACKET_HEADER_MAX_SIZE = 34;          // Maximum size of a packet header.
00035
00036 const DWORD MPEG1_VIDEO_SEQ_HEADER_MIN_SIZE = 12;       // Minimum length of the video sequence header.
00037 const DWORD MPEG1_VIDEO_SEQ_HEADER_MAX_SIZE = 140;      // Maximum length of the video sequence header.
00038
00039 const DWORD MPEG1_AUDIO_FRAME_HEADER_SIZE = 4;
00040
00041
00042 // Codes
00043 const DWORD MPEG1_START_CODE_PREFIX     = 0x00000100;
00044 const DWORD MPEG1_PACK_START_CODE       = 0x000001BA;
00045 const DWORD MPEG1_SYSTEM_HEADER_CODE    = 0x000001BB;
00046 const DWORD MPEG1_SEQUENCE_HEADER_CODE  = 0x000001B3;
00047 const DWORD MPEG1_STOP_CODE             = 0x000001B9;
00048
00049 // Stream ID codes
00050 const BYTE MPEG1_STREAMTYPE_ALL_AUDIO = 0xB8;
00051 const BYTE MPEG1_STREAMTYPE_ALL_VIDEO = 0xB9;
00052 const BYTE MPEG1_STREAMTYPE_RESERVED = 0xBC;
00053 const BYTE MPEG1_STREAMTYPE_PRIVATE1 = 0xBD;
00054 const BYTE MPEG1_STREAMTYPE_PADDING = 0xBE;
00055 const BYTE MPEG1_STREAMTYPE_PRIVATE2 = 0xBF;
00056 const BYTE MPEG1_STREAMTYPE_AUDIO_MASK = 0xC0;
00057 const BYTE MPEG1_STREAMTYPE_VIDEO_MASK = 0xE0;
00058 const BYTE MPEG1_STREAMTYPE_DATA_MASK = 0xF0;
00059
00060
00061
00062 // Systems layer
00063
00064 enum StreamType
00065 {
00066     StreamType_Unknown,
00067     StreamType_AllAudio,
00068     StreamType_AllVideo,
00069     StreamType_Reserved,
00070     StreamType_Private1,
00071     StreamType_Padding,
00072     StreamType_Private2,
00073     StreamType_Audio,   // ISO/IEC 11172-3
00074     StreamType_Video,   // ISO/IEC 11172-2
00075     StreamType_Data
00076 };
00077
00078 struct MPEG1StreamHeader
00079 {
00080     BYTE        stream_id;  // Raw stream_id field.
00081     StreamType  type;       // Stream type (audio, video, etc)
00082     BYTE        number;     // Index within the stream type (audio 0, audio 1, etc)
00083     DWORD       sizeBound;
00084 };
00085
00086 // MPEG1SystemHeader
00087 // Holds information from the system header. This structure is variable
00088 // length, because the last field is an array of stream headers.
00089 struct MPEG1SystemHeader
00090 {
00091     DWORD   cbSize;     // Size of this structure, including the streams array.
00092     DWORD   rateBound;
00093     BYTE    cAudioBound;
00094     BOOL    bFixed;
00095     BOOL    bCSPS;
00096     BOOL    bAudioLock;
00097     BOOL    bVideoLock;
00098     BYTE    cVideoBound;
00099     DWORD   cStreams;
00100     MPEG1StreamHeader streams[1];   // Array of 1 or more stream headers.
00101 };
00102
00103 struct MPEG1PacketHeader
00104 {
00105     BYTE        stream_id;      // Raw stream_id field.
00106     StreamType  type;           // Stream type (audio, video, etc)
00107     BYTE        number;         // Index within the stream type (audio 0, audio 1, etc)
00108     DWORD       cbPacketSize;   // Size of the entire packet (header + payload).
00109     DWORD       cbPayload;      // Size of the packet payload (packet size - header size).
00110     BOOL        bHasPTS;        // Did the packet header contain a Presentation Time Stamp (PTS)?
00111     LONGLONG    PTS;            // Presentation Time Stamp (in 90 kHz clock)
00112 };
00113
00114 // Video
00115
00116 struct MPEG1VideoSeqHeader
00117 {
00118     WORD        width;
00119     WORD        height;
00120     MFRatio     pixelAspectRatio;
00121     MFRatio     frameRate;
00122     DWORD       bitRate;
00123     WORD        cbVBV_Buffer;
00124     BOOL        bConstrained;
00125     DWORD       cbHeader;
00126     BYTE        header[MPEG1_VIDEO_SEQ_HEADER_MAX_SIZE];    // Raw header.
00127 };
00128
00129 // Audio
00130
00131 enum MPEG1AudioLayer
00132 {
00133     MPEG1_Audio_Layer1 = 0,
00134     MPEG1_Audio_Layer2,
00135     MPEG1_Audio_Layer3
00136 };
00137
00138 enum MPEG1AudioMode
00139 {
00140     MPEG1_Audio_Stereo = 0,
00141     MPEG1_Audio_JointStereo,
00142     MPEG1_Audio_DualChannel,
00143     MPEG1_Audio_SingleChannel
00144 };
00145
00146
00147 // Various bit flags used in the audio frame header.
00148 // (Note: These enum values are not the actual values in the audio frame header.)
00149 enum MPEG1AudioFlags
00150 {
00151     MPEG1_AUDIO_PRIVATE_BIT    = 0x01,  // = ACM_MPEG_PRIVATEBIT
00152     MPEG1_AUDIO_COPYRIGHT_BIT  = 0x02,  // = ACM_MPEG_COPYRIGHT
00153     MPEG1_AUDIO_ORIGINAL_BIT   = 0x04,  // = ACM_MPEG_ORIGINALHOME
00154     MPEG1_AUDIO_PROTECTION_BIT = 0x08,  // = ACM_MPEG_PROTECTIONBIT
00155 };
00156
00157
00158 struct MPEG1AudioFrameHeader
00159 {
00160     MPEG1AudioLayer     layer;
00161     DWORD               dwBitRate;        // Bit rate in Kbits / sec
00162     DWORD               dwSamplesPerSec;
00163     WORD                nBlockAlign;
00164     WORD                nChannels;
00165     MPEG1AudioMode      mode;
00166     BYTE                modeExtension;
00167     BYTE                emphasis;
00168     WORD                wFlags;    // bitwise OR of MPEG1AudioFlags
00169 };
00170
00171
00172 // Buffer class:
00173 // Resizable buffer used to hold the MPEG-1 data.
00174
00175 class Buffer
00176 {
00177 public:
00178     Buffer();
00179     ~Buffer()
00180     {
00181         delete [] m_pArray;
00182     }
00183     HRESULT Initalize(DWORD cbSize);
00184
00185     BYTE*   DataPtr();
00186     DWORD   DataSize() const;
00187
00188     // Reserve: Reserves cb bytes of free data in the buffer.
00189     // The reserved bytes start at DataPtr() + DataSize().
00190     HRESULT Reserve(DWORD cb);
00191
00192     // MoveStart: Moves the front of the buffer.
00193     // Call this method after consuming data from the buffer.
00194     HRESULT MoveStart(DWORD cb);
00195
00196     // MoveEnd: Moves the end of the buffer.
00197     // Call this method after reading data into the buffer.
00198     HRESULT MoveEnd(DWORD cb);
00199
00200 private:
00201     BYTE* Ptr() { return m_pArray; }
00202
00203     HRESULT SetSize(DWORD count);
00204     HRESULT Allocate(DWORD alloc);
00205
00206     DWORD   CurrentFreeSize() const;
00207
00208 private:
00209
00210     BYTE       *m_pArray;
00211     DWORD   m_count;        // Nominal count.
00212     DWORD   m_allocated;    // Actual allocation size.
00213
00214     DWORD   m_begin;
00215     DWORD   m_end;  // 1 past the last element
00216 };
00217
00218
00219 // Parser class:
00220 // Parses an MPEG-1 systems-layer stream.
00221 class Parser
00222 {
00223 public:
00224
00225     Parser();
00226     ~Parser();
00227
00228     HRESULT ParseBytes(const BYTE *pData, DWORD cbLen, DWORD *pAte);
00229
00230     BOOL    HasSystemHeader() const { return m_pHeader != NULL; }
00231     HRESULT GetSystemHeader(MPEG1SystemHeader **ppHeader);
00232
00233     BOOL    HasPacket() const { return m_bHasPacketHeader; }
00234     const MPEG1PacketHeader& PacketHeader() { assert(m_bHasPacketHeader); return m_curPacketHeader; }
00235
00236     DWORD   PayloadSize() const { assert(m_bHasPacketHeader); return m_curPacketHeader.cbPayload; }
00237     void    ClearPacket() { m_bHasPacketHeader = FALSE; }
00238
00239     BOOL    IsEndOfStream() const { return m_bEOS; }
00240
00241 private:
00242
00243     HRESULT FindNextStartCode(const BYTE *pData, DWORD cbLen, DWORD *pAte);
00244     HRESULT ParsePackHeader(const BYTE *pData, DWORD cbLen, DWORD *pAte);
00245     HRESULT ParseSystemHeader(const BYTE *pData, DWORD cbLen, DWORD *pAte);
00246     HRESULT ParsePacketHeader(const BYTE *pData, DWORD cbLen, DWORD *pAte);
00247     HRESULT OnEndOfStream();
00248
00249 private:
00250
00251     LONGLONG            m_SCR;
00252     DWORD               m_muxRate;
00253
00254     MPEG1SystemHeader   *m_pHeader;
00255     // Note: Size of header = sizeof(MPEG1SystemHeader) + (sizeof(MPEG1StreamHeader) * (cStreams - 1))
00256
00257     BOOL                m_bHasPacketHeader;
00258     MPEG1PacketHeader   m_curPacketHeader;  // Most recent packet header.
00259
00260     BOOL                m_bEOS;
00261 };
00262
00263
00264 HRESULT ReadVideoSequenceHeader(_In_reads_bytes_(cbData) const BYTE *pData, DWORD cbData, MPEG1VideoSeqHeader& seqHeader, _Out_ DWORD *pAte);
00265
00266 HRESULT ReadAudioFrameHeader(const BYTE *pData, DWORD cbData, MPEG1AudioFrameHeader& audioHeader, DWORD *pAte);
Generated on Sat Nov 23 2024 16:08:21 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::ThreadPool::ThreadPoolSample Member List

This is the complete list of members for SDKSample::ThreadPool::ThreadPoolSample, including all inherited members.
GetStatusString(ThreadPool::Status status) | SDKSample::ThreadPool::ThreadPoolSample | [static]
MillisecondsToTimeSpan(long milliseconds) | SDKSample::ThreadPool::ThreadPoolSample | [static]
Generated on Sat Nov 23 2024 16:09:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::TileContent::TileWidePeekImageCollection02 Member List

This is the complete list of members for NotificationsExtensions::TileContent::TileWidePeekImageCollection02, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
Branding | NotificationsExtensions::TileContent::TileNotificationBase |
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
ImageMain | NotificationsExtensions::TileContent::TileWidePeekImageCollection02 |
Images | NotificationsExtensions::NotificationBase |
ImageSmallColumn1Row1 | NotificationsExtensions::TileContent::TileWidePeekImageCollection02 |
ImageSmallColumn1Row2 | NotificationsExtensions::TileContent::TileWidePeekImageCollection02 |
ImageSmallColumn2Row1 | NotificationsExtensions::TileContent::TileWidePeekImageCollection02 |
ImageSmallColumn2Row2 | NotificationsExtensions::TileContent::TileWidePeekImageCollection02 |
Lang | NotificationsExtensions::NotificationBase |
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
RequireSquareContent | NotificationsExtensions::TileContent::TileWideBase |
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SquareContent | NotificationsExtensions::TileContent::TileWideBase |
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextBody1 | NotificationsExtensions::TileContent::TileWidePeekImageCollection02 |
TextBody2 | NotificationsExtensions::TileContent::TileWidePeekImageCollection02 |
TextBody3 | NotificationsExtensions::TileContent::TileWidePeekImageCollection02 |
TextBody4 | NotificationsExtensions::TileContent::TileWidePeekImageCollection02 |
TextFields | NotificationsExtensions::NotificationBase |
TextHeading | NotificationsExtensions::TileContent::TileWidePeekImageCollection02 |
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWidePeekImageCollection02() | NotificationsExtensions::TileContent::TileWidePeekImageCollection02 | [inline]
TileWidePeekImageCollection02() | NotificationsExtensions::TileContent::TileWidePeekImageCollection02 | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:44 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAudio2 audio file playback/C++/DirectXSample.h Source File

  • XAudio2 audio file playback

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
00010 // This header defines helper utilities to make DirectX APIs work with exceptions.
00011 namespace DX
00012 {
00013     inline void ThrowIfFailed(HRESULT hr)
00014     {
00015         if (FAILED(hr))
00016         {
00017             // Set a breakpoint on this line to catch DX API errors.
00018             throw Platform::Exception::CreateException(hr);
00019         }
00020     }
00021 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Credential locker/C++/App.xaml.cpp Source File

  • Credential locker

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: OrientationSensor/C++/Constants.cpp Source File

  • OrientationSensor

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     { "Orientation sensor data events", "SDKSample.OrientationSensorCPP.Scenario1" },
00020     { "Poll orientation sensor readings", "SDKSample.OrientationSensorCPP.Scenario2" }
00021 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File and folder thumbnail/C++/pch.cpp Source File

  • File and folder thumbnail

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D perspective transform/C++/D2DPerspectiveTransform.h Source File

  • Direct2D perspective transform

D2DPerspectiveTransform.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 "DirectXBase.h"
00011 #include "SampleOverlay.h"
00012
00013 ref class D2DPerspectiveTransform : public DirectXBase, public Windows::ApplicationModel::Core::IFrameworkView
00014 {
00015 internal:
00016     D2DPerspectiveTransform();
00017
00018     // DirectXBase Methods
00019     virtual void CreateDeviceIndependentResources() override;
00020     virtual void CreateDeviceResources() override;
00021     virtual void CreateWindowSizeDependentResources() override;
00022     virtual void Render() override;
00023
00024 public:
00025     // IFrameworkView Methods
00026     virtual void Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00027     virtual void SetWindow(_In_ Windows::UI::Core::CoreWindow^ window);
00028     virtual void Load(_In_ Platform::String^ entryPoint);
00029     virtual void Run();
00030     virtual void Uninitialize();
00031
00032 private:
00033     // Event Handlers
00034     void OnWindowSizeChanged(
00035         _In_ Windows::UI::Core::CoreWindow^ sender,
00036         _In_ Windows::UI::Core::WindowSizeChangedEventArgs^ args
00037         );
00038
00039     void OnLogicalDpiChanged(
00040         _In_ Platform::Object^ sender
00041         );
00042
00043     void OnDisplayContentsInvalidated(
00044         _In_ Platform::Object^ sender
00045         );
00046
00047     void OnActivated(
00048         _In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView,
00049         _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^ args
00050         );
00051
00052     void OnSuspending(
00053         _In_ Platform::Object^ sender,
00054         _In_ Windows::ApplicationModel::SuspendingEventArgs^ args
00055         );
00056
00057     void OnResuming(
00058         _In_ Platform::Object^ sender,
00059         _In_ Platform::Object^ args
00060         );
00061
00062     // Declare event handlers for responding to touch gestures
00063     void OnPointerPressed(
00064         _In_ Windows::UI::Core::CoreWindow^ window,
00065         _In_ Windows::UI::Core::PointerEventArgs^ args
00066         );
00067
00068     void OnPointerReleased(
00069         _In_ Windows::UI::Core::CoreWindow^ window,
00070         _In_ Windows::UI::Core::PointerEventArgs^ args
00071         );
00072
00073     void OnPointerMoved(
00074         _In_ Windows::UI::Core::CoreWindow^ window,
00075         _In_ Windows::UI::Core::PointerEventArgs^ args
00076         );
00077
00078     // Declare GestureRecognizer Event Handlers
00079     void OnManipulationUpdated(
00080         _In_ Windows::UI::Input::GestureRecognizer^ recognizer,
00081         _In_ Windows::UI::Input::ManipulationUpdatedEventArgs^ args
00082         );
00083
00084     SampleOverlay^                                          m_sampleOverlay;
00085     Microsoft::WRL::ComPtr<ID2D1Bitmap1>                    m_bitmapPerspective;
00086     Platform::Agile<Windows::UI::Input::GestureRecognizer>  m_gestureRecognizer;
00087     float                                                   m_rotationAngle;
00088 };
00089
00090 ref class DirectXAppSource : Windows::ApplicationModel::Core::IFrameworkViewSource
00091 {
00092 public:
00093     virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00094 };
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/GameHud.h Source File

  • DirectX 3D shooting game

GameHud.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 // GameHud:
00011 // This class maintains the resources necessary to draw the Heads Up Display, which is a
00012 // 2D overlay on top of the main 3D graphics generated for the game.
00013 // The GameHud Render method expects to be called within the context of a D2D BeginDraw
00014 // and makes D2D drawing calls to draw the text elements on the window.
00015
00016 #include "Simple3DGame.h"
00017 #include "DirectXSample.h"
00018
00019 ref class Simple3DGame;
00020
00021 ref class GameHud
00022 {
00023 internal:
00024     GameHud(
00025         _In_ Platform::String^ titleHeader,
00026         _In_ Platform::String^ titleBody
00027         );
00028
00029     void CreateDeviceIndependentResources(
00030         _In_ IDWriteFactory* dwriteFactory,
00031         _In_ IWICImagingFactory* wicFactory
00032         );
00033
00034     void CreateDeviceResources(_In_ ID2D1DeviceContext* d2dContext);
00035     void UpdateForWindowSizeChange(_In_ Windows::Foundation::Rect windowBounds);
00036     void Render(
00037         _In_ Simple3DGame^ game,
00038         _In_ ID2D1DeviceContext* d2dContext,
00039         _In_ Windows::Foundation::Rect windowBounds
00040         );
00041
00042 private:
00043     Microsoft::WRL::ComPtr<IDWriteFactory>              m_dwriteFactory;
00044     Microsoft::WRL::ComPtr<IWICImagingFactory>          m_wicFactory;
00045
00046     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>        m_textBrush;
00047     Microsoft::WRL::ComPtr<IDWriteTextFormat>           m_textFormatBody;
00048     Microsoft::WRL::ComPtr<IDWriteTextFormat>           m_textFormatBodySymbol;
00049
00050     Microsoft::WRL::ComPtr<IDWriteTextFormat>           m_textFormatTitleHeader;
00051     Microsoft::WRL::ComPtr<IDWriteTextFormat>           m_textFormatTitleBody;
00052     Microsoft::WRL::ComPtr<ID2D1Bitmap>                 m_logoBitmap;
00053     Microsoft::WRL::ComPtr<IDWriteTextLayout>           m_titleHeaderLayout;
00054     Microsoft::WRL::ComPtr<IDWriteTextLayout>           m_titleBodyLayout;
00055
00056     bool                                                m_showTitle;
00057     Platform::String^                                   m_titleHeader;
00058     Platform::String^                                   m_titleBody;
00059
00060     float                                               m_titleBodyVerticalOffset;
00061     D2D1_SIZE_F                                         m_logoSize;
00062     D2D1_SIZE_F                                         m_maxTitleSize;
00063 };
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/ImageViewModel.cpp Source File

  • Hilo C++
  • Hilo

ImageViewModel.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 #include "ImageNavigationData.h"
00009 #include "ImageViewModel.h"
00010 #include "IPhoto.h"
00011 #include "IPhotoGroup.h"
00012 #include "DelegateCommand.h"
00013 #include "TaskExceptionsExtensions.h"
00014 #include "Repository.h"
00015 #include "CalendarExtensions.h"
00016
00017 using namespace concurrency;
00018 using namespace Hilo;
00019 using namespace Platform;
00020 using namespace Platform::Collections;
00021 using namespace std;
00022 using namespace Windows::Foundation;
00023 using namespace Windows::Foundation::Collections;
00024 using namespace Windows::UI::ViewManagement;
00025 using namespace Windows::UI::Xaml::Input;
00026 using namespace Windows::UI::Xaml::Navigation;
00027
00028 String^ const QueryMapKey = "query";
00029 String^ const FilePathMapKey = "filePath";
00030 String^ const FileDateMapKey = "fileDate";
00031
00032 ImageViewModel::ImageViewModel(shared_ptr<Repository> repository, shared_ptr<ExceptionPolicy> exceptionPolicy) :
00033     ViewModelBase(exceptionPolicy), m_repository(repository)
00034 {
00035     m_cropImageCommand = ref new DelegateCommand(
00036         ref new ExecuteDelegate(this, &ImageViewModel::CropImage),
00037         ref new CanExecuteDelegate(this, &ImageViewModel::CanProcessImage));
00038     m_rotateImageCommand = ref new DelegateCommand(
00039         ref new ExecuteDelegate(this, &ImageViewModel::RotateImage),
00040         ref new CanExecuteDelegate(this, &ImageViewModel::CanProcessImage));
00041     m_cartoonizeImageCommand = ref new DelegateCommand(
00042         ref new ExecuteDelegate(this, &ImageViewModel::CartoonizeImage),
00043         ref new CanExecuteDelegate(this, &ImageViewModel::CanProcessImage));
00044
00045     auto wr = WeakReference(this);
00046     function<void()> callback = [wr] {
00047         auto vm = wr.Resolve<ImageViewModel>();
00048         if (nullptr != vm)
00049         {
00050             vm->OnDataChanged();
00051         }
00052     };
00053     m_repository->AddObserver(callback, PageType::Image);
00054 }
00055
00056 ImageViewModel::~ImageViewModel()
00057 {
00058     if (nullptr != m_repository)
00059     {
00060         m_repository->RemoveObserver(PageType::Image);
00061     }
00062 }
00063
00064 ICommand^ ImageViewModel::CropImageCommand::get()
00065 {
00066     return m_cropImageCommand;
00067 }
00068
00069 ICommand^ ImageViewModel::RotateImageCommand::get()
00070 {
00071     return m_rotateImageCommand;
00072 }
00073
00074 ICommand^ ImageViewModel::CartoonizeImageCommand::get()
00075 {
00076     return m_cartoonizeImageCommand;
00077 }
00078
00079 IObservableVector<IPhoto^>^ ImageViewModel::Photos::get()
00080 {
00081     if (m_photos == nullptr)
00082     {
00083         OnDataChanged();
00084     }
00085     return m_photos;
00086 }
00087
00088 task<void> ImageViewModel::QueryPhotosAsync()
00089 {
00090     assert(IsMainThread());
00091     if (m_photos == nullptr)
00092     {
00093         m_photos = ref new Vector<IPhoto^, PhotoPathComparer>();
00094     }
00095
00096     m_photosCts = cancellation_token_source();
00097     cancellation_token token = m_photosCts.get_token();
00098     auto t = m_repository->GetPhotosForDateRangeQueryAsync(m_query);
00099     return t.then([this](IVectorView<IPhoto^>^ photos)
00100     {
00101         assert(IsBackgroundThread());
00102         auto temp = ref new Vector<IPhoto^>();
00103         for (auto photo : photos)
00104         {
00105             temp->Append(photo);
00106         };
00107         return temp;
00108     }, task_continuation_context::use_arbitrary()).then([this](Vector<IPhoto^>^ temp)
00109     {
00110         assert(IsMainThread());
00111         auto size = temp->Size;
00112         if (size > 0)
00113         {
00114             Array<IPhoto^>^ many = ref new Array<IPhoto^>(temp->Size);
00115             temp->GetMany(0, many);
00116             m_photos->ReplaceAll(many);
00117         }
00118         else
00119         {
00120             m_photo = nullptr;
00121         }
00122
00123     }).then([this](task<void> priorTask)
00124     {
00125         assert(IsMainThread());
00126         try
00127         {
00128             priorTask.get();
00129         }
00130         catch(const concurrency::task_canceled &)
00131         {
00132             // Didn't load the photos so reset the underlying items.
00133             m_photos = nullptr;
00134         };
00135     });
00136 }
00137
00138 Object^ ImageViewModel::SelectedItem::get()
00139 {
00140     if (nullptr == m_photo && !m_runningQuerySinglePhotoAsync)
00141     {
00142         m_runningQuerySinglePhotoAsync = true;
00143
00144         QuerySinglePhotoAsync().then([this](task<void> priorTask)
00145         {
00146             assert(IsMainThread());
00147             m_runningQuerySinglePhotoAsync = false;
00148             priorTask.get();
00149             OnPropertyChanged("SelectedItem");
00150         }).then(ObserveException<void>(m_exceptionPolicy));
00151     }
00152     return m_photo;
00153 }
00154
00155 void ImageViewModel::SelectedItem::set(Object^ value)
00156 {
00157     IPhoto^ newPhoto = dynamic_cast<IPhoto^>(value);
00158     PhotoPathComparer compare;
00159     bool equal = compare(m_photo, newPhoto);
00160
00161     if (!equal && nullptr != newPhoto && !m_runningQuerySinglePhotoAsync)
00162     {
00163         ClearCachedData();
00164         m_photo = newPhoto;
00165         bool result = CanProcessImage(nullptr);
00166         m_rotateImageCommand->CanExecute(result);
00167         m_cropImageCommand->CanExecute(result);
00168         m_cartoonizeImageCommand->CanExecute(result);
00169         OnPropertyChanged("SelectedItem");
00170     }
00171 }
00172
00173 String^ ImageViewModel::MonthAndYear::get()
00174 {
00175     return CalendarExtensions::GetLocalizedMonthAndYear(m_fileDate);
00176 }
00177
00178 // See http://go.microsoft.com/fwlink/?LinkId=267280 for more info on Hilo's implementation of suspend/resume.
00179 void ImageViewModel::SaveState(IMap<String^, Object^>^ stateMap)
00180 {
00181     if (m_photo != nullptr)
00182     {
00183         std::wstringstream stringSerialization;
00184         stringSerialization << m_photo->DateTaken.UniversalTime ;
00185
00186         stateMap->Insert(FilePathMapKey, m_photo->Path);
00187         stateMap->Insert(FileDateMapKey, ref new String(stringSerialization.str().c_str()));
00188         stateMap->Insert(QueryMapKey, m_query);
00189     }
00190 }
00191
00192 // See http://go.microsoft.com/fwlink/?LinkId=267280 for more info on Hilo's implementation of suspend/resume.
00193 void ImageViewModel::LoadState(IMap<String^, Object^>^ stateMap)
00194 {
00195     if (stateMap != nullptr)
00196     {
00197         auto filePath = dynamic_cast<String^>(stateMap->Lookup(FilePathMapKey));
00198
00199         auto fileDateString = dynamic_cast<String^>(stateMap->Lookup(FileDateMapKey));
00200         DateTime fileDate;
00201         fileDate.UniversalTime = _wtoi64(fileDateString->Data());
00202
00203         auto query = dynamic_cast<String^>(stateMap->Lookup(QueryMapKey));
00204
00205         Initialize(filePath, fileDate, query);
00206     }
00207 }
00208
00209 task<void> ImageViewModel::QuerySinglePhotoAsync()
00210 {
00211     assert(IsMainThread());
00212
00213     m_photoCts.cancel();
00214     m_photoCts = cancellation_token_source();
00215     auto token = m_photoCts.get_token();
00216
00217     if (m_filePath == nullptr) return create_empty_task();
00218
00219     auto photoTask = m_repository->GetSinglePhotoAsync(m_filePath);
00220     return photoTask.then([this](IPhoto^ photo)
00221     {
00222         assert(IsMainThread());
00223         if (photo == nullptr)
00224         {
00225             GoHome();
00226             cancel_current_task();
00227         }
00228         m_photo = photo;
00229     }).then([this](task<void> priorTask)
00230     {
00231         assert(IsMainThread());
00232         try
00233         {
00234             priorTask.get();
00235         }
00236         catch (const concurrency::task_canceled&)
00237         {
00238             m_photo = nullptr;
00239         }
00240     });
00241 }
00242
00243 // See http://go.microsoft.com/fwlink/?LinkId=267280 for more info on Hilo's implementation of suspend/resume.
00244 void ImageViewModel::OnNavigatedTo(NavigationEventArgs^ e)
00245 {
00246     auto data = dynamic_cast<String^>(e->Parameter);
00247     ImageNavigationData imageData(data);
00248     Initialize(imageData.GetFilePath(), imageData.GetFileDate(), imageData.GetDateQuery());
00249 }
00250
00251 void ImageViewModel::OnNavigatedFrom(NavigationEventArgs^ e)
00252 {
00253     m_photoCts.cancel();
00254     m_photosCts.cancel();
00255     ClearCachedData();
00256 }
00257
00258 void ImageViewModel::Initialize(String^ filePath, DateTime fileDate, String^ query)
00259 {
00260     m_filePath = filePath;
00261     m_fileDate = fileDate;
00262     m_query = query;
00263     m_photos = nullptr;
00264     m_photo = nullptr;
00265     m_runningQuerySinglePhotoAsync = false;
00266     m_runningQueryPhotosAsync = false;
00267 }
00268
00269 String^ ImageViewModel::GetStateFilePath()
00270 {
00271     return m_filePath;
00272 }
00273
00274 String^ ImageViewModel::GetStateQuery()
00275 {
00276     return m_query;
00277 }
00278
00279 DateTime ImageViewModel::GetStateFileDate()
00280 {
00281     return m_fileDate;
00282 }
00283
00284 void ImageViewModel::CropImage(Object^ parameter)
00285 {
00286     ImageNavigationData data(m_photo);
00287     ViewModelBase::GoToPage(PageType::Crop, data.SerializeToString());
00288 }
00289
00290 void ImageViewModel::RotateImage(Object^ parameter)
00291 {
00292     ImageNavigationData data(m_photo);
00293     ViewModelBase::GoToPage(PageType::Rotate, data.SerializeToString());
00294 }
00295
00296 void ImageViewModel::CartoonizeImage(Object^ parameter)
00297 {
00298     ImageNavigationData data(m_photo);
00299     ViewModelBase::GoToPage(PageType::Cartoonize, data.SerializeToString());
00300 }
00301
00302 bool ImageViewModel::CanProcessImage(Object^ parameter)
00303 {
00304     return (m_photo != nullptr && !m_photo->IsInvalidThumbnail);
00305 }
00306
00307 void ImageViewModel::OnDataChanged()
00308 {
00309     assert(IsMainThread());
00310
00311     if (m_runningQueryPhotosAsync)
00312     {
00313         m_receivedChangeWhileRunning = true;
00314     }
00315
00316     if (!m_runningQueryPhotosAsync)
00317     {
00318         m_runningQueryPhotosAsync = true;
00319         run_async_non_interactive([this]()
00320         {
00321             QueryPhotosAsync().then([this]
00322             {
00323                 assert(IsMainThread());
00324                 if (!m_receivedChangeWhileRunning)
00325                 {
00326                     OnPropertyChanged("Photos");
00327                     OnPropertyChanged("SelectedItem");
00328                 }
00329                 m_runningQueryPhotosAsync = false;
00330                 if (m_receivedChangeWhileRunning)
00331                 {
00332                     m_receivedChangeWhileRunning = false;
00333                     OnDataChanged();
00334                 }
00335             }).then(ObserveException<void>(m_exceptionPolicy));
00336         });
00337     }
00338 }
00339
00340 void ImageViewModel::ClearCachedData()
00341 {
00342     assert(IsMainThread());
00343
00344     if (m_photo != nullptr)
00345     {
00346         m_photo->ClearImageData();
00347     }
00348 }
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::FlipViewCPP::sealed Member List

This is the complete list of members for SDKSample::FlipViewCPP::sealed, including all inherited members.
__pad0__ | SDKSample::FlipViewCPP::sealed |
bHorizontal | SDKSample::FlipViewCPP::sealed | [private]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::FlipViewCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::FlipViewCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::FlipViewCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::FlipViewCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::FlipViewCPP::sealed | [protected, virtual]
Orientation_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::FlipViewCPP::sealed | [protected]
Orientation_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::FlipViewCPP::sealed | [private]
rootPage | SDKSample::FlipViewCPP::sealed | [private]
Scenario1() | SDKSample::FlipViewCPP::sealed |
Scenario2() | SDKSample::FlipViewCPP::sealed |
Scenario3() | SDKSample::FlipViewCPP::sealed |
Scenario4() | SDKSample::FlipViewCPP::sealed |
Scenario5() | SDKSample::FlipViewCPP::sealed |
SelectTemplateCore(Platform::Object^item, Windows::UI::Xaml::DependencyObject^container) override | SDKSample::FlipViewCPP::sealed | [inline, protected, virtual]
TOCButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::FlipViewCPP::sealed | [private]
Generated on Sat Nov 23 2024 16:09:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Mobile broadband account provisioning/C++/Constants.cpp Source File

  • Mobile broadband account provisioning

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
00021     { "Provision for mobile network operators", "SDKSample.ProvisioningAgent.ProvisionMno" },
00022     { "Update profile cost", "SDKSample.ProvisioningAgent.UpdateCost" },
00023     { "Update profile data usage", "SDKSample.ProvisioningAgent.UpdateUsage" },
00024     { "Provision for other operators", "SDKSample.ProvisioningAgent.ProvisionOtherOperator" }
00025 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Reading and writing data/C++/WriteReadStream.xaml.h Source File

  • Reading and writing data

WriteReadStream.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 // WriteReadStream.xaml.h
00013 // Declaration of the WriteReadStream class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "WriteReadStream.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace DataReaderWriter
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 WriteReadStream sealed
00031         {
00032         public:
00033             WriteReadStream();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void TransferData(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:08:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Clipboard app/C++/MainPage.xaml.h Source File

  • Clipboard app

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace Clipboard
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     [Windows::Foundation::Metadata::WebHostHidden]
00052     public ref class MainPage sealed
00053     {
00054     public:
00055         MainPage();
00056
00057         property bool AutoSizeInputSectionWhenSnapped
00058         {
00059             bool get()
00060             {
00061                 return autoSizeInputSectionWhenSnapped;
00062             }
00063
00064             void set(bool value)
00065             {
00066                 autoSizeInputSectionWhenSnapped = value;
00067             }
00068         }
00069
00070         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00071
00072         void NotifyUserBackgroundThread(Platform::String^ message, NotifyType type);
00073         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00074         void LoadScenario(Platform::String^ scenarioName);
00075         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00076         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00077
00078     private:
00079         void SetFeatureName(Platform::String^ strFeature);
00080         void PopulateScenarios();
00081         void InvalidateSize();
00082         void InvalidateViewState();
00083         ~MainPage();
00084
00085         Platform::Collections::Vector<Object^>^ ScenarioList;
00086         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00087         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00088         bool autoSizeInputSectionWhenSnapped;
00089
00090     protected:
00091         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00092         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00093         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00094
00095     internal:
00096         static MainPage^ Current;
00097     };
00098 }
Generated on Sat Nov 23 2024 16:07:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::SplashScreen::sealed Member List

This is the complete list of members for SDKSample::SplashScreen::sealed, including all inherited members.
__pad0__ | SDKSample::SplashScreen::sealed | [private]
dismissed | SDKSample::SplashScreen::sealed | [private]
DismissedEventHandler(Windows::ApplicationModel::Activation::SplashScreen^sender, Object^e) | SDKSample::SplashScreen::sealed | [private]
ExtendedSplash(Windows::ApplicationModel::Activation::SplashScreen^splash, bool loadState) | SDKSample::SplashScreen::sealed |
ExtendedSplash_OnResize(Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | SDKSample::SplashScreen::sealed | [private]
LearnMoreButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::SplashScreen::sealed | [private]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::SplashScreen::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::SplashScreen::sealed | [protected, virtual]
PositionImage() | SDKSample::SplashScreen::sealed | [private]
rootFrame | SDKSample::SplashScreen::sealed | [private]
Scenario1() | SDKSample::SplashScreen::sealed |
Scenario2() | SDKSample::SplashScreen::sealed |
splash | SDKSample::SplashScreen::sealed | [private]
Generated on Sat Nov 23 2024 16:09:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Network status background/C++/NetworkStatusApp/pch.cpp Source File

  • Network status background
  • NetworkStatusApp

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/BasicReaderWriter.h Source File

  • Direct3D resource loading

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     Platform::String^ m_locationPath;
00019
00020 internal:
00021     BasicReaderWriter();
00022     BasicReaderWriter(
00023         _In_ Windows::Storage::StorageFolder^ folder
00024         );
00025
00026     Platform::Array<byte>^ ReadData(
00027         _In_ Platform::String^ filename
00028         );
00029
00030     concurrency::task<Platform::Array<byte>^> ReadDataAsync(
00031         _In_ Platform::String^ filename
00032         );
00033
00034     uint32 WriteData(
00035         _In_ Platform::String^ filename,
00036         _In_ const Platform::Array<byte>^ fileData
00037         );
00038
00039     concurrency::task<void> WriteDataAsync(
00040         _In_ Platform::String^ filename,
00041         _In_ const Platform::Array<byte>^ fileData
00042         );
00043 };
Generated on Sat Nov 23 2024 16:08:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX marble maze game/C++/DirectXBase.h Source File

  • DirectX marble maze game

DirectXBase.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 "DirectXSample.h"
00011
00012 // Helper class that initializes DirectX APIs for both 2D and 3D rendering.
00013 // Some of the code in this class may be omitted if only 2D or only 3D rendering is being used.
00014 ref class DirectXBase abstract
00015 {
00016 internal:
00017     DirectXBase();
00018
00019     virtual void Initialize(Windows::UI::Core::CoreWindow^ window, float dpi);
00020     virtual void HandleDeviceLost();
00021     virtual void CreateDeviceIndependentResources();
00022     virtual void CreateDeviceResources();
00023     virtual void SetDpi(float dpi);
00024     virtual void UpdateForWindowSizeChange();
00025     virtual void CreateWindowSizeDependentResources();
00026     virtual void Render() = 0;
00027     virtual void Present();
00028     void ValidateDevice();
00029
00030 protected private:
00031     Platform::Agile<Windows::UI::Core::CoreWindow>  m_window;
00032
00033     // DirectWrite & Windows Imaging Component Objects.
00034     Microsoft::WRL::ComPtr<IDWriteFactory1>         m_dwriteFactory;
00035     Microsoft::WRL::ComPtr<IWICImagingFactory2>     m_wicFactory;
00036
00037     // DirectX Core Objects. Required for 2D and 3D.
00038     Microsoft::WRL::ComPtr<ID3D11Device1>           m_d3dDevice;
00039     Microsoft::WRL::ComPtr<ID3D11DeviceContext1>    m_d3dContext;
00040     Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00041     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00042
00043     // Direct2D Rendering Objects. Required for 2D.
00044     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00046     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00047     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmap;
00048
00049     // Direct3D Rendering Objects. Required for 3D.
00050     Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00051
00052     // Cached renderer properties.
00053     D3D_FEATURE_LEVEL                               m_featureLevel;
00054     Windows::Foundation::Size                       m_renderTargetSize;
00055     Windows::Foundation::Rect                       m_windowBounds;
00056     float                                           m_dpi;
00057     bool                                            m_windowSizeChangeInProgress;
00058 };
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Web authentication broker/C++/MainPage.xaml.cpp Source File

  • Web authentication broker

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:44 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Print/C++/ScenarioInput5.xaml.h Source File

  • Print

ScenarioInput5.xaml.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 //
00009 // ScenarioInput5.xaml.h
00010 // Declaration of the ScenarioInput5 class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioInput5.g.h"
00017 #include "MainPage.xaml.h"
00018 #include "DisplayContent.h"
00019
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Printing;
00022
00023 namespace PrintSample
00024 {
00025     class InvalidPageException
00026     {
00027     private:
00028         std::wstring m_displayMessage;
00029
00030     public:
00031
00032         InvalidPageException(std::wstring &message)
00033         {
00034             m_displayMessage = message;
00035         }
00036
00037         ~InvalidPageException()
00038         {
00039         }
00040
00041         std::wstring get_DisplayMessage()
00042         {
00043             return m_displayMessage;
00044         }
00045     };
00046
00047
00048     /// <summary>
00049     /// Scenario that demos a page range implementation
00050     /// </summary>
00051     [Windows::Foundation::Metadata::WebHostHidden]
00052     public ref class ScenarioInput5 sealed
00053     {
00054     public:
00055         ScenarioInput5();
00056
00057     protected:
00058         virtual void PreparetPrintContent() override;
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         virtual void PrintTaskRequested(Windows::Graphics::Printing::PrintManager^ sender, Windows::Graphics::Printing::PrintTaskRequestedEventArgs^ e) override;
00069
00070
00071         /// <summary>
00072         /// Removes pages that are not in the given range
00073         /// </summary>
00074         /// <param name="sender">The list of preview pages</param>
00075         /// <param name="e"></param>
00076         /// <note> Handling preview for page range
00077         /// Developers have the control over how the preview should look when the user specifies a valid page range.
00078         /// There are three common ways to handle this:
00079         /// 1) Preview remains unaffected by the page range and all the pages are shown independent of the specified page range.
00080         /// 2) Preview is changed and only the pages specified in the range are shown to the user.
00081         /// 3) Preview is changed, showing all the pages and graying out the pages not in page range.
00082         /// We chose option (2) for this sample, developers can choose their preview option.
00083         /// </note>
00084         virtual void OnContentCreated() override;
00085
00086
00087         /// <summary>
00088         /// This function creates and adds one print preview page to the internal cache of print preview
00089         /// pages stored in m_printPreviewPages.
00090         /// </summary>
00091         /// <param name="lastRTBOAdded">Last RichTextBlockOverflow element added in the current content</param>
00092         /// <param name="printPageDescription">Printer's page description</param>
00093         virtual RichTextBlockOverflow^ AddOnePrintPreviewPage(RichTextBlockOverflow^ lastRTBOAdded, Windows::Graphics::Printing::PrintPageDescription printPageDescription) override;
00094
00095     private:
00096
00097         /// <summary>
00098         /// Determines if the Page Range Edit option is visible
00099         /// </summary>
00100         bool                                                m_pageRangeEditVisible;
00101
00102         /// <summary>
00103         /// Collection used to hold the pages in the specified range option
00104         /// </summary>
00105         std::vector<int>                                    m_pageList;
00106
00107         /// <summary>
00108         /// Number of total pages determined by the current combination of settings (without page range)
00109         /// </summary>
00110         size_t                                              m_totalPages;
00111
00112         /// <summary>
00113         /// Flag used to determine if content selection mode is on
00114         /// </summary>
00115         bool                                                m_selectionMode;
00116
00117         /// <summary>
00118         /// Option change event handler
00119         /// </summary>
00120         /// <param name="sender">PrintTaskOptionsDetails object</param>
00121         /// <param name="args">the event arguments containing the changed option id</param>
00122         void printDetailedOptions_OptionChanged(Windows::Graphics::Printing::OptionDetails::PrintTaskOptionDetails^ sender,
00123                                                 Windows::Graphics::Printing::OptionDetails::PrintTaskOptionChangedEventArgs^ args);
00124
00125         /// <summary>
00126         /// Helper function used to triger a preview refresh
00127         /// </summary>
00128         void RefreshPreview();
00129
00130         /// <summary>
00131         /// Helper function used to split a string based on some delimiters
00132         /// </summary>
00133         /// <param name="string">String to be splited</param>
00134         /// <param name="delimiter">Delimiter character used to split the string</param>
00135         /// <param name="words">Splited (output)words</param>
00136         void SplitString(String^ string, wchar_t delimiter, std::vector<std::wstring>& words);
00137
00138         /// <summary>
00139         /// This is where we parse the range field
00140         /// </summary>
00141         /// <param name="pageRange">the page range value</param>
00142         void GetPagesInRange(String^ pageRange);
00143
00144         /// <summary>
00145         /// Removes the PageRange edit from the charm window
00146         /// </summary>
00147         /// <param name="printTaskOptionDetails">Details regarding PrintTaskOptions</param>
00148         void RemovePageRangeEdit(Windows::Graphics::Printing::OptionDetails::PrintTaskOptionDetails^ printTaskOptionDetails);
00149
00150         void ShowContent(String^ selectionText);
00151
00152     public:
00153         virtual void OnNavigatedTo(NavigationEventArgs^ e) override;
00154         virtual void OnNavigatedFrom(NavigationEventArgs^ e) override;
00155     };
00156 }
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Real-time communication/C++/App.xaml.h Source File

  • Real-time communication

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SimpleCommunication
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028
00029     public:
00030         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00031         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00032
00033     private:
00034         void SetupWindowing(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs);
00035     };
00036 }
00037
00038
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/YearGroup.h Source File

  • Hilo C++
  • Hilo

YearGroup.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
00009 #include "IYearGroup.h"
00010
00011 namespace Hilo
00012 {
00013     interface class IMonthBlock;
00014     class ExceptionPolicy;
00015     class Repository;
00016
00017     // The YearGroup class provides the data for the image browser's zoomed-out view of the user's picture library.
00018     [Windows::UI::Xaml::Data::Bindable]
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class YearGroup sealed : public IYearGroup, public Windows::UI::Xaml::Data::INotifyPropertyChanged
00021     {
00022     internal:
00023         YearGroup(Windows::Foundation::DateTime yearDate, Windows::Storage::Search::IStorageFolderQueryOperations^ folderQuery, std::shared_ptr<Repository> repository, std::shared_ptr<ExceptionPolicy> exceptionPolicy);
00024
00025     public:
00026         virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler^ PropertyChanged;
00027
00028         property Platform::String^ Title
00029         {
00030             virtual Platform::String^ get();
00031         }
00032
00033         property int Year
00034         {
00035             virtual int get();
00036         }
00037
00038         property Windows::Foundation::Collections::IObservableVector<IMonthBlock^>^ Items
00039         {
00040             virtual Windows::Foundation::Collections::IObservableVector<IMonthBlock^>^ get();
00041         }
00042
00043     private:
00044         Platform::String^ m_name;
00045         Windows::Foundation::DateTime m_yearDate;
00046         std::shared_ptr<ExceptionPolicy> m_exceptionPolicy;
00047         std::shared_ptr<Repository> m_repository;
00048         int m_year;
00049         Platform::Collections::Vector<IMonthBlock^>^ m_months;
00050         Windows::Storage::Search::IStorageFolderQueryOperations^ m_folderQuery;
00051
00052         void OnPropertyChanged(Platform::String^ propertyName);
00053     };
00054 }
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File access/C++/common/suspensionmanager.h Source File

  • File access
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

VideoView Member List

This is the complete list of members for VideoView, including all inherited members.
__pad0__ | VideoView |
Initialize(_In_ Platform::Agile< Windows::UI::Core::CoreWindow > window, _In_ Platform::Agile< Windows::ApplicationModel::Core::CoreApplicationView > applicationView) | VideoView |
m_applicationView | VideoView | [private]
m_player | VideoView | [private]
m_window | VideoView | [private]
OnKeyPressed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::KeyEventArgs^args) | VideoView |
OnPointerPressed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | VideoView |
OnResuming(_In_ Platform::Object^sender, _In_ Platform::Object^args) | VideoView |
OnSuspending(_In_ Platform::Object^sender, _In_ Windows::ApplicationModel::SuspendingEventArgs^args) | VideoView |
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | VideoView |
Run() | VideoView |
Generated on Sat Nov 23 2024 16:09:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

XAudio2SoundPlayer::ImplData Member List

This is the complete list of members for XAudio2SoundPlayer::ImplData, including all inherited members.
callbackHander | XAudio2SoundPlayer::ImplData |
ImplData::ImplData(Platform::Array< byte >^data) | XAudio2SoundPlayer::ImplData | [inline]
isPlaying | XAudio2SoundPlayer::ImplData |
playData | XAudio2SoundPlayer::ImplData |
sourceVoice | XAudio2SoundPlayer::ImplData |
~ImplData() | XAudio2SoundPlayer::ImplData | [inline]
Generated on Sat Nov 23 2024 16:09:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML scrolling, panning, and zooming/C++/App.xaml.h Source File

  • XAML scrolling, panning, and zooming

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File access/C++/Scenario5.xaml.cpp Source File

  • File access

Scenario5.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 // Scenario5.xaml.cpp
00013 // Implementation of the Scenario5 class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario5.xaml.h"
00018
00019 using namespace SDKSample::FileAccess;
00020
00021 using namespace concurrency;
00022 using namespace Platform;
00023 using namespace Platform::Collections;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Windows::Globalization::DateTimeFormatting;
00027 using namespace Windows::Storage;
00028 using namespace Windows::Storage::FileProperties;
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     ShowPropertiesButton->Click += ref new RoutedEventHandler(this, &Scenario5::ShowPropertiesButton_Click);
00038 }
00039
00040 DateTimeFormatter^ Scenario5::dateFormat = ref new DateTimeFormatter("shortdate");
00041 DateTimeFormatter^ Scenario5::timeFormat = ref new DateTimeFormatter("longtime");
00042 String^ Scenario5::dateAccessedProperty = "System.DateAccessed";
00043 String^ Scenario5::fileOwnerProperty    = "System.FileOwner";
00044
00045 void Scenario5::ShowPropertiesButton_Click(Object^ sender, RoutedEventArgs^ e)
00046 {
00047     rootPage->ResetScenarioOutput(OutputTextBlock);
00048     StorageFile^ file = rootPage->SampleFile;
00049     if (file != nullptr)
00050     {
00051         // Get top level file properties
00052         OutputTextBlock->Text = "File name: " + file->Name;
00053         OutputTextBlock->Text += "\nFile type: " + file->FileType;
00054
00055         // Get basic properties
00056         create_task(file->GetBasicPropertiesAsync()).then([this, file](task<BasicProperties^> task)
00057         {
00058             try
00059             {
00060                 BasicProperties^ basicProperties = task.get();
00061                 String^ dateModifiedString = dateFormat->Format(basicProperties->DateModified) + " " + timeFormat->Format(basicProperties->DateModified);
00062                 OutputTextBlock->Text += "\nFile size: " + basicProperties->Size.ToString() + " bytes" + "\nDate modified: " + dateModifiedString;
00063             }
00064             catch(COMException^ ex)
00065             {
00066                 rootPage->HandleFileNotFoundException(ex);
00067             }
00068         }).then([this, file]()
00069         {
00070             // Get extra properties
00071             auto propertiesName = ref new Vector<String^>();
00072             propertiesName->Append(dateAccessedProperty);
00073             propertiesName->Append(fileOwnerProperty);
00074             return file->Properties->RetrievePropertiesAsync(propertiesName);
00075         }).then([this](IMap<String^, Object^>^ extraProperties)
00076         {
00077             auto propValue = extraProperties->Lookup(dateAccessedProperty);
00078             if (propValue != nullptr)
00079             {
00080                 DateTime dateAccessed = (DateTime)propValue;
00081                 OutputTextBlock->Text += "\nDate accessed: " + dateFormat->Format(dateAccessed) + " " + timeFormat->Format(dateAccessed);
00082             }
00083             propValue = extraProperties->Lookup(fileOwnerProperty);
00084             if (propValue != nullptr)
00085             {
00086                 OutputTextBlock->Text += "\nFile owner: " + propValue;
00087             }
00088         });
00089     }
00090 }
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text display/C++/pch.h Source File

  • XAML text display

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Check if current session is remote/C++/RemoteSession.xaml.cpp Source File

  • Check if current session is remote

RemoteSession.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 // RemoteSession.xaml.cpp
00013 // Implementation of the RemoteSession class
00014 //
00015
00016 #include "pch.h"
00017 #include "Wrl.h"
00018 #include "RemoteSession.xaml.h"
00019
00020 using namespace SDKSample::IsRemoteSession;
00021
00022 using namespace Windows::Foundation;
00023 using namespace Windows::System::RemoteDesktop;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Controls;
00026 using namespace Windows::UI::Xaml::Navigation;
00027
00028
00029 RemoteSession::RemoteSession()
00030 {
00031     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 void RemoteSession::OnNavigatedTo(NavigationEventArgs^ e)
00040 {
00041     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00042     // as NotifyUser()
00043     rootPage = MainPage::Current;
00044 }
00045
00046 void RemoteSession::Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00047 {
00048     Button^ b = safe_cast<Button^>(sender);
00049     if (b != nullptr)
00050     {
00051         rootPage->NotifyUser("You clicked the " + b->Name + " button", NotifyType::StatusMessage);
00052     }
00053     OutputTextBlock1->Text = "The current session is : " + (Windows::System::RemoteDesktop::InteractiveSession::IsRemote ? "Remote" : "Local");
00054 }
00055
Generated on Sat Nov 23 2024 16:07:58 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media capture using capture device/C#,C++/MainPage.xaml.cs Source File

  • Media capture using capture device
  • C#,C++

MainPage.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.ViewManagement;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Markup;
00016 using Windows.UI.Xaml.Navigation;
00017
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 MainPage : SDKTemplate.Common.LayoutAwarePage
00025     {
00026         public event System.EventHandler ScenarioLoaded;
00027         public event EventHandler<MainPageSizeChangedEventArgs> MainPageResized;
00028         public bool AutoSizeInputSectionWhenSnapped = true;
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         private Frame HiddenFrame = null;
00041
00042         public MainPage()
00043         {
00044             this.InitializeComponent();
00045
00046             // This is a static public property that will allow downstream pages to get
00047             // a handle to the MainPage instance in order to call methods that are in this class.
00048             Current = this;
00049
00050             // This frame is hidden, meaning it is never shown.  It is simply used to load
00051             // each scenario page and then pluck out the input and output sections and
00052             // place them into the UserControls on the main page.
00053             HiddenFrame = new Windows.UI.Xaml.Controls.Frame();
00054             HiddenFrame.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
00055             ContentRoot.Children.Add(HiddenFrame);
00056
00057             // Populate the sample title from the constant in the Constants.cs file.
00058             SetFeatureName(FEATURE_NAME);
00059             Scenarios.SelectionChanged += Scenarios_SelectionChanged;
00060             SizeChanged += MainPage_SizeChanged;
00061         }
00062
00063         void MainPage_SizeChanged(object sender, SizeChangedEventArgs e)
00064         {
00065             InvalidateSize();
00066             if (MainPageResized != null)
00067             {
00068                 MainPageSizeChangedEventArgs args = new MainPageSizeChangedEventArgs();
00069                 args.ViewState = ApplicationView.Value;
00070                 MainPageResized(this, args);
00071             }
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             PopulateScenarios();
00082             InvalidateViewState();
00083         }
00084
00085         private void InvalidateSize()
00086         {
00087             // Get the window width
00088             double windowWidth = this.ActualWidth;
00089             if (windowWidth != 0.0)
00090             {
00091                 // Get the width of the ListBox.
00092                 double listBoxWidth = Scenarios.ActualWidth;
00093
00094                 // Is the ListBox using any margins that we need to consider?
00095                 double listBoxMarginLeft = Scenarios.Margin.Left;
00096                 double listBoxMarginRight = Scenarios.Margin.Right;
00097
00098                 // Figure out how much room is left after considering the list box width
00099                 double availableWidth = windowWidth - listBoxWidth;
00100
00101                 // Is the top most child using margins?
00102                 double layoutRootMarginLeft = ContentRoot.Margin.Left;
00103                 double layoutRootMarginRight = ContentRoot.Margin.Right;
00104
00105                 // We have different widths to use depending on the view state
00106                 if (ApplicationView.Value != ApplicationViewState.Snapped)
00107                 {
00108                     // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00109                     // and the LayoutRoot's margins
00110                     InputSection.Width = availableWidth - (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight);
00111                 }
00112                 else
00113                 {
00114                     // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00115                     if (AutoSizeInputSectionWhenSnapped)
00116                     {
00117                         InputSection.Width = windowWidth - (layoutRootMarginLeft + layoutRootMarginRight);
00118                     }
00119                 }
00120             }
00121             InvalidateViewState();
00122         }
00123
00124         private void InvalidateViewState()
00125         {
00126             if (ApplicationView.Value == ApplicationViewState.Snapped)
00127             {
00128                 Grid.SetRow(DescriptionText, 3);
00129                 Grid.SetColumn(DescriptionText, 0);
00130
00131                 Grid.SetRow(InputSection, 4);
00132                 Grid.SetColumn(InputSection, 0);
00133
00134                 Grid.SetRow(FooterPanel, 2);
00135                 Grid.SetColumn(FooterPanel, 0);
00136             }
00137             else
00138             {
00139                 Grid.SetRow(DescriptionText, 1);
00140                 Grid.SetColumn(DescriptionText, 1);
00141
00142                 Grid.SetRow(InputSection, 2);
00143                 Grid.SetColumn(InputSection, 1);
00144
00145                 Grid.SetRow(FooterPanel, 1);
00146                 Grid.SetColumn(FooterPanel, 1);
00147             }
00148
00149             // Since we don't load the scenario page in the traditional manner (we just pluck out the
00150             // input and output sections from the page) we need to ensure that any VSM code used
00151             // by the scenario's input and output sections is fired.
00152             VisualStateManager.GoToState((Control)InputSection, "Input" + ApplicationView.Value.ToString(), false);
00153             VisualStateManager.GoToState((Control)OutputSection, "Output" + ApplicationView.Value.ToString(), false);
00154         }
00155
00156         private void PopulateScenarios()
00157         {
00158             System.Collections.ObjectModel.ObservableCollection<object> ScenarioList = new System.Collections.ObjectModel.ObservableCollection<object>();
00159             int i = 0;
00160
00161             // Populate the ListBox with the list of scenarios as defined in Constants.cs.
00162             foreach (Scenario s in scenarios)
00163             {
00164                 ListBoxItem item = new ListBoxItem();
00165                 s.Title = (++i).ToString() + ") " + s.Title;
00166                 item.Content = s;
00167                 item.Name = s.ClassType.FullName;
00168                 ScenarioList.Add(item);
00169             }
00170
00171             // Bind the ListBox to the scenario list.
00172             Scenarios.ItemsSource = ScenarioList;
00173
00174             // Starting scenario is the first or based upon a previous selection.
00175             int startingScenarioIndex = -1;
00176
00177             if (SuspensionManager.SessionState.ContainsKey("SelectedScenarioIndex"))
00178             {
00179                 int selectedScenarioIndex = Convert.ToInt32(SuspensionManager.SessionState["SelectedScenarioIndex"]);
00180                 startingScenarioIndex = selectedScenarioIndex;
00181             }
00182             Scenarios.SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00183             Scenarios.ScrollIntoView(Scenarios.SelectedItem);
00184         }
00185
00186         /// <summary>
00187         /// This method is responsible for loading the individual input and output sections for each scenario.  This
00188         /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00189         /// and output sections into the respective UserControl on the main page.
00190         /// </summary>
00191         /// <param name="scenarioName"></param>
00192         public void LoadScenario(Type scenarioClass)
00193         {
00194             AutoSizeInputSectionWhenSnapped = true;
00195
00196             // Load the ScenarioX.xaml file into the Frame.
00197             HiddenFrame.Navigate(scenarioClass, this);
00198
00199             // Get the top element, the Page, so we can look up the elements
00200             // that represent the input and output sections of the ScenarioX file.
00201             Page hiddenPage = HiddenFrame.Content as Page;
00202
00203             // Get each element.
00204             UIElement input = hiddenPage.FindName("Input") as UIElement;
00205             UIElement output = hiddenPage.FindName("Output") as UIElement;
00206
00207             if (input == null)
00208             {
00209                 // Malformed input section.
00210                 NotifyUser(String.Format(
00211                     "Cannot load scenario input section for {0}.  Make sure root of input section markup has x:Name of 'Input'",
00212                     scenarioClass.Name), NotifyType.ErrorMessage);
00213                 return;
00214             }
00215
00216             if (output == null)
00217             {
00218                 // Malformed output section.
00219                 NotifyUser(String.Format(
00220                     "Cannot load scenario output section for {0}.  Make sure root of output section markup has x:Name of 'Output'",
00221                     scenarioClass.Name), NotifyType.ErrorMessage);
00222                 return;
00223             }
00224
00225             // Find the LayoutRoot which parents the input and output sections in the main page.
00226             Panel panel = hiddenPage.FindName("LayoutRoot") as Panel;
00227
00228             if (panel != null)
00229             {
00230                 // Get rid of the content that is currently in the intput and output sections.
00231                 panel.Children.Remove(input);
00232                 panel.Children.Remove(output);
00233
00234                 // Populate the input and output sections with the newly loaded content.
00235                 InputSection.Content = input;
00236                 OutputSection.Content = output;
00237             }
00238             else
00239             {
00240                 // Malformed Scenario file.
00241                 NotifyUser(String.Format(
00242                     "Cannot load scenario: '{0}'.  Make sure root tag in the '{0}' file has an x:Name of 'LayoutRoot'",
00243                     scenarioClass.Name), NotifyType.ErrorMessage);
00244             }
00245         }
00246
00247         void Scenarios_SelectionChanged(object sender, SelectionChangedEventArgs e)
00248         {
00249             if (Scenarios.SelectedItem != null)
00250             {
00251                 NotifyUser("", NotifyType.StatusMessage);
00252
00253                 ListBoxItem selectedListBoxItem = Scenarios.SelectedItem as ListBoxItem;
00254                 SuspensionManager.SessionState["SelectedScenarioIndex"] = Scenarios.SelectedIndex;
00255
00256                 Scenario scenario = selectedListBoxItem.Content as Scenario;
00257                 LoadScenario(scenario.ClassType);
00258                 InvalidateSize();
00259
00260                 // Fire the ScenarioLoaded event since we know that everything is loaded now.
00261                 if (ScenarioLoaded != null)
00262                 {
00263                     ScenarioLoaded(this, new EventArgs());
00264                 }
00265             }
00266         }
00267
00268         public void NotifyUser(string strMessage, NotifyType type)
00269         {
00270             switch (type)
00271             {
00272                 // Use the status message style.
00273                 case NotifyType.StatusMessage:
00274                     StatusBlock.Style = Resources["StatusStyle"] as Style;
00275                     break;
00276                 // Use the error message style.
00277                 case NotifyType.ErrorMessage:
00278                     StatusBlock.Style = Resources["ErrorStyle"] as Style;
00279                     break;
00280             }
00281             StatusBlock.Text = strMessage;
00282
00283             // Collapse the StatusBlock if it has no text to conserve real estate.
00284             if (StatusBlock.Text != String.Empty)
00285             {
00286                 StatusBlock.Visibility = Windows.UI.Xaml.Visibility.Visible;
00287             }
00288             else
00289             {
00290                 StatusBlock.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
00291             }
00292         }
00293
00294         async void Footer_Click(object sender, RoutedEventArgs e)
00295         {
00296             await Windows.System.Launcher.LaunchUriAsync(new Uri(((HyperlinkButton)sender).Tag.ToString()));
00297         }
00298
00299         private void SetFeatureName(string str)
00300         {
00301             FeatureName.Text = str;
00302         }
00303     }
00304
00305     public class MainPageSizeChangedEventArgs : EventArgs
00306     {
00307         private ApplicationViewState viewState;
00308
00309         public ApplicationViewState ViewState
00310         {
00311             get { return viewState; }
00312             set { viewState = value; }
00313         }
00314     }
00315
00316     public enum NotifyType
00317     {
00318         StatusMessage,
00319         ErrorMessage
00320     };
00321 }
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Number formatting and parsing/C++/NumberParsing.xaml.h Source File

  • Number formatting and parsing

NumberParsing.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 // NumberParsing.xaml.h
00013 // Declaration of the NumberParsing class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "NumberParsing.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace NumberFormatting
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 NumberParsing sealed
00031         {
00032         public:
00033             NumberParsing();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void Display_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::CustomDeviceAccess::sealed Member List

This is the complete list of members for SDKSample::CustomDeviceAccess::sealed, including all inherited members.
ClearBarGraphTable(void) | SDKSample::CustomDeviceAccess::sealed | [private]
ClearSwitchStateTable() | SDKSample::CustomDeviceAccess::sealed | [private]
CloseFx2Device(void) | SDKSample::CustomDeviceAccess::sealed | [private]
Current_DeviceClosing(Platform::Object^sender, Samples::Devices::Fx2::Fx2Device^device) | SDKSample::CustomDeviceAccess::sealed | [private]
DeviceAsync() | SDKSample::CustomDeviceAccess::sealed |
deviceAsyncGet_Click_1(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CustomDeviceAccess::sealed | [private]
deviceAsyncSet_Click_1(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CustomDeviceAccess::sealed | [private]
deviceClosingHandler | SDKSample::CustomDeviceAccess::sealed | [private]
DeviceConnect() | SDKSample::CustomDeviceAccess::sealed |
deviceConnectDevices_SelectionChanged_1(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | SDKSample::CustomDeviceAccess::sealed | [private]
deviceConnectStart_Click_1(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CustomDeviceAccess::sealed | [private]
deviceConnectStop_Click_1(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CustomDeviceAccess::sealed | [private]
DeviceEvents() | SDKSample::CustomDeviceAccess::sealed |
deviceEventsGet_Click_1(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CustomDeviceAccess::sealed | [private]
deviceEventsRegister_Click_1(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CustomDeviceAccess::sealed | [private]
DeviceListEntry(Windows::Devices::Enumeration::DeviceInformation^DeviceInterface) | SDKSample::CustomDeviceAccess::sealed | [inline]
m_Device | SDKSample::CustomDeviceAccess::sealed |
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::CustomDeviceAccess::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::CustomDeviceAccess::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::CustomDeviceAccess::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::CustomDeviceAccess::sealed | [protected, virtual]
OnSwitchStateChangedEvent(Samples::Devices::Fx2::Fx2Device^sender, Samples::Devices::Fx2::SwitchStateChangedEventArgs^e) | SDKSample::CustomDeviceAccess::sealed | [private]
OpenFx2Device(Platform::String^Id) | SDKSample::CustomDeviceAccess::sealed | [private]
previousSwitchValues | SDKSample::CustomDeviceAccess::sealed | [private]
RegisterForSwitchStateChangedEvent(bool r) | SDKSample::CustomDeviceAccess::sealed | [private]
rootPage | SDKSample::CustomDeviceAccess::sealed | [private]
switchChangedEventsHandler | SDKSample::CustomDeviceAccess::sealed | [private]
switchChangedEventsRegistered | SDKSample::CustomDeviceAccess::sealed | [private]
UpdateBarGraphTable(Platform::Array< bool >^BarGraphArray) | SDKSample::CustomDeviceAccess::sealed | [private]
UpdateRegisterButton(void) | SDKSample::CustomDeviceAccess::sealed | [private]
UpdateStartStopButtons(void) | SDKSample::CustomDeviceAccess::sealed | [private]
UpdateSwitchStateTable(Platform::Array< bool >^SwitchStateArray) | SDKSample::CustomDeviceAccess::sealed | [private]
Generated on Sat Nov 23 2024 16:09:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: AtomPub/C++/common/suspensionmanager.h Source File

  • AtomPub
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Hilo::Repository Member List

This is the complete list of members for Hilo::Repository, including all inherited members.
AddObserver(const std::function< void()> callback, PageType pageType)=0 | Hilo::ObservableQuery | [pure virtual]
GetFolderPhotoCountAsync(Windows::Storage::Search::IStorageFolderQueryOperations^folderQuery)=0 | Hilo::Repository | [pure virtual]
GetMonthGroupedPhotosWithCacheAsync(std::shared_ptr< PhotoCache > photoCache, concurrency::cancellation_token token)=0 | Hilo::Repository | [pure virtual]
GetPhotoDataForMonthGroup(IPhotoGroup^photoGroup, Windows::Storage::Search::IStorageFolderQueryOperations^folderQuery, unsigned int maxNumberOfItems)=0 | Hilo::Repository | [pure virtual]
GetPhotosForDateRangeQueryAsync(Platform::String^dateRangeQuery)=0 | Hilo::Repository | [pure virtual]
GetPhotosForPictureHubGroupAsync(IPhotoGroup^photoGroup, unsigned int maxNumberOfItems)=0 | Hilo::Repository | [pure virtual]
GetPhotoStorageFilesAsync(Platform::String^query, unsigned int maxNumberOfItems)=0 | Hilo::Repository | [pure virtual]
GetSinglePhotoAsync(Platform::String^photoPath)=0 | Hilo::Repository | [pure virtual]
GetYearGroupedMonthsAsync(concurrency::cancellation_token token)=0 | Hilo::Repository | [pure virtual]
HasPhotosInRangeAsync(Platform::String^dateRangeQuery, Windows::Storage::Search::IStorageFolderQueryOperations^folderQuery)=0 | Hilo::Repository | [pure virtual]
NotifyAllObservers()=0 | Hilo::Repository | [pure virtual]
RemoveObserver(PageType pageType)=0 | Hilo::ObservableQuery | [pure virtual]
Generated on Sat Nov 23 2024 16:09:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File picker contracts/C++/MainPage_SaveFile.xaml.cpp Source File

  • File picker contracts

MainPage_SaveFile.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 // MainPage_SaveFile.xaml.cpp
00013 // Implementation of the MainPage_SaveFile class
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "MainPage_SaveFile.xaml.h"
00019
00020 using namespace SDKSample::FilePickerContracts;
00021
00022 using namespace concurrency;
00023 using namespace Platform;
00024 using namespace Windows::Storage;
00025 using namespace Windows::Storage::Pickers;
00026 using namespace Windows::UI::Xaml;
00027 using namespace Windows::UI::Xaml::Controls;
00028 using namespace Windows::UI::Xaml::Navigation;
00029
00030 MainPage_SaveFile::MainPage_SaveFile()
00031 {
00032     InitializeComponent();
00033     SaveFileButton->Click += ref new RoutedEventHandler(this, &MainPage_SaveFile::SaveFileButton_Click);
00034 }
00035
00036 void MainPage_SaveFile::SaveFileButton_Click(Object^ sender, RoutedEventArgs^ e)
00037 {
00038     MainPage^ page = MainPage::Current;
00039
00040     page->ResetScenarioOutput(OutputTextBlock);
00041     if (page->EnsureUnsnapped())
00042     {
00043         // Set up and launch the FileSavePicker
00044         auto fileSavePicker = ref new FileSavePicker();
00045         auto fileExtensions = ref new Platform::Collections::Vector<String^>();
00046         fileExtensions->Append(".png");
00047         fileSavePicker->FileTypeChoices->Insert("PNG", fileExtensions);
00048
00049         create_task(fileSavePicker->PickSaveFileAsync()).then([this](StorageFile^ file)
00050         {
00051             if (file != nullptr)
00052             {
00053                 // At this point, the app can begin writing to the provided save file
00054                 OutputTextBlock->Text = file->Name;
00055             }
00056         });
00057     }
00058 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C#,C++/MediaExtensions/Polar/PolarTransform.idl Source File

  • Media extensions
  • C#,C++
  • MediaExtensions
  • Polar

PolarTransform.idl

Go to the documentation of this file.
00001 import "Windows.Media.idl";
00002
00003 #include <sdkddkver.h>
00004
00005 namespace PolarTransform
00006 {
00007   [version(NTDDI_WIN8)]
00008   runtimeclass PolarEffect
00009     {
00010     [default] interface Windows.Media.IMediaExtension;
00011   }
00012 }
Generated on Sat Nov 23 2024 16:08:21 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Secondary tiles/C#,C++/UnpinTile.xaml.cpp Source File

  • Secondary tiles
  • C#,C++

UnpinTile.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 // UnpinTile.xaml.cpp
00013 // Implementation of the UnpinTile class
00014 //
00015
00016 #include "pch.h"
00017 #include "UnpinTile.xaml.h"
00018
00019 using namespace SecondaryTiles;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::StartScreen;
00024 using namespace Windows::UI::Xaml::Navigation;
00025 using namespace Windows::Foundation;
00026 using namespace Platform;
00027 using namespace concurrency;
00028
00029
00030 UnpinTile::UnpinTile()
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 void UnpinTile::OnNavigatedTo(NavigationEventArgs^ e)
00041 {
00042     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00043     // as NotifyUser()
00044     rootPage = MainPage::current;
00045     // Preserve the app bar
00046     appBar = rootPage->BottomAppBar;
00047     // Now null it so we don't show the appbar in this scenario
00048     rootPage->BottomAppBar = nullptr;
00049 }
00050
00051 /// <summary>
00052 /// Invoked when this page is about to be navigated out 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 void UnpinTile::OnNavigatingFrom(NavigatingCancelEventArgs^ e)
00057 {
00058     // Restore the app bar
00059     rootPage->BottomAppBar = appBar;
00060 }
00061
00062 void SecondaryTiles::UnpinTile::UnpinSecondaryTile_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00063 {
00064     Button^ button = safe_cast<Button^>(sender);
00065     if (button != nullptr)
00066     {
00067         if (SecondaryTile::Exists(rootPage->tileId))
00068         {
00069             // First prepare the tile to be unpinned
00070             auto secondaryTile = ref new SecondaryTile(rootPage->tileId);
00071
00072             // Now make the delete request
00073             auto const rect = rootPage->GetElementRect(safe_cast<FrameworkElement^>(sender));
00074             create_task(secondaryTile->RequestDeleteForSelectionAsync(rect, Windows::UI::Popups::Placement::Below)).then([this](bool isUnPinned)
00075             {
00076                 if (isUnPinned)
00077                 {
00078                     rootPage->NotifyUser("Secondary tile successfully unpinned.", NotifyType::StatusMessage);
00079                 }
00080                 else
00081                 {
00082                     rootPage->NotifyUser("Secondary tile not unpinned.", NotifyType::ErrorMessage);
00083                 }
00084             });
00085         }
00086         else
00087         {
00088             rootPage->NotifyUser(rootPage->tileId + " not currently pinned.", NotifyType::ErrorMessage);
00089         }
00090     }
00091 }
Generated on Sat Nov 23 2024 16:08:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File picker contracts/C++/CachedFileUpdaterPage.xaml.h Source File

  • File picker contracts

CachedFileUpdaterPage.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 // CachedFileUpdaterPage.xaml.h
00013 // Declaration of the CachedFileUpdaterPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "CachedFileUpdaterPage.g.h"
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     namespace FilePickerContracts
00026     {
00027         [Windows::Foundation::Metadata::WebHostHidden]
00028         public ref class CachedFileUpdaterPage sealed
00029         {
00030         public:
00031             CachedFileUpdaterPage();
00032             void Activate(Windows::ApplicationModel::Activation::CachedFileUpdaterActivatedEventArgs^ e);
00033
00034             static property Platform::String^ FEATURE_NAME
00035             {
00036                 Platform::String^ get()
00037                 {
00038                     return ref new Platform::String(L"Cached File Updater Page");
00039                 }
00040             }
00041
00042             static property Platform::Array<Scenario>^ scenarios
00043             {
00044                 Platform::Array<Scenario>^ get()
00045                 {
00046                     if (CachedFileUpdaterPage::Current->cachedFileUpdaterUI->UpdateTarget == Windows::Storage::Provider::CachedFileTarget::Local)
00047                     {
00048                         return localScenariosInner;
00049                     }
00050                     else
00051                     {
00052                         return remoteScenariosInner;
00053                     }
00054                 }
00055             }
00056
00057         internal:
00058             property bool AutoSizeInputSectionWhenSnapped
00059             {
00060                 bool get()
00061                 {
00062                     return autoSizeInputSectionWhenSnapped;
00063                 }
00064
00065                 void set(bool value)
00066                 {
00067                     autoSizeInputSectionWhenSnapped = value;
00068                 }
00069             }
00070
00071             property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00072             {
00073                 Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00074                 {
00075                     return safe_cast<App^>(App::Current)->LaunchArgs;
00076                 }
00077             }
00078
00079             bool EnsureUnsnapped();
00080             void ResetScenarioOutput(Windows::UI::Xaml::Controls::TextBlock^ textblock);
00081             void NotifyUser(Platform::String^ strMessage, NotifyType type);
00082             void LoadScenario(Platform::String^ scenarioName);
00083             event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00084             event Windows::Foundation::EventHandler<PageSizeChangedEventArgs^>^ PageResized;
00085
00086         private:
00087             void PopulateScenarios();
00088             void InvalidateSize();
00089             void InvalidateViewState();
00090             void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00091
00092             Platform::Collections::Vector<Object^>^ ScenarioList;
00093             Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00094             bool autoSizeInputSectionWhenSnapped;
00095             static Platform::Array<Scenario>^ localScenariosInner;
00096             static Platform::Array<Scenario>^ remoteScenariosInner;
00097
00098         protected:
00099             void CachedFileUpdaterPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00100             void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00101             virtual void LoadState(Platform::Object^ navigationParameter,
00102                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00103             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00104
00105         private:
00106             void OnFileUpdateRequested(Windows::Storage::Provider::CachedFileUpdaterUI^ sender, Windows::Storage::Provider::FileUpdateRequestedEventArgs^ e);
00107             void OnUIRequested(Windows::Storage::Provider::CachedFileUpdaterUI^ sender, Platform::Object^ e);
00108
00109         internal:
00110             static CachedFileUpdaterPage^ Current;
00111             Windows::Storage::Provider::FileUpdateRequest^ fileUpdateRequest;
00112             Windows::Storage::Provider::FileUpdateRequestDeferral^ fileUpdateRequestDeferral;
00113             Windows::Storage::Provider::CachedFileUpdaterUI^ cachedFileUpdaterUI;
00114         };
00115     }
00116 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML FlipView control/C++/Scenario3.xaml.cpp Source File

  • XAML FlipView control

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 "SampleDataSource.h"
00019
00020 using namespace SDKSample::FlipViewCPP;
00021 using namespace SDKSample::FlipViewData;
00022
00023 using namespace Windows::UI::Xaml;
00024 using namespace Windows::UI::Xaml::Controls;
00025 using namespace Windows::UI::Xaml::Navigation;
00026
00027 Scenario3^ Scenario3::Current;
00028
00029 Scenario3::Scenario3()
00030 {
00031     InitializeComponent();
00032   Current = this;
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 void Scenario3::OnNavigatedTo(NavigationEventArgs^ e)
00041 {
00042     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00043     // as NotifyUser()
00044     rootPage = MainPage::Current;
00045
00046   // Construct the table of contents used for navigating the FlipView
00047     // Create a StackPanel to host the TOC
00048     StackPanel^ sp = ref new StackPanel();
00049     sp->Orientation = Orientation::Vertical;
00050   sp->HorizontalAlignment = Windows::UI::Xaml::HorizontalAlignment::Center;
00051
00052   // Add the TOC title
00053     TextBlock^ tb = ref new TextBlock();
00054     tb->Text = "Table of Contents";
00055   tb->Style = dynamic_cast<Windows::UI::Xaml::Style^>(Scenario3::Current->Resources->Lookup("TOCTitle"));
00056     sp->Children->Append(tb);
00057
00058   // Get our sample data
00059   auto sampleData = ref new FlipViewData::SampleDataSource();
00060
00061   // Create the TOC from the data
00062     // Use buttons for each TOC entry using the Tag property
00063     // to contain the index of the target
00064     UINT i = 0;
00065   UINT count = sampleData->Items->Size;
00066   while(i<count)
00067   {
00068     SampleDataItem^ sItem = dynamic_cast<SampleDataItem^>(sampleData->Items->GetAt(i));
00069     if(sItem)
00070     {
00071       Button^ b = ref new Button();
00072       b->Style = dynamic_cast<Windows::UI::Xaml::Style^>(Scenario3::Current->Resources->Lookup("ButtonStyle1"));
00073       b->Content = sItem->Title;
00074       b->Click += ref new RoutedEventHandler(this, & Scenario3::TOCButton_Click);
00075       b->Tag = i.ToString();
00076       sp->Children->Append(b);
00077       b->TabIndex = i + 1;
00078       i++;
00079     }
00080     else
00081       break;
00082   }
00083
00084
00085   // Add the TOC to our data set
00086     sampleData->Items->InsertAt(0, sp);
00087
00088     // Use a template selector to style the TOC entry differently from the other data entries
00089     FlipView3->ItemTemplateSelector = ref new ItemSelector();
00090   FlipView3->ItemsSource = sampleData->Items;
00091 }
00092
00093
00094 void SDKSample::FlipViewCPP::Scenario3::TOCButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00095 {
00096   Button^ b = safe_cast<Button^>(sender);
00097     if (b != nullptr)
00098     {
00099     FlipView3->SelectedIndex = b->TabIndex;
00100     }
00101 }
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DXGI offer and reclaim resources/C++/DirectXSample.h Source File

  • DXGI offer and reclaim resources

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
00010 // This header defines helper utilities to make DirectX APIs work with exceptions.
00011 namespace DX
00012 {
00013     inline void ThrowIfFailed(HRESULT hr)
00014     {
00015         if (FAILED(hr))
00016         {
00017             // Set a breakpoint on this line to catch DX API errors.
00018             throw Platform::Exception::CreateException(hr);
00019         }
00020     }
00021 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Web authentication broker/C++/Scenario2.xaml.cpp Source File

  • Web authentication broker

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 SDKSample::WebAuthentication;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 using namespace Concurrency;
00026 using namespace Platform;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Security::Authentication::Web;
00030
00031 Scenario2::Scenario2()
00032 {
00033     InitializeComponent();
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 Scenario2::OnNavigatedTo(NavigationEventArgs^ e)
00042 {
00043     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00044     // as NotifyUser()
00045     rootPage = MainPage::Current;
00046 }
00047
00048 void SDKSample::WebAuthentication::Scenario2::Launch_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00049 {
00050     GoogleDebugArea->Text = "";
00051     String^ googleURL = "https://accounts.google.com/o/oauth2/auth?";
00052     auto clientID = GoogleClientID->Text;
00053     if (clientID == nullptr || clientID->IsEmpty())
00054     {
00055         GoogleDebugArea->Text = "Enter a ClientID for Google";
00056         return;
00057     }
00058
00059     googleURL += "client_id=" + clientID + "&redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code&scope=http%3A%2F%2Fpicasaweb.google.com%2Fdata";
00060
00061     try
00062     {
00063         auto startURI = ref new Uri(googleURL);
00064         auto endURI = ref new Uri("https://accounts.google.com/o/oauth2/approval?");
00065         GoogleDebugArea->Text += "Navigating to: " + googleURL + "\n";
00066
00067         create_task(WebAuthenticationBroker::AuthenticateAsync(WebAuthenticationOptions::UseTitle, startURI, endURI)).then([this](WebAuthenticationResult^ result)
00068         {
00069             String^ statusString;
00070             switch (result->ResponseStatus)
00071             {
00072             case WebAuthenticationStatus::ErrorHttp:
00073                 statusString = "ErrorHttp: " + result->ResponseErrorDetail;
00074                 break;
00075             case WebAuthenticationStatus::Success:
00076                 statusString = "Success";
00077         GoogleReturnedToken->Text += result->ResponseData;
00078                 break;
00079             case WebAuthenticationStatus::UserCancel:
00080                 statusString = "UserCancel";
00081                 break;
00082             }
00083
00084             GoogleDebugArea->Text += "Status returned by WebAuth broker: " + statusString;
00085         });
00086     }
00087     catch (Exception^ ex)
00088     {
00089         GoogleDebugArea->Text += "Error launching WebAuth " + ex->Message;
00090         return;
00091     }
00092 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Simple3DGameXaml::sealed Member List

This is the complete list of members for Simple3DGameXaml::sealed, including all inherited members.
__pad0__ | Simple3DGameXaml::sealed |
App() | Simple3DGameXaml::sealed |
CycleBackground() | Simple3DGameXaml::sealed |
GetSwapChainBackgroundPanel() | Simple3DGameXaml::sealed | [inline]
HideGameInfoOverlay() | Simple3DGameXaml::sealed | [private]
HideGameInfoOverlay() | Simple3DGameXaml::sealed |
HideSnapped() | Simple3DGameXaml::sealed | [private]
HideSnapped() | Simple3DGameXaml::sealed |
InitializeGameState() | Simple3DGameXaml::sealed | [private]
InitializeLicense() | Simple3DGameXaml::sealed | [private]
InitializeLicenseCore() | Simple3DGameXaml::sealed | [private]
isApp | Simple3DGameXaml::sealed |
license | Simple3DGameXaml::sealed |
LicenseChanged(Windows::ApplicationModel::Store::ListingInformation^listing, Windows::ApplicationModel::Store::LicenseInformation^license) | Simple3DGameXaml::sealed |
m_app | Simple3DGameXaml::sealed | [private]
m_controller | Simple3DGameXaml::sealed | [private]
m_foreground | Simple3DGameXaml::sealed | [private]
m_formattedPrice | Simple3DGameXaml::sealed | [private]
m_game | Simple3DGameXaml::sealed | [private]
m_gameInfoOverlayState | Simple3DGameXaml::sealed | [private]
m_haveFocus | Simple3DGameXaml::sealed | [private]
m_isApp | Simple3DGameXaml::sealed | [private]
m_isAppActive | Simple3DGameXaml::sealed | [private]
m_isAppTrial | Simple3DGameXaml::sealed | [private]
m_isAvailableForPurchase | Simple3DGameXaml::sealed | [private]
m_isProductActive | Simple3DGameXaml::sealed | [private]
m_isTrial | Simple3DGameXaml::sealed | [private]
m_licenseInformation | Simple3DGameXaml::sealed | [private]
m_licenseState | Simple3DGameXaml::sealed | [private]
m_listingInformation | Simple3DGameXaml::sealed | [private]
m_mainPage | Simple3DGameXaml::sealed | [private]
m_onRenderingEventToken | Simple3DGameXaml::sealed | [private]
m_pauseRequested | Simple3DGameXaml::sealed | [private]
m_possiblePurchaseUpgrade | Simple3DGameXaml::sealed | [private]
m_pressComplete | Simple3DGameXaml::sealed | [private]
m_pressResult | Simple3DGameXaml::sealed | [private]
m_productId | Simple3DGameXaml::sealed | [private]
m_renderer | Simple3DGameXaml::sealed | [private]
m_renderNeeded | Simple3DGameXaml::sealed | [private]
m_status | Simple3DGameXaml::sealed | [private]
m_title | Simple3DGameXaml::sealed | [private]
m_updateState | Simple3DGameXaml::sealed | [private]
m_updateStateNext | Simple3DGameXaml::sealed | [private]
m_visible | Simple3DGameXaml::sealed | [private]
MainPage() | Simple3DGameXaml::sealed |
OnAppBarOpened(Object^sender, Object^args) | Simple3DGameXaml::sealed | [protected]
OnBuyAppButtonTapped(Object^sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^args) | Simple3DGameXaml::sealed | [protected]
OnBuySelectorClicked(Object^sender, Windows::UI::Xaml::RoutedEventArgs^args) | Simple3DGameXaml::sealed | [protected]
OnChangeBackgroundButtonClicked(Object^sender, Windows::UI::Xaml::RoutedEventArgs^args) | Simple3DGameXaml::sealed | [protected]
OnDeviceLost() | Simple3DGameXaml::sealed | [private]
OnDeviceReset() | Simple3DGameXaml::sealed | [private]
OnDisplayContentsInvalidated(_In_ Platform::Object^sender) | Simple3DGameXaml::sealed | [private]
OnGameInfoOverlayTapped(Object^sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^args) | Simple3DGameXaml::sealed | [protected]
OnLaunched(_In_ Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^args) override | Simple3DGameXaml::sealed | [virtual]
OnLicenseChanged() | Simple3DGameXaml::sealed | [private]
OnLoadStoreClicked(Object^sender, Windows::UI::Xaml::RoutedEventArgs^args) | Simple3DGameXaml::sealed | [protected]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | Simple3DGameXaml::sealed | [private]
OnPlayButtonClicked(Object^sender, Windows::UI::Xaml::RoutedEventArgs^args) | Simple3DGameXaml::sealed | [protected]
OnRendering(_In_ Object^sender, _In_ Object^args) | Simple3DGameXaml::sealed | [private]
OnResetButtonClicked(Object^sender, Windows::UI::Xaml::RoutedEventArgs^args) | Simple3DGameXaml::sealed | [protected]
OnResetLicenseButtonClicked(Object^sender, Windows::UI::Xaml::RoutedEventArgs^args) | Simple3DGameXaml::sealed | [protected]
OnResuming(_In_ Platform::Object^sender, _In_ Platform::Object^args) | Simple3DGameXaml::sealed | [private]
OnStoreReturnClicked(Object^sender, Windows::UI::Xaml::RoutedEventArgs^args) | Simple3DGameXaml::sealed | [protected]
OnSuspending(_In_ Platform::Object^sender, _In_ Windows::ApplicationModel::SuspendingEventArgs^args) | Simple3DGameXaml::sealed | [private]
OnVisibilityChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::VisibilityChangedEventArgs^args) | Simple3DGameXaml::sealed | [private]
OnWindowActivationChanged(_In_ Platform::Object^sender, _In_ Windows::UI::Core::WindowActivatedEventArgs^args) | Simple3DGameXaml::sealed | [private]
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | Simple3DGameXaml::sealed | [private]
OnWindowSizeChanged() | Simple3DGameXaml::sealed |
OptionalTrialUpgrade() | Simple3DGameXaml::sealed | [protected]
PauseRequested() | Simple3DGameXaml::sealed | [inline]
PressComplete() | Simple3DGameXaml::sealed | [inline]
productId | Simple3DGameXaml::sealed |
PropertyChanged | Simple3DGameXaml::sealed |
ResetGame() | Simple3DGameXaml::sealed |
ResetLicense() | Simple3DGameXaml::sealed |
SetAction(GameInfoOverlayCommand command) | Simple3DGameXaml::sealed | [private]
SetAction(GameInfoOverlayCommand action) | Simple3DGameXaml::sealed |
SetApp(App^app) | Simple3DGameXaml::sealed |
SetBackground(unsigned int background) | Simple3DGameXaml::sealed |
SetGameInfoOverlay(GameInfoOverlayState state) | Simple3DGameXaml::sealed | [private]
SetGameLoading() | Simple3DGameXaml::sealed |
SetGameOver(bool win, int maxLevel, int hitCount, int shotCount, int highScore) | Simple3DGameXaml::sealed |
SetGameStats(int maxLevel, int hitCount, int shotCount) | Simple3DGameXaml::sealed |
SetLevelStart(int level, Platform::String^objective, float timeLimit, float bonusTime) | Simple3DGameXaml::sealed |
SetPause(int level, int hitCount, int shotCount, float timeRemaining) | Simple3DGameXaml::sealed |
SetProductItems(Windows::ApplicationModel::Store::ListingInformation^listing, Windows::ApplicationModel::Store::LicenseInformation^license) | Simple3DGameXaml::sealed |
SetSnapped() | Simple3DGameXaml::sealed | [private]
SetSnapped() | Simple3DGameXaml::sealed |
SetStatus(Windows::ApplicationModel::Store::LicenseInformation^license) | Simple3DGameXaml::sealed | [private]
ShowGameInfoOverlay() | Simple3DGameXaml::sealed | [private]
ShowGameInfoOverlay() | Simple3DGameXaml::sealed |
ShowStoreFlyout() | Simple3DGameXaml::sealed | [protected]
Update() | Simple3DGameXaml::sealed | [private]
UpdateContent(Windows::ApplicationModel::Store::ListingInformation^listing) | Simple3DGameXaml::sealed |
UpdateViewState() | Simple3DGameXaml::sealed | [private]
~App() | Simple3DGameXaml::sealed | [private]
Generated on Sat Nov 23 2024 16:09:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite vertical text/C++/FlowLayout.cpp Source File

  • DirectWrite vertical text

FlowLayout.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 "TextAnalysis.h"
00010 #include "FlowSource.h"
00011 #include "FlowSink.h"
00012 #include "FlowLayout.h"
00013
00014 namespace
00015 {
00016     // Estimates the maximum number of glyph indices needed to hold a string of
00017     // a given length.  This is the formula given in the Uniscribe SDK and should
00018     // cover most cases. Degenerate cases will require a reallocation.
00019     UINT32 EstimateGlyphCount(UINT32 textLength)
00020     {
00021         return 3 * textLength / 2 + 16;
00022     }
00023
00024     HRESULT GetGlyphMetrics(
00025         IDWriteFontFace* fontFace,
00026         DWRITE_MEASURING_MODE measuringMode,
00027         float fontEmSize,
00028         bool isSideways,
00029         UINT32 glyphCount,
00030         _In_reads_(glyphCount) UINT16* glyphIds,
00031         _Out_writes_(glyphCount) DWRITE_GLYPH_METRICS* glyphRunMetrics
00032         )
00033     {
00034         // Call the right function depending on the measuring mode.
00035         switch (measuringMode)
00036         {
00037         case DWRITE_MEASURING_MODE_GDI_CLASSIC:
00038         case DWRITE_MEASURING_MODE_GDI_NATURAL:
00039             return fontFace->GetGdiCompatibleGlyphMetrics(
00040                 fontEmSize,
00041                 1.0,
00042                 nullptr,
00043                 measuringMode == DWRITE_MEASURING_MODE_GDI_NATURAL,
00044                 glyphIds,
00045                 glyphCount,
00046                 glyphRunMetrics,
00047                 isSideways
00048                 );
00049
00050         case DWRITE_MEASURING_MODE_NATURAL:
00051         default:
00052             return fontFace->GetDesignGlyphMetrics(glyphIds, glyphCount, glyphRunMetrics, isSideways);
00053         }
00054     }
00055 }
00056
00057 void FlowLayout::SetTextFormat(Microsoft::WRL::ComPtr<IDWriteTextFormat> textFormat)
00058 {
00059     // Initializes properties using a text format, like font family, font size,
00060     // and reading direction. For simplicity, this custom layout supports
00061     // minimal formatting. No mixed formatting or alignment modes are supported.
00062     Microsoft::WRL::ComPtr<IDWriteFontCollection>  fontCollection;
00063     Microsoft::WRL::ComPtr<IDWriteFontFamily>      fontFamily;
00064     Microsoft::WRL::ComPtr<IDWriteFont>            font;
00065
00066     wchar_t fontFamilyName[100];
00067
00068     // note the reading direction from the format is ignored
00069     m_fontEmSize = textFormat->GetFontSize();
00070
00071     DX::ThrowIfFailed(
00072         textFormat->GetLocaleName(m_localeName, ARRAYSIZE(m_localeName))
00073         );
00074
00075     // Map font and style to fontFace.
00076     // Need the font collection to map from font name to actual font.
00077     DX::ThrowIfFailed(
00078         textFormat->GetFontCollection(&fontCollection)
00079         );
00080
00081     if (fontCollection == nullptr)
00082     {
00083         // No font collection was set in the format, so use the system default.
00084         m_dwriteFactory->GetSystemFontCollection(&fontCollection);
00085     }
00086
00087     // Find matching family name in collection.
00088     textFormat->GetFontFamilyName(fontFamilyName, ARRAYSIZE(fontFamilyName));
00089
00090     UINT32 fontIndex = 0;
00091
00092     BOOL fontExists = false;
00093
00094     DX::ThrowIfFailed(
00095         fontCollection->FindFamilyName(fontFamilyName, &fontIndex, &fontExists)
00096         );
00097
00098     if (!fontExists)
00099     {
00100         // If the given font does not exist, take what we can get
00101         // (displaying something instead of nothing), choosing the foremost
00102         // font in the collection.
00103         fontIndex = 0;
00104     }
00105
00106     DX::ThrowIfFailed(
00107         fontCollection->GetFontFamily(fontIndex, &fontFamily)
00108         );
00109
00110     DX::ThrowIfFailed(
00111         fontFamily->GetFirstMatchingFont(
00112             textFormat->GetFontWeight(),
00113             textFormat->GetFontStretch(),
00114             textFormat->GetFontStyle(),
00115             &font
00116             )
00117         );
00118
00119     DX::ThrowIfFailed(
00120         font->CreateFontFace(&m_fontFace)
00121     );
00122 }
00123
00124 void FlowLayout::SetNumberSubstitution(Microsoft::WRL::ComPtr<IDWriteNumberSubstitution> numberSubstitution)
00125 {
00126     m_numberSubstitution = numberSubstitution;
00127 }
00128
00129 void FlowLayout::SetReadingDirection(ReadingDirection readingDirection)
00130 {
00131     m_readingDirection = readingDirection;
00132 }
00133
00134 ReadingDirection FlowLayout::GetReadingDirection()
00135 {
00136     return m_readingDirection;
00137 }
00138
00139 void FlowLayout::SetGlyphOrientationMode(GlyphOrientationMode glyphOrientationMode)
00140 {
00141     m_glyphOrientationMode = glyphOrientationMode;
00142 }
00143
00144 GlyphOrientationMode FlowLayout::GetGlyphOrientationMode()
00145 {
00146     return m_glyphOrientationMode;
00147 }
00148
00149 void FlowLayout::SetJustificationMode(JustificationMode justificationMode)
00150 {
00151     m_justificationMode = justificationMode;
00152 }
00153
00154 void FlowLayout::SetText(
00155     const wchar_t* text,
00156     UINT32 textLength
00157     )
00158 {
00159     // Analyzes the given text and keeps the results for later reflow.
00160     m_isTextAnalysisComplete = false;
00161
00162     m_text.assign(text, textLength);
00163 }
00164
00165 void FlowLayout::GetText(
00166     _Out_ const wchar_t** text,
00167     _Out_ UINT32* textLength
00168     )
00169 {
00170     *text = &m_text[0];
00171     *textLength = static_cast<UINT32>(m_text.size());
00172 }
00173
00174 void FlowLayout::AnalyzeText()
00175 {
00176     // Analyzes the given text and keeps the results for later reflow.
00177
00178     m_isTextAnalysisComplete = false;
00179
00180     if (m_fontFace == nullptr)
00181     {
00182         throw ref new Platform::FailureException;
00183     }
00184
00185     // Create a text analyzer.
00186     Microsoft::WRL::ComPtr<IDWriteTextAnalyzer> textAnalyzer0;
00187     Microsoft::WRL::ComPtr<IDWriteTextAnalyzer1> textAnalyzer;
00188
00189     DX::ThrowIfFailed(
00190         m_dwriteFactory->CreateTextAnalyzer(&textAnalyzer0)
00191         );
00192
00193     DX::ThrowIfFailed(
00194         textAnalyzer0.As(&textAnalyzer)
00195         );
00196
00197     // Record the analyzer's results.
00198     TextAnalysis textAnalysis(
00199         m_text.c_str(),
00200         static_cast<UINT32>(m_text.size()),
00201         m_localeName,
00202         m_numberSubstitution.Get(),
00203         m_readingDirection,
00204         m_glyphOrientationMode
00205         );
00206
00207     DX::ThrowIfFailed(
00208         textAnalysis.GenerateResults(textAnalyzer, m_runs, m_breakpoints)
00209         );
00210
00211     // Convert the entire text to glyphs.
00212     ShapeGlyphRuns(textAnalyzer);
00213
00214     m_isTextAnalysisComplete = true;
00215 }
00216
00217 void FlowLayout::ShapeGlyphRuns(Microsoft::WRL::ComPtr<IDWriteTextAnalyzer> textAnalyzer)
00218 {
00219     UINT32 textLength = static_cast<UINT32>(m_text.size());
00220
00221     // Estimate the maximum number of glyph indices needed to hold a string.
00222     UINT32 estimatedGlyphCount = EstimateGlyphCount(textLength);
00223
00224     m_glyphIndices.resize(estimatedGlyphCount);
00225     m_glyphOffsets.resize(estimatedGlyphCount);
00226     m_glyphAdvances.resize(estimatedGlyphCount);
00227     m_glyphClusters.resize(textLength);
00228
00229     UINT32 glyphStart = 0;
00230
00231     // Shape each run separately. This is needed whenever script, locale,
00232     // or reading direction changes.
00233     for (UINT32 runIndex = 0; runIndex < m_runs.size(); ++runIndex)
00234     {
00235         ShapeGlyphRun(textAnalyzer, runIndex, glyphStart);
00236     }
00237
00238     m_glyphIndices.resize(glyphStart);
00239     m_glyphOffsets.resize(glyphStart);
00240     m_glyphAdvances.resize(glyphStart);
00241 }
00242
00243 void FlowLayout::ShapeGlyphRun(
00244     Microsoft::WRL::ComPtr<IDWriteTextAnalyzer> textAnalyzer,
00245     UINT32 runIndex,
00246     _Inout_ UINT32& glyphStart
00247     )
00248 {
00249     // Shapes a single run of text into glyphs.
00250     // Alternately, you could iteratively interleave shaping and line
00251     // breaking to reduce the number glyphs held onto at once. It's simpler
00252     // for this demostration to just do shaping and line breaking as two
00253     // separate processes, but realize that this does have the consequence that
00254     // certain advanced fonts containing line specific features (like Gabriola)
00255     // will shape as if the line is not broken.
00256
00257     TextAnalysis::Run& run  = m_runs[runIndex];
00258     UINT32 textStart        = run.textStart;
00259     UINT32 textLength       = run.textLength;
00260     UINT32 maxGlyphCount    = static_cast<UINT32>(m_glyphIndices.size() - glyphStart);
00261     UINT32 actualGlyphCount = 0;
00262
00263     run.glyphStart          = glyphStart;
00264     run.glyphCount          = 0;
00265
00266     if (textLength == 0)
00267     {
00268         return;
00269     }
00270
00271     // Allocate space for shaping to fill with glyphs and other information,
00272     // with about as many glyphs as there are text characters. We'll actually
00273     // need more glyphs than codepoints if they are decomposed into separate
00274     // glyphs, or fewer glyphs than codepoints if multiple are substituted
00275     // into a single glyph. In any case, the shaping process will need some
00276     // room to apply those rules to even make that determintation.
00277     if (textLength > maxGlyphCount)
00278     {
00279         maxGlyphCount = EstimateGlyphCount(textLength);
00280         UINT32 totalGlyphsArrayCount = glyphStart + maxGlyphCount;
00281         m_glyphIndices.resize(totalGlyphsArrayCount);
00282     }
00283
00284     std::vector<DWRITE_SHAPING_TEXT_PROPERTIES>  textProps(textLength);
00285     std::vector<DWRITE_SHAPING_GLYPH_PROPERTIES> glyphProps(maxGlyphCount);
00286
00287     // Get the glyphs from the text, retrying if needed.
00288     DWRITE_FONT_FEATURE verticalFontFeatures[] = {DWRITE_FONT_FEATURE_TAG_VERTICAL_WRITING, 1};
00289     DWRITE_TYPOGRAPHIC_FEATURES verticalFontFeatureList = {&verticalFontFeatures[0], 1};
00290     DWRITE_TYPOGRAPHIC_FEATURES emptyFontFeatureList = {nullptr, 0};
00291     DWRITE_TYPOGRAPHIC_FEATURES const* fontFeatureListPointer = nullptr;
00292     const UINT32 fontFeatureLengths[1] = {textLength};
00293
00294     bool useFontFeatures = false;
00295     if (run.isSideways)
00296     {
00297         fontFeatureListPointer = &verticalFontFeatureList;
00298         useFontFeatures = true;
00299     }
00300
00301     DX::ThrowIfFailed(
00302         textAnalyzer->GetGlyphs(
00303             &m_text[textStart],
00304             textLength,
00305             m_fontFace.Get(),
00306             run.isSideways,
00307             run.isReversed,
00308             &run.script,
00309             m_localeName,
00310             (run.isNumberSubstituted) ? m_numberSubstitution.Get() : nullptr,
00311             nullptr,
00312             nullptr,
00313             0,
00314             maxGlyphCount,
00315             &m_glyphClusters[textStart],
00316             &textProps[0],
00317             &m_glyphIndices[glyphStart],
00318             &glyphProps[0],
00319             &actualGlyphCount
00320             )
00321         );
00322
00323     // Get the placement of the all the glyphs.
00324     m_glyphAdvances.resize(max(static_cast<size_t>(glyphStart + actualGlyphCount), m_glyphAdvances.size()));
00325     m_glyphOffsets.resize(max(static_cast<size_t>(glyphStart + actualGlyphCount), m_glyphOffsets.size()));
00326
00327     DX::ThrowIfFailed(
00328         textAnalyzer->GetGlyphPlacements(
00329             &m_text[textStart],
00330             &m_glyphClusters[textStart],
00331             &textProps[0],
00332             textLength,
00333             &m_glyphIndices[glyphStart],
00334             &glyphProps[0],
00335             actualGlyphCount,
00336             m_fontFace.Get(),
00337             m_fontEmSize,
00338             run.isSideways,
00339             run.isReversed,
00340             &run.script,
00341             m_localeName,
00342             nullptr,
00343             nullptr,
00344             0,
00345             &m_glyphAdvances[glyphStart],
00346             &m_glyphOffsets[glyphStart]
00347             )
00348         );
00349
00350     // Certain fonts, like Batang, contain glyphs for hidden control
00351     // and formatting characters. So we'll want to explicitly force their
00352     // advance to zero.
00353     if (run.script.shapes & DWRITE_SCRIPT_SHAPES_NO_VISUAL)
00354     {
00355         std::fill(
00356             m_glyphAdvances.begin() + glyphStart,
00357             m_glyphAdvances.begin() + glyphStart + actualGlyphCount,
00358             0.0f
00359             );
00360     }
00361
00362     // Set the final glyph count of this run and advance the starting glyph.
00363     run.glyphCount = actualGlyphCount;
00364     glyphStart    += actualGlyphCount;
00365 }
00366
00367 void FlowLayout::FlowText(
00368     Microsoft::WRL::ComPtr<FlowLayoutSource> flowSource,
00369     Microsoft::WRL::ComPtr<FlowLayoutSink> flowSink
00370     )
00371 {
00372     // Reflow all the text, from source to sink.
00373     if (!m_isTextAnalysisComplete)
00374     {
00375         throw ref new Platform::FailureException();
00376     }
00377
00378     // Determine the font line height, needed by the flow source.
00379     DWRITE_FONT_METRICS fontMetrics = {};
00380     m_fontFace->GetMetrics(&fontMetrics);
00381
00382     float fontHeight = (fontMetrics.ascent + fontMetrics.descent + fontMetrics.lineGap)
00383         * m_fontEmSize / fontMetrics.designUnitsPerEm;
00384
00385     // Get ready for series of glyph runs.
00386     flowSink->Prepare(static_cast<UINT32>(m_glyphIndices.size()));
00387
00388     // Set initial cluster position to beginning of text.
00389     ClusterPosition cluster, nextCluster;
00390     SetClusterPosition(cluster, 0);
00391
00392     FlowLayoutSource::RectF rect;
00393     UINT32 textLength = static_cast<UINT32>(m_text.size());
00394
00395     // Iteratively pull rect's from the source,
00396     // and push as much text will fit to the sink.
00397     while (cluster.textPosition < textLength)
00398     {
00399         // Pull the next rect from the source.
00400         if (!flowSource->GetNextRect(fontHeight, m_readingDirection, &rect))
00401         {
00402             break;
00403         }
00404
00405         if (rect.right <= rect.left && rect.bottom <= rect.top)
00406         {
00407             break; // Stop upon reaching zero sized rects.
00408         }
00409
00410         // Determine length of line.
00411         float uSize = (m_readingDirection & ReadingDirectionPrimaryAxis)
00412                     ? rect.bottom - rect.top
00413                     : rect.right  - rect.left;
00414
00415         if (uSize >= 0)
00416         {
00417             // Fit as many clusters between breakpoints that will go in.
00418             if (!FitText(cluster, textLength, uSize, &nextCluster))
00419                 break;
00420
00421             // Push the glyph runs to the sink.
00422             if (!ProduceGlyphRuns(flowSink, rect, cluster, nextCluster))
00423                 break;
00424
00425             cluster = nextCluster;
00426         }
00427     }
00428 }
00429
00430 bool FlowLayout::FitText(
00431     const ClusterPosition& clusterStart,
00432     UINT32 textEnd,
00433     float maxWidth,
00434     _Out_ ClusterPosition* clusterEnd
00435     )
00436 {
00437     // Fits as much text as possible into the given width,
00438     // using the clusters and advances returned by DWrite.
00439
00440     // Set the starting cluster to the starting text position,
00441     // and continue until we exceed the maximum width or hit
00442     // a hard break.
00443     ClusterPosition cluster(clusterStart);
00444     ClusterPosition nextCluster(clusterStart);
00445     UINT32 validBreakPosition   = cluster.textPosition;
00446     UINT32 bestBreakPosition    = cluster.textPosition;
00447     float textWidth             = 0;
00448
00449     while (cluster.textPosition < textEnd)
00450     {
00451         // Use breakpoint information to find where we can safely break words.
00452         AdvanceClusterPosition(nextCluster);
00453         const DWRITE_LINE_BREAKPOINT breakpoint = m_breakpoints[nextCluster.textPosition - 1];
00454
00455         // Check whether we exceeded the amount of text that can fit,
00456         // unless it's whitespace, which we allow to flow beyond the end.
00457         textWidth += GetClusterRangeWidth(cluster, nextCluster);
00458         if (textWidth > maxWidth && !breakpoint.isWhitespace)
00459         {
00460             // Want a minimum of one cluster.
00461             if (validBreakPosition > clusterStart.textPosition)
00462             {
00463                 break;
00464             }
00465         }
00466
00467         validBreakPosition = nextCluster.textPosition;
00468
00469         // See if we can break after this character cluster, and if so,
00470         // mark it as the new potential break point.
00471         if (breakpoint.breakConditionAfter != DWRITE_BREAK_CONDITION_MAY_NOT_BREAK)
00472         {
00473             bestBreakPosition = validBreakPosition;
00474             if (breakpoint.breakConditionAfter == DWRITE_BREAK_CONDITION_MUST_BREAK)
00475             {
00476                 break; // we have a hard return, so we've fit all we can.
00477             }
00478         }
00479         cluster = nextCluster;
00480     }
00481
00482     // Want last best position that didn't break a word, but if that's not available,
00483     // fit at least one cluster (emergency line breaking).
00484     if (bestBreakPosition == clusterStart.textPosition)
00485     {
00486         bestBreakPosition =  validBreakPosition;
00487     }
00488
00489     SetClusterPosition(cluster, bestBreakPosition);
00490
00491     *clusterEnd = cluster;
00492
00493     return 1;
00494 }
00495
00496 bool FlowLayout::ProduceGlyphRuns(
00497     Microsoft::WRL::ComPtr<FlowLayoutSink> flowSink,
00498     const FlowLayoutSource::RectF& rect,
00499     const ClusterPosition& clusterStart,
00500     const ClusterPosition& clusterEnd
00501     ) const
00502 {
00503     // Produce a series of glyph runs from the given range
00504     // and send them to the sink. If the entire text fit
00505     // into the rect, then we'll only pass on a single glyph
00506     // run.
00507
00508     const bool isVertical = (m_readingDirection & ReadingDirectionPrimaryAxis) != 0;
00509     const bool isReversedPrimaryDirection = (m_readingDirection & ReadingDirectionPrimaryProgression) != 0;
00510
00511     // Determine length of line.
00512     const float uSize = (m_readingDirection & ReadingDirectionPrimaryAxis)
00513         ? rect.bottom - rect.top
00514         : rect.right  - rect.left;
00515
00516     // Figure out how many runs we cross, because this is the number
00517     // of distinct glyph runs we'll need to reorder visually.
00518
00519     UINT32 runIndexEnd = clusterEnd.runIndex;
00520     if (clusterEnd.textPosition > m_runs[runIndexEnd].textStart)
00521     {
00522         ++runIndexEnd; // Only partially cover the run, so round up.
00523     }
00524
00525     // Fill in mapping from visual run to logical sequential run.
00526     UINT32 bidiOrdering[100];
00527     UINT32 totalRuns = runIndexEnd - clusterStart.runIndex;
00528     totalRuns = min(totalRuns, static_cast<UINT32>(ARRAYSIZE(bidiOrdering)));
00529
00530     ProduceBidiOrdering(
00531         clusterStart.runIndex,
00532         totalRuns,
00533         &bidiOrdering[0]
00534         );
00535
00536     // Ignore any trailing whitespace
00537
00538     // Look backward from end until we find non-space.
00539     UINT32 trailingWsPosition = clusterEnd.textPosition;
00540     for (; trailingWsPosition > clusterStart.textPosition; --trailingWsPosition)
00541     {
00542         if (!m_breakpoints[trailingWsPosition-1].isWhitespace)
00543         {
00544             break; // Encountered last significant character.
00545         }
00546     }
00547
00548     // Set the glyph run's ending cluster to the last whitespace.
00549     ClusterPosition clusterWsEnd(clusterStart);
00550     SetClusterPosition(clusterWsEnd, trailingWsPosition);
00551
00552     // Produce justified advances to reduce the jagged edge.
00553     std::vector<float> justifiedAdvances;
00554     ProduceJustifiedAdvances(uSize, clusterStart, clusterWsEnd, justifiedAdvances);
00555     UINT32 justificationGlyphStart = GetClusterGlyphStart(clusterStart);
00556
00557     // Determine starting point for alignment.
00558     float u         = (isVertical) ? rect.top  : rect.left;
00559     float v         = (isVertical) ? rect.left : rect.bottom;
00560     float ascent    = 0;
00561     float descent   = 0;
00562     float central   = 0;
00563
00564     DWRITE_FONT_METRICS fontMetrics;
00565     m_fontFace->GetMetrics(&fontMetrics);
00566
00567     ascent  = (fontMetrics.ascent  * m_fontEmSize / fontMetrics.designUnitsPerEm);
00568     descent = (fontMetrics.descent * m_fontEmSize / fontMetrics.designUnitsPerEm);
00569     central = (((fontMetrics.descent + fontMetrics.ascent) / 2) * m_fontEmSize / fontMetrics.designUnitsPerEm);
00570
00571     if (isReversedPrimaryDirection)
00572     {
00573         // For RTL, we neeed the run width to adjust the origin
00574         // so it starts on the right side.
00575         UINT32 glyphStart = GetClusterGlyphStart(clusterStart);
00576         UINT32 glyphEnd   = GetClusterGlyphStart(clusterWsEnd);
00577
00578         if (glyphStart < glyphEnd)
00579         {
00580             float lineWidth = GetClusterRangeWidth(
00581                 glyphStart - justificationGlyphStart,
00582                 glyphEnd   - justificationGlyphStart,
00583                 &justifiedAdvances.front()
00584                 );
00585             u += uSize - lineWidth;
00586         }
00587     }
00588
00589     for (size_t i = 0; i < totalRuns; ++i)
00590     {
00591         const TextAnalysis::Run& run    = m_runs[bidiOrdering[i]];
00592         UINT32 glyphStart               = run.glyphStart;
00593         UINT32 glyphEnd                 = glyphStart + run.glyphCount;
00594
00595         // If the run is only partially covered, we'll need to find
00596         // the subsection of glyphs that were fit.
00597         if (clusterStart.textPosition > run.textStart)
00598         {
00599             glyphStart = GetClusterGlyphStart(clusterStart);
00600         }
00601         if (clusterWsEnd.textPosition < run.textStart + run.textLength)
00602         {
00603             glyphEnd = GetClusterGlyphStart(clusterWsEnd);
00604         }
00605         if ((glyphStart >= glyphEnd)
00606             || (run.script.shapes & DWRITE_SCRIPT_SHAPES_NO_VISUAL))
00607         {
00608             // The itemizer told us not to draw this character,
00609             // either because it was a formatting, control, or other hidden character.
00610             continue;
00611         }
00612
00613         // The run width is needed to know how far to move forward,
00614         // and to flip the origin for right-to-left text.
00615         float runWidth = GetClusterRangeWidth(
00616             glyphStart - justificationGlyphStart,
00617             glyphEnd   - justificationGlyphStart,
00618             &justifiedAdvances.front()
00619             );
00620
00621         // Adjust glyph run to the appropriate baseline.
00622         float vAdjustment;
00623         if (run.isSideways)
00624         {
00625             vAdjustment = central;
00626         }
00627         else
00628         {
00629             if (!!(run.bidiLevel & 1) != run.isReversed)
00630             {
00631                 vAdjustment = ascent; // occurs for Arabic in stacked vertical and Mongolian in inline horizontal
00632             }
00633             else
00634             {
00635                 vAdjustment = descent; // the common case
00636             }
00637         }
00638         float adjustedV = v + (isVertical ? vAdjustment : -vAdjustment);
00639         float adjustedU = u + ((run.bidiLevel & 1) ? runWidth : 0); // origin starts from right if RTL
00640
00641         // Flush this glyph run.
00642         flowSink->SetGlyphRun(
00643             isVertical ? adjustedV : adjustedU,
00644             isVertical ? adjustedU : adjustedV,
00645             glyphEnd - glyphStart,
00646             &m_glyphIndices[glyphStart],
00647             &justifiedAdvances[glyphStart - justificationGlyphStart],
00648             &m_glyphOffsets[glyphStart],
00649             m_fontFace,
00650             m_fontEmSize,
00651             run.glyphOrientation,
00652             run.isReversed,
00653             run.isSideways
00654             );
00655
00656         u += runWidth;
00657     }
00658     return 1;
00659 }
00660
00661 void FlowLayout::ProduceBidiOrdering(
00662     UINT32 spanStart,
00663     UINT32 spanCount,
00664     _Out_writes_(spanCount) UINT32* spanIndices
00665     ) const
00666 {
00667     // Produces an index mapping from sequential order to visual bidi order.
00668     // The function progresses forward, checking the bidi level of each
00669     // pair of spans, reversing when needed.
00670     //
00671     // See the Unicode technical report 9 for an explanation.
00672     // http://www.unicode.org/reports/tr9/tr9-17.html
00673
00674     // Fill all entries with initial indices
00675     for (UINT32 i = 0; i < spanCount; ++i)
00676     {
00677         spanIndices[i] = spanStart + i;
00678     }
00679
00680     if (spanCount <= 1)
00681     {
00682         return;
00683     }
00684
00685     size_t runStart = 0;
00686     UINT32 currentLevel = m_runs[spanStart].bidiLevel;
00687
00688     // Rearrange each run to produced reordered spans.
00689     for (size_t i = 0; i < spanCount; ++i)
00690     {
00691         size_t runEnd       = i + 1;
00692         UINT32 nextLevel    = (runEnd < spanCount)
00693                             ? m_runs[spanIndices[runEnd]].bidiLevel
00694                             : 0; // past last element
00695
00696         // We only care about transitions, particularly high to low,
00697         // because that means we have a run behind us where we can
00698         // do something.
00699
00700         if (currentLevel <= nextLevel) // This is now the beginning of the next run.
00701         {
00702             if (currentLevel < nextLevel)
00703             {
00704                 currentLevel = nextLevel;
00705                 runStart     = i + 1;
00706             }
00707             continue; // Skip past equal levels, or increasing stairsteps.
00708         }
00709
00710         do // currentLevel > nextLevel
00711         {
00712             // Recede to find start of the run and previous level.
00713             UINT32 previousLevel;
00714             for (;;)
00715             {
00716                 if (runStart <= 0) // reached front of index list
00717                 {
00718                     previousLevel = 0; // position before string has bidi level of 0
00719                     break;
00720                 }
00721                 if (m_runs[spanIndices[--runStart]].bidiLevel < currentLevel)
00722                 {
00723                     previousLevel = m_runs[spanIndices[runStart]].bidiLevel;
00724                     ++runStart; // compensate for going one element past
00725                     break;
00726                 }
00727             }
00728
00729             // Reverse the indices, if the difference between the current and
00730             // next/previous levels is odd. Otherwise, it would be a no-op, so
00731             // don't bother.
00732             if ((min(currentLevel - nextLevel, currentLevel - previousLevel) & 1) != 0)
00733             {
00734                 std::reverse(spanIndices + runStart, spanIndices + runEnd);
00735             }
00736
00737             // Descend to the next lower level, the greater of previous and next
00738             currentLevel = max(previousLevel, nextLevel);
00739         }
00740         while (currentLevel > nextLevel); // Continue until completely flattened.
00741     }
00742 }
00743
00744 void FlowLayout::ProduceJustifiedAdvances(
00745     float maxWidth,
00746     const ClusterPosition& clusterStart,
00747     const ClusterPosition& clusterEnd,
00748     _Out_ std::vector<float>& justifiedAdvances
00749     ) const
00750 {
00751     // Performs simple inter-word justification
00752     // using the breakpoint analysis whitespace property.
00753
00754     // Copy out default, unjustified advances.
00755     UINT32 glyphStart   = GetClusterGlyphStart(clusterStart);
00756     UINT32 glyphEnd     = GetClusterGlyphStart(clusterEnd);
00757
00758     justifiedAdvances.assign(m_glyphAdvances.begin() + glyphStart, m_glyphAdvances.begin() + glyphEnd);
00759
00760
00761     if (m_justificationMode == JustificationModeNone)
00762     {
00763         return; // Nothing to justify.
00764     }
00765
00766     if (glyphEnd - glyphStart == 0)
00767     {
00768         return; // No glyphs to modify.
00769     }
00770
00771     if (maxWidth <= 0)
00772     {
00773         return; // Text can't fit anyway.
00774     }
00775
00776     // First, count how many spaces there are in the text range.
00777     ClusterPosition cluster(clusterStart);
00778     UINT32 whitespaceCount = 0;
00779
00780     while (cluster.textPosition < clusterEnd.textPosition)
00781     {
00782         if (m_breakpoints[cluster.textPosition].isWhitespace)
00783         {
00784             ++whitespaceCount;
00785         }
00786         AdvanceClusterPosition(cluster);
00787     }
00788     if (whitespaceCount <= 0)
00789     {
00790         return; // Can't justify using spaces, since none exist.
00791     }
00792
00793     // Second, determine the needed contribution to each space.
00794     float lineWidth             = GetClusterRangeWidth(glyphStart, glyphEnd, &m_glyphAdvances.front());
00795     float justificationPerSpace = (maxWidth - lineWidth) / whitespaceCount;
00796
00797     if (justificationPerSpace  <= 0)
00798     {
00799         return; // Either already justified or would be negative justification.
00800     }
00801
00802     if (justificationPerSpace > m_maxSpaceWidth)
00803     {
00804         return; // Avoid justification if it would space the line out awkwardly far.
00805     }
00806
00807     // Lastly, adjust the advance widths, adding the difference to each space character.
00808     cluster = clusterStart;
00809     while (cluster.textPosition < clusterEnd.textPosition)
00810     {
00811         if (m_breakpoints[cluster.textPosition].isWhitespace)
00812         {
00813             justifiedAdvances[GetClusterGlyphStart(cluster) - glyphStart] += justificationPerSpace;
00814         }
00815
00816         AdvanceClusterPosition(cluster);
00817     }
00818 }
00819
00820 // Since layout should never split text clusters, we want to move ahead whole
00821 // clusters at a time.
00822 void FlowLayout::SetClusterPosition(
00823     _Inout_ ClusterPosition& cluster,
00824     UINT32 textPosition
00825     ) const
00826 {
00827     // Updates the current position and seeks its matching text analysis run.
00828     cluster.textPosition = textPosition;
00829
00830     // If the new text position is outside the previous analysis run,
00831     // find the right one.
00832     if (textPosition >= cluster.runEndPosition
00833         || !m_runs[cluster.runIndex].ContainsTextPosition(textPosition))
00834     {
00835         // If we can resume the search from the previous run index,
00836         // (meaning the new text position comes after the previously
00837         // seeked one), we can save some time. Otherwise restart from
00838         // the beginning.
00839
00840         UINT32 newRunIndex = 0;
00841         if (textPosition >= m_runs[cluster.runIndex].textStart)
00842         {
00843             newRunIndex = cluster.runIndex;
00844         }
00845
00846         // Find new run that contains the text position.
00847         newRunIndex = static_cast<UINT32>(
00848             std::find(m_runs.begin() + newRunIndex, m_runs.end(), textPosition)
00849             - m_runs.begin()
00850             );
00851
00852         // Keep run index within the list, rather than pointing off the end.
00853         if (newRunIndex >= m_runs.size())
00854         {
00855             newRunIndex  = static_cast<UINT32>(m_runs.size() - 1);
00856         }
00857
00858         // Cache the position of the next analysis run to efficiently
00859         // move forward in the clustermap.
00860         const TextAnalysis::Run& matchingRun    = m_runs[newRunIndex];
00861         cluster.runIndex                        = newRunIndex;
00862         cluster.runEndPosition                  = matchingRun.textStart + matchingRun.textLength;
00863     }
00864 }
00865
00866 void FlowLayout::AdvanceClusterPosition(
00867     _Inout_ ClusterPosition& cluster
00868     ) const
00869 {
00870     // Looks forward in the cluster map until finding a new cluster,
00871     // or until we reach the end of a cluster run returned by shaping.
00872     //
00873     // Glyph shaping can produce a clustermap where a:
00874     //  - A single codepoint maps to a single glyph (simple Latin and precomposed CJK)
00875     //  - A single codepoint to several glyphs (diacritics decomposed into distinct glyphs)
00876     //  - Multiple codepoints are coalesced into a single glyph.
00877     //
00878     UINT32 textPosition = cluster.textPosition;
00879     UINT32 clusterId    = m_glyphClusters[textPosition];
00880
00881     for (++textPosition; textPosition < cluster.runEndPosition; ++textPosition)
00882     {
00883         if (m_glyphClusters[textPosition] != clusterId)
00884         {
00885             // Now pointing to the next cluster.
00886             cluster.textPosition = textPosition;
00887             return;
00888         }
00889     }
00890     if (textPosition == cluster.runEndPosition)
00891     {
00892         // We crossed a text analysis run.
00893         SetClusterPosition(cluster, textPosition);
00894     }
00895 }
00896
00897 UINT32 FlowLayout::GetClusterGlyphStart(const ClusterPosition& cluster) const
00898 {
00899     // Maps from text position to corresponding starting index in the glyph array.
00900     // This is needed because there isn't a 1:1 correspondence between text and
00901     // glyphs produced.
00902
00903     UINT32 glyphStart = m_runs[cluster.runIndex].glyphStart;
00904
00905     return (cluster.textPosition < m_glyphClusters.size())
00906         ? glyphStart + m_glyphClusters[cluster.textPosition]
00907         : glyphStart + m_runs[cluster.runIndex].glyphCount;
00908 }
00909
00910 float FlowLayout::GetClusterRangeWidth(
00911     const ClusterPosition& clusterStart,
00912     const ClusterPosition& clusterEnd
00913     ) const
00914 {
00915     // Sums the glyph advances between two cluster positions,
00916     // useful for determining how long a line or word is.
00917     return GetClusterRangeWidth(
00918         GetClusterGlyphStart(clusterStart),
00919         GetClusterGlyphStart(clusterEnd),
00920         &m_glyphAdvances.front()
00921         );
00922 }
00923
00924 float FlowLayout::GetClusterRangeWidth(
00925     UINT32 glyphStart,
00926     UINT32 glyphEnd,
00927     const float* glyphAdvances
00928     ) const
00929 {
00930     // Sums the glyph advances between two glyph offsets, given an explicit
00931     // advances array - useful for determining how long a line or word is.
00932     return std::accumulate(glyphAdvances + glyphStart, glyphAdvances + glyphEnd, 0.0f);
00933 }
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DXGI swap chain rotation/C++/DirectXSample.h Source File

  • DXGI swap chain rotation

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
00010 // This header defines helper utilities to make DirectX APIs work with exceptions.
00011 namespace DX
00012 {
00013     inline void ThrowIfFailed(HRESULT hr)
00014     {
00015         if (FAILED(hr))
00016         {
00017             // Set a breakpoint on this line to catch DX API errors.
00018             throw Platform::Exception::CreateException(hr);
00019         }
00020     }
00021 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::ToastContent::ToastText04 Member List

This is the complete list of members for NotificationsExtensions::ToastContent::ToastText04, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
Audio | NotificationsExtensions::ToastContent::ToastNotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
CreateNotification() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline]
Duration | NotificationsExtensions::ToastContent::ToastNotificationBase |
GetContent() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline, virtual]
GetContent() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline, virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
Launch | NotificationsExtensions::ToastContent::ToastNotificationBase |
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextBody1 | NotificationsExtensions::ToastContent::ToastText04 |
TextBody2 | NotificationsExtensions::ToastContent::ToastText04 |
TextFields | NotificationsExtensions::NotificationBase |
TextHeading | NotificationsExtensions::ToastContent::ToastText04 |
ToastNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline]
ToastNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline]
ToastText04() | NotificationsExtensions::ToastContent::ToastText04 | [inline]
ToastText04() | NotificationsExtensions::ToastContent::ToastText04 | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Thread pool/C++/common/LayoutAwarePage.cpp Source File

  • Thread pool
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:33 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Sharing content source app/C++/ShareHtml.xaml.h Source File

  • Sharing content source app

ShareHtml.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 // ShareHtml.xaml.h
00013 // Declaration of the ShareHtml class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "SharePage.h"
00020 #include "ShareHtml.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKSample
00024 {
00025     namespace ShareSource
00026     {
00027         public ref class ShareHtml sealed
00028         {
00029         public:
00030             ShareHtml();
00031
00032         protected:
00033             virtual bool GetShareContent(Windows::ApplicationModel::DataTransfer::DataRequest^ request) override;
00034
00035         private:
00036             void ShareWebView_LoadCompleted(Platform::Object^ sender, Windows::UI::Xaml::Navigation::NavigationEventArgs^ e);
00037         };
00038     }
00039 }
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Compression/C++/common/suspensionmanager.h Source File

  • Compression
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: StreamSocket/C++/Scenario2.xaml.cpp Source File

  • StreamSocket

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 StreamSocketSample;
00020
00021 using namespace Concurrency;
00022 using namespace Platform;
00023 using namespace Windows::ApplicationModel::Core;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Networking;
00026 using namespace Windows::Networking::Sockets;
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 }
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 Scenario2::OnNavigatedTo(NavigationEventArgs^ e)
00042 {
00043     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00044     // as NotifyUser()
00045     rootPage = MainPage::Current;
00046 }
00047
00048
00049 void Scenario2::ConnectSocket_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00050 {
00051     // Overriding the socket here is safe as it will be deleted once all references to it are gone. However, in many cases this
00052     // is a dangerous pattern to override data semi-randomly (each time user clicked the button) so we block it here.
00053     if (CoreApplication::Properties->HasKey("clientSocket"))
00054     {
00055         rootPage->NotifyUser("This step has already been executed. Please move to the next one.", NotifyType::ErrorMessage);
00056         return;
00057     }
00058
00059     if (ServiceNameForConnect->Text == nullptr)
00060     {
00061         rootPage->NotifyUser("Please provide a service name.", NotifyType::ErrorMessage);
00062         return;
00063     }
00064
00065     // By default 'HostNameForConnect' is disabled and host name validation is not required. When enabling the text
00066     // box validating the host name is required since it was received from an untrusted source (user input).
00067     // The host name is validated by catching InvalidArgumentExceptions thrown by the HostName constructor for invalid
00068     // input.
00069     // Note that when enabling the text box users may provide names for hosts on the intErnet that require the
00070     // "Internet (Client)" capability.
00071     HostName^ hostName;
00072     try
00073     {
00074         hostName = ref new HostName(HostNameForConnect->Text);
00075     }
00076     catch (InvalidArgumentException^ e)
00077     {
00078         rootPage->NotifyUser("Error: Invalid host name.", NotifyType::ErrorMessage);
00079         return;
00080     }
00081
00082     StreamSocket^ socket = ref new StreamSocket();
00083
00084     // Save the socket, so subsequent steps can use it.
00085     CoreApplication::Properties->Insert("clientSocket", socket);
00086
00087     rootPage->NotifyUser("Connecting to: " + HostNameForConnect->Text, NotifyType::StatusMessage);
00088
00089     // Connect to the server (in our case the listener we created in previous step).
00090     task<void>(socket->ConnectAsync(hostName, ServiceNameForConnect->Text, SocketProtectionLevel::PlainSocket)).then([this] (task<void> previousTask)
00091     {
00092         try
00093         {
00094             // Try getting all exceptions from the continuation chain above this point.
00095             previousTask.get();
00096             rootPage->NotifyUser("Connected", NotifyType::StatusMessage);
00097
00098             // Mark the socket as connected. We do not really care about the value of the property, the mere existance if it means that we are connected.
00099             CoreApplication::Properties->Insert("connected", nullptr);
00100         }
00101         catch (Exception^ exception)
00102         {
00103             rootPage->NotifyUser("Connect failed with error: " + exception->Message, NotifyType::ErrorMessage);
00104         }
00105     });
00106 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Splash screen/C++/Scenario1.xaml.cpp Source File

  • Splash screen

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::SplashScreen;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 Scenario1::Scenario1()
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 Scenario1::OnNavigatedTo(NavigationEventArgs^ e)
00036 {
00037     if (MainPage::Current->Dismissed)
00038     {
00039         OutputTextBlock->Text = "Received the splash screen dismissal event.";
00040     }
00041     else
00042     {
00043         OutputTextBlock->Text = "The application didn't receive the splash screen dismissal event.";
00044     }
00045 }
Generated on Sat Nov 23 2024 16:07:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D tutorial/C++/Lesson5.Components/Direct3DTutorial.cpp Source File

  • Direct3D tutorial
  • Lesson5.Components

Direct3DTutorial.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 "Direct3DTutorial.h"
00010 #include "BasicShapes.h"
00011 #include "BasicLoader.h"
00012
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::Foundation;
00015 using namespace Windows::UI::Core;
00016
00017 Direct3DTutorial::Direct3DTutorial()
00018 {
00019 }
00020
00021 void Direct3DTutorial::CreateDeviceIndependentResources()
00022 {
00023     DirectXBase::CreateDeviceIndependentResources();
00024 }
00025
00026 void Direct3DTutorial::CreateDeviceResources()
00027 {
00028     DirectXBase::CreateDeviceResources();
00029
00030     BasicLoader^ loader = ref new BasicLoader(m_d3dDevice.Get());
00031
00032     loader->LoadShader(
00033         L"SimpleVertexShader.cso",
00034         nullptr,
00035         0,
00036         &m_vertexShader,
00037         &m_inputLayout
00038         );
00039
00040     // create the vertex and index buffers for drawing the cube
00041
00042     BasicShapes^ shapes = ref new BasicShapes(m_d3dDevice.Get());
00043
00044     shapes->CreateCube(
00045         &m_vertexBuffer,
00046         &m_indexBuffer,
00047         nullptr,
00048         &m_indexCount
00049         );
00050
00051     // create the constant buffer for updating model and camera data
00052     CD3D11_BUFFER_DESC constantBufferDesc(sizeof(ConstantBuffer), D3D11_BIND_CONSTANT_BUFFER);
00053     DX::ThrowIfFailed(
00054         m_d3dDevice->CreateBuffer(
00055             &constantBufferDesc,
00056             nullptr,             // leave the buffer uninitialized
00057             &m_constantBuffer
00058             )
00059         );
00060
00061     loader->LoadShader(
00062         L"SimplePixelShader.cso",
00063         &m_pixelShader
00064         );
00065
00066     loader->LoadTexture(
00067         L"reftexture.dds",
00068         &m_texture,
00069         &m_textureSRV
00070         );
00071
00072     // create the sampler
00073     D3D11_SAMPLER_DESC samplerDesc;
00074     ZeroMemory(&samplerDesc, sizeof(D3D11_SAMPLER_DESC));
00075     samplerDesc.Filter = D3D11_FILTER_ANISOTROPIC;
00076     samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
00077     samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
00078     samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
00079     samplerDesc.MipLODBias = 0.0f;
00080     // use 4x on feature level 9.2 and above, otherwise use only 2x
00081     samplerDesc.MaxAnisotropy = m_featureLevel > D3D_FEATURE_LEVEL_9_1 ? 4 : 2;
00082     samplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
00083     samplerDesc.BorderColor[0] = 0.0f;
00084     samplerDesc.BorderColor[1] = 0.0f;
00085     samplerDesc.BorderColor[2] = 0.0f;
00086     samplerDesc.BorderColor[3] = 0.0f;
00087     // allow use of all mip levels
00088     samplerDesc.MinLOD = 0;
00089     samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
00090
00091     DX::ThrowIfFailed(
00092         m_d3dDevice->CreateSamplerState(
00093             &samplerDesc,
00094             &m_sampler)
00095         );
00096
00097     m_camera = ref new BasicCamera();
00098
00099     m_sampleOverlay = ref new SampleOverlay();
00100
00101     m_sampleOverlay->Initialize(
00102         m_d2dDevice.Get(),
00103         m_d2dContext.Get(),
00104         m_wicFactory.Get(),
00105         m_dwriteFactory.Get(),
00106         "C++ and Direct3D tutorial sample for Windows Store apps"
00107         );
00108 }
00109
00110 void Direct3DTutorial::CreateWindowSizeDependentResources()
00111 {
00112     DirectXBase::CreateWindowSizeDependentResources();
00113
00114     // update the 3D projection matrix
00115     m_camera->SetProjectionParameters(
00116         70.0f,                                                // use a 70-degree vertical field of view
00117         m_renderTargetSize.Width / m_renderTargetSize.Height, // specify the aspect ratio of the window
00118         0.01f,                                                // specify the nearest Z-distance at which to draw vertices
00119         100.0f                                                // specify the farthest Z-distance at which to draw vertices
00120         );
00121
00122     // save the new projection matrix to the constant buffer data struct
00123     m_camera->GetProjectionMatrix(&m_constantBufferData.projection);
00124
00125     m_sampleOverlay->UpdateForWindowSizeChange();
00126 }
00127
00128 void Direct3DTutorial::Update(float timeTotal, float timeDelta)
00129 {
00130     // update the model matrix based on the time
00131     m_constantBufferData.model = rotationY(-timeTotal * 60.0f);
00132
00133     // update the view matrix based on the camera position
00134     // note that for this sample, the camera position is fixed
00135     m_camera->SetViewParameters(
00136         float3(0, 1.0f, 2.0f),
00137         float3(0, 0, 0),
00138         float3(0, 1, 0)
00139         );
00140
00141     m_camera->GetViewMatrix(&m_constantBufferData.view);
00142
00143     // update the constant buffer with the new data
00144     m_d3dContext->UpdateSubresource(
00145         m_constantBuffer.Get(),
00146         0,
00147         nullptr,
00148         &m_constantBufferData,
00149         0,
00150         0
00151         );
00152 }
00153
00154 void Direct3DTutorial::Render()
00155 {
00156     m_d3dContext->OMSetRenderTargets(
00157         1,
00158         m_d3dRenderTargetView.GetAddressOf(),
00159         m_d3dDepthStencilView.Get()
00160         );
00161
00162     // clear both the render target and depth stencil to default values
00163     const float ClearColor[4] = { 0.071f, 0.040f, 0.561f, 1.0f };
00164     m_d3dContext->ClearRenderTargetView(
00165         m_d3dRenderTargetView.Get(),
00166         ClearColor
00167         );
00168
00169     m_d3dContext->ClearDepthStencilView(
00170         m_d3dDepthStencilView.Get(),
00171         D3D11_CLEAR_DEPTH,
00172         1.0f,
00173         0
00174         );
00175
00176     m_d3dContext->IASetInputLayout(m_inputLayout.Get());
00177
00178     // set the vertex and index buffers, and specify the way they define geometry
00179     UINT stride = sizeof(BasicVertex);
00180     UINT offset = 0;
00181     m_d3dContext->IASetVertexBuffers(
00182         0,                              // starting at the first vertex buffer slot
00183         1,                              // set one vertex buffer binding
00184         m_vertexBuffer.GetAddressOf(),
00185         &stride,                        // specify the size in bytes of a single vertex
00186         &offset                         // specify the base vertex in the buffer
00187         );
00188
00189     // set the index buffer
00190     m_d3dContext->IASetIndexBuffer(
00191         m_indexBuffer.Get(),
00192         DXGI_FORMAT_R16_UINT,   // unsigned short index format
00193         0                       // specify the base index in the buffer
00194         );
00195
00196     // specify the way the vertex and index buffers define geometry
00197     m_d3dContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
00198
00199     // set the vertex shader stage state
00200     m_d3dContext->VSSetShader(
00201         m_vertexShader.Get(),
00202         nullptr,                // don't use shader linkage
00203         0                       // don't use shader linkage
00204         );
00205
00206     m_d3dContext->VSSetConstantBuffers(
00207         0,                              // starting at the first constant buffer slot
00208         1,                              // set one constant buffer binding
00209         m_constantBuffer.GetAddressOf()
00210         );
00211
00212     // set the pixel shader stage state
00213     m_d3dContext->PSSetShader(
00214         m_pixelShader.Get(),
00215         nullptr,                // don't use shader linkage
00216         0                       // don't use shader linkage
00217         );
00218
00219     m_d3dContext->PSSetShaderResources(
00220         0,                          // starting at the first shader resource slot
00221         1,                          // set one shader resource binding
00222         m_textureSRV.GetAddressOf()
00223         );
00224
00225     m_d3dContext->PSSetSamplers(
00226         0,                          // starting at the first sampler slot
00227         1,                          // set one sampler binding
00228         m_sampler.GetAddressOf()
00229         );
00230
00231     // draw the cube
00232     m_d3dContext->DrawIndexed(
00233         m_indexCount,   // draw all created vertices
00234         0,              // starting with the first vertex
00235         0               // and the first index
00236         );
00237
00238     m_sampleOverlay->Render();
00239 }
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Mobile broadband account provisioning/C++/ProvisionMno.xaml.h Source File

  • Mobile broadband account provisioning

ProvisionMno.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 // ProvisionMno.xaml.h
00013 // Declaration of the ProvisionMno class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "ProvisionMno.g.h"
00020 #include "MainPage.xaml.h"
00021 #include "Util.h"
00022
00023 namespace SDKSample
00024 {
00025     namespace ProvisioningAgent
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 ProvisionMno sealed
00032         {
00033         public:
00034             ProvisionMno();
00035
00036         protected:
00037             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00038         private:
00039             MainPage^ rootPage;
00040             Util^ util;
00041             void ProvisionMno_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00042         };
00043     }
00044 }
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Lock screen personalization/C++/App.xaml.cpp Source File

  • Lock screen personalization

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Lock screen personalization/C++/App.xaml.h Source File

  • Lock screen personalization

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML FlipView control/C++/Scenario5.xaml.cpp Source File

  • XAML FlipView control

Scenario5.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 // Scenario5.xaml.cpp
00013 // Implementation of the Scenario5 class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario5.xaml.h"
00018 #include "SampleDataSource.h"
00019
00020 using namespace SDKSample::FlipViewCPP;
00021 using namespace SDKSample::FlipViewData;
00022
00023 using namespace Windows::UI::Xaml;
00024 using namespace Windows::UI::Xaml::Controls;
00025 using namespace Windows::UI::Xaml::Navigation;
00026
00027 Scenario5::Scenario5():bHorizontal(true)
00028 {
00029     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 void Scenario5::OnNavigatedTo(NavigationEventArgs^ e)
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     rootPage = MainPage::Current;
00042
00043   auto sampleData = ref new FlipViewData::SampleDataSource();
00044   FlipView5Horizontal->ItemsSource = sampleData->Items;
00045   FlipView5Vertical->ItemsSource = sampleData->Items;
00046 }
00047
00048 void SDKSample::FlipViewCPP::Scenario5::Orientation_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00049 {
00050     bHorizontal = !bHorizontal;
00051     if (bHorizontal)
00052     {
00053         Orientation->Content = "Vertical";
00054         FlipView5Horizontal->SelectedIndex = FlipView5Vertical->SelectedIndex;
00055         FlipView5Horizontal->Visibility = Windows::UI::Xaml::Visibility::Visible;
00056         FlipView5Vertical->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00057     }
00058     else
00059     {
00060         Orientation->Content = "Horizontal";
00061         FlipView5Vertical->SelectedIndex = FlipView5Horizontal->SelectedIndex;
00062         FlipView5Vertical->Visibility = Windows::UI::Xaml::Visibility::Visible;
00063         FlipView5Horizontal->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00064     }
00065 }
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Folder enumeration/C++/MainPage.xaml.h Source File

  • Folder enumeration

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:46 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite hit testing/C++/DWriteHitTesting.h Source File

  • DirectWrite hit testing

DWriteHitTesting.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 "DirectXBase.h"
00011 #include "SampleOverlay.h"
00012
00013 ref class DWriteHitTesting : public DirectXBase, public Windows::ApplicationModel::Core::IFrameworkView
00014 {
00015 internal:
00016     DWriteHitTesting();
00017
00018     // DirectXBase Methods
00019     virtual void CreateDeviceIndependentResources() override;
00020     virtual void CreateDeviceResources() override;
00021     virtual void CreateWindowSizeDependentResources() override;
00022     virtual void Render() override;
00023
00024 public:
00025     // IFrameworkView Methods
00026     virtual void Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00027     virtual void SetWindow(_In_ Windows::UI::Core::CoreWindow^ window);
00028     virtual void Load(_In_ Platform::String^ entryPoint);
00029     virtual void Run();
00030     virtual void Uninitialize();
00031
00032 private:
00033     // Event Handlers
00034     void OnWindowSizeChanged(
00035         _In_ Windows::UI::Core::CoreWindow^ sender,
00036         _In_ Windows::UI::Core::WindowSizeChangedEventArgs^ args
00037         );
00038
00039     void OnLogicalDpiChanged(
00040         _In_ Platform::Object^ sender
00041         );
00042
00043     void OnDisplayContentsInvalidated(
00044         _In_ Platform::Object^ sender
00045         );
00046
00047     void OnActivated(
00048         _In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView,
00049         _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^ args
00050         );
00051
00052     void OnSuspending(
00053         _In_ Platform::Object^ sender,
00054         _In_ Windows::ApplicationModel::SuspendingEventArgs^ args
00055         );
00056
00057     void OnResuming(
00058         _In_ Platform::Object^ sender,
00059         _In_ Platform::Object^ args
00060         );
00061
00062     void OnPointerPressed(
00063         _In_ Windows::UI::Core::CoreWindow^ sender,
00064         _In_ Windows::UI::Core::PointerEventArgs^ args
00065         );
00066
00067     void SetUnderlineOnRedraw();
00068
00069     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>                    m_blackBrush;
00070     Microsoft::WRL::ComPtr<IDWriteTextFormat>                       m_textFormat;
00071     Microsoft::WRL::ComPtr<IDWriteTypography>                       m_textTypography;
00072     Microsoft::WRL::ComPtr<IDWriteTextLayout>                       m_textLayout;
00073     SampleOverlay^                                                  m_sampleOverlay;
00074     Platform::Array<bool>^                                          m_underlineArray;
00075     Platform::String^                                               m_text;
00076 };
00077
00078 ref class DirectXAppSource : Windows::ApplicationModel::Core::IFrameworkViewSource
00079 {
00080 public:
00081     virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00082 };
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Device auto rotation preferences/C++/PortraitFlipped.xaml.h Source File

  • Device auto rotation preferences

PortraitFlipped.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 // PortraitFlipped.xaml.h
00013 // Declaration of the PortraitFlipped class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "PortraitFlipped.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace Rotation
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 PortraitFlipped sealed
00031         {
00032         public:
00033             PortraitFlipped();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void SetPortraitFlipped_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040       };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:08:02 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Check if current session is remote/C++/MainPage.xaml.cpp Source File

  • Check if current session is remote

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:41 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D sprite/C++/BasicReaderWriter.h Source File

  • Direct3D sprite

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     Platform::String^ m_locationPath;
00019
00020 internal:
00021     BasicReaderWriter();
00022     BasicReaderWriter(
00023         _In_ Windows::Storage::StorageFolder^ folder
00024         );
00025
00026     Platform::Array<byte>^ ReadData(
00027         _In_ Platform::String^ filename
00028         );
00029
00030     concurrency::task<Platform::Array<byte>^> ReadDataAsync(
00031         _In_ Platform::String^ filename
00032         );
00033
00034     uint32 WriteData(
00035         _In_ Platform::String^ filename,
00036         _In_ const Platform::Array<byte>^ fileData
00037         );
00038
00039     concurrency::task<void> WriteDataAsync(
00040         _In_ Platform::String^ filename,
00041         _In_ const Platform::Array<byte>^ fileData
00042         );
00043 };
Generated on Sat Nov 23 2024 16:08:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/DelegateCommand.cpp Source File

  • Hilo C++
  • Hilo

DelegateCommand.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 #include "DelegateCommand.h"
00009
00010 using namespace Hilo;
00011 using namespace Platform;
00012
00013 DelegateCommand::DelegateCommand(ExecuteDelegate^ execute, CanExecuteDelegate^ canExecute) : m_executeDelegate(execute), m_canExecuteDelegate(canExecute)
00014 {
00015 }
00016
00017 void DelegateCommand::Execute(Object^ parameter)
00018 {
00019     assert(m_executeDelegate != nullptr);
00020     if (nullptr != m_executeDelegate)
00021     {
00022         m_executeDelegate(parameter);
00023     }
00024 }
00025
00026 bool DelegateCommand::CanExecute(Object^ parameter)
00027 {
00028     if (m_canExecuteDelegate == nullptr)
00029     {
00030         return true;
00031     }
00032
00033     bool temp = m_canExecuteDelegate(parameter);
00034     if (m_canExecute != temp)
00035     {
00036         m_canExecute = temp;
00037         CanExecuteChanged(this, nullptr);
00038     }
00039     return m_canExecute;
00040 }
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

ScheduledNotificationsSampleCPP::sealed Member List

This is the complete list of members for ScheduledNotificationsSampleCPP::sealed, including all inherited members.
_displayHandlerToken | ScheduledNotificationsSampleCPP::sealed | [private]
_dueTime | ScheduledNotificationsSampleCPP::sealed | [private]
_formatter | ScheduledNotificationsSampleCPP::sealed | [private]
_inputFrame | ScheduledNotificationsSampleCPP::sealed | [private]
_inputFrameLoadedToken | ScheduledNotificationsSampleCPP::sealed | [private]
_inputString | ScheduledNotificationsSampleCPP::sealed | [private]
_isTile | ScheduledNotificationsSampleCPP::sealed | [private]
_itemId | ScheduledNotificationsSampleCPP::sealed | [private]
_items | ScheduledNotificationsSampleCPP::sealed | [private]
_itemType | ScheduledNotificationsSampleCPP::sealed | [private]
_logicalDpiChangedToken | ScheduledNotificationsSampleCPP::sealed | [private]
_outputFrame | ScheduledNotificationsSampleCPP::sealed | [private]
_outputFrameLoadedToken | ScheduledNotificationsSampleCPP::sealed | [private]
_pageLoadedHandlerToken | ScheduledNotificationsSampleCPP::sealed | [private]
_resizeHandlerToken | ScheduledNotificationsSampleCPP::sealed | [private]
_scenariosFrame | ScheduledNotificationsSampleCPP::sealed | [private]
AddItem(Platform::String^itemType, Platform::String^itemId, Platform::String^dueTime, Platform::String^inputString, bool isTile) | ScheduledNotificationsSampleCPP::sealed | [private]
App() | ScheduledNotificationsSampleCPP::sealed |
CheckResolutionAndViewState() | ScheduledNotificationsSampleCPP::sealed | [private]
ConvertResolution(Windows::Graphics::Display::ResolutionScale scale) | ScheduledNotificationsSampleCPP::sealed |
ConvertViewState(Windows::UI::ViewManagement::ApplicationViewState state) | ScheduledNotificationsSampleCPP::sealed |
DisplayProperties_LogicalDpiChanged(Object^sender) | ScheduledNotificationsSampleCPP::sealed | [private]
DoNavigation(Windows::UI::Xaml::Interop::TypeName inPageType, Windows::UI::Xaml::Controls::Frame^inFrame, Windows::UI::Xaml::Interop::TypeName outPageType, Windows::UI::Xaml::Controls::Frame^outFrame) | ScheduledNotificationsSampleCPP::sealed |
Footer_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | ScheduledNotificationsSampleCPP::sealed | [private]
inputFrameNavigated(Object^sender, Windows::UI::Xaml::Navigation::NavigationEventArgs^e) | ScheduledNotificationsSampleCPP::sealed | [private]
LoadData() | ScheduledNotificationsSampleCPP::sealed |
MainPage() | ScheduledNotificationsSampleCPP::sealed |
NotificationData(void) | ScheduledNotificationsSampleCPP::sealed |
NotificationDataSource() | ScheduledNotificationsSampleCPP::sealed |
NotifyUser(Platform::String^strMessage, NotifyType type) | ScheduledNotificationsSampleCPP::sealed |
OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^pArgs) override | ScheduledNotificationsSampleCPP::sealed | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ScheduledNotificationsSampleCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ScheduledNotificationsSampleCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | ScheduledNotificationsSampleCPP::sealed | [protected, virtual]
OnPropertyChanged(Platform::String^propertyName) | ScheduledNotificationsSampleCPP::sealed | [protected]
OnSuspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^pArgs) | ScheduledNotificationsSampleCPP::sealed | [virtual]
OutputFrameLoaded | ScheduledNotificationsSampleCPP::sealed |
outputFrameNavigated(Object^sender, Windows::UI::Xaml::Navigation::NavigationEventArgs^e) | ScheduledNotificationsSampleCPP::sealed | [private]
Page_Loaded(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | ScheduledNotificationsSampleCPP::sealed | [private]
Page_SizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | ScheduledNotificationsSampleCPP::sealed | [private]
PropertyChanged | ScheduledNotificationsSampleCPP::sealed |
Refresh() | ScheduledNotificationsSampleCPP::sealed |
RefreshList_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | ScheduledNotificationsSampleCPP::sealed | [private]
RefreshListView() | ScheduledNotificationsSampleCPP::sealed | [private]
Remove_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | ScheduledNotificationsSampleCPP::sealed | [private]
rootPage | ScheduledNotificationsSampleCPP::sealed | [private]
ScenarioInput1() | ScheduledNotificationsSampleCPP::sealed |
ScenarioInput2() | ScheduledNotificationsSampleCPP::sealed |
ScenarioList() | ScheduledNotificationsSampleCPP::sealed |
ScenarioOutput1() | ScheduledNotificationsSampleCPP::sealed |
ScenarioOutput2() | ScheduledNotificationsSampleCPP::sealed |
Scenarios_SelectionChanged(Object^sender, SelectionChangedEventArgs^e) | ScheduledNotificationsSampleCPP::sealed | [protected]
Schedule_Click(Object^, Windows::UI::Xaml::RoutedEventArgs^e) | ScheduledNotificationsSampleCPP::sealed | [private]
scheduledNotificationsBinding | ScheduledNotificationsSampleCPP::sealed | [private]
ScheduleTile(Platform::String^updateString, Windows::Foundation::DateTime dueTime, Platform::String^idNumberString) | ScheduledNotificationsSampleCPP::sealed | [private]
ScheduleTileWithStringManipulation(Platform::String^updateString, Windows::Foundation::DateTime dueTime, Platform::String^idNumberString) | ScheduledNotificationsSampleCPP::sealed | [private]
ScheduleToast(Platform::String^updateString, Windows::Foundation::DateTime dueTime, Platform::String^idNumberString) | ScheduledNotificationsSampleCPP::sealed | [private]
ScheduleToastWithStringManipulation(Platform::String^updateString, Windows::Foundation::DateTime dueTime, Platform::String^idNumberString) | ScheduledNotificationsSampleCPP::sealed | [private]
set_IsTile(bool isTile) | ScheduledNotificationsSampleCPP::sealed |
SetFeatureName(Platform::String^strFeature) | ScheduledNotificationsSampleCPP::sealed | [private]
~MainPage() | ScheduledNotificationsSampleCPP::sealed | [private]
~ScenarioInput2() | ScheduledNotificationsSampleCPP::sealed | [private]
~ScenarioList() | ScheduledNotificationsSampleCPP::sealed | [private]
~ScenarioOutput1() | ScheduledNotificationsSampleCPP::sealed | [private]
~ScenarioOutput2() | ScheduledNotificationsSampleCPP::sealed | [private]
Generated on Sat Nov 23 2024 16:09:46 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Credential picker/C++/ScenarioOutput2.xaml.cpp Source File

  • Credential picker

ScenarioOutput2.xaml.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 //
00009 // Scenario2Output.xaml.cpp
00010 // Implementation of the Scenario2Output class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioOutput2.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace CredentialPickerCPP;
00018
00019 using namespace Platform;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Graphics::Display;
00023 using namespace Windows::UI::ViewManagement;
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 ScenarioOutput2::ScenarioOutput2()
00033 {
00034     InitializeComponent();
00035 }
00036
00037 ScenarioOutput2::~ScenarioOutput2()
00038 {
00039 }
00040
00041 #pragma region Template-Related Code - Do not remove
00042 void ScenarioOutput2::OnNavigatedTo(NavigationEventArgs^ e)
00043 {
00044     // Get a pointer to our main page.
00045     rootPage = dynamic_cast<MainPage^>(e->Parameter);
00046
00047     // We want to be notified with the OutputFrame is loaded so we can get to the content.
00048     _frameLoadedToken = rootPage->InputFrameLoaded += ref new Windows::Foundation::EventHandler<Platform::Object^>(this, &ScenarioOutput2::rootPage_InputFrameLoaded);
00049 }
00050
00051 void ScenarioOutput2::OnNavigatedFrom(NavigationEventArgs^ e)
00052 {
00053     rootPage->InputFrameLoaded -= _frameLoadedToken;
00054 }
00055
00056 #pragma endregion
00057
00058 #pragma region Use this code if you need access to elements in the input frame - otherwise deletea
00059 void ScenarioOutput2::rootPage_InputFrameLoaded(Object^ sender, Object^ e)
00060 {
00061     // Get a pointer to the content within the OutputFrame.
00062     Page^ inputFrame = dynamic_cast<Page^>(rootPage->InputFrame->Content);
00063
00064     // Go find the elements that we need for this scenario
00065     // ex: flipView1 = dynamic_cast<FlipView^>(inputFrame->FindName("FlipView1"));
00066 }
00067
00068 #pragma endregion
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Folder enumeration/C++/App.xaml.cpp Source File

  • Folder enumeration

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Custom driver access/C++/DLL/WUDFOsrUsbPublic.h Source File

  • Custom driver access
  • DLL

WUDFOsrUsbPublic.h

Go to the documentation of this file.
00001 /*++
00002
00003 Copyright (c) Microsoft Corporation, All Rights Reserved
00004
00005 Module Name:
00006
00007     WUDFOsrUsbPublic.h
00008
00009 Abstract:
00010
00011     This module contains the common declarations shared by driver
00012     and user applications for the UMDF OSR device sample.
00013
00014     Note that this driver does NOT use the same device interface GUID
00015     as the KMDF OSR USB sample.
00016
00017 Environment:
00018
00019     user and kernel
00020
00021 --*/
00022
00023 #pragma once
00024
00025 //
00026 // Define an Interface Guid so that app can find the device and talk to it.
00027 //
00028
00029 // {573E8C73-0CB4-4471-A1BF-FAB26C31D384}
00030 DEFINE_GUID(GUID_DEVINTERFACE_OSRUSBFX2,
00031             0x573e8c73, 0xcb4, 0x4471, 0xa1, 0xbf, 0xfa, 0xb2, 0x6c, 0x31, 0xd3, 0x84);
00032
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML accessibility/C++/Scenario1.xaml.h Source File

  • XAML accessibility

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 SDKSample
00023 {
00024   namespace Accessibility
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::WebHostHiddenAttribute]
00030     public ref class Scenario1 sealed
00031     {
00032     public:
00033       Scenario1();
00034
00035     protected:
00036       virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037     private:
00038       MainPage^ rootPage;
00039     };
00040   }
00041 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D stereoscopic 3D/C++/DirectXApp.cpp Source File

  • Direct3D stereoscopic 3D

DirectXApp.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 "DirectXApp.h"
00010 #include "BasicTimer.h"
00011
00012 using namespace Windows::ApplicationModel;
00013 using namespace Windows::ApplicationModel::Core;
00014 using namespace Windows::ApplicationModel::Activation;
00015 using namespace Windows::UI::Core;
00016 using namespace Windows::UI::Input;
00017 using namespace Windows::System;
00018 using namespace Windows::Storage;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::Graphics::Display;
00022 using namespace Windows::Devices::Input;
00023
00024 DirectXApp::DirectXApp() :
00025     m_windowClosed(false),
00026     m_windowVisible(true)
00027 {
00028 }
00029
00030 void DirectXApp::Initialize(
00031     _In_ CoreApplicationView^ applicationView
00032     )
00033 {
00034     applicationView->Activated +=
00035         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &DirectXApp::OnActivated);
00036
00037     CoreApplication::Suspending +=
00038         ref new EventHandler<SuspendingEventArgs^>(this, &DirectXApp::OnSuspending);
00039
00040     CoreApplication::Resuming +=
00041         ref new EventHandler<Platform::Object^>(this, &DirectXApp::OnResuming);
00042
00043     m_renderer = ref new StereoSimpleD3D();
00044 }
00045
00046 void DirectXApp::SetWindow(
00047     _In_ CoreWindow^ window
00048     )
00049 {
00050     window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
00051
00052     window->SizeChanged +=
00053         ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &DirectXApp::OnWindowSizeChanged);
00054
00055     window->VisibilityChanged +=
00056         ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &DirectXApp::OnVisibilityChanged);
00057
00058     window->Closed +=
00059         ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &DirectXApp::OnWindowClosed);
00060
00061     window->KeyDown +=
00062         ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &DirectXApp::OnKeyDown);
00063
00064     DisplayProperties::LogicalDpiChanged +=
00065         ref new DisplayPropertiesEventHandler(this, &DirectXApp::OnLogicalDpiChanged);
00066
00067     m_renderer->Initialize(window, DisplayProperties::LogicalDpi);
00068 }
00069
00070 void DirectXApp::Load(
00071     _In_ Platform::String^ entryPoint
00072     )
00073 {
00074 }
00075
00076 void DirectXApp::Run()
00077 {
00078     BasicTimer^ timer = ref new BasicTimer();
00079
00080     while (!m_windowClosed)
00081     {
00082         if (m_windowVisible)
00083         {
00084             timer->Update();
00085             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
00086
00087             // render the mono content or the left eye view of the stereo content
00088             m_renderer->Update(0, timer->Total, timer->Delta);
00089             m_renderer->RenderEye(0);
00090             // render the right eye view of the stereo content
00091             if (m_renderer->GetStereoEnabledStatus())
00092             {
00093                 m_renderer->Update(1, timer->Total, timer->Delta);
00094                 m_renderer->RenderEye(1);
00095             }
00096             m_renderer->Present(); // this call is sychronized to the display frame rate
00097         }
00098         else
00099         {
00100             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
00101         }
00102     }
00103 }
00104
00105 void DirectXApp::Uninitialize()
00106 {
00107 }
00108
00109 void DirectXApp::OnWindowSizeChanged(
00110     _In_ CoreWindow^ sender,
00111     _In_ WindowSizeChangedEventArgs^ args
00112     )
00113 {
00114     m_renderer->UpdateForWindowSizeChange();
00115 }
00116
00117 void DirectXApp::OnVisibilityChanged(
00118     _In_ CoreWindow^ sender,
00119     _In_ VisibilityChangedEventArgs^ args
00120     )
00121 {
00122     m_windowVisible = args->Visible;
00123 }
00124
00125 void DirectXApp::OnWindowClosed(
00126     _In_ CoreWindow^ sender,
00127     _In_ CoreWindowEventArgs^ args
00128     )
00129 {
00130     m_windowClosed = true;
00131 }
00132
00133 void DirectXApp::OnLogicalDpiChanged(
00134     _In_ Platform::Object^ sender
00135     )
00136 {
00137     m_renderer->SetDpi(DisplayProperties::LogicalDpi);
00138 }
00139
00140 void DirectXApp::OnKeyDown(
00141     _In_ CoreWindow^ sender,
00142     _In_ KeyEventArgs^ args
00143     )
00144 {
00145     Windows::System::VirtualKey Key;
00146     Key = args->VirtualKey;
00147
00148     // if the image is in stereo, adjust for user keystrokes increasing/decreasing the stereo effect
00149     if (m_renderer->GetStereoEnabledStatus())
00150     {
00151         float stereoExaggeration = m_renderer->GetStereoExaggeration();
00152         // figure out the command from the keyboard
00153         if (Key == VirtualKey::Up)             // increase stereo effect
00154         {
00155             stereoExaggeration += 0.1f;
00156         }
00157         if (Key == VirtualKey::Down)           // descrease stereo effect
00158         {
00159             stereoExaggeration -= 0.1f;
00160         }
00161         stereoExaggeration = min(stereoExaggeration, 2.0f);
00162         stereoExaggeration = max(stereoExaggeration, 0.0f);
00163         m_renderer->SetStereoExaggeration(stereoExaggeration);
00164     }
00165 }
00166
00167 void DirectXApp::OnActivated(
00168     _In_ CoreApplicationView^ applicationView,
00169     _In_ IActivatedEventArgs^ args
00170     )
00171 {
00172     if (args->Kind == ActivationKind::Launch)
00173     {
00174         // Load previously saved state only if the application shut down cleanly last time.
00175         if (args->PreviousExecutionState != ApplicationExecutionState::NotRunning)
00176         {
00177             // When this application is suspended, it stores the drawing state.
00178             // This code attempts to restore the saved state.
00179             IPropertySet^ set = ApplicationData::Current->LocalSettings->Values;
00180             // an int called StereoExaggerationFactor is used as a key
00181             if (set->HasKey("StereoExaggerationFactor"))
00182             {
00183                 float tempStereoExaggerationFactor = (safe_cast<IPropertyValue^>(set->Lookup("StereoExaggerationFactor")))->GetSingle();
00184                 m_renderer->SetStereoExaggeration(tempStereoExaggerationFactor);
00185             }
00186         }
00187     }
00188     else
00189     {
00190         DX::ThrowIfFailed(E_UNEXPECTED);
00191     }
00192     CoreWindow::GetForCurrentThread()->Activate();
00193 }
00194
00195 void DirectXApp::OnSuspending(
00196     _In_ Platform::Object^ sender,
00197     _In_ SuspendingEventArgs^ args
00198     )
00199 {
00200     // This is also a good time to save your application's state in case the process gets terminated.
00201     // That way, when the user relaunches the application, they will return to the position they left.
00202     IPropertySet^ settingsValues = ApplicationData::Current->LocalSettings->Values;
00203     if (settingsValues->HasKey("StereoExaggerationFactor"))
00204     {
00205         settingsValues->Remove("StereoExaggerationFactor");
00206     }
00207
00208     float tempStereoExaggerationFactor = m_renderer->GetStereoExaggeration();
00209     settingsValues->Insert("StereoExaggerationFactor", PropertyValue::CreateSingle(tempStereoExaggerationFactor));
00210 }
00211
00212 void DirectXApp::OnResuming(
00213     _In_ Platform::Object^ sender,
00214     _In_ Platform::Object^ args
00215     )
00216 {
00217 }
00218
00219 IFrameworkView^ DirectXAppSource::CreateView()
00220 {
00221     return ref new DirectXApp();
00222 }
00223
00224 [Platform::MTAThread]
00225 int main(Platform::Array<Platform::String^>^)
00226 {
00227     auto directXAppSource = ref new DirectXAppSource();
00228     CoreApplication::Run(directXAppSource);
00229     return 0;
00230 }
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/MediaExtensions/Mpeg1Source/MPEG1Src.h Source File

  • Media extensions
  • MediaExtensions
  • Mpeg1Source

MPEG1Src.h

Go to the documentation of this file.
00001 //////////////////////////////////////////////////////////////////////////
00002 //
00003 // MPEG1Source.h
00004 // Implements the MPEG-1 media source object.
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
00016 #pragma once
00017
00018 #include <new.h>
00019 #include <windows.h>
00020 #include <assert.h>
00021 #include <wrl\implements.h>
00022
00023 #ifndef _ASSERTE
00024 #define _ASSERTE assert
00025 #endif
00026
00027 #include <windows.media.h>
00028
00029 #include <mftransform.h>
00030
00031 #include <mfapi.h>
00032 #include <mfobjects.h>
00033 #include <mfidl.h>
00034 #include <mferror.h>
00035
00036 //#include <amvideo.h>    // VIDEOINFOHEADER definition
00037 //#include <dvdmedia.h>   // VIDEOINFOHEADER2
00038 //#include <mmreg.h>      // MPEG1WAVEFORMAT
00039
00040 // Common sample files.
00041 #include "linklist.h"
00042
00043 #include "asynccb.h"
00044 #include "OpQueue.h"
00045
00046
00047 template <class T> void SafeRelease(T **ppT)
00048 {
00049     if (*ppT)
00050     {
00051         (*ppT)->Release();
00052         *ppT = NULL;
00053     }
00054 }
00055
00056 void DllAddRef();
00057 void DllRelease();
00058
00059
00060 // Forward declares
00061 class CMPEG1ByteStreamHandler;
00062 class CMPEG1Source;
00063 class CMPEG1Stream;
00064 class SourceOp;
00065
00066 typedef ComPtrList<IMFSample>       SampleList;
00067 typedef ComPtrList<IUnknown, true>  TokenList;    // List of tokens for IMFMediaStream::RequestSample
00068
00069 enum SourceState
00070 {
00071     STATE_INVALID,      // Initial state. Have not started opening the stream.
00072     STATE_OPENING,      // BeginOpen is in progress.
00073     STATE_STOPPED,
00074     STATE_PAUSED,
00075     STATE_STARTED,
00076     STATE_SHUTDOWN
00077 };
00078
00079 #include "Parse.h"          // MPEG-1 parser
00080 #include "MPEG1Stream.h"    // MPEG-1 stream
00081
00082
00083
00084 const UINT32 MAX_STREAMS = 32;
00085
00086 class StreamList
00087 {
00088     CMPEG1Stream*   m_streams[MAX_STREAMS];
00089     BYTE            m_id[MAX_STREAMS];
00090     UINT32          m_count;
00091
00092 public:
00093     StreamList() : m_count(0)
00094     {
00095         ZeroMemory(m_streams, sizeof(m_streams));
00096     }
00097     ~StreamList()
00098     {
00099         Clear();
00100     }
00101
00102     UINT32 GetCount() const { return m_count; }
00103
00104     void Clear()
00105     {
00106         for (UINT32 i = 0; i < MAX_STREAMS; i++)
00107         {
00108             SafeRelease(&m_streams[i]);
00109         }
00110         m_count = 0;
00111     }
00112
00113     HRESULT AddStream(BYTE id, CMPEG1Stream *pStream)
00114     {
00115         if (GetCount() >= MAX_STREAMS)
00116         {
00117             return E_FAIL;
00118         }
00119
00120         m_streams[m_count] = pStream;
00121         pStream->AddRef();
00122
00123         m_id[m_count] = id;
00124
00125         m_count++;
00126
00127         return S_OK;
00128     }
00129
00130     CMPEG1Stream* Find(BYTE id)
00131     {
00132
00133         // This method can return NULL if the source did not create a
00134         // stream for this ID. In particular, this can happen if:
00135         //
00136         // 1) The stream type is not supported. See IsStreamTypeSupported().
00137         // 2) The source is still opening.
00138         //
00139         // Note: This method does not AddRef the stream object. The source
00140         // uses this method to access the streams. If the source hands out
00141         // a stream pointer (e.g. in the MENewStream event), the source
00142         // must AddRef the stream object.
00143
00144         CMPEG1Stream* pStream = NULL;
00145         for (UINT32 i = 0; i < m_count; i++)
00146         {
00147             if (m_id[i] == id)
00148             {
00149                 pStream = m_streams[i];
00150                 break;
00151             }
00152         }
00153         return pStream;
00154     }
00155
00156     // Accessor.
00157     CMPEG1Stream* operator[](DWORD index)
00158     {
00159         assert(index < m_count);
00160         return m_streams[index];
00161     }
00162
00163     // Const accessor.
00164     CMPEG1Stream* const operator[](DWORD index) const
00165     {
00166         assert(index < m_count);
00167         return m_streams[index];
00168     }
00169 };
00170
00171
00172 // Constants
00173
00174 const DWORD INITIAL_BUFFER_SIZE = 4 * 1024; // Initial size of the read buffer. (The buffer expands dynamically.)
00175 const DWORD READ_SIZE = 4 * 1024;           // Size of each read request.
00176 const DWORD SAMPLE_QUEUE = 2;               // How many samples does each stream try to hold in its queue?
00177
00178 // Represents a request for an asynchronous operation.
00179
00180 class SourceOp : public IUnknown
00181 {
00182 public:
00183
00184     enum Operation
00185     {
00186         OP_START,
00187         OP_PAUSE,
00188         OP_STOP,
00189         OP_SETRATE,
00190         OP_REQUEST_DATA,
00191         OP_END_OF_STREAM
00192     };
00193
00194     static HRESULT CreateOp(Operation op, SourceOp **ppOp);
00195     static HRESULT CreateStartOp(IMFPresentationDescriptor *pPD, SourceOp **ppOp);
00196     static HRESULT CreateSetRateOp(BOOL fThin, float flRate, SourceOp **ppOp);
00197
00198     // IUnknown
00199     STDMETHODIMP QueryInterface(REFIID iid, void** ppv);
00200     STDMETHODIMP_(ULONG) AddRef();
00201     STDMETHODIMP_(ULONG) Release();
00202
00203     SourceOp(Operation op);
00204     virtual ~SourceOp();
00205
00206     HRESULT SetData(const PROPVARIANT& var);
00207
00208     Operation Op() const { return m_op; }
00209     const PROPVARIANT& Data() { return m_data;}
00210
00211 protected:
00212     long        m_cRef;     // Reference count.
00213     Operation   m_op;
00214     PROPVARIANT m_data;     // Data for the operation.
00215 };
00216
00217 class StartOp : public SourceOp
00218 {
00219 public:
00220     StartOp(IMFPresentationDescriptor *pPD);
00221     ~StartOp();
00222
00223     HRESULT GetPresentationDescriptor(IMFPresentationDescriptor **ppPD);
00224
00225 protected:
00226     IMFPresentationDescriptor   *m_pPD; // Presentation descriptor for Start operations.
00227
00228 };
00229
00230 class SetRateOp : public SourceOp
00231 {
00232 public:
00233     SetRateOp(BOOL fThin, float flRate);
00234     ~SetRateOp();
00235
00236     BOOL IsThin() const {return m_fThin;}
00237     float GetRate() const {return m_flRate;}
00238
00239 private:
00240     BOOL m_fThin;
00241     float m_flRate;
00242 };
00243
00244 // CMPEG1Source: The media source object.
00245 class CMPEG1Source :
00246     public OpQueue<CMPEG1Source, SourceOp>,
00247     public IMFMediaSource,
00248   public IMFGetService,
00249     public IMFRateControl
00250 {
00251 public:
00252     static HRESULT CreateInstance(CMPEG1Source **ppSource);
00253
00254     // IUnknown
00255     STDMETHODIMP QueryInterface(REFIID iid, void** ppv);
00256     STDMETHODIMP_(ULONG) AddRef();
00257     STDMETHODIMP_(ULONG) Release();
00258
00259     // IMFMediaEventGenerator
00260     STDMETHODIMP BeginGetEvent(IMFAsyncCallback* pCallback,IUnknown* punkState);
00261     STDMETHODIMP EndGetEvent(IMFAsyncResult* pResult, IMFMediaEvent** ppEvent);
00262     STDMETHODIMP GetEvent(DWORD dwFlags, IMFMediaEvent** ppEvent);
00263     STDMETHODIMP QueueEvent(MediaEventType met, REFGUID guidExtendedType, HRESULT hrStatus, const PROPVARIANT* pvValue);
00264
00265     // IMFMediaSource
00266     STDMETHODIMP CreatePresentationDescriptor(IMFPresentationDescriptor** ppPresentationDescriptor);
00267     STDMETHODIMP GetCharacteristics(DWORD* pdwCharacteristics);
00268     STDMETHODIMP Pause();
00269     STDMETHODIMP Shutdown();
00270     STDMETHODIMP Start(
00271         IMFPresentationDescriptor* pPresentationDescriptor,
00272         const GUID* pguidTimeFormat,
00273         const PROPVARIANT* pvarStartPosition
00274     );
00275     STDMETHODIMP Stop();
00276
00277   // IMFGetService
00278     IFACEMETHOD (GetService) ( _In_ REFGUID guidService, _In_ REFIID riid, _Out_opt_ LPVOID *ppvObject);
00279
00280     // IMFRateControl
00281     IFACEMETHOD (SetRate) (BOOL fThin, float flRate);
00282     IFACEMETHOD (GetRate) (_Inout_opt_ BOOL *pfThin, _Inout_opt_ float *pflRate);
00283
00284     // Called by the byte stream handler.
00285     HRESULT BeginOpen(IMFByteStream *pStream, IMFAsyncCallback *pCB, IUnknown *pUnkState);
00286     HRESULT EndOpen(IMFAsyncResult *pResult);
00287
00288     // Queues an asynchronous operation, specify by op-type.
00289     // (This method is public because the streams call it.)
00290     HRESULT QueueAsyncOperation(SourceOp::Operation OpType);
00291
00292     // Lock/Unlock:
00293     // Holds and releases the source's critical section. Called by the streams.
00294   _Acquires_lock_(m_critSec)
00295     void    Lock() { EnterCriticalSection(&m_critSec); }
00296
00297   _Releases_lock_(m_critSec)
00298   void    Unlock() { LeaveCriticalSection(&m_critSec); }
00299
00300     // Callbacks
00301     HRESULT OnByteStreamRead(IMFAsyncResult *pResult);  // Async callback for RequestData
00302
00303 private:
00304
00305     CMPEG1Source(HRESULT& hr);
00306     ~CMPEG1Source();
00307
00308     // CheckShutdown: Returns MF_E_SHUTDOWN if the source was shut down.
00309     HRESULT CheckShutdown() const
00310     {
00311         return ( m_state == STATE_SHUTDOWN ? MF_E_SHUTDOWN : S_OK );
00312     }
00313
00314     HRESULT     CompleteOpen(HRESULT hrStatus);
00315
00316     HRESULT     IsInitialized() const;
00317     BOOL        IsStreamTypeSupported(StreamType type) const;
00318     BOOL        IsStreamActive(const MPEG1PacketHeader& packetHdr);
00319     BOOL        StreamsNeedData() const;
00320
00321     HRESULT     DoStart(StartOp *pOp);
00322     HRESULT     DoStop(SourceOp *pOp);
00323     HRESULT     DoPause(SourceOp *pOp);
00324     HRESULT     DoSetRate(SourceOp *pOp);
00325     HRESULT     OnStreamRequestSample(SourceOp *pOp);
00326     HRESULT     OnEndOfStream(SourceOp *pOp);
00327
00328     HRESULT     InitPresentationDescriptor();
00329     HRESULT     SelectStreams(IMFPresentationDescriptor *pPD, const PROPVARIANT varStart);
00330
00331     HRESULT     RequestData(DWORD cbRequest);
00332     HRESULT     ParseData();
00333     HRESULT     ReadPayload(DWORD *pcbAte, DWORD *pcbNextRequest);
00334     HRESULT     DeliverPayload();
00335     HRESULT     EndOfMPEGStream();
00336
00337     HRESULT     CreateStream(const MPEG1PacketHeader& packetHdr);
00338
00339     HRESULT     ValidatePresentationDescriptor(IMFPresentationDescriptor *pPD);
00340
00341     // Handler for async errors.
00342     void        StreamingError(HRESULT hr);
00343
00344     HRESULT     BeginAsyncOp(SourceOp *pOp);
00345     HRESULT     CompleteAsyncOp(SourceOp *pOp);
00346     HRESULT     DispatchOperation(SourceOp *pOp);
00347     HRESULT     ValidateOperation(SourceOp *pOp);
00348
00349     BOOL        IsRateSupported(float flRate, float *pflAdjustedRate);
00350
00351 private:
00352     long                        m_cRef;                     // reference count
00353
00354     CRITICAL_SECTION            m_critSec;                  // critical section for thread safety
00355     SourceState                 m_state;                    // Current state (running, stopped, paused)
00356
00357     Buffer                      m_ReadBuffer;
00358     Parser                      *m_pParser;
00359
00360     IMFMediaEventQueue          *m_pEventQueue;             // Event generator helper
00361     IMFPresentationDescriptor   *m_pPresentationDescriptor; // Presentation descriptor.
00362     IMFAsyncResult              *m_pBeginOpenResult;        // Result object for async BeginOpen operation.
00363     IMFByteStream               *m_pByteStream;
00364
00365     MPEG1SystemHeader           *m_pHeader;                 // Release with CoTaskMemFree
00366
00367     StreamList                  m_streams;                  // Array of streams.
00368
00369     DWORD                       m_cPendingEOS;              // Pending EOS notifications.
00370     ULONG                       m_cRestartCounter;          // Counter for sample requests.
00371
00372     SourceOp                    *m_pCurrentOp;
00373     SourceOp                    *m_pSampleRequest;
00374
00375     // Async callback helper.
00376     AsyncCallback<CMPEG1Source>  m_OnByteStreamRead;
00377
00378     float                       m_flRate;
00379 };
00380
00381
Generated on Sat Nov 23 2024 16:08:21 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Association launching/C++/ReceiveFileOutput.xaml.cpp Source File

  • Association launching

ReceiveFileOutput.xaml.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 //
00009 // ReceiveFileOutput.xaml.cpp
00010 // Implementation of the ReceiveFileOutput class
00011 //
00012
00013 #include "pch.h"
00014 #include "ReceiveFileOutput.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace AssociationLaunching;
00018
00019 using namespace Platform;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Graphics::Display;
00023 using namespace Windows::UI::ViewManagement;
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 ReceiveFileOutput::ReceiveFileOutput()
00033 {
00034     InitializeComponent();
00035 }
00036
00037 ReceiveFileOutput::~ReceiveFileOutput()
00038 {
00039 }
00040
00041 #pragma region Template-Related Code - Do not remove
00042 void ReceiveFileOutput::OnNavigatedTo(NavigationEventArgs^ e)
00043 {
00044     // Get a pointer to our main page.
00045     rootPage = dynamic_cast<MainPage^>(e->Parameter);
00046 }
00047
00048 void ReceiveFileOutput::OnNavigatedFrom(NavigationEventArgs^ e)
00049 {
00050 }
00051
00052 #pragma endregion
Generated on Sat Nov 23 2024 16:07:57 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Mobile broadband account provisioning/C++/UpdateCost.xaml.cpp Source File

  • Mobile broadband account provisioning

UpdateCost.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 // UpdateCost.xaml.cpp
00013 // Implementation of the UpdateCost class
00014 //
00015
00016 #include "pch.h"
00017 #include "UpdateCost.xaml.h"
00018
00019 using namespace SDKSample::ProvisioningAgent;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024 using namespace Platform;
00025 using namespace Windows::Networking;
00026 using namespace Windows::Networking::Connectivity;
00027 using namespace Windows::Networking::NetworkOperators;
00028
00029
00030 UpdateCost::UpdateCost()
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 void UpdateCost::OnNavigatedTo(NavigationEventArgs^ e)
00041 {
00042     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00043     // as NotifyUser()
00044     rootPage = MainPage::Current;
00045     util = ref new Util();
00046
00047     mediaType->SelectionChanged += ref new SelectionChangedEventHandler(this, &UpdateCost::MediaType_SelectionChanged);
00048     mediaType->SelectedItem = mediaType_Wlan;
00049
00050     networkCostCategory->SelectionChanged += ref new SelectionChangedEventHandler(this, &UpdateCost::NetworkCostCategory_SelectionChanged);
00051     networkCostCategory->SelectedItem = cost_unknown;
00052
00053 }
00054
00055 void UpdateCost::MediaType_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00056 {
00057     if (mediaType->SelectedIndex == 0)
00058     {
00059         profileMediaType = ProfileMediaType::Wlan;
00060     }
00061     else if (mediaType->SelectedIndex == 1)
00062     {
00063         profileMediaType = ProfileMediaType::Wwan;
00064     }
00065 }
00066
00067 void UpdateCost::NetworkCostCategory_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00068 {
00069     if (networkCostCategory->SelectedIndex == 0)
00070     {
00071         networkCostType = NetworkCostType::Unknown;
00072     }
00073     else if (networkCostCategory->SelectedIndex == 1)
00074     {
00075         networkCostType = NetworkCostType::Unrestricted;
00076     }
00077     else if (networkCostCategory->SelectedIndex == 2)
00078     {
00079         networkCostType = NetworkCostType::Fixed;
00080     }
00081     else if (networkCostCategory->SelectedIndex == 3)
00082     {
00083         networkCostType = NetworkCostType::Variable;
00084     }
00085 }
00086
00087
00088 void UpdateCost::UpdateCost_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00089 {
00090     if (profileNameText->Text == L"")
00091     {
00092         rootPage->NotifyUser("Profile name cannot be empty", NotifyType::ErrorMessage);
00093         return;
00094     }
00095
00096     auto profileName = profileNameText->Text;
00097
00098     try
00099     {
00100         // Get the network account ID.
00101         auto networkAccIds = MobileBroadbandAccount::AvailableNetworkAccountIds;
00102         if (networkAccIds->Size == 0)
00103         {
00104             rootPage->NotifyUser("No network account ID found", NotifyType::ErrorMessage);
00105             return;
00106         }
00107
00108         UpdateCostButton->IsEnabled = false;
00109
00110         // For the sake of simplicity, assume we want to use the first account.
00111         // Refer to the MobileBroadbandAccount API's for how to select a specific account ID.
00112         auto networkAccountId = networkAccIds->GetAt(0);
00113
00114         // Create provisioning agent for specified network account ID
00115         auto provisioningAgent = Windows::Networking::NetworkOperators::ProvisioningAgent::CreateFromNetworkAccountId(networkAccountId);
00116
00117         // Retrieve associated provisioned profile
00118         auto provisionedProfile = provisioningAgent->GetProvisionedProfile(profileMediaType, profileName);
00119
00120         // Set the new cost
00121         provisionedProfile->UpdateCost(networkCostType);
00122
00123         wchar_t buf[5000];
00124         HRESULT hr = StringCchPrintf(buf, ARRAYSIZE(buf), L"Profile %s has been updated with the cost type %d", profileName->Data(), networkCostType);
00125         if (FAILED(hr))
00126         {
00127             throw Exception::CreateException(hr);
00128         }
00129         String^ str = ref new String(buf);
00130         rootPage->NotifyUser(str, NotifyType::StatusMessage);
00131     }
00132     catch (Exception^ ex)
00133     {
00134          rootPage->NotifyUser(util->PrintExceptionCode(ex), NotifyType::ErrorMessage);
00135     }
00136
00137     UpdateCostButton->IsEnabled = true;
00138
00139 }
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Splash screen/C++/Scenario2.xaml.cpp Source File

  • Splash screen

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 SDKSample::SplashScreen;
00020
00021 using namespace Windows::Foundation;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Navigation;
00025
00026 Scenario2::Scenario2()
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 Scenario2::OnNavigatedTo(NavigationEventArgs^ e)
00037 {
00038     Rect rect = MainPage::Current->SplashImageRect;
00039     XValue->Text = " " + rect.X.ToString() + ", ";
00040     YValue->Text = " " + rect.Y.ToString() + " with ";
00041     WidthValue->Text = " " + rect.Width.ToString() + ", ";
00042     HeightValue->Text = " " + rect.Height.ToString() + ".";
00043 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D tutorial/C++/Lesson3.Cubes/BasicMath.h Source File

  • Direct3D tutorial
  • Lesson3.Cubes

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 Sat Nov 23 2024 16:08:08 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SValue Member List

This is the complete list of members for SValue, including all inherited members.
dwValue | SValue
pName | SValue
Generated on Sat Nov 23 2024 16:09:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DirectX::LegacyDDS Member List

This is the complete list of members for DirectX::LegacyDDS, including all inherited members.
convFlags | DirectX::LegacyDDS
ddpf | DirectX::LegacyDDS
format | DirectX::LegacyDDS
Generated on Sat Nov 23 2024 16:09:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

MediaExtensionsCS::ScenarioOutput1 Member List

This is the complete list of members for MediaExtensionsCS::ScenarioOutput1, including all inherited members.
__pad0__ | Element |
AcceptChildNode(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^childXmlNode) override | Page | [virtual]
AddChild(_In_ Element^element) | Element |
AddSibling(_In_ Element^element) | Element |
BindResource(_In_ Element^rootElement) | Element | [virtual]
Create(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^xmlNode) | Element | [static]
Draw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
GetFirstChild() | Element | [inline]
GetName() | Element | [inline]
GetNextSibling() | Element | [inline]
GetOpacity() | Element | [inline, virtual]
GetParent() | Element | [inline]
GetSize() | Element | [inline]
Initialize(_In_ Document^document, _In_ Windows::Data::Xml::Dom::XmlElement^xmlElement) | Element | [virtual]
Measure(_In_ Document^document, D2D1_SIZE_F const &parentSize, _Out_ D2D1_RECT_F *bounds) | Element | [virtual]
OnNavigatedFrom(NavigationEventArgs e) | MediaExtensionsCS::ScenarioOutput1 | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | MediaExtensionsCS::ScenarioOutput1 | [inline, protected]
PrepareToDraw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
ReleaseParent() | Element | [virtual]
rootPage | MediaExtensionsCS::ScenarioOutput1 | [private]
ScenarioOutput1() | MediaExtensionsCS::ScenarioOutput1 | [inline]
Generated on Sat Nov 23 2024 16:09:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: SimpleOrientationSensor/C++/common/LayoutAwarePage.h Source File

  • SimpleOrientationSensor
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML FlipView control/C++/Scenario1.xaml.cpp Source File

  • XAML FlipView control

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 #include "SampleDataSource.h"
00019
00020 using namespace SDKSample::FlipViewCPP;
00021 using namespace SDKSample::FlipViewData;
00022
00023 using namespace Windows::UI::Xaml;
00024 using namespace Windows::UI::Xaml::Controls;
00025 using namespace Windows::UI::Xaml::Navigation;
00026
00027 Scenario1::Scenario1()
00028 {
00029     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 void Scenario1::OnNavigatedTo(NavigationEventArgs^ e)
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     rootPage = MainPage::Current;
00042
00043    SampleDataSource^ sampleData = ref new FlipViewData::SampleDataSource();
00044    FlipView1->ItemsSource = sampleData->Items;
00045 }
Generated on Sat Nov 23 2024 16:07:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML high contrast style/C++/App.xaml.h Source File

  • XAML high contrast style

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

CMPEG1Source Member List

This is the complete list of members for CMPEG1Source, including all inherited members.
_Acquires_lock_(m_critSec) void Lock() | CMPEG1Source | [inline]
_Acquires_lock_(m_critSec) void Lock() | CMPEG1Source | [inline]
_Releases_lock_(m_critSec) void Unlock() | CMPEG1Source | [inline]
_Releases_lock_(m_critSec) void Unlock() | CMPEG1Source | [inline]
BeginAsyncOp(SourceOp *pOp) | CMPEG1Source | [private]
BeginAsyncOp(SourceOp *pOp) | CMPEG1Source | [private]
BeginGetEvent(IMFAsyncCallback *pCallback, IUnknown *punkState) | CMPEG1Source |
BeginGetEvent(IMFAsyncCallback *pCallback, IUnknown *punkState) | CMPEG1Source |
BeginOpen(IMFByteStream *pStream, IMFAsyncCallback *pCB, IUnknown *pUnkState) | CMPEG1Source |
BeginOpen(IMFByteStream *pStream, IMFAsyncCallback *pCB, IUnknown *pUnkState) | CMPEG1Source |
CheckShutdown() const | CMPEG1Source | [inline, private]
CheckShutdown() const | CMPEG1Source | [inline, private]
CMPEG1Source(HRESULT &hr) | CMPEG1Source | [private]
CMPEG1Source(HRESULT &hr) | CMPEG1Source | [private]
CompleteAsyncOp(SourceOp *pOp) | CMPEG1Source | [private]
CompleteAsyncOp(SourceOp *pOp) | CMPEG1Source | [private]
CompleteOpen(HRESULT hrStatus) | CMPEG1Source | [private]
CompleteOpen(HRESULT hrStatus) | CMPEG1Source | [private]
CreateInstance(CMPEG1Source **ppSource) | CMPEG1Source | [static]
CreateInstance(CMPEG1Source **ppSource) | CMPEG1Source | [static]
CreatePresentationDescriptor(IMFPresentationDescriptor **ppPresentationDescriptor) | CMPEG1Source |
CreatePresentationDescriptor(IMFPresentationDescriptor **ppPresentationDescriptor) | CMPEG1Source |
CreateStream(const MPEG1PacketHeader &packetHdr) | CMPEG1Source | [private]
CreateStream(const MPEG1PacketHeader &packetHdr) | CMPEG1Source | [private]
DeliverPayload() | CMPEG1Source | [private]
DeliverPayload() | CMPEG1Source | [private]
DispatchOperation(SourceOp *pOp) | CMPEG1Source | [private, virtual]
DispatchOperation(SourceOp *pOp) | CMPEG1Source | [private, virtual]
DoPause(SourceOp *pOp) | CMPEG1Source | [private]
DoPause(SourceOp *pOp) | CMPEG1Source | [private]
DoSetRate(SourceOp *pOp) | CMPEG1Source | [private]
DoSetRate(SourceOp *pOp) | CMPEG1Source | [private]
DoStart(StartOp *pOp) | CMPEG1Source | [private]
DoStart(StartOp *pOp) | CMPEG1Source | [private]
DoStop(SourceOp *pOp) | CMPEG1Source | [private]
DoStop(SourceOp *pOp) | CMPEG1Source | [private]
EndGetEvent(IMFAsyncResult *pResult, IMFMediaEvent **ppEvent) | CMPEG1Source |
EndGetEvent(IMFAsyncResult *pResult, IMFMediaEvent **ppEvent) | CMPEG1Source |
EndOfMPEGStream() | CMPEG1Source | [private]
EndOfMPEGStream() | CMPEG1Source | [private]
EndOpen(IMFAsyncResult *pResult) | CMPEG1Source |
EndOpen(IMFAsyncResult *pResult) | CMPEG1Source |
GetCharacteristics(DWORD *pdwCharacteristics) | CMPEG1Source |
GetCharacteristics(DWORD *pdwCharacteristics) | CMPEG1Source |
GetEvent(DWORD dwFlags, IMFMediaEvent **ppEvent) | CMPEG1Source |
GetEvent(DWORD dwFlags, IMFMediaEvent **ppEvent) | CMPEG1Source |
GetRate(_Inout_opt_ BOOL *pfThin, _Inout_opt_ float *pflRate) | CMPEG1Source |
GetRate(_Inout_opt_ BOOL *pfThin, _Inout_opt_ float *pflRate) | CMPEG1Source |
GetService(_In_ REFGUID guidService, _In_ REFIID riid, _Out_opt_ LPVOID *ppvObject) | CMPEG1Source |
GetService(_In_ REFGUID guidService, _In_ REFIID riid, _Out_opt_ LPVOID *ppvObject) | CMPEG1Source |
InitPresentationDescriptor() | CMPEG1Source | [private]
InitPresentationDescriptor() | CMPEG1Source | [private]
IsInitialized() const | CMPEG1Source | [private]
IsInitialized() const | CMPEG1Source | [private]
IsRateSupported(float flRate, float *pflAdjustedRate) | CMPEG1Source | [private]
IsRateSupported(float flRate, float *pflAdjustedRate) | CMPEG1Source | [private]
IsStreamActive(const MPEG1PacketHeader &packetHdr) | CMPEG1Source | [private]
IsStreamActive(const MPEG1PacketHeader &packetHdr) | CMPEG1Source | [private]
IsStreamTypeSupported(StreamType type) const | CMPEG1Source | [private]
IsStreamTypeSupported(StreamType type) const | CMPEG1Source | [private]
m_cPendingEOS | CMPEG1Source | [private]
m_cRef | CMPEG1Source | [private]
m_cRestartCounter | CMPEG1Source | [private]
m_critSec | CMPEG1Source | [private]
m_critsec | OpQueue< CMPEG1Source, SourceOp > | [protected]
m_flRate | CMPEG1Source | [private]
m_OnByteStreamRead | CMPEG1Source | [private]
m_OnProcessQueue | OpQueue< CMPEG1Source, SourceOp > | [protected]
m_OpQueue | OpQueue< CMPEG1Source, SourceOp > | [protected]
m_pBeginOpenResult | CMPEG1Source | [private]
m_pByteStream | CMPEG1Source | [private]
m_pCurrentOp | CMPEG1Source | [private]
m_pEventQueue | CMPEG1Source | [private]
m_pHeader | CMPEG1Source | [private]
m_pParser | CMPEG1Source | [private]
m_pPresentationDescriptor | CMPEG1Source | [private]
m_pSampleRequest | CMPEG1Source | [private]
m_ReadBuffer | CMPEG1Source | [private]
m_state | CMPEG1Source | [private]
m_streams | CMPEG1Source | [private]
OnByteStreamRead(IMFAsyncResult *pResult) | CMPEG1Source |
OnByteStreamRead(IMFAsyncResult *pResult) | CMPEG1Source |
OnEndOfStream(SourceOp *pOp) | CMPEG1Source | [private]
OnEndOfStream(SourceOp *pOp) | CMPEG1Source | [private]
OnStreamRequestSample(SourceOp *pOp) | CMPEG1Source | [private]
OnStreamRequestSample(SourceOp *pOp) | CMPEG1Source | [private]
OpList typedef | OpQueue< CMPEG1Source, SourceOp > |
OpList typedef | OpQueue< CMPEG1Source, SourceOp > |
OpList typedef | OpQueue< CMPEG1Source, SourceOp > |
OpQueue(CRITICAL_SECTION &critsec) | OpQueue< CMPEG1Source, SourceOp > | [inline, protected]
OpQueue(CRITICAL_SECTION &critsec) | OpQueue< CMPEG1Source, SourceOp > | [inline, protected]
OpQueue(CRITICAL_SECTION &critsec) | OpQueue< CMPEG1Source, SourceOp > | [inline, protected]
ParseData() | CMPEG1Source | [private]
ParseData() | CMPEG1Source | [private]
Pause() | CMPEG1Source |
Pause() | CMPEG1Source |
ProcessQueue() | OpQueue< CMPEG1Source, SourceOp > | [protected]
ProcessQueue() | OpQueue< CMPEG1Source, SourceOp > | [protected]
ProcessQueue() | OpQueue< CMPEG1Source, SourceOp > | [protected]
ProcessQueueAsync(IMFAsyncResult *pResult) | OpQueue< CMPEG1Source, SourceOp > | [protected]
ProcessQueueAsync(IMFAsyncResult *pResult) | OpQueue< CMPEG1Source, SourceOp > | [protected]
ProcessQueueAsync(IMFAsyncResult *pResult) | OpQueue< CMPEG1Source, SourceOp > | [protected]
QueryInterface(REFIID iid, void **ppv) | CMPEG1Source |
QueryInterface(REFIID iid, void **ppv) | CMPEG1Source |
QueueAsyncOperation(SourceOp::Operation OpType) | CMPEG1Source |
QueueAsyncOperation(SourceOp::Operation OpType) | CMPEG1Source |
QueueEvent(MediaEventType met, REFGUID guidExtendedType, HRESULT hrStatus, const PROPVARIANT *pvValue) | CMPEG1Source |
QueueEvent(MediaEventType met, REFGUID guidExtendedType, HRESULT hrStatus, const PROPVARIANT *pvValue) | CMPEG1Source |
QueueOperation(SourceOp *pOp) | OpQueue< CMPEG1Source, SourceOp > |
QueueOperation(SourceOp *pOp) | OpQueue< CMPEG1Source, SourceOp > |
QueueOperation(SourceOp *pOp) | OpQueue< CMPEG1Source, SourceOp > |
ReadPayload(DWORD *pcbAte, DWORD *pcbNextRequest) | CMPEG1Source | [private]
ReadPayload(DWORD *pcbAte, DWORD *pcbNextRequest) | CMPEG1Source | [private]
RequestData(DWORD cbRequest) | CMPEG1Source | [private]
RequestData(DWORD cbRequest) | CMPEG1Source | [private]
SelectStreams(IMFPresentationDescriptor *pPD, const PROPVARIANT varStart) | CMPEG1Source | [private]
SelectStreams(IMFPresentationDescriptor *pPD, const PROPVARIANT varStart) | CMPEG1Source | [private]
SetRate(BOOL fThin, float flRate) | CMPEG1Source |
SetRate(BOOL fThin, float flRate) | CMPEG1Source |
Shutdown() | CMPEG1Source |
Shutdown() | CMPEG1Source |
Start(IMFPresentationDescriptor *pPresentationDescriptor, const GUID *pguidTimeFormat, const PROPVARIANT *pvarStartPosition) | CMPEG1Source |
Start(IMFPresentationDescriptor *pPresentationDescriptor, const GUID *pguidTimeFormat, const PROPVARIANT *pvarStartPosition) | CMPEG1Source |
STDMETHODIMP_(ULONG) AddRef() | CMPEG1Source |
STDMETHODIMP_(ULONG) Release() | CMPEG1Source |
STDMETHODIMP_(ULONG) AddRef() | CMPEG1Source |
STDMETHODIMP_(ULONG) Release() | CMPEG1Source |
Stop() | CMPEG1Source |
Stop() | CMPEG1Source |
StreamingError(HRESULT hr) | CMPEG1Source | [private]
StreamingError(HRESULT hr) | CMPEG1Source | [private]
StreamsNeedData() const | CMPEG1Source | [private]
StreamsNeedData() const | CMPEG1Source | [private]
ValidateOperation(SourceOp *pOp) | CMPEG1Source | [private, virtual]
ValidateOperation(SourceOp *pOp) | CMPEG1Source | [private, virtual]
ValidatePresentationDescriptor(IMFPresentationDescriptor *pPD) | CMPEG1Source | [private]
ValidatePresentationDescriptor(IMFPresentationDescriptor *pPD) | CMPEG1Source | [private]
~CMPEG1Source() | CMPEG1Source | [private]
~CMPEG1Source() | CMPEG1Source | [private]
~OpQueue() | OpQueue< CMPEG1Source, SourceOp > | [inline, protected, virtual]
~OpQueue() | OpQueue< CMPEG1Source, SourceOp > | [inline, protected, virtual]
~OpQueue() | OpQueue< CMPEG1Source, SourceOp > | [inline, protected, virtual]
Generated on Sat Nov 23 2024 16:09:08 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

PageRenderer Member List

This is the complete list of members for PageRenderer, including all inherited members.
__pad0__ | PageRenderer |
ClosePrintControl() | PageRenderer |
ClosePrintControl() | PageRenderer |
CreateDeviceIndependentResources() override | PageRenderer | [virtual]
CreateDeviceIndependentResources() override | PageRenderer | [virtual]
CreateDeviceResources() override | PageRenderer | [virtual]
CreateDeviceResources() override | PageRenderer | [virtual]
CreatePrintControl(_In_ IPrintDocumentPackageTarget *docPackageTarget, _In_ D2D1_PRINT_CONTROL_PROPERTIES *printControlProperties) | PageRenderer |
CreatePrintControl(_In_ IPrintDocumentPackageTarget *docPackageTarget, _In_ D2D1_PRINT_CONTROL_PROPERTIES *printControlProperties) | PageRenderer |
DrawPreviewSurface(_In_ float width, _In_ float height, _In_ float scale, _In_ D2D1_RECT_F contentBox, _In_ uint32 desiredJobPage, _In_ IPrintPreviewDxgiPackageTarget *previewTarget) | PageRenderer |
DrawPreviewSurface(_In_ float width, _In_ float height, _In_ float scale, _In_ D2D1_RECT_F contentBox, _In_ uint32 desiredJobPage, _In_ IPrintPreviewDxgiPackageTarget *previewTarget) | PageRenderer |
GetMessageFormatNoRef() | PageRenderer |
GetMessageFormatNoRef() | PageRenderer |
GetOriginalWicBitmapSourceNoRef() | PageRenderer |
GetTextFormatNoRef() | PageRenderer |
GetTextFormatNoRef() | PageRenderer |
GetWicBitmapSourceWithEmbeddedColorContextNoRef() | PageRenderer |
GetWicColorContextNoRef() | PageRenderer |
m_d2dPrintControl | PageRenderer | [private]
m_displayPageRendererContext | PageRenderer | [private]
m_isSnapped | PageRenderer | [private]
m_messageFormat | PageRenderer | [private]
m_profiledWicBitmap | PageRenderer | [private]
m_sampleOverlay | PageRenderer | [private]
m_textFormat | PageRenderer | [private]
m_wicColorContext | PageRenderer | [private]
m_wicConvertedSource | PageRenderer | [private]
PrintPage(_In_ uint32 pageNumber, _In_ D2D1_RECT_F imageableArea, _In_ D2D1_SIZE_F pageSize, _In_opt_ IStream *pagePrintTicketStream) | PageRenderer |
PrintPage(_In_ uint32 pageNumber, _In_ D2D1_RECT_F imageableArea, _In_ D2D1_SIZE_F pageSize, _In_opt_ IStream *pagePrintTicketStream) | PageRenderer |
Render() override | PageRenderer | [virtual]
Render() override | PageRenderer | [virtual]
SetSnappedMode(_In_ bool isSnapped) | PageRenderer |
SetSnappedMode(_In_ bool isSnapped) | PageRenderer |
UpdateForWindowSizeChange() override | PageRenderer | [virtual]
UpdateForWindowSizeChange() override | PageRenderer | [virtual]
Generated on Sat Nov 23 2024 16:09:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Custom driver access/C++/DLL/fx2device.cpp Source File

  • Custom driver access
  • DLL

fx2device.cpp

Go to the documentation of this file.
00001 ﻿#include "fx2device.h"
00002
00003 Fx2Device::Fx2Device(_In_ IDeviceIoControl* DeviceControl, _In_ String^ Id) : m_DeviceIoControl(DeviceControl),
00004                                                                               m_Id(Id) {
00005     OutputDebugString(L"Fx2 constructor invoked\n");
00006     return;
00007 }
00008
00009 Fx2Device::~Fx2Device ()
00010 {
00011     OutputDebugString(L"Fx2Device destructor invoked\n");
00012     return;
00013 }
00014
00015 String^
00016 Fx2Device::GetDeviceSelector()
00017 {
00018     return L"System.Devices.InterfaceClassGuid:=\"{573E8C73-0CB4-4471-A1BF-FAB26C31D384}\" AND "
00019            L"System.Devices.InterfaceEnabled:=System.StructuredQueryType.Boolean#True";
00020 }
00021
00022 Fx2Device^
00023 Fx2Device::FromId(
00024     _In_ String^ InstancePath
00025     )
00026 {
00027     ComPtr<ICreateDeviceAccessAsync> access;
00028     ComPtr<IDeviceIoControl> deviceControl;
00029     HRESULT hr;
00030
00031     hr = CreateDeviceAccessInstance(InstancePath->Data(),
00032                                     GENERIC_READ | GENERIC_WRITE,
00033                                     &access);
00034     THROW_HR(hr);
00035
00036     //
00037     // Wait on the open
00038     //
00039
00040     hr = access->Wait(INFINITE);
00041     THROW_HR(hr);
00042
00043     hr = access->GetResult(IID_PPV_ARGS(&deviceControl));
00044     THROW_HR(hr);
00045
00046     OutputDebugStringW(L"Creating device\n");
00047
00048     //
00049     // Create an instance of the class and initialize it.
00050     //
00051     return ref new Fx2Device(deviceControl.Get(), InstancePath);
00052 }
00053
00054 String^
00055 Fx2Device::Id::get(void) {
00056     return m_Id;
00057 }
00058
00059 BYTE
00060 Fx2Device::SevenSegmentDisplay::get(VOID) {
00061
00062     BYTE ssValue = 0;
00063     ULONG numBytesReturned;
00064     HRESULT hr;
00065
00066     hr = m_DeviceIoControl->DeviceIoControlSync(
00067             IOCTL_OSRUSBFX2_GET_7_SEGMENT_DISPLAY,
00068             NULL,
00069             0,
00070             &ssValue,
00071             sizeof(ssValue),
00072             &numBytesReturned
00073             );
00074     THROW_HR(hr);
00075
00076     for(int i = 0; i < c_SegmentMaskCe; i += 1) {
00077         if (ssValue == c_SegmentMask[i]) {
00078             return (BYTE) i;
00079         }
00080     }
00081
00082     throw ref new InvalidArgumentException(L"Seven segment display value is not between 0 and 9");
00083 }
00084
00085 void
00086 Fx2Device::SevenSegmentDisplay::set(
00087     _In_ BYTE Value
00088     )
00089 {
00090     BYTE ssValue;
00091     HRESULT hr;
00092     DWORD bytesRead;
00093
00094     if (Value >= c_SegmentMaskCe) {
00095         throw ref new InvalidArgumentException(L"Value must be between 0 and 9");
00096     }
00097
00098     ssValue = c_SegmentMask[Value];
00099
00100     hr = m_DeviceIoControl->DeviceIoControlSync(
00101         IOCTL_OSRUSBFX2_SET_7_SEGMENT_DISPLAY,
00102         &ssValue,
00103         sizeof(ssValue),
00104         NULL,
00105         0,
00106         &bytesRead
00107         );
00108     THROW_HR(hr);
00109 }
00110
00111 Array<bool>^
00112 Fx2Device::SwitchState::get(VOID) {
00113
00114     BYTE ssValue = 0;
00115     ULONG numBytesReturned;
00116     HRESULT hr;
00117
00118     hr = m_DeviceIoControl->DeviceIoControlSync(
00119             IOCTL_OSRUSBFX2_READ_SWITCHES,
00120             NULL,
00121             0,
00122             &ssValue,
00123             sizeof(ssValue),
00124             &numBytesReturned
00125             );
00126     THROW_HR(hr);
00127
00128     Array<bool>^ result = ref new Array<bool>(c_NumSwitches);
00129
00130     for(int i = 0; i < c_NumSwitches; i += 1) {
00131         result[i] = ((ssValue & (1 << i)) != 0);
00132     }
00133
00134     return result;
00135 }
00136
00137 void
00138 Fx2Device::SetBarGraphDisplay(
00139     _In_ const Array<bool>^ Values
00140     )
00141 {
00142     BAR_GRAPH_STATE state;
00143     int valuesCe = Values->Length;
00144     DWORD bytesRead;
00145
00146
00147     state.BarsAsUChar = 0;
00148     for(int i = 0; i < min(c_NumBarsInGraph, valuesCe); i += 1) {
00149         state.BarsAsUChar |= (Values[i] ? 1 : 0) << i;
00150     }
00151
00152     HRESULT hr = m_DeviceIoControl->DeviceIoControlSync(
00153         IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY,
00154         (PBYTE) &state,
00155         sizeof(state),
00156         NULL,
00157         0,
00158         &bytesRead
00159         );
00160
00161     THROW_HR(hr);
00162 }
00163
00164 EventRegistrationToken
00165 Fx2Device::SwitchStateChanged::add(
00166     __in SwitchStateChangedHandler^ h
00167     )
00168 {
00169     EventRegistrationToken t = m_SwitchStateChangedEvent::add(h);
00170
00171     if (InterlockedIncrement(&m_SwitchState.ListenerCount) == 1) {
00172         m_SwitchState.Repeater.Start(
00173             [this](cancellation_token cancelToken, task_continuation_context& context) {
00174
00175                 // register for cancellation and abort the IOCTL if it happens
00176                 auto cancelTokenRegistration = cancelToken.register_callback([=]() {
00177                     m_DeviceIoControl->CancelOperation(m_SwitchState.CancelContext);
00178                 });
00179
00180                 // Create a task chain.  Send an ioctl to get the next switch
00181                 // state change.  Chain a task to convert that into the switch
00182                 // change event.
00183                 auto op =
00184                 StartIoctl(m_DeviceIoControl.Get(),
00185                             IOCTL_OSRUSBFX2_GET_INTERRUPT_MESSAGE,
00186                             NULL,
00187                             0,
00188                             (PBYTE) &m_SwitchState.Buffer,
00189                             sizeof(m_SwitchState.Buffer),
00190                             &m_SwitchState.CancelContext).
00191                 then([=](DeviceControlResult dcr) {
00192
00193                     bool abort = false;
00194                     SwitchStateChangedEventArgs^ e = nullptr;
00195
00196                     // unregister for cancellation
00197                     cancelToken.deregister_callback(cancelTokenRegistration);
00198
00199                     if (dcr.Result == HRESULT_FROM_WIN32(ERROR_OPERATION_ABORTED)) {
00200                         // fall through for cancellation
00201                         abort = true;
00202                     } else if (dcr.Result != S_OK) {
00203                         // Update the error count.  If it exceeds our limit then abort
00204                         // the reader.
00205                         m_SwitchState.FailureCount += 1;
00206                         if (m_SwitchState.FailureCount > 10) {
00207                             e = ref new SwitchStateChangedEventArgs(dcr.Result);
00208                             abort = true;
00209                         }
00210                     } else {
00211                         // Success.  Reset the failure count.
00212                         e = ref new SwitchStateChangedEventArgs(m_SwitchState.Buffer);
00213                         m_SwitchState.FailureCount = 0;
00214                     }
00215
00216                     // Raise the event if appropriate.
00217                     if (e != nullptr) {
00218                         m_SwitchStateChangedEvent(this, e);
00219                     }
00220
00221                     return !abort;
00222                 }, context);    // Since this task raises an event back to javascript
00223                                 // it must run in the context of the original call to
00224                                 // start the Repeater (which was from the UI thread)
00225
00226                 // Return the task chain.  The repeater will run this each
00227                 // time it starts an I/O operation, and takes care of starting
00228                 // the next task
00229                 return op;
00230             }
00231         );
00232     }
00233     return t;
00234 }
00235
00236 void
00237 Fx2Device::SwitchStateChanged::remove(
00238     __in EventRegistrationToken cookie
00239     )
00240 {
00241     m_SwitchStateChangedEvent::remove(cookie);
00242
00243     if (InterlockedDecrement(&m_SwitchState.ListenerCount) == 0) {
00244         m_SwitchState.Repeater.Stop();
00245     }
00246 }
00247
00248 IAsyncOperation<BarGraphDisplayResult^>^ Fx2Device::GetBarGraphDisplayAsync(void) {
00249
00250     // create an async operation object and return it to the caller.  The lambda
00251     // provided is the Start function for the operation, and returns a chain of tasks
00252     // that eventually provides the BarGraphDisplayResult^ object to the caller.
00253
00254     return create_async([this](cancellation_token cancelToken) {
00255
00256         // create the final result object, which we use to store the response
00257         // from the driver.
00258         BarGraphDisplayResult^ bgr = ref new BarGraphDisplayResult();
00259
00260         // Hook up cancellation using the cancel_token.
00261         auto registrationToken = cancelToken.register_callback([this, bgr]() {
00262             ULONG_PTR t = *(bgr->GetCancelToken());
00263             if (t != 0) {
00264                 m_DeviceIoControl->CancelOperation(t);
00265             }
00266         });
00267
00268         // StartIoctl returns a task that completes when the IOCTL completes.
00269         // Attach a follow-on task to convert the IOCTL results into bar graph
00270         // results.
00271         auto taskChain =
00272             StartIoctl(this->m_DeviceIoControl.Get(),
00273                        IOCTL_OSRUSBFX2_GET_BAR_GRAPH_DISPLAY,
00274                        nullptr,
00275                        0,
00276                        (PUCHAR) &(bgr->m_State),
00277                        sizeof(bgr->m_State),
00278                        bgr->GetCancelToken()).
00279             then([bgr,cancelToken,registrationToken](DeviceControlResult result) {
00280                 cancelToken.deregister_callback(registrationToken);
00281                 if ((result.Result == S_OK) &&
00282                     (result.BytesTransferred != sizeof(BAR_GRAPH_STATE))) {
00283                     result.Result = E_FAIL;
00284                 }
00285
00286                 if (result.Result != S_OK) {
00287                     throw Platform::Exception::CreateException(result.Result, L"Error getting bar graph display");
00288                 }
00289
00290                 bgr->UpdateBars();
00291                 return bgr;
00292             });
00293
00294         return taskChain;
00295     });
00296 }
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D stereoscopic 3D/C++/BasicTimer.cpp Source File

  • Direct3D stereoscopic 3D

BasicTimer.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 "BasicTimer.h"
00010
00011 BasicTimer::BasicTimer()
00012 {
00013     if (!QueryPerformanceFrequency(&m_frequency))
00014     {
00015         throw ref new Platform::FailureException();
00016     }
00017     Reset();
00018 }
00019
00020 void BasicTimer::Reset()
00021 {
00022     Update();
00023     m_startTime = m_currentTime;
00024     m_total = 0.0f;
00025     m_delta = 1.0f / 60.0f;
00026 }
00027
00028 void BasicTimer::Update()
00029 {
00030     if (!QueryPerformanceCounter(&m_currentTime))
00031     {
00032         throw ref new Platform::FailureException();
00033     }
00034
00035     m_total = static_cast<float>(
00036         static_cast<double>(m_currentTime.QuadPart-m_startTime.QuadPart) /
00037         static_cast<double>(m_frequency.QuadPart)
00038         );
00039
00040     if (m_lastTime.QuadPart == m_startTime.QuadPart)
00041     {
00042         // If the timer was just reset, report a time delta equivalent to 60Hz frame time.
00043         m_delta = 1.0f / 60.0f;
00044     }
00045     else
00046     {
00047         m_delta = static_cast<float>(
00048             static_cast<double>(m_currentTime.QuadPart-m_lastTime.QuadPart) /
00049             static_cast<double>(m_frequency.QuadPart)
00050             );
00051     }
00052
00053     m_lastTime = m_currentTime;
00054 }
00055
00056 float BasicTimer::Total::get()
00057 {
00058     return m_total;
00059 }
00060
00061 float BasicTimer::Delta::get()
00062 {
00063     return m_delta;
00064 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application data/C++/HighPriority.xaml.cpp Source File

  • Application data

HighPriority.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 // HighPriority.xaml.cpp
00013 // Implementation of the HighPriority class
00014 //
00015
00016 #include "pch.h"
00017 #include "HighPriority.xaml.h"
00018
00019 using namespace SDKSample::ApplicationDataSample;
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::UI::Core;
00027 using namespace Windows::Storage;
00028
00029 HighPriority::HighPriority()
00030 {
00031     InitializeComponent();
00032
00033     ApplicationData^ applicationData = ApplicationData::Current;
00034     roamingSettings = applicationData->RoamingSettings;
00035     applicationData->DataChanged += ref new TypedEventHandler<ApplicationData^, Object^>(this, &HighPriority::DataChangedHandler);
00036
00037     DisplayOutput(false);
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 void HighPriority::OnNavigatedTo(NavigationEventArgs^ e)
00046 {
00047     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00048     // as NotifyUser()
00049     rootPage = MainPage::Current;
00050 }
00051
00052 // Guidance for using the HighPriority setting.
00053 //
00054 // Writing to the HighPriority setting enables a developer to store a small amount of
00055 // data that will be roamed out to the cloud with higher priority than other roaming
00056 // data, when possible.
00057 //
00058 // Applications should carefully consider which data should be stored in the
00059 // HighPriority setting.  "Context" data such as the user's location within
00060 // media, or their current game-baord and high-score, can make the most sense to
00061 // roam with high priority.  By using the HighPriority setting, this information has
00062 // a higher likelihood of being available to the user when they begin to use another
00063 // machine.
00064 //
00065 // Applications should update their HighPriority setting when the user makes
00066 // a significant change to the data it represents.  Examples could include changing
00067 // music tracks, turning the page in a book, or finishing a level in a game.
00068
00069 void HighPriority::IncrementHighPriority_Click(Object^ sender, RoutedEventArgs^ e)
00070 {
00071     int counter = 0;
00072
00073     IPropertyValue^ pv = safe_cast<IPropertyValue^>(roamingSettings->Values->Lookup("HighPriority"));
00074     if (pv != nullptr)
00075     {
00076         counter = pv->GetInt32();
00077     }
00078
00079     roamingSettings->Values->Insert("HighPriority", PropertyValue::CreateInt32(counter + 1));
00080
00081     DisplayOutput(false);
00082 }
00083
00084 void HighPriority::DataChangedHandler(Windows::Storage::ApplicationData^ appData, Object^)
00085 {
00086     // This event handler may be invoked on another thread, so use the Dispatcher to invoke the UI-related code on the UI thread.
00087     auto callback = ref new DispatchedHandler(
00088         [this]() { DisplayOutput(true); },
00089         CallbackContext::Any
00090         );
00091     this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, callback);
00092 }
00093
00094 void HighPriority::DisplayOutput(bool remoteUpdate)
00095 {
00096     int counter = 0;
00097
00098     IPropertyValue^ pv = safe_cast<IPropertyValue^>(roamingSettings->Values->Lookup("HighPriority"));
00099     if (pv != nullptr)
00100     {
00101         counter = pv->GetInt32();
00102     }
00103
00104     OutputTextBlock->Text = "Counter: " + counter.ToString() + (remoteUpdate ? " (updated remotely)" : "");
00105 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::UserAndCustomControls::sealed Member List

This is the complete list of members for SDKSample::UserAndCustomControls::sealed, including all inherited members.
_ImagePathProperty | SDKSample::UserAndCustomControls::sealed | [private, static]
_LabelProperty | SDKSample::UserAndCustomControls::sealed | [private, static]
BasicCustomControl() | SDKSample::UserAndCustomControls::sealed |
BasicUserControl() | SDKSample::UserAndCustomControls::sealed |
ClickMeButtonClicked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::UserAndCustomControls::sealed | [private]
Default_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::UserAndCustomControls::sealed | [private]
Default_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::UserAndCustomControls::sealed | [private]
DoSomething_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::UserAndCustomControls::sealed | [private]
Go_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::UserAndCustomControls::sealed | [private]
ImageWithLabelControl() | SDKSample::UserAndCustomControls::sealed |
NavigateDPHelp(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::UserAndCustomControls::sealed | [private]
NavigateToLink(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::UserAndCustomControls::sealed | [private]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::UserAndCustomControls::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::UserAndCustomControls::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::UserAndCustomControls::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::UserAndCustomControls::sealed | [protected, virtual]
Other_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::UserAndCustomControls::sealed | [private]
Other_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::UserAndCustomControls::sealed | [private]
rootPage | SDKSample::UserAndCustomControls::sealed | [private]
Scenario1() | SDKSample::UserAndCustomControls::sealed |
Scenario2() | SDKSample::UserAndCustomControls::sealed |
Scenario3() | SDKSample::UserAndCustomControls::sealed |
Scenario4() | SDKSample::UserAndCustomControls::sealed |
Generated on Sat Nov 23 2024 16:09:53 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Touch keyboard text input/C++/App.xaml.h Source File

  • Input Touch keyboard text input

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DirectX::D3DX_BC7::EncodeParams Member List

This is the complete list of members for DirectX::D3DX_BC7::EncodeParams, including all inherited members.
aEndPts | DirectX::D3DX_BC7::EncodeParams |
aHDRPixels | DirectX::D3DX_BC7::EncodeParams |
aLDRPixels | DirectX::D3DX_BC7::EncodeParams |
EncodeParams(const HDRColorA *const aOriginal) | DirectX::D3DX_BC7::EncodeParams | [inline]
uMode | DirectX::D3DX_BC7::EncodeParams |
Generated on Sat Nov 23 2024 16:09:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Connecting with WebSockets/C++/Scenario1.xaml.h Source File

  • Connecting with WebSockets

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 using namespace Platform;
00023 using namespace Windows::Foundation;
00024 using namespace Windows::Networking::Sockets;
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::Navigation;
00029 using namespace Windows::Web;
00030
00031 namespace SDKSample
00032 {
00033     namespace WebSocket
00034     {
00035         /// <summary>
00036         /// An empty page that can be used on its own or navigated to within a Frame.
00037         /// </summary>
00038       [Windows::Foundation::Metadata::WebHostHidden]
00039         public ref class Scenario1 sealed
00040         {
00041         public:
00042             Scenario1();
00043
00044         protected:
00045             virtual void OnNavigatedTo(NavigationEventArgs^ e) override;
00046         private:
00047             ~Scenario1();
00048
00049         MainPage^ rootPage;
00050             MessageWebSocket^ messageWebSocket;
00051             DataWriter^ messageWriter;
00052             CRITICAL_SECTION criticalSection;
00053
00054             void Start_Click(Object^ sender, RoutedEventArgs^ e);
00055             void Close_Click(Object^ sender, RoutedEventArgs^ e);
00056             void SendMessage();
00057             void MessageReceived(MessageWebSocket^ sender, MessageWebSocketMessageReceivedEventArgs^ args);
00058             void Closed(IWebSocket^ sender, WebSocketClosedEventArgs^ args);
00059             void MarshalText(TextBox^ output, String^ value);
00060             void MarshalText(TextBox^ output, String^ value, bool append);
00061             void HandleException(Exception^ exception);
00062         };
00063     }
00064 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::Transcode::sealed Member List

This is the complete list of members for SDKSample::Transcode::sealed, including all inherited members.
_CTS | SDKSample::Transcode::sealed | [private]
_InputFile | SDKSample::Transcode::sealed | [private]
_OutputFile | SDKSample::Transcode::sealed | [private]
_OutputFileName | SDKSample::Transcode::sealed | [private]
_Profile | SDKSample::Transcode::sealed | [private]
_start | SDKSample::Transcode::sealed | [private]
_stop | SDKSample::Transcode::sealed | [private]
_Transcoder | SDKSample::Transcode::sealed | [private]
_UseMp4 | SDKSample::Transcode::sealed | [private]
_UseMp4 | SDKSample::Transcode::sealed | [private]
Custom() | SDKSample::Transcode::sealed |
DisableButtons() | SDKSample::Transcode::sealed | [private]
DisableButtons() | SDKSample::Transcode::sealed | [private]
DisableButtons() | SDKSample::Transcode::sealed | [private]
EnableButtons() | SDKSample::Transcode::sealed | [private]
EnableButtons() | SDKSample::Transcode::sealed | [private]
EnableButtons() | SDKSample::Transcode::sealed | [private]
GetCustomProfile() | SDKSample::Transcode::sealed | [private]
GetPresetProfile(Windows::UI::Xaml::Controls::ComboBox^comboBox) | SDKSample::Transcode::sealed | [private]
GetPresetProfile(Windows::UI::Xaml::Controls::ComboBox^comboBox) | SDKSample::Transcode::sealed | [private]
InputPauseButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Transcode::sealed | [private]
InputPauseButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Transcode::sealed | [private]
InputPauseButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Transcode::sealed | [private]
InputPlayButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Transcode::sealed | [private]
InputPlayButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Transcode::sealed | [private]
InputPlayButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Transcode::sealed | [private]
InputStopButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Transcode::sealed | [private]
InputStopButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Transcode::sealed | [private]
InputStopButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Transcode::sealed | [private]
MarkIn(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Transcode::sealed | [private]
MarkOut(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Transcode::sealed | [private]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Transcode::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Transcode::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::Transcode::sealed | [protected, virtual]
OnTargetFormatChanged(Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | SDKSample::Transcode::sealed | [private]
OnTargetFormatChanged(Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | SDKSample::Transcode::sealed | [private]
OnTargetFormatChanged(Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | SDKSample::Transcode::sealed | [private]
OutputPauseButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Transcode::sealed | [private]
OutputPauseButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Transcode::sealed | [private]
OutputPauseButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Transcode::sealed | [private]
OutputPlayButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Transcode::sealed | [private]
OutputPlayButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Transcode::sealed | [private]
OutputPlayButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Transcode::sealed | [private]
OutputStopButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Transcode::sealed | [private]
OutputStopButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Transcode::sealed | [private]
OutputStopButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Transcode::sealed | [private]
PickFile(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Transcode::sealed | [private]
PickFile(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Transcode::sealed | [private]
PickFile(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Transcode::sealed | [private]
PlayFile(Windows::Storage::StorageFile^MediaFile) | SDKSample::Transcode::sealed | [private]
PlayFile(Windows::Storage::StorageFile^MediaFile) | SDKSample::Transcode::sealed | [private]
PlayFile(Windows::Storage::StorageFile^MediaFile) | SDKSample::Transcode::sealed | [private]
Presets() | SDKSample::Transcode::sealed |
rootPage | SDKSample::Transcode::sealed | [private]
SetCancelButton(bool isEnabled) | SDKSample::Transcode::sealed | [private]
SetCancelButton(bool isEnabled) | SDKSample::Transcode::sealed | [private]
SetCancelButton(bool isEnabled) | SDKSample::Transcode::sealed | [private]
SetPickFileButton(bool isEnabled) | SDKSample::Transcode::sealed | [private]
SetPickFileButton(bool isEnabled) | SDKSample::Transcode::sealed | [private]
SetPickFileButton(bool isEnabled) | SDKSample::Transcode::sealed | [private]
StopPlayers() | SDKSample::Transcode::sealed | [private]
StopPlayers() | SDKSample::Transcode::sealed | [private]
StopPlayers() | SDKSample::Transcode::sealed | [private]
TranscodeCancel(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Transcode::sealed | [private]
TranscodeCancel(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Transcode::sealed | [private]
TranscodeCancel(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Transcode::sealed | [private]
TranscodeComplete(Windows::Foundation::IAsyncActionWithProgress< double >^asyncInfo, Windows::Foundation::AsyncStatus status) | SDKSample::Transcode::sealed | [private]
TranscodeCustom(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Transcode::sealed | [private]
TranscodeError(Platform::String^error) | SDKSample::Transcode::sealed | [private]
TranscodeError(Platform::String^error) | SDKSample::Transcode::sealed | [private]
TranscodeError(Platform::String^error) | SDKSample::Transcode::sealed | [private]
TranscodeFailure(Windows::Media::Transcoding::TranscodeFailureReason reason) | SDKSample::Transcode::sealed | [private]
TranscodeFailure(Windows::Media::Transcoding::TranscodeFailureReason reason) | SDKSample::Transcode::sealed | [private]
TranscodeFailure(Windows::Media::Transcoding::TranscodeFailureReason reason) | SDKSample::Transcode::sealed | [private]
TranscodePreset(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Transcode::sealed | [private]
TranscodeProgress(Windows::Foundation::IAsyncActionWithProgress< double >^asyncInfo, double percent) | SDKSample::Transcode::sealed | [private]
TranscodeProgress(Windows::Foundation::IAsyncActionWithProgress< double >^asyncInfo, double percent) | SDKSample::Transcode::sealed | [private]
TranscodeProgress(Windows::Foundation::IAsyncActionWithProgress< double >^asyncInfo, double percent) | SDKSample::Transcode::sealed | [private]
TranscodeTrim(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::Transcode::sealed | [private]
Trim() | SDKSample::Transcode::sealed |
Generated on Sat Nov 23 2024 16:09:53 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/Audio.h Source File

  • XAML DirectX 3D shooting game

Audio.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 // Audio:
00011 // This class uses XAudio2 to provide sound output.  It creates two
00012 // engines - one for music and the other for sound effects - each as
00013 // a separate mastering voice.
00014 // The SuspendAudio and ResumeAudio methods can be used to stop
00015 // and start all audio playback.
00016
00017 ref class Audio
00018 {
00019 internal:
00020     Audio();
00021
00022     void Initialize();
00023     void CreateDeviceIndependentResources();
00024     IXAudio2* MusicEngine();
00025     IXAudio2* SoundEffectEngine();
00026     void SuspendAudio();
00027     void ResumeAudio();
00028
00029 protected private:
00030     bool                                m_audioAvailable;
00031     Microsoft::WRL::ComPtr<IXAudio2>    m_musicEngine;
00032     Microsoft::WRL::ComPtr<IXAudio2>    m_soundEffectEngine;
00033     IXAudio2MasteringVoice*             m_musicMasteringVoice;
00034     IXAudio2MasteringVoice*             m_soundEffectMasteringVoice;
00035 };
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File picker/C++/App.xaml.cpp Source File

  • File picker

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Raw notifications/C++/MainAppSample/ScenarioList.xaml.h Source File

  • Raw notifications
  • MainAppSample

ScenarioList.xaml.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 //
00009 // ScenarioList.xaml.h
00010 // Declaration of the ScenarioList class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioList.g.h"
00017 #include "MainPage.g.h"
00018
00019 using namespace Windows::UI::Xaml::Controls;
00020 using namespace CppSamplesUtils;
00021
00022 namespace RawNotificationsSampleCPP
00023 {
00024   [Windows::Foundation::Metadata::WebHostHidden]
00025   public ref class ScenarioList sealed
00026   {
00027   public:
00028     ScenarioList();
00029
00030   protected:
00031     void Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e);
00032     virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00033
00034   private:
00035     ~ScenarioList();
00036     MainPage^ rootPage;
00037   };
00038 }
Generated on Sat Nov 23 2024 16:07:57 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text display/C++/Scenario4.xaml.cpp Source File

  • XAML text display

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::TextDisplay;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 Scenario4::Scenario4()
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 Scenario4::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 SDKSample::TextDisplay::Scenario4::Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00043 {
00044     Button^ b = safe_cast<Button^>(sender);
00045     if (b != nullptr)
00046     {
00047         rootPage->NotifyUser("You clicked the " + b->Name + " button", NotifyType::StatusMessage);
00048     }
00049 }
00050
00051 void SDKSample::TextDisplay::Scenario4::Other_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00052 {
00053     Button^ b = safe_cast<Button^>(sender);
00054     if (b != nullptr)
00055     {
00056         rootPage->NotifyUser("You clicked the " + b->Name + " button", NotifyType::StatusMessage);
00057     }
00058 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Transcoding media/C++/MainPage.xaml.cpp Source File

  • Transcoding media

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:44 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/GameTimer.h Source File

  • XAML DirectX 3D shooting game

GameTimer.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 ref class GameTimer
00011 {
00012 internal:
00013     GameTimer();
00014
00015     float PlayingTime();            // Return the Elapsed time the Game has been active in seconds since Reset
00016     void PlayingTime(float time);   // Set the Elapsed playing time -- used for restarting in the middle of a game
00017     float DeltaTime();              // Return the Delta time between the last two updates
00018
00019     void Reset();
00020     void Start();
00021     void Stop();
00022     void Update();
00023     bool Active() { return m_active; };
00024
00025 private:
00026     float m_secondsPerCount;  // 1.0 / Frequency
00027     float m_deltaTime;
00028
00029     LARGE_INTEGER m_baseTime;
00030     LARGE_INTEGER m_pausedTime;
00031     LARGE_INTEGER m_stopTime;
00032     LARGE_INTEGER m_previousTime;
00033     LARGE_INTEGER m_currentTime;
00034
00035     bool m_active;
00036 };
00037
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Number formatting and parsing/C++/MainPage.xaml.h Source File

  • Number formatting and parsing

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:46 for Win8-Examples by doxygen 1.7.1


Win8-Examples: ControlChannelTrigger StreamWebSocket/C++/Background/pch.cpp Source File

  • ControlChannelTrigger StreamWebSocket
  • Background

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 Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/DDSTextureLoader.h Source File

  • DirectX 3D shooting game

DDSTextureLoader.h

Go to the documentation of this file.
00001 //--------------------------------------------------------------------------------------
00002 // File: DDSTextureLoader.h
00003 //
00004 // Function for loading a DDS texture and creating a Direct3D 11 runtime resource for it
00005 //
00006 // Note this function is 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
00018 #pragma once
00019
00020 void CreateDDSTextureFromMemory(
00021     _In_ ID3D11Device* d3dDevice,
00022     _In_reads_bytes_(ddsDataSize) const byte* ddsData,
00023     _In_ size_t ddsDataSize,
00024     _Out_opt_ ID3D11Resource** texture,
00025     _Out_opt_ ID3D11ShaderResourceView** textureView,
00026     _In_ size_t maxsize = 0
00027     );
Generated on Sat Nov 23 2024 16:08:11 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File picker contracts/C++/MainPage_CachedFile.xaml.cpp Source File

  • File picker contracts

MainPage_CachedFile.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 // MainPage_CachedFile.xaml.cpp
00013 // Implementation of the MainPage_CachedFile class
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "MainPage_CachedFile.xaml.h"
00019
00020 using namespace SDKSample::FilePickerContracts;
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::Pickers;
00027 using namespace Windows::UI::Xaml;
00028 using namespace Windows::UI::Xaml::Controls;
00029 using namespace Windows::UI::Xaml::Navigation;
00030
00031 MainPage_CachedFile::MainPage_CachedFile()
00032 {
00033     InitializeComponent();
00034 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/DirectXBase.h Source File

  • Direct3D resource loading

DirectXBase.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 "DirectXSample.h"
00011
00012 // Helper class that initializes DirectX APIs for both 2D and 3D rendering.
00013 // Some of the code in this class may be omitted if only 2D or only 3D rendering is being used.
00014 ref class DirectXBase abstract
00015 {
00016 internal:
00017     DirectXBase();
00018
00019     virtual void Initialize(Windows::UI::Core::CoreWindow^ window, float dpi);
00020     virtual void HandleDeviceLost();
00021     virtual void CreateDeviceIndependentResources();
00022     virtual void CreateDeviceResources();
00023     virtual void SetDpi(float dpi);
00024     virtual void UpdateForWindowSizeChange();
00025     virtual void CreateWindowSizeDependentResources();
00026     virtual void Render() = 0;
00027     virtual void Present();
00028     void ValidateDevice();
00029
00030 protected private:
00031     Platform::Agile<Windows::UI::Core::CoreWindow>  m_window;
00032
00033     // DirectWrite & Windows Imaging Component Objects.
00034     Microsoft::WRL::ComPtr<IDWriteFactory1>         m_dwriteFactory;
00035     Microsoft::WRL::ComPtr<IWICImagingFactory2>     m_wicFactory;
00036
00037     // DirectX Core Objects. Required for 2D and 3D.
00038     Microsoft::WRL::ComPtr<ID3D11Device1>           m_d3dDevice;
00039     Microsoft::WRL::ComPtr<ID3D11DeviceContext1>    m_d3dContext;
00040     Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00041     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00042
00043     // Direct2D Rendering Objects. Required for 2D.
00044     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00046     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00047     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmap;
00048
00049     // Direct3D Rendering Objects. Required for 3D.
00050     Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00051
00052     // Cached renderer properties.
00053     D3D_FEATURE_LEVEL                               m_featureLevel;
00054     Windows::Foundation::Size                       m_renderTargetSize;
00055     Windows::Foundation::Rect                       m_windowBounds;
00056     float                                           m_dpi;
00057     bool                                            m_windowSizeChangeInProgress;
00058 };
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media engine native C++ video playback/C++/meplayer.h Source File

  • Media engine native C++ video playback

meplayer.h

Go to the documentation of this file.
00001 //
00002 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00003 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00004 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00005 // PARTICULAR PURPOSE.
00006 //
00007 // Copyright (c) Microsoft Corporation. All rights reserved.
00008 //
00009 #pragma once
00010
00011 #include <wrl.h>
00012 #include <mfmediaengine.h>
00013 #include <d3d11_1.h>
00014 //#include <d3d10.h>
00015 #include <ppltasks.h>
00016 #include <agile.h>
00017
00018 #ifndef MEPLAYER_H
00019 #define MEPLAYER_H
00020
00021 #define ME_CAN_SEEK 0x00000002
00022
00023 namespace MEDIA
00024 {
00025     inline void ThrowIfFailed(HRESULT hr)
00026     {
00027         if (FAILED(hr))
00028         {
00029             // Set a breakpoint on this line to catch DirectX API errors
00030             throw Platform::Exception::CreateException(hr);
00031         }
00032     }
00033 }
00034
00035 //-----------------------------------------------------------------------------
00036 // MediaEngineNotifyCallback
00037 //
00038 // Defines the callback method to process media engine events.
00039 //-----------------------------------------------------------------------------
00040
00041 ref struct MediaEngineNotifyCallback abstract
00042 {
00043 internal:
00044     virtual void OnMediaEngineEvent(DWORD meEvent) = 0;
00045 };
00046
00047 // MEPlayer: Manages the Media Engine.
00048
00049 ref class MEPlayer: public MediaEngineNotifyCallback
00050 {
00051     // DX11 related
00052     Microsoft::WRL::ComPtr<ID3D11Device>                m_spDX11Device;
00053     Microsoft::WRL::ComPtr<ID3D11DeviceContext>         m_spDX11DeviceContext;
00054     Microsoft::WRL::ComPtr<IDXGIOutput>                 m_spDXGIOutput;
00055     Microsoft::WRL::ComPtr<IDXGISwapChain1>             m_spDX11SwapChain;
00056     Microsoft::WRL::ComPtr<IMFDXGIDeviceManager>        m_spDXGIManager;
00057
00058     // Media Engine related
00059     Microsoft::WRL::ComPtr<IMFMediaEngine>              m_spMediaEngine;
00060     Microsoft::WRL::ComPtr<IMFMediaEngineEx>            m_spEngineEx;
00061
00062     BSTR                                    m_bstrURL;
00063     BOOL                                    m_fPlaying;
00064     BOOL                                    m_fLoop;
00065     BOOL                                    m_fEOS;
00066     BOOL                                    m_fStopTimer;
00067     RECT                                    m_rcTarget;
00068     DXGI_FORMAT                             m_d3dFormat;
00069     MFARGB                                  m_bkgColor;
00070
00071     HANDLE                                  m_TimerThreadHandle;
00072     CRITICAL_SECTION                        m_critSec;
00073
00074     concurrency::task<Windows::Storage::StorageFile^>   m_pickFileTask;
00075     concurrency::cancellation_token_source              m_tcs;
00076     BOOL                                                m_fInitSuccess;
00077     BOOL                                                m_fExitApp;
00078     BOOL                                                m_fUseDX;
00079
00080 internal:
00081
00082     MEPlayer();
00083
00084     // DX11 related
00085     void CreateDX11Device();
00086     void CreateBackBuffers();
00087
00088     // Initialize/Shutdown
00089     void Initialize(Windows::UI::Core::CoreWindow^ window);
00090     void Shutdown();
00091     BOOL ExitApp();
00092
00093     // Media Engine related
00094     virtual void OnMediaEngineEvent(DWORD meEvent) override;
00095
00096     // Media Engine related Options
00097     void AutoPlay(BOOL autoPlay)
00098     {
00099         if (m_spMediaEngine)
00100         {
00101             m_spMediaEngine->SetAutoPlay(autoPlay);
00102         }
00103     }
00104
00105     void Loop()
00106     {
00107         if (m_spMediaEngine)
00108         {
00109             (m_fLoop) ? m_fLoop = FALSE : m_fLoop = TRUE;
00110             m_spMediaEngine->SetLoop(m_fLoop);
00111         }
00112     }
00113
00114     BOOL IsPlaying()
00115     {
00116         return m_fPlaying;
00117     }
00118
00119     void CloseFilePicker()
00120     {
00121         m_tcs.cancel();
00122     }
00123
00124     // Loading
00125     void OpenFile();
00126     void SetURL(Platform::String^ szURL);
00127     void SetBytestream(Windows::Storage::Streams::IRandomAccessStream^ streamHandle);
00128
00129     // Transport state
00130     void Play();
00131     void Pause();
00132     void FrameStep();
00133
00134     // Audio
00135     void SetVolume(float fVol);
00136     void SetBalance(float fBal);
00137     void Mute(BOOL mute);
00138
00139     // Video
00140     void ResizeVideo(HWND hwnd);
00141     void EnableVideoEffect(BOOL enable);
00142
00143     // Seeking and duration.
00144     void GetDuration(double *pDuration, BOOL *pbCanSeek);
00145     void SetPlaybackPosition(float pos);
00146     double  GetPlaybackPosition();
00147     BOOL    IsSeeking();
00148
00149     // Window Event Handlers
00150     void UpdateForWindowSizeChange();
00151
00152     // Timer thread related
00153     void StartTimer();
00154     void StopTimer();
00155     void OnTimer();
00156     DWORD RealVSyncTimer();
00157
00158 private:
00159     ~MEPlayer();
00160     Platform::Agile<Windows::UI::Core::CoreWindow> m_window;
00161 };
00162
00163 #endif /* MEPLAYER_H */
Generated on Sat Nov 23 2024 16:08:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

LinearAnimation< T > Member List

This is the complete list of members for LinearAnimation< T >, including all inherited members.
Animation(T start, T end, T duration) | Animation< T > | [inline]
ComputeValue(T time) | LinearAnimation< T > | [inline, protected, virtual]
GetDuration() | Animation< T > | [inline]
GetEnd() | Animation< T > | [inline]
GetStart() | Animation< T > | [inline]
GetValue(T time) | Animation< T > | [inline]
LinearAnimation(T start=0, T end=0, T duration=0) | LinearAnimation< T > | [inline]
m_Duration | Animation< T > | [protected]
m_End | Animation< T > | [protected]
m_Start | Animation< T > | [protected]
SetDuration(T duration) | Animation< T > | [inline]
SetEnd(T end) | Animation< T > | [inline]
SetStart(T start) | Animation< T > | [inline]
Generated on Sat Nov 23 2024 16:09:15 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML personality animations/C++/Page1.xaml.h Source File

  • XAML personality animations

Page1.xaml.h

Go to the documentation of this file.
00001 ﻿//
00002 // Page1.xaml.h
00003 // Declaration of the Page1 class
00004 //
00005
00006 #pragma once
00007
00008 #include "Page1.g.h"
00009 #include "SampleData/SampleDataSource.h"
00010
00011 using namespace SDKSample::ExpressionBlendSampleDataSampleDataSource;
00012
00013 namespace SDKSample
00014 {
00015 namespace PersonalityAnimations
00016 {
00017   /// <summary>
00018   /// An empty page that can be used on its own or navigated to within a Frame.
00019   /// </summary>
00020   public ref class Page1 sealed
00021   {
00022   public:
00023     Page1();
00024
00025   protected:
00026     virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00027
00028   private:
00029     MessageData^ messageData;
00030   };
00031 }
00032 }
Generated on Sat Nov 23 2024 16:08:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML Direct2D lighting effects/C++/D2DLightingEffectsRenderer.h Source File

  • XAML Direct2D lighting effects

D2DLightingEffectsRenderer.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 "DirectXBase.h"
00011
00012 enum class LightingEffect
00013 {
00014     PointSpecular,
00015     SpotSpecular,
00016     DistantSpecular,
00017     PointDiffuse,
00018     SpotDiffuse,
00019     DistantDiffuse
00020 };
00021
00022 // Each lighting effect has its own property enumerations. This list standardizes
00023 // the enumerations across all the different effects.
00024 enum class LightingProperty
00025 {
00026     LightPositionZ,
00027     SpecularExponent,
00028     SpecularConstant,
00029     DiffuseConstant,
00030     Focus,
00031     LimitingConeAngle,
00032     Elevation,
00033     Azimuth,
00034     SurfaceScale
00035 };
00036
00037 ref class D2DLightingEffectsRenderer : public DirectXBase
00038 {
00039 internal:
00040     D2DLightingEffectsRenderer();
00041
00042     virtual void HandleDeviceLost() override;
00043     virtual void CreateDeviceIndependentResources() override;
00044     virtual void CreateDeviceResources() override;
00045     virtual void CreateWindowSizeDependentResources() override;
00046     virtual void Render() override;
00047
00048     void OnPointerMoved(float x, float y);
00049
00050     void SetLightingEffect(LightingEffect lightingEffect);
00051     void SetLightingProperty(LightingProperty lightingProperty, float value);
00052
00053     void UpdateForViewStateChanged(Windows::UI::ViewManagement::ApplicationViewState state);
00054
00055     bool NeedsResourceUpdate()
00056     {
00057         return m_needsResourceUpdate;
00058     }
00059
00060 private:
00061     Windows::UI::ViewManagement::ApplicationViewState       m_windowState;
00062     bool                                                    m_needsResourceUpdate;
00063
00064     Microsoft::WRL::ComPtr<IWICFormatConverter>             m_wicConverter;
00065     D2D1_SIZE_U                                             m_imageSize;
00066
00067     Microsoft::WRL::ComPtr<ID2D1Effect>                     m_bitmapSourceEffect;
00068
00069     Microsoft::WRL::ComPtr<ID2D1Effect>                     m_currentEffect;
00070     Microsoft::WRL::ComPtr<ID2D1Effect>                     m_pointSpecularEffect;
00071     Microsoft::WRL::ComPtr<ID2D1Effect>                     m_spotSpecularEffect;
00072     Microsoft::WRL::ComPtr<ID2D1Effect>                     m_distantSpecularEffect;
00073     Microsoft::WRL::ComPtr<ID2D1Effect>                     m_pointDiffuseEffect;
00074     Microsoft::WRL::ComPtr<ID2D1Effect>                     m_spotDiffuseEffect;
00075     Microsoft::WRL::ComPtr<ID2D1Effect>                     m_distantDiffuseEffect;
00076
00077     float                                                   m_lightPositionZ;
00078 };
Generated on Sat Nov 23 2024 16:08:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

PrintSample::sealed Member List

This is the complete list of members for PrintSample::sealed, including all inherited members.
_displayHandlerToken | PrintSample::sealed | [private]
_inputFrame | PrintSample::sealed | [private]
_inputFrameLoadedToken | PrintSample::sealed | [private]
_logicalDpiChangedToken | PrintSample::sealed | [private]
_outputFrame | PrintSample::sealed | [private]
_outputFrameLoadedToken | PrintSample::sealed | [private]
_pageLoadedHandlerToken | PrintSample::sealed | [private]
_scenariosFrame | PrintSample::sealed | [private]
_sizeChangedHandlerToken | PrintSample::sealed | [private]
AddOnePrintPreviewPage(RichTextBlockOverflow^lastRTBOAdded, Windows::Graphics::Printing::PrintPageDescription printPageDescription) override | PrintSample::sealed | [protected, virtual]
AddOnePrintPreviewPage(RichTextBlockOverflow^lastRTBOAdded, Windows::Graphics::Printing::PrintPageDescription printPageDescription) override | PrintSample::sealed | [protected, virtual]
AddPrintPages(Object^sender, AddPagesEventArgs^e) override | PrintSample::sealed | [protected, virtual]
App() | PrintSample::sealed |
CheckResolutionAndViewState() | PrintSample::sealed | [private]
ClearPageCollection() | PrintSample::sealed | [protected]
ContinuationPage() | PrintSample::sealed |
ContinuationPage(Windows::UI::Xaml::Controls::RichTextBlockOverflow^textLinkContainer) | PrintSample::sealed |
ConvertResolution(ResolutionScale scale) | PrintSample::sealed |
ConvertViewState(ApplicationViewState state) | PrintSample::sealed |
CreatePrintPreviewPages(Object^sender, PaginateEventArgs^e) override | PrintSample::sealed | [protected, virtual]
CreatePrintPreviewPages(Object^sender, PaginateEventArgs^e) override | PrintSample::sealed | [protected, virtual]
DisplayProperties_LogicalDpiChanged(Object^sender) | PrintSample::sealed | [private]
DoNavigation(TypeName pageType, Windows::UI::Xaml::Controls::Frame^frame) | PrintSample::sealed |
DPI96 | PrintSample::sealed | [private, static]
Footer_Click(Object^sender, RoutedEventArgs^e) | PrintSample::sealed | [private]
GetPagesInRange(String^pageRange) | PrintSample::sealed | [private]
GetPrintPreviewPage(Object^sender, GetPreviewPageEventArgs^e) override | PrintSample::sealed | [protected, virtual]
inputFrameNavigated(Object^sender, NavigationEventArgs^e) | PrintSample::sealed | [private]
InvokePrintButtonClick(Object^sender, RoutedEventArgs^e) | PrintSample::sealed | [private]
LoadBitmap(Windows::Foundation::Uri^source, bool landscape) | PrintSample::sealed | [private]
m_csPrintSync | PrintSample::sealed | [private]
m_currentPageDescription | PrintSample::sealed | [private]
m_imageText | PrintSample::sealed | [private]
m_pageCollection | PrintSample::sealed | [private]
m_pageList | PrintSample::sealed | [private]
m_pageRangeEditVisible | PrintSample::sealed | [private]
m_photoScale | PrintSample::sealed | [private]
m_photoSize | PrintSample::sealed | [private]
m_requestCount | PrintSample::sealed | [private]
m_selectionMode | PrintSample::sealed | [private]
m_totalPages | PrintSample::sealed | [private]
MainPage() | PrintSample::sealed |
NotifyUser(String^strMessage, NotifyType type) | PrintSample::sealed |
NumberOfPhotos | PrintSample::sealed | [private, static]
OnContentCreated() override | PrintSample::sealed | [protected, virtual]
OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^pArgs) override | PrintSample::sealed | [virtual]
OnNavigatedFrom(NavigationEventArgs^e) override | PrintSample::sealed | [virtual]
OnNavigatedFrom(NavigationEventArgs^e) override | PrintSample::sealed | [virtual]
OnNavigatedFrom(NavigationEventArgs^e) override | PrintSample::sealed | [virtual]
OnNavigatedFrom(NavigationEventArgs^e) override | PrintSample::sealed | [virtual]
OnNavigatedFrom(NavigationEventArgs^e) override | PrintSample::sealed | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | PrintSample::sealed | [protected, virtual]
OnNavigatedTo(NavigationEventArgs^e) override | PrintSample::sealed | [virtual]
OnNavigatedTo(NavigationEventArgs^e) override | PrintSample::sealed | [virtual]
OnNavigatedTo(NavigationEventArgs^e) override | PrintSample::sealed | [virtual]
OnNavigatedTo(NavigationEventArgs^e) override | PrintSample::sealed | [virtual]
OnNavigatedTo(NavigationEventArgs^e) override | PrintSample::sealed | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | PrintSample::sealed | [protected, virtual]
OnSuspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^pArgs) | PrintSample::sealed | [virtual]
OutputFrameLoaded | PrintSample::sealed |
outputFrameNavigated(Object^sender, NavigationEventArgs^e) | PrintSample::sealed | [private]
Page_Loaded(Object^sender, RoutedEventArgs^e) | PrintSample::sealed | [private]
Page_SizeChanged(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::WindowSizeChangedEventArgs^args) | PrintSample::sealed | [private]
PreparetPrintContent() override | PrintSample::sealed | [protected, virtual]
PreparetPrintContent() override | PrintSample::sealed | [protected, virtual]
PreparetPrintContent() override | PrintSample::sealed | [protected, virtual]
PreparetPrintContent() override | PrintSample::sealed | [protected, virtual]
PreparetPrintContent() override | PrintSample::sealed | [protected, virtual]
PreviewUnavailable() | PrintSample::sealed |
PreviewUnavailable(Windows::Foundation::Size paperSize, Windows::Foundation::Size printableSize) | PrintSample::sealed |
printDetailedOptions_OptionChanged(Windows::Graphics::Printing::OptionDetails::PrintTaskOptionDetails^sender, Windows::Graphics::Printing::OptionDetails::PrintTaskOptionChangedEventArgs^args) | PrintSample::sealed | [private]
PrintDetailedOptionsOptionChanged(Windows::Graphics::Printing::OptionDetails::PrintTaskOptionDetails^sender, Windows::Graphics::Printing::OptionDetails::PrintTaskOptionChangedEventArgs^args) | PrintSample::sealed | [protected]
PrintTaskRequested(Windows::Graphics::Printing::PrintManager^sender, Windows::Graphics::Printing::PrintTaskRequestedEventArgs^e) override | PrintSample::sealed | [protected, virtual]
PrintTaskRequested(Windows::Graphics::Printing::PrintManager^sender, Windows::Graphics::Printing::PrintTaskRequestedEventArgs^e) override | PrintSample::sealed | [protected, virtual]
PrintTaskRequested(Windows::Graphics::Printing::PrintManager^sender, Windows::Graphics::Printing::PrintTaskRequestedEventArgs^e) override | PrintSample::sealed | [protected, virtual]
PrintTaskRequested(Windows::Graphics::Printing::PrintManager^sender, Windows::Graphics::Printing::PrintTaskRequestedEventArgs^e) override | PrintSample::sealed | [protected, virtual]
RefreshPreview() | PrintSample::sealed | [private]
RefreshPreview() | PrintSample::sealed | [private]
RefreshPreview() | PrintSample::sealed | [protected]
RegisterForPrintingButtonClick(Object^sender, RoutedEventArgs^e) | PrintSample::sealed | [private]
RemovePageRangeEdit(Windows::Graphics::Printing::OptionDetails::PrintTaskOptionDetails^printTaskOptionDetails) | PrintSample::sealed | [private]
rootPage | PrintSample::sealed | [private]
ScenarioInput1() | PrintSample::sealed |
ScenarioInput2() | PrintSample::sealed |
ScenarioInput3() | PrintSample::sealed |
ScenarioInput4() | PrintSample::sealed |
ScenarioInput5() | PrintSample::sealed |
ScenarioInput6() | PrintSample::sealed |
ScenarioInput6::GeneratePage(int photoNumber, PageDescription pageDescription) | PrintSample::sealed | [private]
ScenarioList() | PrintSample::sealed |
ScenarioOutput1() | PrintSample::sealed |
ScenarioOutput2() | PrintSample::sealed |
ScenarioOutput3() | PrintSample::sealed |
ScenarioOutput4() | PrintSample::sealed |
ScenarioOutput5() | PrintSample::sealed |
ScenarioOutput6() | PrintSample::sealed |
Scenarios_SelectionChanged(Object^sender, SelectionChangedEventArgs^e) | PrintSample::sealed | [protected]
SetFeatureName(Platform::String^strFeature) | PrintSample::sealed | [private]
ShowContent(String^selectionText) | PrintSample::sealed | [private]
SplitString(String^string, wchar_t delimiter, std::vector< std::wstring > &words) | PrintSample::sealed | [private]
Swap(T &v1, T &v2) | PrintSample::sealed | [private, static]
~App() | PrintSample::sealed | [private]
~MainPage() | PrintSample::sealed | [private]
~ScenarioList() | PrintSample::sealed | [private]
~ScenarioOutput1() | PrintSample::sealed | [private]
~ScenarioOutput2() | PrintSample::sealed | [private]
~ScenarioOutput3() | PrintSample::sealed | [private]
~ScenarioOutput4() | PrintSample::sealed | [private]
~ScenarioOutput6() | PrintSample::sealed | [private]
Generated on Sat Nov 23 2024 16:09:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Message dialog/C++/App.xaml.h Source File

  • Message dialog

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D magazine app/C++/Renderer.cpp Source File

  • Direct2D magazine app

Renderer.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
00010 using namespace Microsoft::WRL;
00011 using namespace Windows::Foundation;
00012 using namespace Windows::UI::Xaml;
00013
00014 // Initialize all DirectX resources
00015 Renderer::Renderer(
00016     Rect windowBounds,
00017     float dpi
00018     ) :
00019     m_windowBounds(windowBounds),
00020     m_dpi(dpi),
00021     m_featureLevel(),
00022     m_d2dFactory(),
00023     m_d2dDevice(),
00024     m_d2dDeviceContext(),
00025     m_wicFactory(),
00026     m_dxgiDevice()
00027 {
00028     CreateDeviceIndependentResources();
00029     CreateDeviceResources();
00030 }
00031
00032 // Recreate all device resources and set them back to the current state.
00033 void Renderer::HandleDeviceLost()
00034 {
00035     CreateDeviceResources();
00036     DeviceLost();
00037 }
00038
00039 // These are the resources required independent of hardware.
00040 void Renderer::CreateDeviceIndependentResources()
00041 {
00042     D2D1_FACTORY_OPTIONS options;
00043     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00044
00045 #if defined(_DEBUG)
00046     // If the project is in a debug build, enable Direct2D debugging via Direct2D SDK layer.
00047     // Enabling SDK debug layer can help catch coding mistakes such as invalid calls and
00048     // resource leaking that needs to be fixed during the development cycle.
00049     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00050 #endif
00051
00052     DX::ThrowIfFailed(
00053         D2D1CreateFactory(
00054             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00055             __uuidof(ID2D1Factory1),
00056             &options,
00057             &m_d2dFactory
00058             )
00059         );
00060
00061     DX::ThrowIfFailed(
00062         CoCreateInstance(
00063             CLSID_WICImagingFactory,
00064             nullptr,
00065             CLSCTX_INPROC_SERVER,
00066             IID_PPV_ARGS(&m_wicFactory)
00067             )
00068         );
00069 }
00070
00071 // These are the resources that depend on hardware.
00072 void Renderer::CreateDeviceResources()
00073 {
00074     // This flag adds support for surfaces with a different color channel ordering than the API default.
00075     // It is recommended usage, and is required for compatibility with Direct2D.
00076     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00077
00078 #if defined(_DEBUG)
00079     // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00080     creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00081 #endif
00082
00083     // This array defines the set of DirectX hardware feature levels this app will support.
00084     // Note the ordering should be preserved.
00085     D3D_FEATURE_LEVEL featureLevels[] =
00086     {
00087         D3D_FEATURE_LEVEL_11_1,
00088         D3D_FEATURE_LEVEL_11_0,
00089         D3D_FEATURE_LEVEL_10_1,
00090         D3D_FEATURE_LEVEL_10_0,
00091         D3D_FEATURE_LEVEL_9_3,
00092         D3D_FEATURE_LEVEL_9_2,
00093         D3D_FEATURE_LEVEL_9_1
00094     };
00095
00096     // Create the D3D11 API device object, and get a corresponding context.
00097     ComPtr<ID3D11Device> d3dDevice;
00098     ComPtr<ID3D11DeviceContext> d3dContext;
00099     DX::ThrowIfFailed(
00100         D3D11CreateDevice(
00101             nullptr,                    // specify null to use the default adapter
00102             D3D_DRIVER_TYPE_HARDWARE,
00103             0,                          // leave as 0 unless software device
00104             creationFlags,              // optionally set debug and Direct2D compatibility flags
00105             featureLevels,              // list of feature levels this app can support
00106             ARRAYSIZE(featureLevels),   // number of entries in above list
00107             D3D11_SDK_VERSION,          // always set this to D3D11_SDK_VERSION for Metro style apps
00108             &d3dDevice,                 // returns the Direct3D device created
00109             &m_featureLevel,            // returns feature level of device created
00110             &d3dContext                 // returns the device immediate context
00111             )
00112         );
00113
00114     // Obtain the underlying DXGI device of the Direct3D11.1 device.
00115     DX::ThrowIfFailed(
00116         d3dDevice.As(&m_dxgiDevice)
00117         );
00118
00119     // Obtain the Direct2D device for 2-D rendering.
00120     DX::ThrowIfFailed(
00121         m_d2dFactory->CreateDevice(m_dxgiDevice.Get(), &m_d2dDevice)
00122         );
00123
00124     // And get its corresponding device context object.
00125     DX::ThrowIfFailed(
00126         m_d2dDevice->CreateDeviceContext(
00127             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00128             &m_d2dDeviceContext
00129             )
00130         );
00131
00132     // Since this device context will be used to draw content onto XAML surface image source,
00133     // it needs to operate as pixels. Setting pixel unit mode is a way to tell Direct2D to treat
00134     // the incoming coordinates and vectors, typically as DIPs, as in pixels.
00135     m_d2dDeviceContext->SetUnitMode(D2D1_UNIT_MODE_PIXELS);
00136
00137     // Despite treating incoming values as pixels, it is still very important to tell Direct2D
00138     // the logical DPI the application operates on. Direct2D uses the DPI value as a hint to
00139     // optimize internal rendering policy such as to determine when is appropriate to enable
00140     // symmetric text rendering modes. Not specifying the appropriate DPI in this case will hurt
00141     // application performance.
00142     m_d2dDeviceContext->SetDpi(m_dpi, m_dpi);
00143
00144     // When an application performs animation or image composition of graphics content, it is important
00145     // to use Direct2D grayscale text rendering mode rather than ClearType. The ClearType technique
00146     // operates on the color channels and not the alpha channel, and therefore unable to correctly perform
00147     // image composition or sub-pixel animation of text. ClearType is still a method of choice when it
00148     // comes to direct rendering of text to the destination surface with no subsequent composition required.
00149     m_d2dDeviceContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00150 }
00151
00152 // Helps track the DPI in the helper class.
00153 void Renderer::SetDpi(float dpi)
00154 {
00155     if (dpi != m_dpi)
00156     {
00157         m_dpi = dpi;
00158
00159         m_d2dDeviceContext->SetDpi(m_dpi, m_dpi);
00160     }
00161 }
00162
00163 void Renderer::UpdateWindowSize()
00164 {
00165     m_windowBounds = Window::Current->Bounds;
00166 }
00167
00168 void Renderer::GetD2DDeviceContext(_Outptr_ ID2D1DeviceContext** d2dDeviceContext)
00169 {
00170     *d2dDeviceContext = ComPtr<ID2D1DeviceContext>(m_d2dDeviceContext).Detach();
00171 }
00172
00173 void Renderer::GetDXGIDevice(_Outptr_ IDXGIDevice** dxgiDevice)
00174 {
00175     *dxgiDevice = ComPtr<IDXGIDevice>(m_dxgiDevice).Detach();
00176 }
00177
00178 void Renderer::GetWICImagingFactory(_Outptr_ IWICImagingFactory2** wicFactory)
00179 {
00180     *wicFactory = ComPtr<IWICImagingFactory2>(m_wicFactory).Detach();
00181 }
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Accelerometer sensor/C++/common/suspensionmanager.cpp Source File

  • Accelerometer sensor
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML AppBar control/C++/common/LayoutAwarePage.h Source File

  • XAML AppBar control
  • common

LayoutAwarePage.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 #include <collection.h>
00015
00016 namespace AppBarControl
00017 {
00018     namespace Common
00019     {
00020         /// <summary>
00021         /// Typical implementation of Page that provides several important conveniences: application
00022         /// view state to visual state mapping, GoBack and GoHome event handlers, and a default view
00023         /// model.
00024         /// </summary>
00025         [Windows::Foundation::Metadata::WebHostHidden]
00026         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00027         {
00028         internal:
00029             LayoutAwarePage();
00030         public:
00031             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00032             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00033             void InvalidateVisualState();
00034             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00035             {
00036                 Windows::UI::Xaml::DependencyProperty^ get();
00037             };
00038             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Object^>^ DefaultViewModel
00039             {
00040                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Object^>^ get();
00041                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Object^>^ value);
00042             }
00043
00044         protected:
00045             virtual void GoHome(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00046             virtual void GoBack(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00048
00049         private:
00050             Platform::Collections::Map<Platform::String^, Object^>^ _defaultViewModel;
00051             Windows::Foundation::EventRegistrationToken _windowSizeEventToken;
00052             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00053             void WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00054         };
00055     }
00056 }
Generated on Sat Nov 23 2024 16:07:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Splash screen/C++/App.xaml.cpp Source File

  • Splash screen

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "App.xaml.h"
00018 #include "MainPage.xaml.h"
00019 #include "ExtendedSplash.xaml.h"
00020
00021 using namespace SDKSample;
00022 using namespace SDKSample::Common;
00023 using namespace SDKSample::SplashScreen;
00024
00025 using namespace concurrency;
00026 using namespace Platform;
00027 using namespace Windows::ApplicationModel;
00028 using namespace Windows::ApplicationModel::Activation;
00029 using namespace Windows::UI::Xaml;
00030 using namespace Windows::UI::Xaml::Controls;
00031 using namespace Windows::UI::Xaml::Interop;
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     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00041 }
00042
00043 /// <summary>
00044 /// Invoked when the application is launched normally by the end user.  Other entry points will
00045 /// be used when the application is launched to open a specific file, to display search results,
00046 /// and so forth.
00047 /// </summary>
00048 /// <param name="pArgs">Details about the launch request and process.</param>
00049 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00050 {
00051     this->LaunchArgs = pArgs;
00052
00053     // Show extended splash and load state if necessary only when the app is not running
00054     if (pArgs->PreviousExecutionState != ApplicationExecutionState::Running)
00055     {
00056         bool loadState = (pArgs->PreviousExecutionState == Activation::ApplicationExecutionState::Terminated);
00057         ExtendedSplash^ extendedSplash = ref new ExtendedSplash(pArgs->SplashScreen, loadState);
00058         Window::Current->Content = extendedSplash;
00059     }
00060
00061     // Finish app activation so that the system splash screen gets dismissed
00062     Window::Current->Activate();
00063 }
00064
00065 /// <summary>
00066 /// Invoked when application execution is being suspended.  Application state is saved
00067 /// without knowing whether the application will be terminated or resumed with the contents
00068 /// of memory still intact.
00069 /// </summary>
00070 /// <param name="sender">The source of the suspend request.</param>
00071 /// <param name="e">Details about the suspend request.</param>
00072 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00073 {
00074     (void) sender;    // Unused parameter
00075
00076     auto deferral = e->SuspendingOperation->GetDeferral();
00077     SuspensionManager::SaveAsync().then([=]()
00078     {
00079         deferral->Complete();
00080     });
00081 }
Generated on Sat Nov 23 2024 16:07:28 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Geolocation/C++/backgroundtask/pch.cpp Source File

  • Geolocation
  • 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 //
00012 // pch.cpp
00013 // Include the standard header and generate the precompiled header.
00014 //
00015
00016 #include "pch.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX touch input/C++/DirectXSample.h Source File

  • DirectX touch input

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
00010 // This header defines helper utilities to make DirectX APIs work with exceptions.
00011 namespace DX
00012 {
00013     inline void ThrowIfFailed(HRESULT hr)
00014     {
00015         if (FAILED(hr))
00016         {
00017             // Set a breakpoint on this line to catch DX API errors.
00018             throw Platform::Exception::CreateException(hr);
00019         }
00020     }
00021 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: OrientationSensor/C++/common/suspensionmanager.cpp Source File

  • OrientationSensor
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:37 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Certificate enrollment/C++/pch.cpp Source File

  • Certificate enrollment

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 Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/Level1.cpp Source File

  • XAML DirectX 3D shooting game

Level1.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 "Level1.h"
00010 #include "Face.h"
00011
00012 using namespace DirectX;
00013
00014 //----------------------------------------------------------------------
00015
00016 Level1::Level1()
00017 {
00018     m_timeLimit = 20.0f;
00019     m_objective =  "Hit each of the targets before time runs out.\nTouch to aim.  Tap in right box to fire.  Drag in left box to move.";
00020 }
00021
00022 //----------------------------------------------------------------------
00023
00024 void Level1::Initialize(std::vector<GameObject^> 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.begin(); object != objects.end(); object++)
00041     {
00042         if (Face^ target = dynamic_cast<Face^>(*object))
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 }
00064
00065 //----------------------------------------------------------------------
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Audio Session (WASAPI)/C++/MainPage.xaml.cpp Source File

  • Windows Audio Session (WASAPI)
  • C++

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:44 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Lock screen apps/C#,C++/ScenarioInput3.xaml.h Source File

  • Lock screen apps
  • C#,C++

ScenarioInput3.xaml.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 "ScenarioInput3.g.h"
00012 #include "MainPage.g.h"
00013
00014 namespace LockScreenAppsCPP
00015 {
00016   [Windows::Foundation::Metadata::WebHostHidden]
00017     public ref class ScenarioInput3 sealed
00018     {
00019     public:
00020         ScenarioInput3();
00021
00022     protected:
00023         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00024
00025     private:
00026         void CreateBadgeTile_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00027         void CreateBadgeAndTextTile_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00028         ~ScenarioInput3();
00029
00030     Windows::Foundation::Rect GetElementRect(Windows::UI::Xaml::FrameworkElement^ element);
00031         MainPage^ rootPage;
00032     };
00033 }
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML WebView control/C++/PageWithAppBar.xaml.h Source File

  • XAML WebView control

PageWithAppBar.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 // PageWithAppBar.xaml.h
00013 // Declaration of the PageWithAppBar class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "PageWithAppBar.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace WebViewControl
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 PageWithAppBar sealed
00031         {
00032         public:
00033             PageWithAppBar();
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         private:
00039             MainPage^ rootPage;
00040             void BottomAppBar_Opened(Platform::Object^ sender, Platform::Object^ obj);
00041             void BottomAppBar_Closed(Platform::Object^ sender, Platform::Object^ obj);
00042             void Home_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00043         };
00044     }
00045 }
Generated on Sat Nov 23 2024 16:08:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Association launching/C++/pch.cpp Source File

  • Association launching

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 //
00009 // pch.cpp
00010 // Include the standard header and generate the precompiled header.
00011 //
00012
00013 #include "pch.h"
Generated on Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

FPSCounter::AtlasText Member List

This is the complete list of members for FPSCounter::AtlasText, including all inherited members.
advanceWidth | FPSCounter::AtlasText
atlasRect | FPSCounter::AtlasText
originOffset | FPSCounter::AtlasText
Generated on Sat Nov 23 2024 16:09:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Lock screen personalization/C++/common/LayoutAwarePage.h Source File

  • Lock screen personalization
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Check if current session is remote/C++/RemoteSession.xaml.h Source File

  • Check if current session is remote

RemoteSession.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 // RemoteSession.xaml.h
00013 // Declaration of the RemoteSession class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "RemoteSession.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace IsRemoteSession
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 RemoteSession sealed
00031         {
00032         public:
00033             RemoteSession();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:07:58 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

VideoBufferLock Member List

This is the complete list of members for VideoBufferLock, including all inherited members.
_bLocked2D | VideoBufferLock | [private]
_bLocked2D2 | VideoBufferLock | [private]
_bLockedBuffer | VideoBufferLock | [private]
_lPitch | VideoBufferLock | [private]
_pData | VideoBufferLock | [private]
_pInputBuffer | VideoBufferLock | [private]
_pInputBuffer2D | VideoBufferLock | [private]
_pInputBuffer2D2 | VideoBufferLock | [private]
GetData() | VideoBufferLock | [inline]
GetData() | VideoBufferLock | [inline]
GetStride() | VideoBufferLock | [inline]
GetStride() | VideoBufferLock | [inline]
Lock(__in IMFMediaBuffer *pBuffer, __in MF2DBuffer_LockFlags flags, __in UINT uiMinSize, __in LONG lDefaultStride) | VideoBufferLock | [inline]
Lock(__in IMFMediaBuffer *pBuffer, __in MF2DBuffer_LockFlags flags, __in UINT uiMinSize, __in LONG lDefaultStride) | VideoBufferLock | [inline]
LockBuffer(LONG lDefaultStride, DWORD dwHeightInPixels, BYTE **ppbScanLine0, LONG *plStride) | VideoBufferLock | [inline]
LockBuffer(LONG lDefaultStride, DWORD dwHeightInPixels, BYTE **ppbScanLine0, LONG *plStride) | VideoBufferLock | [inline]
m_p2DBuffer | VideoBufferLock | [private]
m_pBuffer | VideoBufferLock | [private]
Unlock() | VideoBufferLock | [inline]
Unlock() | VideoBufferLock | [inline]
UnlockBuffer() | VideoBufferLock | [inline]
UnlockBuffer() | VideoBufferLock | [inline]
VideoBufferLock(IMFMediaBuffer *pBuffer) | VideoBufferLock | [inline]
VideoBufferLock() | VideoBufferLock | [inline]
VideoBufferLock(IMFMediaBuffer *pBuffer) | VideoBufferLock | [inline]
VideoBufferLock() | VideoBufferLock | [inline]
~VideoBufferLock() | VideoBufferLock | [inline]
~VideoBufferLock() | VideoBufferLock | [inline]
~VideoBufferLock() | VideoBufferLock | [inline]
~VideoBufferLock() | VideoBufferLock | [inline]
Generated on Sat Nov 23 2024 16:09:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media capture using capture device/C++/common/LayoutAwarePage.h Source File

  • Media capture using capture device
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D tutorial/C++/Lesson5.Components/BasicShapes.cpp Source File

  • Direct3D tutorial
  • Lesson5.Components

BasicShapes.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 #pragma once
00009
00010 #include "pch.h"
00011 #include "BasicShapes.h"
00012 #include "DirectXSample.h"
00013 #include <memory>
00014
00015 BasicShapes::BasicShapes(ID3D11Device *d3dDevice) : m_d3dDevice(d3dDevice)
00016 {
00017 }
00018
00019 void BasicShapes::CreateVertexBuffer(
00020     _In_ unsigned int numVertices,
00021     _In_ BasicVertex *vertexData,
00022     _Out_ ID3D11Buffer **vertexBuffer
00023     )
00024 {
00025     *vertexBuffer = nullptr;
00026     Microsoft::WRL::ComPtr<ID3D11Buffer> vertexBufferInternal;
00027
00028     D3D11_BUFFER_DESC VertexBufferDesc;
00029     VertexBufferDesc.ByteWidth = sizeof(BasicVertex) * numVertices;
00030     VertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
00031     VertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
00032     VertexBufferDesc.CPUAccessFlags = 0;
00033     VertexBufferDesc.MiscFlags = 0;
00034     VertexBufferDesc.StructureByteStride = 0;
00035
00036     D3D11_SUBRESOURCE_DATA VertexBufferData;
00037     VertexBufferData.pSysMem = vertexData;
00038     VertexBufferData.SysMemPitch = 0;
00039     VertexBufferData.SysMemSlicePitch = 0;
00040
00041     DX::ThrowIfFailed(
00042         m_d3dDevice->CreateBuffer(
00043             &VertexBufferDesc,
00044             &VertexBufferData,
00045             &vertexBufferInternal
00046             )
00047         );
00048
00049
00050     *vertexBuffer = vertexBufferInternal.Detach();
00051 }
00052
00053 void BasicShapes::CreateIndexBuffer(
00054     _In_ unsigned int numIndices,
00055     _In_ unsigned short *indexData,
00056     _Out_ ID3D11Buffer **indexBuffer
00057     )
00058 {
00059     *indexBuffer = nullptr;
00060     Microsoft::WRL::ComPtr<ID3D11Buffer> indexBufferInternal;
00061
00062     D3D11_BUFFER_DESC IndexBufferDesc;
00063     IndexBufferDesc.ByteWidth = sizeof(unsigned short) * numIndices;
00064     IndexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
00065     IndexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
00066     IndexBufferDesc.CPUAccessFlags = 0;
00067     IndexBufferDesc.MiscFlags = 0;
00068     IndexBufferDesc.StructureByteStride = 0;
00069
00070     D3D11_SUBRESOURCE_DATA IndexBufferData;
00071     IndexBufferData.pSysMem = indexData;
00072     IndexBufferData.SysMemPitch = 0;
00073     IndexBufferData.SysMemSlicePitch = 0;
00074
00075     DX::ThrowIfFailed(
00076         m_d3dDevice->CreateBuffer(
00077             &IndexBufferDesc,
00078             &IndexBufferData,
00079             &indexBufferInternal
00080             )
00081         );
00082
00083     *indexBuffer = indexBufferInternal.Detach();
00084 }
00085
00086 void BasicShapes::CreateTangentVertexBuffer(
00087     _In_ unsigned int numVertices,
00088     _In_ TangentVertex *vertexData,
00089     _Out_ ID3D11Buffer **vertexBuffer
00090     )
00091 {
00092     *vertexBuffer = nullptr;
00093     Microsoft::WRL::ComPtr<ID3D11Buffer> vertexBufferInternal;
00094
00095     D3D11_BUFFER_DESC VertexBufferDesc;
00096     VertexBufferDesc.ByteWidth = sizeof(TangentVertex) * numVertices;
00097     VertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
00098     VertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
00099     VertexBufferDesc.CPUAccessFlags = 0;
00100     VertexBufferDesc.MiscFlags = 0;
00101     VertexBufferDesc.StructureByteStride = 0;
00102
00103     D3D11_SUBRESOURCE_DATA VertexBufferData;
00104     VertexBufferData.pSysMem = vertexData;
00105     VertexBufferData.SysMemPitch = 0;
00106     VertexBufferData.SysMemSlicePitch = 0;
00107
00108     DX::ThrowIfFailed(
00109         m_d3dDevice->CreateBuffer(
00110             &VertexBufferDesc,
00111             &VertexBufferData,
00112             &vertexBufferInternal
00113             )
00114         );
00115
00116
00117     *vertexBuffer = vertexBufferInternal.Detach();
00118 }
00119
00120 void BasicShapes::CreateCube(
00121     _Out_ ID3D11Buffer **vertexBuffer,
00122     _Out_ ID3D11Buffer **indexBuffer,
00123     _Out_opt_ unsigned int *vertexCount,
00124     _Out_opt_ unsigned int *indexCount
00125     )
00126 {
00127     BasicVertex cubeVertices[] =
00128     {
00129         { float3(-0.5f, 0.5f, -0.5f), float3(0.0f, 1.0f, 0.0f), float2(0.0f, 0.0f) }, // +Y (top face)
00130         { float3( 0.5f, 0.5f, -0.5f), float3(0.0f, 1.0f, 0.0f), float2(1.0f, 0.0f) },
00131         { float3( 0.5f, 0.5f,  0.5f), float3(0.0f, 1.0f, 0.0f), float2(1.0f, 1.0f) },
00132         { float3(-0.5f, 0.5f,  0.5f), float3(0.0f, 1.0f, 0.0f), float2(0.0f, 1.0f) },
00133
00134         { float3(-0.5f, -0.5f,  0.5f), float3(0.0f, -1.0f, 0.0f), float2(0.0f, 0.0f) }, // -Y (bottom face)
00135         { float3( 0.5f, -0.5f,  0.5f), float3(0.0f, -1.0f, 0.0f), float2(1.0f, 0.0f) },
00136         { float3 (0.5f, -0.5f, -0.5f), float3(0.0f, -1.0f, 0.0f), float2(1.0f, 1.0f) },
00137         { float3(-0.5f, -0.5f, -0.5f), float3(0.0f, -1.0f, 0.0f), float2(0.0f, 1.0f) },
00138
00139         { float3(0.5f,  0.5f,  0.5f), float3(1.0f, 0.0f, 0.0f), float2(0.0f, 0.0f) }, // +X (right face)
00140         { float3(0.5f,  0.5f, -0.5f), float3(1.0f, 0.0f, 0.0f), float2(1.0f, 0.0f) },
00141         { float3(0.5f, -0.5f, -0.5f), float3(1.0f, 0.0f, 0.0f), float2(1.0f, 1.0f) },
00142         { float3(0.5f, -0.5f,  0.5f), float3(1.0f, 0.0f, 0.0f), float2(0.0f, 1.0f) },
00143
00144         { float3(-0.5f,  0.5f, -0.5f), float3(-1.0f, 0.0f, 0.0f), float2(0.0f, 0.0f) }, // -X (left face)
00145         { float3(-0.5f,  0.5f,  0.5f), float3(-1.0f, 0.0f, 0.0f), float2(1.0f, 0.0f) },
00146         { float3(-0.5f, -0.5f,  0.5f), float3(-1.0f, 0.0f, 0.0f), float2(1.0f, 1.0f) },
00147         { float3(-0.5f, -0.5f, -0.5f), float3(-1.0f, 0.0f, 0.0f), float2(0.0f, 1.0f) },
00148
00149         { float3(-0.5f,  0.5f, 0.5f), float3(0.0f, 0.0f, 1.0f), float2(0.0f, 0.0f) }, // +Z (front face)
00150         { float3( 0.5f,  0.5f, 0.5f), float3(0.0f, 0.0f, 1.0f), float2(1.0f, 0.0f) },
00151         { float3( 0.5f, -0.5f, 0.5f), float3(0.0f, 0.0f, 1.0f), float2(1.0f, 1.0f) },
00152         { float3(-0.5f, -0.5f, 0.5f), float3(0.0f, 0.0f, 1.0f), float2(0.0f, 1.0f) },
00153
00154         { float3( 0.5f,  0.5f, -0.5f), float3(0.0f, 0.0f, -1.0f), float2(0.0f, 0.0f) }, // -Z (back face)
00155         { float3(-0.5f,  0.5f, -0.5f), float3(0.0f, 0.0f, -1.0f), float2(1.0f, 0.0f) },
00156         { float3(-0.5f, -0.5f, -0.5f), float3(0.0f, 0.0f, -1.0f), float2(1.0f, 1.0f) },
00157         { float3( 0.5f, -0.5f, -0.5f), float3(0.0f, 0.0f, -1.0f), float2(0.0f, 1.0f) },
00158     };
00159
00160     unsigned short cubeIndices[] =
00161     {
00162         0, 1, 2,
00163         0, 2, 3,
00164
00165         4, 5, 6,
00166         4, 6, 7,
00167
00168         8, 9, 10,
00169         8, 10, 11,
00170
00171         12, 13, 14,
00172         12, 14, 15,
00173
00174         16, 17, 18,
00175         16, 18, 19,
00176
00177         20, 21, 22,
00178         20, 22, 23
00179     };
00180
00181     CreateVertexBuffer(
00182         ARRAYSIZE(cubeVertices),
00183         cubeVertices,
00184         vertexBuffer
00185         );
00186     if (vertexCount != nullptr)
00187     {
00188         *vertexCount = ARRAYSIZE(cubeVertices);
00189     }
00190
00191     CreateIndexBuffer(
00192         ARRAYSIZE(cubeIndices),
00193         cubeIndices,
00194         indexBuffer
00195         );
00196     if (indexCount != nullptr)
00197     {
00198         *indexCount = ARRAYSIZE(cubeIndices);
00199     }
00200 }
00201
00202 void BasicShapes::CreateBox(
00203     float3 r,
00204     _Out_ ID3D11Buffer **vertexBuffer,
00205     _Out_ ID3D11Buffer **indexBuffer,
00206     _Out_opt_ unsigned int *vertexCount,
00207     _Out_opt_ unsigned int *indexCount
00208     )
00209 {
00210     BasicVertex boxVertices[] =
00211     {
00212         // FLOOR
00213         {float3(-r.x, -r.y,  r.z), float3(0.0f, 1.0f, 0.0f), float2(0.0f, 0.0f)},
00214         {float3( r.x, -r.y,  r.z), float3(0.0f, 1.0f, 0.0f), float2(1.0f, 0.0f)},
00215         {float3(-r.x, -r.y, -r.z), float3(0.0f, 1.0f, 0.0f), float2(0.0f, 1.5f)},
00216         {float3( r.x, -r.y, -r.z), float3(0.0f, 1.0f, 0.0f), float2(1.0f, 1.5f)},
00217         // WALL
00218         {float3(-r.x,  r.y, r.z), float3(0.0f, 0.0f, -1.0f), float2(0.0f, 0.0f)},
00219         {float3( r.x,  r.y, r.z), float3(0.0f, 0.0f, -1.0f), float2(2.0f, 0.0f)},
00220         {float3(-r.x, -r.y, r.z), float3(0.0f, 0.0f, -1.0f), float2(0.0f, 1.5f)},
00221         {float3( r.x, -r.y, r.z), float3(0.0f, 0.0f, -1.0f), float2(2.0f, 1.5f)},
00222         // WALL
00223         {float3(r.x,  r.y,  r.z), float3(-1.0f, 0.0f, 0.0f), float2(0.0f, 0.0f)},
00224         {float3(r.x,  r.y, -r.z), float3(-1.0f, 0.0f, 0.0f), float2(r.y,  0.0f)},
00225         {float3(r.x, -r.y,  r.z), float3(-1.0f, 0.0f, 0.0f), float2(0.0f, 1.5f)},
00226         {float3(r.x, -r.y, -r.z), float3(-1.0f, 0.0f, 0.0f), float2(r.y,  1.5f)},
00227         // WALL
00228         {float3( r.x,  r.y, -r.z), float3(0.0f, 0.0f, 1.0f), float2(0.0f, 0.0f)},
00229         {float3(-r.x,  r.y, -r.z), float3(0.0f, 0.0f, 1.0f), float2(2.0f, 0.0f)},
00230         {float3( r.x, -r.y, -r.z), float3(0.0f, 0.0f, 1.0f), float2(0.0f, 1.5f)},
00231         {float3(-r.x, -r.y, -r.z), float3(0.0f, 0.0f, 1.0f), float2(2.0f, 1.5f)},
00232         // WALL
00233         {float3(-r.x,  r.y, -r.z), float3(1.0f, 0.0f, 0.0f), float2(0.0f, 0.0f)},
00234         {float3(-r.x,  r.y,  r.z), float3(1.0f, 0.0f, 0.0f), float2(r.y,  0.0f)},
00235         {float3(-r.x, -r.y, -r.z), float3(1.0f, 0.0f, 0.0f), float2(0.0f, 1.5f)},
00236         {float3(-r.x, -r.y,  r.z), float3(1.0f, 0.0f, 0.0f), float2(r.y,  1.5f)},
00237         // CEILING
00238         {float3(-r.x, r.y, -r.z), float3(0.0f, -1.0f, 0.0f), float2(-0.15f, 0.0f)},
00239         {float3( r.x, r.y, -r.z), float3(0.0f, -1.0f, 0.0f), float2( 1.25f, 0.0f)},
00240         {float3(-r.x, r.y,  r.z), float3(0.0f, -1.0f, 0.0f), float2(-0.15f, 2.1f)},
00241         {float3( r.x, r.y,  r.z), float3(0.0f, -1.0f, 0.0f), float2( 1.25f, 2.1f)},
00242     };
00243
00244     unsigned short boxIndices[] =
00245     {
00246         0, 2, 1,
00247         1, 2, 3,
00248
00249         4, 6, 5,
00250         5, 6, 7,
00251
00252         8, 10, 9,
00253         9, 10, 11,
00254
00255         12, 14, 13,
00256         13, 14, 15,
00257
00258         16, 18, 17,
00259         17, 18, 19,
00260
00261         20, 22, 21,
00262         21, 22, 23,
00263     };
00264
00265     CreateVertexBuffer(
00266         ARRAYSIZE(boxVertices),
00267         boxVertices,
00268         vertexBuffer
00269         );
00270     if (vertexCount != nullptr)
00271     {
00272         *vertexCount = ARRAYSIZE(boxVertices);
00273     }
00274
00275     CreateIndexBuffer(
00276         ARRAYSIZE(boxIndices),
00277         boxIndices,
00278         indexBuffer
00279         );
00280     if (indexCount != nullptr)
00281     {
00282         *indexCount = ARRAYSIZE(boxIndices);
00283     }
00284 }
00285
00286 void BasicShapes::CreateSphere(
00287     _Out_ ID3D11Buffer **vertexBuffer,
00288     _Out_ ID3D11Buffer **indexBuffer,
00289     _Out_opt_ unsigned int *vertexCount,
00290     _Out_opt_ unsigned int *indexCount
00291     )
00292 {
00293     const int numSegments = 64;
00294     const int numSlices = numSegments / 2;
00295
00296     const int numVertices = (numSlices + 1) * (numSegments + 1);
00297     std::unique_ptr<BasicVertex[]> sphereVertices(new BasicVertex[numVertices]);
00298
00299     for (int slice = 0; slice <= numSlices; slice++)
00300     {
00301         float v = (float)slice/(float)numSlices;
00302         float inclination = v * PI_F;
00303         float y = cos(inclination);
00304         float r = sin(inclination);
00305         for (int segment = 0; segment <= numSegments; segment++)
00306         {
00307             float u = (float)segment/(float)numSegments;
00308             float azimuth = u * PI_F * 2.0f;
00309             int index = slice * (numSegments+1) + segment;
00310             sphereVertices[index].pos = float3(r * sin(azimuth), y, r * cos(azimuth));
00311             sphereVertices[index].norm = sphereVertices[index].pos;
00312             sphereVertices[index].tex = float2(u, v);
00313         }
00314     }
00315
00316     const int numIndices = numSlices * (numSegments-2) * 6;
00317     std::unique_ptr<unsigned short[]> sphereIndices(new unsigned short[numIndices]);
00318
00319     unsigned int index = 0;
00320     for (int slice = 0; slice < numSlices; slice++)
00321     {
00322         unsigned short sliceBase0 = (unsigned short)((slice)*(numSegments+1));
00323         unsigned short sliceBase1 = (unsigned short)((slice+1)*(numSegments+1));
00324         for (int segment = 0; segment < numSegments; segment++)
00325         {
00326             if (slice > 0)
00327             {
00328                 sphereIndices[index++] = sliceBase0 + segment;
00329                 sphereIndices[index++] = sliceBase0 + segment + 1;
00330                 sphereIndices[index++] = sliceBase1 + segment + 1;
00331             }
00332             if (slice < numSlices-1)
00333             {
00334                 sphereIndices[index++] = sliceBase0 + segment;
00335                 sphereIndices[index++] = sliceBase1 + segment + 1;
00336                 sphereIndices[index++] = sliceBase1 + segment;
00337             }
00338         }
00339     }
00340
00341     CreateVertexBuffer(
00342         numVertices,
00343         sphereVertices.get(),
00344         vertexBuffer
00345         );
00346     if (vertexCount != nullptr)
00347     {
00348         *vertexCount = numVertices;
00349     }
00350
00351     CreateIndexBuffer(
00352         numIndices,
00353         sphereIndices.get(),
00354         indexBuffer
00355         );
00356     if (indexCount != nullptr)
00357     {
00358         *indexCount = numIndices;
00359     }
00360 }
00361 void BasicShapes::CreateTangentSphere(
00362     _Out_ ID3D11Buffer **vertexBuffer,
00363     _Out_ ID3D11Buffer **indexBuffer,
00364     _Out_opt_ unsigned int *vertexCount,
00365     _Out_opt_ unsigned int *indexCount
00366     )
00367 {
00368     const int numSegments = 64;
00369     const int numSlices = numSegments / 2;
00370
00371     const int numVertices = (numSlices + 1) * (numSegments + 1);
00372     std::unique_ptr<TangentVertex[]> sphereVertices(new TangentVertex[numVertices]);
00373
00374     for (int slice = 0; slice <= numSlices; slice++)
00375     {
00376         float v = (float)slice/(float)numSlices;
00377         float inclination = v * PI_F;
00378         float y = cos(inclination);
00379         float r = sin(inclination);
00380         for (int segment = 0; segment <= numSegments; segment++)
00381         {
00382             float u = (float)segment/(float)numSegments;
00383             float azimuth = u * PI_F * 2.0f;
00384             int index = slice * (numSegments+1) + segment;
00385             sphereVertices[index].pos = float3(r*sin(azimuth), y, r*cos(azimuth));
00386             sphereVertices[index].tex = float2(u, v);
00387             sphereVertices[index].uTan = float3(cos(azimuth), 0, -sin(azimuth));
00388             sphereVertices[index].vTan = float3(cos(inclination)*sin(azimuth), -sin(inclination), cos(inclination)*cos(azimuth));
00389
00390         }
00391     }
00392
00393     const int numIndices = numSlices * (numSegments-2) * 6;
00394     std::unique_ptr<unsigned short[]> sphereIndices(new unsigned short[numIndices]);
00395
00396     unsigned int index = 0;
00397     for (int slice = 0; slice < numSlices; slice++)
00398     {
00399         unsigned short sliceBase0 = (unsigned short)((slice)*(numSegments+1));
00400         unsigned short sliceBase1 = (unsigned short)((slice+1)*(numSegments+1));
00401         for (int segment = 0; segment < numSegments; segment++)
00402         {
00403             if (slice > 0)
00404             {
00405                 sphereIndices[index++] = sliceBase0 + segment;
00406                 sphereIndices[index++] = sliceBase0 + segment + 1;
00407                 sphereIndices[index++] = sliceBase1 + segment + 1;
00408             }
00409             if (slice < numSlices-1)
00410             {
00411                 sphereIndices[index++] = sliceBase0 + segment;
00412                 sphereIndices[index++] = sliceBase1 + segment + 1;
00413                 sphereIndices[index++] = sliceBase1 + segment;
00414             }
00415         }
00416     }
00417
00418     CreateTangentVertexBuffer(
00419         numVertices,
00420         sphereVertices.get(),
00421         vertexBuffer
00422         );
00423     if (vertexCount != nullptr)
00424     {
00425         *vertexCount = numVertices;
00426     }
00427
00428     CreateIndexBuffer(
00429         numIndices,
00430         sphereIndices.get(),
00431         indexBuffer
00432         );
00433     if (indexCount != nullptr)
00434     {
00435         *indexCount = numIndices;
00436     }
00437 }
00438
00439 void BasicShapes::CreateReferenceAxis(
00440     _Out_ ID3D11Buffer **vertexBuffer,
00441     _Out_ ID3D11Buffer **indexBuffer,
00442     _Out_opt_ unsigned int *vertexCount,
00443     _Out_opt_ unsigned int *indexCount
00444     )
00445 {
00446     BasicVertex axisVertices[] =
00447     {
00448         { float3( 0.500f, 0.000f, 0.000f), float3( 0.125f, 0.500f, 0.500f), float2(0.250f, 0.250f) },
00449         { float3( 0.000f, 0.125f, 0.000f), float3( 0.125f, 0.500f, 0.500f), float2(0.250f, 0.250f) },
00450         { float3( 0.000f, 0.000f, 0.125f), float3( 0.125f, 0.500f, 0.500f), float2(0.250f, 0.250f) },
00451         { float3( 0.500f, 0.000f, 0.000f), float3( 0.125f,-0.500f, 0.500f), float2(0.250f, 0.250f) },
00452         { float3( 0.000f, 0.000f, 0.125f), float3( 0.125f,-0.500f, 0.500f), float2(0.250f, 0.250f) },
00453         { float3( 0.000f,-0.125f, 0.000f), float3( 0.125f,-0.500f, 0.500f), float2(0.250f, 0.250f) },
00454         { float3( 0.500f, 0.000f, 0.000f), float3( 0.125f,-0.500f,-0.500f), float2(0.250f, 0.250f) },
00455         { float3( 0.000f,-0.125f, 0.000f), float3( 0.125f,-0.500f,-0.500f), float2(0.250f, 0.250f) },
00456         { float3( 0.000f, 0.000f,-0.125f), float3( 0.125f,-0.500f,-0.500f), float2(0.250f, 0.250f) },
00457         { float3( 0.500f, 0.000f, 0.000f), float3( 0.125f, 0.500f,-0.500f), float2(0.250f, 0.250f) },
00458         { float3( 0.000f, 0.000f,-0.125f), float3( 0.125f, 0.500f,-0.500f), float2(0.250f, 0.250f) },
00459         { float3( 0.000f, 0.125f, 0.000f), float3( 0.125f, 0.500f,-0.500f), float2(0.250f, 0.250f) },
00460         { float3( 0.000f, 0.125f, 0.000f), float3(-0.125f, 0.000f, 0.000f), float2(0.250f, 0.250f) },
00461         { float3( 0.000f, 0.000f,-0.125f), float3(-0.125f, 0.000f, 0.000f), float2(0.250f, 0.250f) },
00462         { float3( 0.000f,-0.125f, 0.000f), float3(-0.125f, 0.000f, 0.000f), float2(0.250f, 0.250f) },
00463         { float3( 0.000f, 0.000f, 0.125f), float3(-0.125f, 0.000f, 0.000f), float2(0.250f, 0.250f) },
00464         { float3(-0.500f, 0.000f, 0.000f), float3(-0.125f, 0.500f, 0.500f), float2(0.250f, 0.500f) },
00465         { float3( 0.000f, 0.000f, 0.125f), float3(-0.125f, 0.500f, 0.500f), float2(0.250f, 0.500f) },
00466         { float3( 0.000f, 0.125f, 0.000f), float3(-0.125f, 0.500f, 0.500f), float2(0.250f, 0.500f) },
00467         { float3(-0.500f, 0.000f, 0.000f), float3(-0.125f, 0.500f,-0.500f), float2(0.250f, 0.500f) },
00468         { float3( 0.000f, 0.125f, 0.000f), float3(-0.125f, 0.500f,-0.500f), float2(0.250f, 0.500f) },
00469         { float3( 0.000f, 0.000f,-0.125f), float3(-0.125f, 0.500f,-0.500f), float2(0.250f, 0.500f) },
00470         { float3(-0.500f, 0.000f, 0.000f), float3(-0.125f,-0.500f,-0.500f), float2(0.250f, 0.500f) },
00471         { float3( 0.000f, 0.000f,-0.125f), float3(-0.125f,-0.500f,-0.500f), float2(0.250f, 0.500f) },
00472         { float3( 0.000f,-0.125f, 0.000f), float3(-0.125f,-0.500f,-0.500f), float2(0.250f, 0.500f) },
00473         { float3(-0.500f, 0.000f, 0.000f), float3(-0.125f,-0.500f, 0.500f), float2(0.250f, 0.500f) },
00474         { float3( 0.000f,-0.125f, 0.000f), float3(-0.125f,-0.500f, 0.500f), float2(0.250f, 0.500f) },
00475         { float3( 0.000f, 0.000f, 0.125f), float3(-0.125f,-0.500f, 0.500f), float2(0.250f, 0.500f) },
00476         { float3( 0.000f, 0.000f, 0.125f), float3( 0.125f, 0.000f, 0.000f), float2(0.250f, 0.500f) },
00477         { float3( 0.000f,-0.125f, 0.000f), float3( 0.125f, 0.000f, 0.000f), float2(0.250f, 0.500f) },
00478         { float3( 0.000f, 0.000f,-0.125f), float3( 0.125f, 0.000f, 0.000f), float2(0.250f, 0.500f) },
00479         { float3( 0.000f, 0.125f, 0.000f), float3( 0.125f, 0.000f, 0.000f), float2(0.250f, 0.500f) },
00480         { float3( 0.000f, 0.500f, 0.000f), float3( 0.500f, 0.125f, 0.500f), float2(0.500f, 0.250f) },
00481         { float3( 0.000f, 0.000f, 0.125f), float3( 0.500f, 0.125f, 0.500f), float2(0.500f, 0.250f) },
00482         { float3( 0.125f, 0.000f, 0.000f), float3( 0.500f, 0.125f, 0.500f), float2(0.500f, 0.250f) },
00483         { float3( 0.000f, 0.500f, 0.000f), float3( 0.500f, 0.125f,-0.500f), float2(0.500f, 0.250f) },
00484         { float3( 0.125f, 0.000f, 0.000f), float3( 0.500f, 0.125f,-0.500f), float2(0.500f, 0.250f) },
00485         { float3( 0.000f, 0.000f,-0.125f), float3( 0.500f, 0.125f,-0.500f), float2(0.500f, 0.250f) },
00486         { float3( 0.000f, 0.500f, 0.000f), float3(-0.500f, 0.125f,-0.500f), float2(0.500f, 0.250f) },
00487         { float3( 0.000f, 0.000f,-0.125f), float3(-0.500f, 0.125f,-0.500f), float2(0.500f, 0.250f) },
00488         { float3(-0.125f, 0.000f, 0.000f), float3(-0.500f, 0.125f,-0.500f), float2(0.500f, 0.250f) },
00489         { float3( 0.000f, 0.500f, 0.000f), float3(-0.500f, 0.125f, 0.500f), float2(0.500f, 0.250f) },
00490         { float3(-0.125f, 0.000f, 0.000f), float3(-0.500f, 0.125f, 0.500f), float2(0.500f, 0.250f) },
00491         { float3( 0.000f, 0.000f, 0.125f), float3(-0.500f, 0.125f, 0.500f), float2(0.500f, 0.250f) },
00492         { float3( 0.125f, 0.000f, 0.000f), float3( 0.000f,-0.125f, 0.000f), float2(0.500f, 0.250f) },
00493         { float3( 0.000f, 0.000f, 0.125f), float3( 0.000f,-0.125f, 0.000f), float2(0.500f, 0.250f) },
00494         { float3(-0.125f, 0.000f, 0.000f), float3( 0.000f,-0.125f, 0.000f), float2(0.500f, 0.250f) },
00495         { float3( 0.000f, 0.000f,-0.125f), float3( 0.000f,-0.125f, 0.000f), float2(0.500f, 0.250f) },
00496         { float3( 0.000f,-0.500f, 0.000f), float3( 0.500f,-0.125f, 0.500f), float2(0.500f, 0.500f) },
00497         { float3( 0.125f, 0.000f, 0.000f), float3( 0.500f,-0.125f, 0.500f), float2(0.500f, 0.500f) },
00498         { float3( 0.000f, 0.000f, 0.125f), float3( 0.500f,-0.125f, 0.500f), float2(0.500f, 0.500f) },
00499         { float3( 0.000f,-0.500f, 0.000f), float3(-0.500f,-0.125f, 0.500f), float2(0.500f, 0.500f) },
00500         { float3( 0.000f, 0.000f, 0.125f), float3(-0.500f,-0.125f, 0.500f), float2(0.500f, 0.500f) },
00501         { float3(-0.125f, 0.000f, 0.000f), float3(-0.500f,-0.125f, 0.500f), float2(0.500f, 0.500f) },
00502         { float3( 0.000f,-0.500f, 0.000f), float3(-0.500f,-0.125f,-0.500f), float2(0.500f, 0.500f) },
00503         { float3(-0.125f, 0.000f, 0.000f), float3(-0.500f,-0.125f,-0.500f), float2(0.500f, 0.500f) },
00504         { float3( 0.000f, 0.000f,-0.125f), float3(-0.500f,-0.125f,-0.500f), float2(0.500f, 0.500f) },
00505         { float3( 0.000f,-0.500f, 0.000f), float3( 0.500f,-0.125f,-0.500f), float2(0.500f, 0.500f) },
00506         { float3( 0.000f, 0.000f,-0.125f), float3( 0.500f,-0.125f,-0.500f), float2(0.500f, 0.500f) },
00507         { float3( 0.125f, 0.000f, 0.000f), float3( 0.500f,-0.125f,-0.500f), float2(0.500f, 0.500f) },
00508         { float3( 0.000f, 0.000f,-0.125f), float3( 0.000f, 0.125f, 0.000f), float2(0.500f, 0.500f) },
00509         { float3(-0.125f, 0.000f, 0.000f), float3( 0.000f, 0.125f, 0.000f), float2(0.500f, 0.500f) },
00510         { float3( 0.000f, 0.000f, 0.125f), float3( 0.000f, 0.125f, 0.000f), float2(0.500f, 0.500f) },
00511         { float3( 0.125f, 0.000f, 0.000f), float3( 0.000f, 0.125f, 0.000f), float2(0.500f, 0.500f) },
00512         { float3( 0.000f, 0.000f, 0.500f), float3( 0.500f, 0.500f, 0.125f), float2(0.750f, 0.250f) },
00513         { float3( 0.125f, 0.000f, 0.000f), float3( 0.500f, 0.500f, 0.125f), float2(0.750f, 0.250f) },
00514         { float3( 0.000f, 0.125f, 0.000f), float3( 0.500f, 0.500f, 0.125f), float2(0.750f, 0.250f) },
00515         { float3( 0.000f, 0.000f, 0.500f), float3(-0.500f, 0.500f, 0.125f), float2(0.750f, 0.250f) },
00516         { float3( 0.000f, 0.125f, 0.000f), float3(-0.500f, 0.500f, 0.125f), float2(0.750f, 0.250f) },
00517         { float3(-0.125f, 0.000f, 0.000f), float3(-0.500f, 0.500f, 0.125f), float2(0.750f, 0.250f) },
00518         { float3( 0.000f, 0.000f, 0.500f), float3(-0.500f,-0.500f, 0.125f), float2(0.750f, 0.250f) },
00519         { float3(-0.125f, 0.000f, 0.000f), float3(-0.500f,-0.500f, 0.125f), float2(0.750f, 0.250f) },
00520         { float3( 0.000f,-0.125f, 0.000f), float3(-0.500f,-0.500f, 0.125f), float2(0.750f, 0.250f) },
00521         { float3( 0.000f, 0.000f, 0.500f), float3( 0.500f,-0.500f, 0.125f), float2(0.750f, 0.250f) },
00522         { float3( 0.000f,-0.125f, 0.000f), float3( 0.500f,-0.500f, 0.125f), float2(0.750f, 0.250f) },
00523         { float3( 0.125f, 0.000f, 0.000f), float3( 0.500f,-0.500f, 0.125f), float2(0.750f, 0.250f) },
00524         { float3( 0.125f, 0.000f, 0.000f), float3( 0.000f, 0.000f,-0.125f), float2(0.750f, 0.250f) },
00525         { float3( 0.000f,-0.125f, 0.000f), float3( 0.000f, 0.000f,-0.125f), float2(0.750f, 0.250f) },
00526         { float3(-0.125f, 0.000f, 0.000f), float3( 0.000f, 0.000f,-0.125f), float2(0.750f, 0.250f) },
00527         { float3( 0.000f, 0.125f, 0.000f), float3( 0.000f, 0.000f,-0.125f), float2(0.750f, 0.250f) },
00528         { float3( 0.000f, 0.000f,-0.500f), float3( 0.500f, 0.500f,-0.125f), float2(0.750f, 0.500f) },
00529         { float3( 0.000f, 0.125f, 0.000f), float3( 0.500f, 0.500f,-0.125f), float2(0.750f, 0.500f) },
00530         { float3( 0.125f, 0.000f, 0.000f), float3( 0.500f, 0.500f,-0.125f), float2(0.750f, 0.500f) },
00531         { float3( 0.000f, 0.000f,-0.500f), float3( 0.500f,-0.500f,-0.125f), float2(0.750f, 0.500f) },
00532         { float3( 0.125f, 0.000f, 0.000f), float3( 0.500f,-0.500f,-0.125f), float2(0.750f, 0.500f) },
00533         { float3( 0.000f,-0.125f, 0.000f), float3( 0.500f,-0.500f,-0.125f), float2(0.750f, 0.500f) },
00534         { float3( 0.000f, 0.000f,-0.500f), float3(-0.500f,-0.500f,-0.125f), float2(0.750f, 0.500f) },
00535         { float3( 0.000f,-0.125f, 0.000f), float3(-0.500f,-0.500f,-0.125f), float2(0.750f, 0.500f) },
00536         { float3(-0.125f, 0.000f, 0.000f), float3(-0.500f,-0.500f,-0.125f), float2(0.750f, 0.500f) },
00537         { float3( 0.000f, 0.000f,-0.500f), float3(-0.500f, 0.500f,-0.125f), float2(0.750f, 0.500f) },
00538         { float3(-0.125f, 0.000f, 0.000f), float3(-0.500f, 0.500f,-0.125f), float2(0.750f, 0.500f) },
00539         { float3( 0.000f, 0.125f, 0.000f), float3(-0.500f, 0.500f,-0.125f), float2(0.750f, 0.500f) },
00540         { float3( 0.000f, 0.125f, 0.000f), float3( 0.000f, 0.000f, 0.125f), float2(0.750f, 0.500f) },
00541         { float3(-0.125f, 0.000f, 0.000f), float3( 0.000f, 0.000f, 0.125f), float2(0.750f, 0.500f) },
00542         { float3( 0.000f,-0.125f, 0.000f), float3( 0.000f, 0.000f, 0.125f), float2(0.750f, 0.500f) },
00543         { float3( 0.125f, 0.000f, 0.000f), float3( 0.000f, 0.000f, 0.125f), float2(0.750f, 0.500f) },
00544     };
00545
00546     unsigned short axisIndices[] =
00547     {
00548          0,  2,  1,
00549          3,  5,  4,
00550          6,  8,  7,
00551          9, 11, 10,
00552         12, 14, 13,
00553         12, 15, 14,
00554         16, 18, 17,
00555         19, 21, 20,
00556         22, 24, 23,
00557         25, 27, 26,
00558         28, 30, 29,
00559         28, 31, 30,
00560         32, 34, 33,
00561         35, 37, 36,
00562         38, 40, 39,
00563         41, 43, 42,
00564         44, 46, 45,
00565         44, 47, 46,
00566         48, 50, 49,
00567         51, 53, 52,
00568         54, 56, 55,
00569         57, 59, 58,
00570         60, 62, 61,
00571         60, 63, 62,
00572         64, 66, 65,
00573         67, 69, 68,
00574         70, 72, 71,
00575         73, 75, 74,
00576         76, 78, 77,
00577         76, 79, 78,
00578         80, 82, 81,
00579         83, 85, 84,
00580         86, 88, 87,
00581         89, 91, 90,
00582         92, 94, 93,
00583         92, 95, 94,
00584     };
00585
00586     CreateVertexBuffer(
00587         ARRAYSIZE(axisVertices),
00588         axisVertices,
00589         vertexBuffer
00590         );
00591     if (vertexCount != nullptr)
00592     {
00593         *vertexCount = ARRAYSIZE(axisVertices);
00594     }
00595
00596     CreateIndexBuffer(
00597         ARRAYSIZE(axisIndices),
00598         axisIndices,
00599         indexBuffer
00600         );
00601     if (indexCount != nullptr)
00602     {
00603         *indexCount = ARRAYSIZE(axisIndices);
00604     }
00605 }
Generated on Sat Nov 23 2024 16:08:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SimpleCommunication::CaptureFailedEventArgs Member List

This is the complete list of members for SimpleCommunication::CaptureFailedEventArgs, including all inherited members.
__pad0__ | SimpleCommunication::CaptureFailedEventArgs |
_message | SimpleCommunication::CaptureFailedEventArgs |
_message(message) | SimpleCommunication::CaptureFailedEventArgs | [inline]
message | SimpleCommunication::CaptureFailedEventArgs |
Generated on Sat Nov 23 2024 16:09:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::HomeGroup::sealed Member List

This is the complete list of members for SDKSample::HomeGroup::sealed, including all inherited members.
Default_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::HomeGroup::sealed | [private]
Default_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::HomeGroup::sealed | [private]
Default_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::HomeGroup::sealed | [private]
Default_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::HomeGroup::sealed | [private]
HomeGroupAdvancedSearch() | SDKSample::HomeGroup::sealed |
HomeGroupPicker() | SDKSample::HomeGroup::sealed |
HomeGroupVideoStream() | SDKSample::HomeGroup::sealed |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::HomeGroup::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::HomeGroup::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::HomeGroup::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::HomeGroup::sealed | [protected, virtual]
rootPage | SDKSample::HomeGroup::sealed | [private]
SearchHomeGroup() | SDKSample::HomeGroup::sealed |
SetButtons() | SDKSample::HomeGroup::sealed | [private]
Generated on Sat Nov 23 2024 16:09:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application resources and localization/C++/Scenario10.xaml.h Source File

  • Application resources and localization

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 SDKSample
00022 {
00023     namespace ApplicationResources
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 Scenario10 sealed
00030         {
00031         public:
00032             Scenario10();
00033
00034         protected:
00035             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00036         private:
00037             MainPage^ rootPage;
00038             void Scenario10Button_Show_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039
00040         void Scenario10_SearchMultipleResourceIds(Windows::ApplicationModel::Resources::Core::ResourceContext^ context, Platform::Collections::Vector<Platform::String^>^ resourceIds);
00041         void Scenario10_ShowCandidates(Platform::String^ resourceId, Windows::Foundation::Collections::IVectorView<Windows::ApplicationModel::Resources::Core::ResourceCandidate^>^ resourceCandidates);
00042         };
00043     }
00044 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

handle_closer Member List

This is the complete list of members for handle_closer, including all inherited members.
operator()(HANDLE h) handle_closer [inline]
Generated on Sat Nov 23 2024 16:09:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Extended Linguistic Services (ELS)/C++/LanguageDetection.xaml.h Source File

  • Extended Linguistic Services (ELS)
  • C++

LanguageDetection.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 // LanguageDetection.xaml.h
00013 // Declaration of the LanguageDetection class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "LanguageDetection.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace ELS
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 LanguageDetection sealed
00031         {
00032         public:
00033             LanguageDetection();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037
00038         private:
00039             MainPage^ rootPage;
00040             void Go_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         };
00042     }
00043 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Lock screen personalization/C++/SetLockscreenImage.xaml.cpp Source File

  • Lock screen personalization

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 SDKSample::Personalization;
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     if (rootPage->EnsureUnsnapped())
00059     {
00060         rootPage->NotifyUser(" ", NotifyType::StatusMessage);
00061         FileOpenPicker^ imagePicker = ref new FileOpenPicker();
00062         imagePicker->ViewMode = PickerViewMode::Thumbnail;
00063         imagePicker->SuggestedStartLocation = PickerLocationId::PicturesLibrary;
00064         imagePicker->FileTypeFilter->Append(".jpg");
00065         imagePicker->FileTypeFilter->Append(".jpeg");
00066         imagePicker->FileTypeFilter->Append(".png");
00067         imagePicker->FileTypeFilter->Append(".bmp");
00068
00069         create_task(imagePicker->PickSingleFileAsync()).then([this](StorageFile^ imageFile)
00070         {
00071             if (imageFile != nullptr)
00072             {
00073                 rootPage->NotifyUser("Selected image: " + imageFile->Name, NotifyType::StatusMessage);
00074
00075                 // Application now has access to the picked file, setting image to lockscreen.
00076                 create_task(LockScreen::SetImageFileAsync(imageFile)).then([this](task<void> result)
00077                 {
00078                     try
00079                     {
00080                         // Use result.get() to trigger exception if invalid image is chosen
00081                         result.get();
00082                         // Retrieve the lock screen image that was set
00083                         auto imageStream = Windows::System::UserProfile::LockScreen::GetImageStream();
00084                         if (imageStream != nullptr)
00085                         {
00086                             auto bitmapImage = ref new BitmapImage();
00087                             bitmapImage->SetSource(imageStream);
00088                             SetLockscreenImageOutputImage->Source = bitmapImage;
00089                             SetLockscreenImageOutputImage->Visibility = Windows::UI::Xaml::Visibility::Visible;
00090                         }
00091                         else
00092                         {
00093                             SetLockscreenImageOutputImage->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00094                             rootPage->NotifyUser("Setting the lock screen image failed.  Make sure your copy of Windows is activated.", NotifyType::ErrorMessage);
00095                         }
00096                     }
00097                     catch (Exception ^ex)
00098                     {
00099                         SetLockscreenImageOutputImage->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00100                         rootPage->NotifyUser("Invalid image selected or error opening stream.", NotifyType::ErrorMessage);
00101                     }
00102                 });
00103             }
00104             else
00105             {
00106                 rootPage->NotifyUser("No image was selected", NotifyType::StatusMessage);
00107                 create_task(Package::Current->InstalledLocation->CreateFileAsync("Assets\\placeholder-sdk.png",
00108                     CreationCollisionOption::OpenIfExists))
00109                     .then([this](StorageFile^ imageFile) -> IAsyncOperation<IRandomAccessStreamWithContentType^>^
00110                 {
00111                     return imageFile->OpenReadAsync();
00112                 }).then([this](IRandomAccessStreamWithContentType^ imageStream)
00113                 {
00114                     auto bitmapImage = ref new BitmapImage();
00115                     bitmapImage->SetSource(imageStream);
00116                     SetLockscreenImageOutputImage->Source = bitmapImage;
00117                 });
00118             }
00119         });
00120     }
00121 }
Generated on Sat Nov 23 2024 16:08:19 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Custom driver access/C#,C++/app_cs/Constants.cs Source File

  • Custom driver access
  • C#,C++
  • app_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
00014 namespace SDKTemplate
00015 {
00016     public partial class MainPage : SDKTemplate.Common.LayoutAwarePage
00017     {
00018         // Change the string below to reflect the name of your sample.
00019         // This is used on the main page as the title of the sample.
00020         public const string FEATURE_NAME = "Custom Device Access";
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 = "Connecting to the Fx2 Device", ClassType = typeof(CustomDeviceAccess.DeviceConnect) },
00030             new Scenario() { Title = "Getting and Setting device properties", ClassType = typeof(CustomDeviceAccess.DeviceProperties) },
00031             new Scenario() { Title = "Registering for device events", ClassType = typeof(CustomDeviceAccess.DeviceEvents) },
00032             new Scenario() { Title = "Invoking asynchronous device methods", ClassType = typeof(CustomDeviceAccess.DeviceAsync) }
00033         };
00034     }
00035
00036     public class Scenario
00037     {
00038         public string Title { get; set; }
00039
00040         public Type ClassType { get; set; }
00041
00042         public override string ToString()
00043         {
00044             return Title;
00045         }
00046     }
00047 }
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D tutorial/C++/Lesson5.Components/pch.h Source File

  • Direct3D tutorial
  • Lesson5.Components

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 <d3d11_1.h>
00012 #include <d2d1_1.h>
00013 #include <d2d1effects.h>
00014 #include <dwrite_1.h>
00015 #include <wincodec.h>
00016 #include <agile.h>
00017 #include "BasicMath.h"
00018
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text editing/C++/Common/LayoutAwarePage.cpp Source File

  • XAML text editing
  • Common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite hit testing/C++/DirectXSample.h Source File

  • DirectWrite hit testing

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
00010 // This header defines helper utilities to make DirectX APIs work with exceptions.
00011 namespace DX
00012 {
00013     inline void ThrowIfFailed(HRESULT hr)
00014     {
00015         if (FAILED(hr))
00016         {
00017             // Set a breakpoint on this line to catch DX API errors.
00018             throw Platform::Exception::CreateException(hr);
00019         }
00020     }
00021 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D sprite/C++/DDSTextureLoader.cpp Source File

  • Direct3D sprite

DDSTextureLoader.cpp

Go to the documentation of this file.
00001 //--------------------------------------------------------------------------------------
00002 // File: DDSTextureLoader.cpp
00003 //
00004 // Function for loading a DDS texture and creating a Direct3D 11 runtime resource for it
00005 //
00006 // Note this function is 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
00018 #include "pch.h"
00019 #include <dxgiformat.h>
00020 #include <assert.h>
00021 #include <memory>
00022 #include <algorithm>
00023 #include "DDSTextureLoader.h"
00024 #include "DirectXSample.h"
00025
00026 using namespace Microsoft::WRL;
00027
00028 //--------------------------------------------------------------------------------------
00029 // Macros
00030 //--------------------------------------------------------------------------------------
00031 #ifndef MAKEFOURCC
00032     #define MAKEFOURCC(ch0, ch1, ch2, ch3)                              \
00033                 ((uint32)(byte)(ch0) | ((uint32)(byte)(ch1) << 8) |       \
00034                 ((uint32)(byte)(ch2) << 16) | ((uint32)(byte)(ch3) << 24))
00035 #endif /* defined(MAKEFOURCC) */
00036
00037 //--------------------------------------------------------------------------------------
00038 // DDS file structure definitions
00039 //
00040 // See DDS.h in the 'Texconv' sample and the 'DirectXTex' library
00041 //--------------------------------------------------------------------------------------
00042 #pragma pack(push, 1)
00043
00044 #define DDS_MAGIC 0x20534444 // "DDS "
00045
00046 struct DDS_PIXELFORMAT
00047 {
00048     uint32  size;
00049     uint32  flags;
00050     uint32  fourCC;
00051     uint32  RGBBitCount;
00052     uint32  RBitMask;
00053     uint32  GBitMask;
00054     uint32  BBitMask;
00055     uint32  ABitMask;
00056 };
00057
00058 #define DDS_FOURCC      0x00000004  // DDPF_FOURCC
00059 #define DDS_RGB         0x00000040  // DDPF_RGB
00060 #define DDS_RGBA        0x00000041  // DDPF_RGB | DDPF_ALPHAPIXELS
00061 #define DDS_LUMINANCE   0x00020000  // DDPF_LUMINANCE
00062 #define DDS_LUMINANCEA  0x00020001  // DDPF_LUMINANCE | DDPF_ALPHAPIXELS
00063 #define DDS_ALPHA       0x00000002  // DDPF_ALPHA
00064 #define DDS_PAL8        0x00000020  // DDPF_PALETTEINDEXED8
00065
00066 #define DDS_HEADER_FLAGS_TEXTURE        0x00001007  // DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT
00067 #define DDS_HEADER_FLAGS_MIPMAP         0x00020000  // DDSD_MIPMAPCOUNT
00068 #define DDS_HEADER_FLAGS_VOLUME         0x00800000  // DDSD_DEPTH
00069 #define DDS_HEADER_FLAGS_PITCH          0x00000008  // DDSD_PITCH
00070 #define DDS_HEADER_FLAGS_LINEARSIZE     0x00080000  // DDSD_LINEARSIZE
00071
00072 #define DDS_HEIGHT 0x00000002 // DDSD_HEIGHT
00073 #define DDS_WIDTH  0x00000004 // DDSD_WIDTH
00074
00075 #define DDS_SURFACE_FLAGS_TEXTURE 0x00001000 // DDSCAPS_TEXTURE
00076 #define DDS_SURFACE_FLAGS_MIPMAP  0x00400008 // DDSCAPS_COMPLEX | DDSCAPS_MIPMAP
00077 #define DDS_SURFACE_FLAGS_CUBEMAP 0x00000008 // DDSCAPS_COMPLEX
00078
00079 #define DDS_CUBEMAP_POSITIVEX 0x00000600 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEX
00080 #define DDS_CUBEMAP_NEGATIVEX 0x00000a00 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEX
00081 #define DDS_CUBEMAP_POSITIVEY 0x00001200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEY
00082 #define DDS_CUBEMAP_NEGATIVEY 0x00002200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEY
00083 #define DDS_CUBEMAP_POSITIVEZ 0x00004200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEZ
00084 #define DDS_CUBEMAP_NEGATIVEZ 0x00008200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEZ
00085
00086 #define DDS_CUBEMAP_ALLFACES (DDS_CUBEMAP_POSITIVEX | DDS_CUBEMAP_NEGATIVEX |\
00087                               DDS_CUBEMAP_POSITIVEY | DDS_CUBEMAP_NEGATIVEY |\
00088                               DDS_CUBEMAP_POSITIVEZ | DDS_CUBEMAP_NEGATIVEZ)
00089
00090 #define DDS_CUBEMAP 0x00000200 // DDSCAPS2_CUBEMAP
00091
00092 #define DDS_FLAGS_VOLUME 0x00200000 // DDSCAPS2_VOLUME
00093
00094 typedef struct
00095 {
00096     uint32          size;
00097     uint32          flags;
00098     uint32          height;
00099     uint32          width;
00100     uint32          pitchOrLinearSize;
00101     uint32          depth; // only if DDS_HEADER_FLAGS_VOLUME is set in flags
00102     uint32          mipMapCount;
00103     uint32          reserved1[11];
00104     DDS_PIXELFORMAT ddspf;
00105     uint32          caps;
00106     uint32          caps2;
00107     uint32          caps3;
00108     uint32          caps4;
00109     uint32          reserved2;
00110 } DDS_HEADER;
00111
00112 typedef struct
00113 {
00114     DXGI_FORMAT dxgiFormat;
00115     uint32      resourceDimension;
00116     uint32      miscFlag; // see D3D11_RESOURCE_MISC_FLAG
00117     uint32      arraySize;
00118     uint32      reserved;
00119 } DDS_HEADER_DXT10;
00120
00121 #pragma pack(pop)
00122
00123 //--------------------------------------------------------------------------------------
00124 // Return the BPP for a particular format
00125 //--------------------------------------------------------------------------------------
00126 static size_t BitsPerPixel(_In_ DXGI_FORMAT fmt)
00127 {
00128     switch (fmt)
00129     {
00130     case DXGI_FORMAT_R32G32B32A32_TYPELESS:
00131     case DXGI_FORMAT_R32G32B32A32_FLOAT:
00132     case DXGI_FORMAT_R32G32B32A32_UINT:
00133     case DXGI_FORMAT_R32G32B32A32_SINT:
00134         return 128;
00135
00136     case DXGI_FORMAT_R32G32B32_TYPELESS:
00137     case DXGI_FORMAT_R32G32B32_FLOAT:
00138     case DXGI_FORMAT_R32G32B32_UINT:
00139     case DXGI_FORMAT_R32G32B32_SINT:
00140         return 96;
00141
00142     case DXGI_FORMAT_R16G16B16A16_TYPELESS:
00143     case DXGI_FORMAT_R16G16B16A16_FLOAT:
00144     case DXGI_FORMAT_R16G16B16A16_UNORM:
00145     case DXGI_FORMAT_R16G16B16A16_UINT:
00146     case DXGI_FORMAT_R16G16B16A16_SNORM:
00147     case DXGI_FORMAT_R16G16B16A16_SINT:
00148     case DXGI_FORMAT_R32G32_TYPELESS:
00149     case DXGI_FORMAT_R32G32_FLOAT:
00150     case DXGI_FORMAT_R32G32_UINT:
00151     case DXGI_FORMAT_R32G32_SINT:
00152     case DXGI_FORMAT_R32G8X24_TYPELESS:
00153     case DXGI_FORMAT_D32_FLOAT_S8X24_UINT:
00154     case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS:
00155     case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT:
00156         return 64;
00157
00158     case DXGI_FORMAT_R10G10B10A2_TYPELESS:
00159     case DXGI_FORMAT_R10G10B10A2_UNORM:
00160     case DXGI_FORMAT_R10G10B10A2_UINT:
00161     case DXGI_FORMAT_R11G11B10_FLOAT:
00162     case DXGI_FORMAT_R8G8B8A8_TYPELESS:
00163     case DXGI_FORMAT_R8G8B8A8_UNORM:
00164     case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
00165     case DXGI_FORMAT_R8G8B8A8_UINT:
00166     case DXGI_FORMAT_R8G8B8A8_SNORM:
00167     case DXGI_FORMAT_R8G8B8A8_SINT:
00168     case DXGI_FORMAT_R16G16_TYPELESS:
00169     case DXGI_FORMAT_R16G16_FLOAT:
00170     case DXGI_FORMAT_R16G16_UNORM:
00171     case DXGI_FORMAT_R16G16_UINT:
00172     case DXGI_FORMAT_R16G16_SNORM:
00173     case DXGI_FORMAT_R16G16_SINT:
00174     case DXGI_FORMAT_R32_TYPELESS:
00175     case DXGI_FORMAT_D32_FLOAT:
00176     case DXGI_FORMAT_R32_FLOAT:
00177     case DXGI_FORMAT_R32_UINT:
00178     case DXGI_FORMAT_R32_SINT:
00179     case DXGI_FORMAT_R24G8_TYPELESS:
00180     case DXGI_FORMAT_D24_UNORM_S8_UINT:
00181     case DXGI_FORMAT_R24_UNORM_X8_TYPELESS:
00182     case DXGI_FORMAT_X24_TYPELESS_G8_UINT:
00183     case DXGI_FORMAT_R9G9B9E5_SHAREDEXP:
00184     case DXGI_FORMAT_R8G8_B8G8_UNORM:
00185     case DXGI_FORMAT_G8R8_G8B8_UNORM:
00186     case DXGI_FORMAT_B8G8R8A8_UNORM:
00187     case DXGI_FORMAT_B8G8R8X8_UNORM:
00188     case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM:
00189     case DXGI_FORMAT_B8G8R8A8_TYPELESS:
00190     case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
00191     case DXGI_FORMAT_B8G8R8X8_TYPELESS:
00192     case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB:
00193         return 32;
00194
00195     case DXGI_FORMAT_R8G8_TYPELESS:
00196     case DXGI_FORMAT_R8G8_UNORM:
00197     case DXGI_FORMAT_R8G8_UINT:
00198     case DXGI_FORMAT_R8G8_SNORM:
00199     case DXGI_FORMAT_R8G8_SINT:
00200     case DXGI_FORMAT_R16_TYPELESS:
00201     case DXGI_FORMAT_R16_FLOAT:
00202     case DXGI_FORMAT_D16_UNORM:
00203     case DXGI_FORMAT_R16_UNORM:
00204     case DXGI_FORMAT_R16_UINT:
00205     case DXGI_FORMAT_R16_SNORM:
00206     case DXGI_FORMAT_R16_SINT:
00207     case DXGI_FORMAT_B5G6R5_UNORM:
00208     case DXGI_FORMAT_B5G5R5A1_UNORM:
00209     case DXGI_FORMAT_B4G4R4A4_UNORM:
00210         return 16;
00211
00212     case DXGI_FORMAT_R8_TYPELESS:
00213     case DXGI_FORMAT_R8_UNORM:
00214     case DXGI_FORMAT_R8_UINT:
00215     case DXGI_FORMAT_R8_SNORM:
00216     case DXGI_FORMAT_R8_SINT:
00217     case DXGI_FORMAT_A8_UNORM:
00218         return 8;
00219
00220     case DXGI_FORMAT_R1_UNORM:
00221         return 1;
00222
00223     case DXGI_FORMAT_BC1_TYPELESS:
00224     case DXGI_FORMAT_BC1_UNORM:
00225     case DXGI_FORMAT_BC1_UNORM_SRGB:
00226     case DXGI_FORMAT_BC4_TYPELESS:
00227     case DXGI_FORMAT_BC4_UNORM:
00228     case DXGI_FORMAT_BC4_SNORM:
00229         return 4;
00230
00231     case DXGI_FORMAT_BC2_TYPELESS:
00232     case DXGI_FORMAT_BC2_UNORM:
00233     case DXGI_FORMAT_BC2_UNORM_SRGB:
00234     case DXGI_FORMAT_BC3_TYPELESS:
00235     case DXGI_FORMAT_BC3_UNORM:
00236     case DXGI_FORMAT_BC3_UNORM_SRGB:
00237     case DXGI_FORMAT_BC5_TYPELESS:
00238     case DXGI_FORMAT_BC5_UNORM:
00239     case DXGI_FORMAT_BC5_SNORM:
00240     case DXGI_FORMAT_BC6H_TYPELESS:
00241     case DXGI_FORMAT_BC6H_UF16:
00242     case DXGI_FORMAT_BC6H_SF16:
00243     case DXGI_FORMAT_BC7_TYPELESS:
00244     case DXGI_FORMAT_BC7_UNORM:
00245     case DXGI_FORMAT_BC7_UNORM_SRGB:
00246         return 8;
00247
00248     default:
00249         return 0;
00250     }
00251 }
00252
00253
00254 //--------------------------------------------------------------------------------------
00255 // Get surface information for a particular format
00256 //--------------------------------------------------------------------------------------
00257 static void GetSurfaceInfo(
00258     _In_ size_t width,
00259     _In_ size_t height,
00260     _In_ DXGI_FORMAT fmt,
00261     _Out_opt_ size_t* outNumBytes,
00262     _Out_opt_ size_t* outRowBytes,
00263     _Out_opt_ size_t* outNumRows
00264     )
00265 {
00266     size_t numBytes = 0;
00267     size_t rowBytes = 0;
00268     size_t numRows = 0;
00269
00270     bool bc = false;
00271     bool packed  = false;
00272     size_t bcnumBytesPerBlock = 0;
00273     switch (fmt)
00274     {
00275     case DXGI_FORMAT_BC1_TYPELESS:
00276     case DXGI_FORMAT_BC1_UNORM:
00277     case DXGI_FORMAT_BC1_UNORM_SRGB:
00278     case DXGI_FORMAT_BC4_TYPELESS:
00279     case DXGI_FORMAT_BC4_UNORM:
00280     case DXGI_FORMAT_BC4_SNORM:
00281         bc = true;
00282         bcnumBytesPerBlock = 8;
00283         break;
00284
00285     case DXGI_FORMAT_BC2_TYPELESS:
00286     case DXGI_FORMAT_BC2_UNORM:
00287     case DXGI_FORMAT_BC2_UNORM_SRGB:
00288     case DXGI_FORMAT_BC3_TYPELESS:
00289     case DXGI_FORMAT_BC3_UNORM:
00290     case DXGI_FORMAT_BC3_UNORM_SRGB:
00291     case DXGI_FORMAT_BC5_TYPELESS:
00292     case DXGI_FORMAT_BC5_UNORM:
00293     case DXGI_FORMAT_BC5_SNORM:
00294     case DXGI_FORMAT_BC6H_TYPELESS:
00295     case DXGI_FORMAT_BC6H_UF16:
00296     case DXGI_FORMAT_BC6H_SF16:
00297     case DXGI_FORMAT_BC7_TYPELESS:
00298     case DXGI_FORMAT_BC7_UNORM:
00299     case DXGI_FORMAT_BC7_UNORM_SRGB:
00300         bc = true;
00301         bcnumBytesPerBlock = 16;
00302         break;
00303
00304     case DXGI_FORMAT_R8G8_B8G8_UNORM:
00305     case DXGI_FORMAT_G8R8_G8B8_UNORM:
00306         packed = true;
00307         break;
00308     }
00309
00310     if (bc)
00311     {
00312         size_t numBlocksWide = 0;
00313         if (width > 0)
00314         {
00315             numBlocksWide = std::max<size_t>(1, (width + 3) / 4);
00316         }
00317         size_t numBlocksHigh = 0;
00318         if (height > 0)
00319         {
00320             numBlocksHigh = std::max<size_t>(1, (height + 3) / 4);
00321         }
00322         rowBytes = numBlocksWide * bcnumBytesPerBlock;
00323         numRows = numBlocksHigh;
00324     }
00325     else if (packed)
00326     {
00327         rowBytes = ((width + 1) >> 1) * 4;
00328         numRows = height;
00329     }
00330     else
00331     {
00332         size_t bpp = BitsPerPixel(fmt);
00333         rowBytes = (width * bpp + 7) / 8; // round up to nearest byte
00334         numRows = height;
00335     }
00336
00337     numBytes = rowBytes * numRows;
00338     if (outNumBytes)
00339     {
00340         *outNumBytes = numBytes;
00341     }
00342     if (outRowBytes)
00343     {
00344         *outRowBytes = rowBytes;
00345     }
00346     if (outNumRows)
00347     {
00348         *outNumRows = numRows;
00349     }
00350 }
00351
00352
00353 //--------------------------------------------------------------------------------------
00354 #define ISBITMASK(r, g, b, a) (ddpf.RBitMask == r && ddpf.GBitMask == g && ddpf.BBitMask == b && ddpf.ABitMask == a)
00355
00356 static DXGI_FORMAT GetDXGIFormat(const DDS_PIXELFORMAT& ddpf)
00357 {
00358     if (ddpf.flags & DDS_RGB)
00359     {
00360         // Note that sRGB formats are written using the "DX10" extended header
00361
00362         switch (ddpf.RGBBitCount)
00363         {
00364         case 32:
00365             if (ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000))
00366             {
00367                 return DXGI_FORMAT_R8G8B8A8_UNORM;
00368             }
00369
00370             if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000))
00371             {
00372                 return DXGI_FORMAT_B8G8R8A8_UNORM;
00373             }
00374
00375             if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0x00000000))
00376             {
00377                 return DXGI_FORMAT_B8G8R8X8_UNORM;
00378             }
00379
00380             // No DXGI format maps to ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0x00000000) aka D3DFMT_X8B8G8R8
00381
00382             // Note that many common DDS reader/writers (including D3DX) swap the
00383             // the RED/BLUE masks for 10:10:10:2 formats. We assumme
00384             // below that the 'backwards' header mask is being used since it is most
00385             // likely written by D3DX. The more robust solution is to use the 'DX10'
00386             // header extension and specify the DXGI_FORMAT_R10G10B10A2_UNORM format directly
00387
00388             // For 'correct' writers, this should be 0x000003ff, 0x000ffc00, 0x3ff00000 for RGB data
00389             if (ISBITMASK(0x3ff00000, 0x000ffc00, 0x000003ff, 0xc0000000))
00390             {
00391                 return DXGI_FORMAT_R10G10B10A2_UNORM;
00392             }
00393
00394             // No DXGI format maps to ISBITMASK(0x000003ff, 0x000ffc00, 0x3ff00000, 0xc0000000) aka D3DFMT_A2R10G10B10
00395
00396             if (ISBITMASK(0x0000ffff, 0xffff0000, 0x00000000, 0x00000000))
00397             {
00398                 return DXGI_FORMAT_R16G16_UNORM;
00399             }
00400
00401             if (ISBITMASK(0xffffffff, 0x00000000, 0x00000000, 0x00000000))
00402             {
00403                 // Only 32-bit color channel format in D3D9 was R32F
00404                 return DXGI_FORMAT_R32_FLOAT; // D3DX writes this out as a FourCC of 114
00405             }
00406             break;
00407
00408         case 24:
00409             // No 24bpp DXGI formats aka D3DFMT_R8G8B8
00410             break;
00411
00412         case 16:
00413             if (ISBITMASK(0x7c00, 0x03e0, 0x001f, 0x8000))
00414             {
00415                 return DXGI_FORMAT_B5G5R5A1_UNORM;
00416             }
00417             if (ISBITMASK(0xf800, 0x07e0, 0x001f, 0x0000))
00418             {
00419                 return DXGI_FORMAT_B5G6R5_UNORM;
00420             }
00421
00422             // No DXGI format maps to ISBITMASK(0x7c00, 0x03e0, 0x001f, 0x0000) aka D3DFMT_X1R5G5B5
00423             if (ISBITMASK(0x0f00, 0x00f0, 0x000f, 0xf000))
00424             {
00425                 return DXGI_FORMAT_B4G4R4A4_UNORM;
00426             }
00427
00428             // No DXGI format maps to ISBITMASK(0x0f00, 0x00f0, 0x000f, 0x0000) aka D3DFMT_X4R4G4B4
00429
00430             // No 3:3:2, 3:3:2:8, or paletted DXGI formats aka D3DFMT_A8R3G3B2, D3DFMT_R3G3B2, D3DFMT_P8, D3DFMT_A8P8, etc.
00431             break;
00432         }
00433     }
00434     else if (ddpf.flags & DDS_LUMINANCE)
00435     {
00436         if (8 == ddpf.RGBBitCount)
00437         {
00438             if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x00000000))
00439             {
00440                 return DXGI_FORMAT_R8_UNORM; // D3DX10/11 writes this out as DX10 extension
00441             }
00442
00443             // No DXGI format maps to ISBITMASK(0x0f, 0x00, 0x00, 0xf0) aka D3DFMT_A4L4
00444         }
00445
00446         if (16 == ddpf.RGBBitCount)
00447         {
00448             if (ISBITMASK(0x0000ffff, 0x00000000, 0x00000000, 0x00000000))
00449             {
00450                 return DXGI_FORMAT_R16_UNORM; // D3DX10/11 writes this out as DX10 extension
00451             }
00452             if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x0000ff00))
00453             {
00454                 return DXGI_FORMAT_R8G8_UNORM; // D3DX10/11 writes this out as DX10 extension
00455             }
00456         }
00457     }
00458     else if (ddpf.flags & DDS_ALPHA)
00459     {
00460         if (8 == ddpf.RGBBitCount)
00461         {
00462             return DXGI_FORMAT_A8_UNORM;
00463         }
00464     }
00465     else if (ddpf.flags & DDS_FOURCC)
00466     {
00467         if (MAKEFOURCC('D', 'X', 'T', '1') == ddpf.fourCC)
00468         {
00469             return DXGI_FORMAT_BC1_UNORM;
00470         }
00471         if (MAKEFOURCC('D', 'X', 'T', '3') == ddpf.fourCC)
00472         {
00473             return DXGI_FORMAT_BC2_UNORM;
00474         }
00475         if (MAKEFOURCC('D', 'X', 'T', '5') == ddpf.fourCC)
00476         {
00477             return DXGI_FORMAT_BC3_UNORM;
00478         }
00479
00480         // While pre-mulitplied alpha isn't directly supported by the DXGI formats,
00481         // they are basically the same as these BC formats so they can be mapped
00482         if (MAKEFOURCC('D', 'X', 'T', '2') == ddpf.fourCC)
00483         {
00484             return DXGI_FORMAT_BC2_UNORM;
00485         }
00486         if (MAKEFOURCC('D', 'X', 'T', '4') == ddpf.fourCC)
00487         {
00488             return DXGI_FORMAT_BC3_UNORM;
00489         }
00490
00491         if (MAKEFOURCC('A', 'T', 'I', '1') == ddpf.fourCC)
00492         {
00493             return DXGI_FORMAT_BC4_UNORM;
00494         }
00495         if (MAKEFOURCC('B', 'C', '4', 'U') == ddpf.fourCC)
00496         {
00497             return DXGI_FORMAT_BC4_UNORM;
00498         }
00499         if (MAKEFOURCC('B', 'C', '4', 'S') == ddpf.fourCC)
00500         {
00501             return DXGI_FORMAT_BC4_SNORM;
00502         }
00503
00504         if (MAKEFOURCC('A', 'T', 'I', '2') == ddpf.fourCC)
00505         {
00506             return DXGI_FORMAT_BC5_UNORM;
00507         }
00508         if (MAKEFOURCC('B', 'C', '5', 'U') == ddpf.fourCC)
00509         {
00510             return DXGI_FORMAT_BC5_UNORM;
00511         }
00512         if (MAKEFOURCC('B', 'C', '5', 'S') == ddpf.fourCC)
00513         {
00514             return DXGI_FORMAT_BC5_SNORM;
00515         }
00516
00517         // BC6H and BC7 are written using the "DX10" extended header
00518
00519         if (MAKEFOURCC('R', 'G', 'B', 'G') == ddpf.fourCC)
00520         {
00521             return DXGI_FORMAT_R8G8_B8G8_UNORM;
00522         }
00523         if (MAKEFOURCC('G', 'R', 'G', 'B') == ddpf.fourCC)
00524         {
00525             return DXGI_FORMAT_G8R8_G8B8_UNORM;
00526         }
00527
00528         // Check for D3DFORMAT enums being set here
00529         switch (ddpf.fourCC)
00530         {
00531         case 36: // D3DFMT_A16B16G16R16
00532             return DXGI_FORMAT_R16G16B16A16_UNORM;
00533
00534         case 110: // D3DFMT_Q16W16V16U16
00535             return DXGI_FORMAT_R16G16B16A16_SNORM;
00536
00537         case 111: // D3DFMT_R16F
00538             return DXGI_FORMAT_R16_FLOAT;
00539
00540         case 112: // D3DFMT_G16R16F
00541             return DXGI_FORMAT_R16G16_FLOAT;
00542
00543         case 113: // D3DFMT_A16B16G16R16F
00544             return DXGI_FORMAT_R16G16B16A16_FLOAT;
00545
00546         case 114: // D3DFMT_R32F
00547             return DXGI_FORMAT_R32_FLOAT;
00548
00549         case 115: // D3DFMT_G32R32F
00550             return DXGI_FORMAT_R32G32_FLOAT;
00551
00552         case 116: // D3DFMT_A32B32G32R32F
00553             return DXGI_FORMAT_R32G32B32A32_FLOAT;
00554         }
00555     }
00556
00557     return DXGI_FORMAT_UNKNOWN;
00558 }
00559
00560
00561 //--------------------------------------------------------------------------------------
00562 static void FillInitData(
00563     _In_ size_t width,
00564     _In_ size_t height,
00565     _In_ size_t depth,
00566     _In_ size_t mipCount,
00567     _In_ size_t arraySize,
00568     _In_ DXGI_FORMAT format,
00569     _In_ size_t maxsize,
00570     _In_ size_t bitSize,
00571     _In_reads_bytes_(bitSize) const byte* bitData,
00572     _Out_ size_t& twidth,
00573     _Out_ size_t& theight,
00574     _Out_ size_t& tdepth,
00575     _Out_ size_t& skipMip,
00576     _Out_writes_(mipCount*arraySize) D3D11_SUBRESOURCE_DATA* initData
00577     )
00578 {
00579     if (!bitData || !initData)
00580     {
00581         throw ref new Platform::InvalidArgumentException();
00582     }
00583
00584     skipMip = 0;
00585     twidth = 0;
00586     theight = 0;
00587     tdepth = 0;
00588
00589     size_t NumBytes = 0;
00590     size_t RowBytes = 0;
00591     size_t NumRows = 0;
00592     const byte* pSrcBits = bitData;
00593     const byte* pEndBits = bitData + bitSize;
00594
00595     size_t index = 0;
00596     for (size_t j = 0; j < arraySize; j++)
00597     {
00598         size_t w = width;
00599         size_t h = height;
00600         size_t d = depth;
00601         for (size_t i = 0; i < mipCount; i++)
00602         {
00603             GetSurfaceInfo(w, h, format, &NumBytes, &RowBytes, &NumRows);
00604
00605             if ((mipCount <= 1) || !maxsize || (w <= maxsize && h <= maxsize && d <= maxsize))
00606             {
00607                 if (!twidth)
00608                 {
00609                     twidth = w;
00610                     theight = h;
00611                     tdepth = d;
00612                 }
00613
00614                 initData[index].pSysMem = (const void*)pSrcBits;
00615                 initData[index].SysMemPitch = static_cast<UINT>(RowBytes);
00616                 initData[index].SysMemSlicePitch = static_cast<UINT>(NumBytes);
00617                 ++index;
00618             }
00619             else
00620             {
00621                 ++skipMip;
00622             }
00623
00624             if (pSrcBits + (NumBytes*d) > pEndBits)
00625             {
00626                 throw ref new Platform::OutOfBoundsException();
00627             }
00628
00629             pSrcBits += NumBytes * d;
00630
00631             w = w >> 1;
00632             h = h >> 1;
00633             d = d >> 1;
00634             if (w == 0)
00635             {
00636                 w = 1;
00637             }
00638             if (h == 0)
00639             {
00640                 h = 1;
00641             }
00642             if (d == 0)
00643             {
00644                 d = 1;
00645             }
00646         }
00647     }
00648
00649     if (!index)
00650     {
00651         throw ref new Platform::FailureException();
00652     }
00653 }
00654
00655
00656 //--------------------------------------------------------------------------------------
00657 static HRESULT CreateD3DResources(
00658     _In_ ID3D11Device* d3dDevice,
00659     _In_ uint32 resDim,
00660     _In_ size_t width,
00661     _In_ size_t height,
00662     _In_ size_t depth,
00663     _In_ size_t mipCount,
00664     _In_ size_t arraySize,
00665     _In_ DXGI_FORMAT format,
00666     _In_ bool isCubeMap,
00667     _In_reads_(mipCount*arraySize) D3D11_SUBRESOURCE_DATA* initData,
00668     _Out_opt_ ID3D11Resource** texture,
00669     _Out_opt_ ID3D11ShaderResourceView** textureView
00670     )
00671 {
00672     if (!d3dDevice || !initData)
00673     {
00674         return E_INVALIDARG;
00675     }
00676
00677     HRESULT hr = E_FAIL;
00678
00679     switch (resDim)
00680     {
00681         case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
00682             {
00683                 D3D11_TEXTURE1D_DESC desc;
00684                 desc.Width = static_cast<UINT>(width);
00685                 desc.MipLevels = static_cast<UINT>(mipCount);
00686                 desc.ArraySize = static_cast<UINT>(arraySize);
00687                 desc.Format = format;
00688                 desc.Usage = D3D11_USAGE_DEFAULT;
00689                 desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
00690                 desc.CPUAccessFlags = 0;
00691                 desc.MiscFlags = 0;
00692
00693                 ID3D11Texture1D* tex = nullptr;
00694                 hr = d3dDevice->CreateTexture1D(&desc, initData, &tex);
00695
00696                 if (SUCCEEDED(hr) && tex != 0)
00697                 {
00698                     if (textureView != 0)
00699                     {
00700                         D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
00701                         memset(&SRVDesc, 0, sizeof(SRVDesc));
00702                         SRVDesc.Format = format;
00703
00704                         if (arraySize > 1)
00705                         {
00706                             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE1DARRAY;
00707                             SRVDesc.Texture1DArray.MipLevels = desc.MipLevels;
00708                             SRVDesc.Texture1DArray.ArraySize = static_cast<UINT>(arraySize);
00709                         }
00710                         else
00711                         {
00712                             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE1D;
00713                             SRVDesc.Texture1D.MipLevels = desc.MipLevels;
00714                         }
00715
00716                         hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView);
00717
00718                         if (FAILED(hr))
00719                         {
00720                             tex->Release();
00721                             return hr;
00722                         }
00723                     }
00724
00725                     if (texture != 0)
00726                     {
00727                         *texture = tex;
00728                     }
00729                     else
00730                     {
00731                         tex->Release();
00732                     }
00733                 }
00734             }
00735             break;
00736
00737         case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
00738             {
00739                 D3D11_TEXTURE2D_DESC desc;
00740                 desc.Width = static_cast<UINT>(width);
00741                 desc.Height = static_cast<UINT>(height);
00742                 desc.MipLevels = static_cast<UINT>(mipCount);
00743                 desc.ArraySize = static_cast<UINT>(arraySize);
00744                 desc.Format = format;
00745                 desc.SampleDesc.Count = 1;
00746                 desc.SampleDesc.Quality = 0;
00747                 desc.Usage = D3D11_USAGE_DEFAULT;
00748                 desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
00749                 desc.CPUAccessFlags = 0;
00750                 desc.MiscFlags = (isCubeMap) ? D3D11_RESOURCE_MISC_TEXTURECUBE : 0;
00751
00752                 ID3D11Texture2D* tex = nullptr;
00753                 hr = d3dDevice->CreateTexture2D(&desc, initData, &tex);
00754
00755                 if (SUCCEEDED(hr) && tex != 0)
00756                 {
00757                     if (textureView != 0)
00758                     {
00759                         D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
00760                         memset(&SRVDesc, 0, sizeof(SRVDesc));
00761                         SRVDesc.Format = format;
00762
00763                         if (isCubeMap)
00764                         {
00765                             if (arraySize > 6)
00766                             {
00767                                 SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURECUBEARRAY;
00768                                 SRVDesc.TextureCubeArray.MipLevels = desc.MipLevels;
00769
00770                                 // Earlier we set arraySize to (NumCubes * 6)
00771                                 SRVDesc.TextureCubeArray.NumCubes = static_cast<UINT>(arraySize / 6);
00772                             }
00773                             else
00774                             {
00775                                 SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURECUBE;
00776                                 SRVDesc.TextureCube.MipLevels = desc.MipLevels;
00777                             }
00778                         }
00779                         else if (arraySize > 1)
00780                         {
00781                             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE2DARRAY;
00782                             SRVDesc.Texture2DArray.MipLevels = desc.MipLevels;
00783                             SRVDesc.Texture2DArray.ArraySize = static_cast<UINT>(arraySize);
00784                         }
00785                         else
00786                         {
00787                             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE2D;
00788                             SRVDesc.Texture2D.MipLevels = desc.MipLevels;
00789                         }
00790
00791                         hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView);
00792
00793                         if (FAILED(hr))
00794                         {
00795                             tex->Release();
00796                             return hr;
00797                         }
00798                     }
00799
00800                     if (texture != 0)
00801                     {
00802                         *texture = tex;
00803                     }
00804                     else
00805                     {
00806                         tex->Release();
00807                     }
00808                 }
00809             }
00810             break;
00811
00812         case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
00813             {
00814                 D3D11_TEXTURE3D_DESC desc;
00815                 desc.Width = static_cast<UINT>(width);
00816                 desc.Height = static_cast<UINT>(height);
00817                 desc.Depth = static_cast<UINT>(depth);
00818                 desc.MipLevels = static_cast<UINT>(mipCount);
00819                 desc.Format = format;
00820                 desc.Usage = D3D11_USAGE_DEFAULT;
00821                 desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
00822                 desc.CPUAccessFlags = 0;
00823                 desc.MiscFlags = 0;
00824
00825                 ID3D11Texture3D* tex = nullptr;
00826                 hr = d3dDevice->CreateTexture3D(&desc, initData, &tex);
00827
00828                 if (SUCCEEDED(hr) && tex != 0)
00829                 {
00830                     if (textureView != 0)
00831                     {
00832                         D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
00833                         memset(&SRVDesc, 0, sizeof(SRVDesc));
00834                         SRVDesc.Format = format;
00835                         SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE3D;
00836                         SRVDesc.Texture3D.MipLevels = desc.MipLevels;
00837
00838                         hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView);
00839
00840                         if (FAILED(hr))
00841                         {
00842                             tex->Release();
00843                             return hr;
00844                         }
00845                     }
00846
00847                     if (texture != 0)
00848                     {
00849                         *texture = tex;
00850                     }
00851                     else
00852                     {
00853                         tex->Release();
00854                     }
00855                 }
00856             }
00857             break;
00858     }
00859
00860     return hr;
00861 }
00862
00863
00864 //--------------------------------------------------------------------------------------
00865 static void CreateTextureFromDDS(
00866     _In_ ID3D11Device* d3dDevice,
00867     _In_ const DDS_HEADER* header,
00868     _In_reads_bytes_(bitSize) const byte* bitData,
00869     _In_ size_t bitSize,
00870     _Out_opt_ ID3D11Resource** texture,
00871     _Out_opt_ ID3D11ShaderResourceView** textureView,
00872     _In_ size_t maxsize
00873     )
00874 {
00875     HRESULT hr = S_OK;
00876
00877     size_t width = header->width;
00878     size_t height = header->height;
00879     size_t depth = header->depth;
00880
00881     uint32 resDim = D3D11_RESOURCE_DIMENSION_UNKNOWN;
00882     size_t arraySize = 1;
00883     DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;
00884     bool isCubeMap = false;
00885
00886     size_t mipCount = header->mipMapCount;
00887     if (0 == mipCount)
00888     {
00889         mipCount = 1;
00890     }
00891
00892     if ((header->ddspf.flags & DDS_FOURCC) &&
00893         (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC))
00894     {
00895         const DDS_HEADER_DXT10* d3d10ext = reinterpret_cast<const DDS_HEADER_DXT10*>((const char*)header + sizeof(DDS_HEADER));
00896
00897         arraySize = d3d10ext->arraySize;
00898         if (arraySize == 0)
00899         {
00900             throw ref new Platform::FailureException();
00901         }
00902
00903         if (BitsPerPixel(d3d10ext->dxgiFormat) == 0)
00904         {
00905             throw ref new Platform::FailureException();
00906         }
00907
00908         format = d3d10ext->dxgiFormat;
00909
00910         switch (d3d10ext->resourceDimension)
00911         {
00912         case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
00913             // D3DX writes 1D textures with a fixed Height of 1
00914             if ((header->flags & DDS_HEIGHT) && height != 1)
00915             {
00916                 throw ref new Platform::FailureException();
00917             }
00918             height = depth = 1;
00919             break;
00920
00921         case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
00922             if (d3d10ext->miscFlag & D3D11_RESOURCE_MISC_TEXTURECUBE)
00923             {
00924                 arraySize *= 6;
00925                 isCubeMap = true;
00926             }
00927             depth = 1;
00928             break;
00929
00930         case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
00931             if (!(header->flags & DDS_HEADER_FLAGS_VOLUME))
00932             {
00933                 throw ref new Platform::FailureException();
00934             }
00935
00936             if (arraySize > 1)
00937             {
00938                 throw ref new Platform::FailureException();
00939             }
00940             break;
00941
00942         default:
00943             return throw ref new Platform::FailureException();
00944         }
00945
00946         resDim = d3d10ext->resourceDimension;
00947     }
00948     else
00949     {
00950         format = GetDXGIFormat(header->ddspf);
00951
00952         if (format == DXGI_FORMAT_UNKNOWN)
00953         {
00954             return throw ref new Platform::FailureException();
00955         }
00956
00957         if (header->flags & DDS_HEADER_FLAGS_VOLUME)
00958         {
00959             resDim = D3D11_RESOURCE_DIMENSION_TEXTURE3D;
00960         }
00961         else
00962         {
00963             if (header->caps2 & DDS_CUBEMAP)
00964             {
00965                 // We require all six faces to be defined
00966                 if ((header->caps2 & DDS_CUBEMAP_ALLFACES) != DDS_CUBEMAP_ALLFACES)
00967                 {
00968                     return throw ref new Platform::FailureException();
00969                 }
00970
00971                 arraySize = 6;
00972                 isCubeMap = true;
00973             }
00974
00975             depth = 1;
00976             resDim = D3D11_RESOURCE_DIMENSION_TEXTURE2D;
00977
00978             // Note there's no way for a legacy Direct3D 9 DDS to express a '1D' texture
00979         }
00980
00981         assert(BitsPerPixel(format) != 0);
00982     }
00983
00984     // Bound sizes (for security purposes we don't trust DDS file metadata larger than the D3D 11.x hardware requirements)
00985     if (mipCount > D3D11_REQ_MIP_LEVELS)
00986     {
00987         return throw ref new Platform::FailureException();
00988     }
00989
00990     switch (resDim)
00991     {
00992         case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
00993             if ((arraySize > D3D11_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION) ||
00994                 (width > D3D11_REQ_TEXTURE1D_U_DIMENSION))
00995             {
00996                 return throw ref new Platform::FailureException();
00997             }
00998             break;
00999
01000         case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
01001             if (isCubeMap)
01002             {
01003                 // This is the right bound because we set arraySize to (NumCubes*6) above
01004                 if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) ||
01005                     (width > D3D11_REQ_TEXTURECUBE_DIMENSION) ||
01006                     (height > D3D11_REQ_TEXTURECUBE_DIMENSION))
01007                 {
01008                     return throw ref new Platform::FailureException();
01009                 }
01010             }
01011             else if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) ||
01012                     (width > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION) ||
01013                     (height > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION))
01014             {
01015                 return throw ref new Platform::FailureException();
01016             }
01017             break;
01018
01019         case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
01020             if ((arraySize > 1) ||
01021                 (width > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) ||
01022                 (height > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) ||
01023                 (depth > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION))
01024             {
01025                 return throw ref new Platform::FailureException();
01026             }
01027             break;
01028     }
01029
01030     // Create the texture
01031     std::unique_ptr<D3D11_SUBRESOURCE_DATA> initData(new D3D11_SUBRESOURCE_DATA[mipCount * arraySize]);
01032
01033     size_t skipMip = 0;
01034     size_t twidth = 0;
01035     size_t theight = 0;
01036     size_t tdepth = 0;
01037     FillInitData(width, height, depth, mipCount, arraySize, format, maxsize, bitSize, bitData, twidth, theight, tdepth, skipMip, initData.get());
01038
01039     hr = CreateD3DResources(d3dDevice, resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize, format, isCubeMap, initData.get(), texture, textureView);
01040
01041     if (FAILED(hr) && !maxsize && (mipCount > 1))
01042     {
01043         // Retry with a maxsize determined by feature level
01044         switch (d3dDevice->GetFeatureLevel())
01045         {
01046         case D3D_FEATURE_LEVEL_9_1:
01047         case D3D_FEATURE_LEVEL_9_2:
01048             if (isCubeMap)
01049             {
01050                 maxsize = D3D_FL9_1_REQ_TEXTURECUBE_DIMENSION;
01051             }
01052             else
01053             {
01054                 maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D)
01055                     ? D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION
01056                     : D3D_FL9_1_REQ_TEXTURE2D_U_OR_V_DIMENSION;
01057             }
01058             break;
01059
01060         case D3D_FEATURE_LEVEL_9_3:
01061             maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D)
01062                 ? D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION
01063                 : D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION;
01064             break;
01065
01066         default: // D3D_FEATURE_LEVEL_10_0 & D3D_FEATURE_LEVEL_10_1
01067             maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D)
01068                 ? D3D10_REQ_TEXTURE3D_U_V_OR_W_DIMENSION
01069                 : D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION;
01070             break;
01071         }
01072
01073         FillInitData(width, height, depth, mipCount, arraySize, format, maxsize, bitSize, bitData, twidth, theight, tdepth, skipMip, initData.get());
01074
01075         hr = CreateD3DResources(d3dDevice, resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize, format, isCubeMap, initData.get(), texture, textureView);
01076     }
01077
01078     DX::ThrowIfFailed(hr);
01079 }
01080
01081 //--------------------------------------------------------------------------------------
01082 void CreateDDSTextureFromMemory(
01083     _In_ ID3D11Device* d3dDevice,
01084     _In_reads_bytes_(ddsDataSize) const byte* ddsData,
01085     _In_ size_t ddsDataSize,
01086     _Out_opt_ ID3D11Resource** texture,
01087     _Out_opt_ ID3D11ShaderResourceView** textureView,
01088     _In_ size_t maxsize
01089     )
01090 {
01091     if (!d3dDevice || !ddsData || (!texture && !textureView))
01092     {
01093         throw ref new Platform::InvalidArgumentException();
01094     }
01095
01096     // Validate DDS file in memory
01097     if (ddsDataSize < (sizeof(uint32) + sizeof(DDS_HEADER)))
01098     {
01099         throw ref new Platform::FailureException();
01100     }
01101
01102     uint32 dwMagicNumber = *(const uint32*)(ddsData);
01103     if (dwMagicNumber != DDS_MAGIC)
01104     {
01105         throw ref new Platform::FailureException();
01106     }
01107
01108     const DDS_HEADER* header = reinterpret_cast<const DDS_HEADER*>(ddsData + sizeof(uint32));
01109
01110     // Verify header to validate DDS file
01111     if (header->size != sizeof(DDS_HEADER) ||
01112         header->ddspf.size != sizeof(DDS_PIXELFORMAT))
01113     {
01114         throw ref new Platform::FailureException();
01115     }
01116
01117     // Check for DX10 extension
01118     bool bDXT10Header = false;
01119     if ((header->ddspf.flags & DDS_FOURCC) &&
01120         (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC))
01121     {
01122         // Must be long enough for both headers and magic value
01123         if (ddsDataSize < (sizeof(DDS_HEADER) + sizeof(uint32) + sizeof(DDS_HEADER_DXT10)))
01124         {
01125             throw ref new Platform::FailureException();
01126         }
01127
01128         bDXT10Header = true;
01129     }
01130
01131     ptrdiff_t offset = sizeof(uint32) + sizeof(DDS_HEADER) + (bDXT10Header ? sizeof(DDS_HEADER_DXT10) : 0);
01132
01133     CreateTextureFromDDS(d3dDevice, header, ddsData + offset, ddsDataSize - offset, texture, textureView, maxsize);
01134 }
Generated on Sat Nov 23 2024 16:08:10 for Win8-Examples by doxygen 1.7.1


Win8-Examples: SMS background task/C++/SmsBackgroundTaskSample/App.xaml.h Source File

  • SMS background task
  • SmsBackgroundTaskSample

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: HttpClient/C++/Scenario4.xaml.h Source File

  • HttpClient

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 "HttpRequest.h"
00022
00023 namespace SDKSample
00024 {
00025     namespace HttpClientSample
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 Scenario4 sealed
00032         {
00033         public:
00034             Scenario4();
00035
00036         protected:
00037             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00038
00039         private:
00040             MainPage^ rootPage;
00041             Web::HttpRequest httpRequest;
00042             concurrency::cancellation_token_source cancellationTokenSource;
00043             void Start_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00044             void Cancel_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00045             void DisplayTextResult(const std::wstring& response, Windows::UI::Xaml::Controls::TextBox^ output);
00046         };
00047     }
00048 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::CameraCapture::sealed Member List

This is the complete list of members for SDKSample::CameraCapture::sealed, including all inherited members.
appSettings | SDKSample::CameraCapture::sealed | [private]
CapturePhoto() | SDKSample::CameraCapture::sealed |
CapturePhoto_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CameraCapture::sealed | [private]
CaptureVideo() | SDKSample::CameraCapture::sealed |
CaptureVideo_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CameraCapture::sealed | [private]
LoadPhoto(Platform::String^filepath) | SDKSample::CameraCapture::sealed | [private]
LoadVideo(Platform::String^filePath) | SDKSample::CameraCapture::sealed | [private]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::CameraCapture::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::CameraCapture::sealed | [protected, virtual]
Reset_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CameraCapture::sealed | [private]
Reset_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CameraCapture::sealed | [private]
rootPage | SDKSample::CameraCapture::sealed | [private]
Generated on Sat Nov 23 2024 16:09:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text display/C++/Common/LayoutAwarePage.cpp Source File

  • XAML text display
  • Common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:33 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/MediaExtensions/Mpeg1Source/MPEG1Stream.cpp Source File

  • Media extensions
  • MediaExtensions
  • Mpeg1Source

MPEG1Stream.cpp

Go to the documentation of this file.
00001 //////////////////////////////////////////////////////////////////////////
00002 //
00003 // MPEG1Stream.cpp
00004 // Implements the stream object (IMFMediaStream) for the MPEG-1 source.
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 #include "MPEG1Src.h"
00016
00017 #pragma warning( push )
00018 #pragma warning( disable : 4355 )  // 'this' used in base member initializer list
00019
00020
00021 /* CMPEG1Stream::SourceLock class methods */
00022
00023 //-------------------------------------------------------------------
00024 // CMPEG1Stream::SourceLock constructor - locks the source
00025 //-------------------------------------------------------------------
00026
00027 _Acquires_lock_(m_pSource)
00028 CMPEG1Stream::SourceLock::SourceLock(CMPEG1Source *pSource)
00029     : m_pSource(NULL)
00030 {
00031     if (pSource)
00032     {
00033         m_pSource = pSource;
00034         m_pSource->AddRef();
00035         m_pSource->Lock();
00036     }
00037 }
00038
00039 //-------------------------------------------------------------------
00040 // CMPEG1Stream::SourceLock destructor - unlocks the source
00041 //-------------------------------------------------------------------
00042
00043 _Releases_lock_(m_pSource)
00044 CMPEG1Stream::SourceLock::~SourceLock()
00045 {
00046     if (m_pSource)
00047     {
00048         m_pSource->Unlock();
00049         m_pSource->Release();
00050     }
00051 }
00052
00053
00054
00055 /* Public class methods */
00056
00057 //-------------------------------------------------------------------
00058 // IUnknown methods
00059 //-------------------------------------------------------------------
00060
00061 ULONG CMPEG1Stream::AddRef()
00062 {
00063     return _InterlockedIncrement(&m_cRef);
00064 }
00065
00066 ULONG CMPEG1Stream::Release()
00067 {
00068     LONG cRef = _InterlockedDecrement(&m_cRef);
00069     if (cRef == 0)
00070     {
00071         delete this;
00072     }
00073     return cRef;
00074 }
00075
00076 HRESULT CMPEG1Stream::QueryInterface(REFIID riid, void** ppv)
00077 {
00078     if (ppv == nullptr)
00079     {
00080         return E_POINTER;
00081     }
00082
00083     HRESULT hr = E_NOINTERFACE;
00084     if (riid == IID_IUnknown ||
00085         riid == IID_IMFMediaEventGenerator ||
00086         riid == IID_IMFMediaStream)
00087     {
00088         (*ppv) = static_cast<IMFMediaStream *>(this);
00089         AddRef();
00090         hr = S_OK;
00091     }
00092
00093     return hr;
00094 }
00095
00096
00097 //-------------------------------------------------------------------
00098 // IMFMediaEventGenerator methods
00099 //
00100 // For remarks, see MPEG1Source.cpp
00101 //-------------------------------------------------------------------
00102
00103 HRESULT CMPEG1Stream::BeginGetEvent(IMFAsyncCallback* pCallback,IUnknown* punkState)
00104 {
00105     HRESULT hr = S_OK;
00106
00107     SourceLock lock(m_pSource);
00108
00109     hr = CheckShutdown();
00110
00111     if (SUCCEEDED(hr))
00112     {
00113         hr = m_pEventQueue->BeginGetEvent(pCallback, punkState);
00114     }
00115
00116     return hr;
00117 }
00118
00119 HRESULT CMPEG1Stream::EndGetEvent(IMFAsyncResult* pResult, IMFMediaEvent** ppEvent)
00120 {
00121     HRESULT hr = S_OK;
00122
00123     SourceLock lock(m_pSource);
00124
00125     hr = CheckShutdown();
00126
00127     if (SUCCEEDED(hr))
00128     {
00129         hr = m_pEventQueue->EndGetEvent(pResult, ppEvent);
00130     }
00131
00132     return hr;
00133 }
00134
00135 HRESULT CMPEG1Stream::GetEvent(DWORD dwFlags, IMFMediaEvent** ppEvent)
00136 {
00137     HRESULT hr = S_OK;
00138
00139     IMFMediaEventQueue *pQueue = NULL;
00140
00141     { // scope for lock
00142
00143         SourceLock lock(m_pSource);
00144
00145         // Check shutdown
00146         hr = CheckShutdown();
00147
00148         // Cache a local pointer to the queue.
00149         if (SUCCEEDED(hr))
00150         {
00151             pQueue = m_pEventQueue;
00152             pQueue->AddRef();
00153         }
00154     }   // release lock
00155
00156     // Use the local pointer to call GetEvent.
00157     if (SUCCEEDED(hr))
00158     {
00159         hr = pQueue->GetEvent(dwFlags, ppEvent);
00160     }
00161
00162     SafeRelease(&pQueue);
00163     return hr;
00164 }
00165
00166 HRESULT CMPEG1Stream::QueueEvent(MediaEventType met, REFGUID guidExtendedType, HRESULT hrStatus, const PROPVARIANT* pvValue)
00167 {
00168     HRESULT hr = S_OK;
00169
00170     SourceLock lock(m_pSource);
00171
00172     hr = CheckShutdown();
00173
00174     if (SUCCEEDED(hr))
00175     {
00176         hr = m_pEventQueue->QueueEventParamVar(met, guidExtendedType, hrStatus, pvValue);
00177     }
00178
00179     return hr;
00180 }
00181
00182 //-------------------------------------------------------------------
00183 // IMFMediaStream methods
00184 //-------------------------------------------------------------------
00185
00186
00187 //-------------------------------------------------------------------
00188 // GetMediaSource:
00189 // Returns a pointer to the media source.
00190 //-------------------------------------------------------------------
00191
00192 HRESULT CMPEG1Stream::GetMediaSource(IMFMediaSource** ppMediaSource)
00193 {
00194     SourceLock lock(m_pSource);
00195
00196     if (ppMediaSource == NULL)
00197     {
00198         return E_POINTER;
00199     }
00200
00201     if (m_pSource == NULL)
00202     {
00203         return E_UNEXPECTED;
00204     }
00205
00206     HRESULT hr = S_OK;
00207
00208     hr = CheckShutdown();
00209
00210     // QI the source for IMFMediaSource.
00211     // (Does not hold the source's critical section.)
00212     if (SUCCEEDED(hr))
00213     {
00214         hr = m_pSource->QueryInterface(IID_PPV_ARGS(ppMediaSource));
00215     }
00216     return hr;
00217 }
00218
00219
00220 //-------------------------------------------------------------------
00221 // GetStreamDescriptor:
00222 // Returns a pointer to the stream descriptor for this stream.
00223 //-------------------------------------------------------------------
00224
00225 HRESULT CMPEG1Stream::GetStreamDescriptor(IMFStreamDescriptor** ppStreamDescriptor)
00226 {
00227     SourceLock lock(m_pSource);
00228
00229     if (ppStreamDescriptor == NULL)
00230     {
00231         return E_POINTER;
00232     }
00233
00234     if (m_pStreamDescriptor == NULL)
00235     {
00236         return E_UNEXPECTED;
00237     }
00238
00239     HRESULT hr = CheckShutdown();
00240
00241     if (SUCCEEDED(hr))
00242     {
00243         *ppStreamDescriptor = m_pStreamDescriptor;
00244         (*ppStreamDescriptor)->AddRef();
00245
00246     };
00247     return hr;
00248 }
00249
00250
00251 //-------------------------------------------------------------------
00252 // RequestSample:
00253 // Requests data from the stream.
00254 //
00255 // pToken: Token used to track the request. Can be NULL.
00256 //-------------------------------------------------------------------
00257
00258 HRESULT CMPEG1Stream::RequestSample(IUnknown* pToken)
00259 {
00260     HRESULT hr = S_OK;
00261     IMFMediaSource *pSource = NULL;
00262
00263     // Hold the media source object's critical section.
00264     SourceLock lock(m_pSource);
00265
00266     hr = CheckShutdown();
00267     if (FAILED(hr))
00268     {
00269         goto done;
00270     }
00271
00272     if (m_state == STATE_STOPPED)
00273     {
00274         hr = MF_E_INVALIDREQUEST;
00275         goto done;
00276     }
00277
00278     if (!m_bActive)
00279     {
00280         // If the stream is not active, it should not get sample requests.
00281         hr = MF_E_INVALIDREQUEST;
00282         goto done;
00283     }
00284
00285     if (m_bEOS && m_Samples.IsEmpty())
00286     {
00287         // This stream has already reached the end of the stream, and the
00288         // sample queue is empty.
00289         hr = MF_E_END_OF_STREAM;
00290         goto done;
00291     }
00292
00293     hr = m_Requests.InsertBack(pToken);
00294     if (FAILED(hr))
00295     {
00296         goto done;
00297     }
00298
00299     // Dispatch the request.
00300     hr = DispatchSamples();
00301     if (FAILED(hr))
00302     {
00303         goto done;
00304     }
00305
00306 done:
00307     if (FAILED(hr) && (m_state != STATE_SHUTDOWN))
00308     {
00309         // An error occurred. Send an MEError even from the source,
00310         // unless the source is already shut down.
00311         hr = m_pSource->QueueEvent(MEError, GUID_NULL, hr, NULL);
00312     }
00313     return hr;
00314 }
00315
00316
00317
00318 //-------------------------------------------------------------------
00319 // Public non-interface methods
00320 //-------------------------------------------------------------------
00321
00322
00323 CMPEG1Stream::CMPEG1Stream(CMPEG1Source *pSource, IMFStreamDescriptor *pSD, HRESULT& hr) :
00324     m_cRef(1),
00325     m_pEventQueue(NULL),
00326     m_state(STATE_STOPPED),
00327     m_bActive(FALSE),
00328     m_bEOS(FALSE),
00329     m_flRate(1.0f)
00330 {
00331     auto module = ::Microsoft::WRL::GetModuleBase();
00332     if (module != nullptr)
00333     {
00334         module->IncrementObjectCount();
00335     }
00336
00337   assert(pSource != NULL);
00338     assert(pSD != NULL);
00339
00340     m_pSource = pSource;
00341     m_pSource->AddRef();
00342
00343     m_pStreamDescriptor = pSD;
00344     m_pStreamDescriptor->AddRef();
00345
00346     // Create the media event queue.
00347     hr = MFCreateEventQueue(&m_pEventQueue);
00348 }
00349
00350 CMPEG1Stream::~CMPEG1Stream()
00351 {
00352     assert(m_state == STATE_SHUTDOWN);
00353     SafeRelease(&m_pSource);
00354
00355     auto module = ::Microsoft::WRL::GetModuleBase();
00356     if (module != nullptr)
00357     {
00358         module->DecrementObjectCount();
00359     }
00360 }
00361
00362
00363
00364 //-------------------------------------------------------------------
00365 // Activate
00366 // Activates or deactivates the stream. Called by the media source.
00367 //-------------------------------------------------------------------
00368
00369 HRESULT CMPEG1Stream::Activate(BOOL bActive)
00370 {
00371     SourceLock lock(m_pSource);
00372
00373     if (bActive == m_bActive)
00374     {
00375         return S_OK; // No op
00376     }
00377
00378     m_bActive = bActive;
00379
00380     if (!bActive)
00381     {
00382         m_Samples.Clear();
00383         m_Requests.Clear();
00384     }
00385     return S_OK;
00386 }
00387
00388
00389 //-------------------------------------------------------------------
00390 // Start
00391 // Starts the stream. Called by the media source.
00392 //
00393 // varStart: Starting position.
00394 //-------------------------------------------------------------------
00395
00396 HRESULT CMPEG1Stream::Start(const PROPVARIANT& varStart)
00397 {
00398     SourceLock lock(m_pSource);
00399
00400     HRESULT hr = S_OK;
00401
00402     hr = CheckShutdown();
00403
00404     // Queue the stream-started event.
00405     if (SUCCEEDED(hr))
00406     {
00407         hr = QueueEvent(MEStreamStarted, GUID_NULL, S_OK, &varStart);
00408     }
00409
00410     if (SUCCEEDED(hr))
00411     {
00412         m_state = STATE_STARTED;
00413     }
00414
00415     // If we are restarting from paused, there may be
00416     // queue sample requests. Dispatch them now.
00417     if (SUCCEEDED(hr))
00418     {
00419         hr = DispatchSamples();
00420     }
00421     return hr;
00422 }
00423
00424
00425 //-------------------------------------------------------------------
00426 // Pause
00427 // Pauses the stream. Called by the media source.
00428 //-------------------------------------------------------------------
00429
00430 HRESULT CMPEG1Stream::Pause()
00431 {
00432     SourceLock lock(m_pSource);
00433
00434     HRESULT hr = S_OK;
00435
00436     hr = CheckShutdown();
00437
00438     if (SUCCEEDED(hr))
00439     {
00440         m_state = STATE_PAUSED;
00441
00442         hr = QueueEvent(MEStreamPaused, GUID_NULL, S_OK, NULL);
00443     }
00444
00445     return hr;
00446 }
00447
00448
00449 //-------------------------------------------------------------------
00450 // Stop
00451 // Stops the stream. Called by the media source.
00452 //-------------------------------------------------------------------
00453
00454 HRESULT CMPEG1Stream::Stop()
00455 {
00456     SourceLock lock(m_pSource);
00457
00458     HRESULT hr = S_OK;
00459
00460     hr = CheckShutdown();
00461
00462     if (SUCCEEDED(hr))
00463     {
00464         m_Requests.Clear();
00465         m_Samples.Clear();
00466
00467         m_state = STATE_STOPPED;
00468
00469         hr = QueueEvent(MEStreamStopped, GUID_NULL, S_OK, NULL);
00470     }
00471
00472     return hr;
00473 }
00474
00475 //-------------------------------------------------------------------
00476 // SetRate
00477 // Sets rate of the stream. Called by the media source.
00478 //-------------------------------------------------------------------
00479
00480 HRESULT CMPEG1Stream::SetRate(float flRate)
00481 {
00482     HRESULT hr = S_OK;
00483     SourceLock lock(m_pSource);
00484
00485     hr = CheckShutdown();
00486
00487     if (SUCCEEDED(hr))
00488     {
00489         m_flRate = flRate;
00490     }
00491
00492     return hr;
00493 }
00494
00495 //-------------------------------------------------------------------
00496 // EndOfStream
00497 // Notifies the stream that the source reached the end of the MPEG-1
00498 // stream. For more information, see CMPEG1Source::EndOfMPEGStream().
00499 //-------------------------------------------------------------------
00500
00501 HRESULT CMPEG1Stream::EndOfStream()
00502 {
00503     SourceLock lock(m_pSource);
00504
00505     m_bEOS = TRUE;
00506
00507     return DispatchSamples();
00508 }
00509
00510
00511 //-------------------------------------------------------------------
00512 // Shutdown
00513 // Shuts down the stream and releases all resources.
00514 //-------------------------------------------------------------------
00515
00516 HRESULT CMPEG1Stream::Shutdown()
00517 {
00518     SourceLock lock(m_pSource);
00519
00520     HRESULT hr = S_OK;
00521
00522     hr = CheckShutdown();
00523
00524     if (SUCCEEDED(hr))
00525     {
00526         m_state = STATE_SHUTDOWN;
00527
00528         // Shut down the event queue.
00529         if (m_pEventQueue)
00530         {
00531             m_pEventQueue->Shutdown();
00532         }
00533
00534         // Release objects.
00535         m_Samples.Clear();
00536         m_Requests.Clear();
00537
00538         SafeRelease(&m_pStreamDescriptor);
00539         SafeRelease(&m_pEventQueue);
00540
00541         // NOTE:
00542         // Do NOT release the source pointer here, because the stream uses
00543         // it to hold the critical section. In particular, the stream must
00544         // hold the critical section when checking the shutdown status,
00545         // which obviously can occur after the stream is shut down.
00546
00547         // It is OK to hold a ref count on the source after shutdown,
00548         // because the source releases its ref count(s) on the streams,
00549         // which breaks the circular ref count.
00550     }
00551
00552     return hr;
00553 }
00554
00555
00556 //-------------------------------------------------------------------
00557 // NeedsData
00558 // Returns TRUE if the stream needs more data.
00559 //-------------------------------------------------------------------
00560
00561 BOOL CMPEG1Stream::NeedsData()
00562 {
00563     SourceLock lock(m_pSource);
00564
00565     // Note: The stream tries to keep a minimum number of samples
00566     // queued ahead.
00567
00568     return (m_bActive && !m_bEOS && (m_Samples.GetCount() < SAMPLE_QUEUE));
00569 }
00570
00571
00572 //-------------------------------------------------------------------
00573 // DeliverPayload
00574 // Delivers a sample to the stream.
00575 //-------------------------------------------------------------------
00576
00577 HRESULT CMPEG1Stream::DeliverPayload(IMFSample *pSample)
00578 {
00579     SourceLock lock(m_pSource);
00580
00581     HRESULT hr = S_OK;
00582
00583     // Queue the sample.
00584     hr = m_Samples.InsertBack(pSample);
00585
00586     // Deliver the sample if there is an outstanding request.
00587     if (SUCCEEDED(hr))
00588     {
00589         hr = DispatchSamples();
00590     }
00591
00592     return hr;
00593 }
00594
00595 /* Private methods */
00596
00597 //-------------------------------------------------------------------
00598 // DispatchSamples
00599 // Dispatches as many pending sample requests as possible.
00600 //-------------------------------------------------------------------
00601
00602 HRESULT CMPEG1Stream::DispatchSamples()
00603 {
00604     HRESULT hr = S_OK;
00605     BOOL bNeedData = FALSE;
00606     BOOL bEOS = FALSE;
00607
00608     SourceLock lock(m_pSource);
00609
00610     // An I/O request can complete after the source is paused, stopped, or
00611     // shut down. Do not deliver samples unless the source is running.
00612     if (m_state != STATE_STARTED)
00613     {
00614         return S_OK;
00615     }
00616
00617     IMFSample *pSample = NULL;
00618     IUnknown  *pToken = NULL;
00619
00620     // Deliver as many samples as we can.
00621     while (!m_Samples.IsEmpty() && !m_Requests.IsEmpty())
00622     {
00623         // Pull the next sample from the queue.
00624         hr = m_Samples.RemoveFront(&pSample);
00625         if (FAILED(hr))
00626         {
00627             goto done;
00628         }
00629
00630         // Pull the next request token from the queue. Tokens can be NULL.
00631         hr = m_Requests.RemoveFront(&pToken);
00632         if (FAILED(hr))
00633         {
00634             goto done;
00635         }
00636
00637         if (pToken)
00638         {
00639             // Set the token on the sample.
00640             hr = pSample->SetUnknown(MFSampleExtension_Token, pToken);
00641             if (FAILED(hr))
00642             {
00643                 goto done;
00644             }
00645         }
00646
00647         // Send an MEMediaSample event with the sample.
00648         hr = m_pEventQueue->QueueEventParamUnk(
00649             MEMediaSample, GUID_NULL, S_OK, pSample);
00650
00651         if (FAILED(hr))
00652         {
00653             goto done;
00654         }
00655
00656         SafeRelease(&pSample);
00657         SafeRelease(&pToken);
00658     }
00659
00660     if (m_Samples.IsEmpty() && m_bEOS)
00661     {
00662         // The sample queue is empty AND we have reached the end of the source
00663         // stream. Notify the pipeline by sending the end-of-stream event.
00664
00665         hr = m_pEventQueue->QueueEventParamVar(
00666             MEEndOfStream, GUID_NULL, S_OK, NULL);
00667
00668         if (FAILED(hr))
00669         {
00670             goto done;
00671         }
00672
00673         // Notify the source. It will send the end-of-presentation event.
00674         hr = m_pSource->QueueAsyncOperation(SourceOp::OP_END_OF_STREAM);
00675         if (FAILED(hr))
00676         {
00677             goto done;
00678         }
00679     }
00680     else if (NeedsData())
00681     {
00682         // The sample queue is empty; the request queue is not empty; and we
00683         // have not reached the end of the stream. Ask for more data.
00684         hr = m_pSource->QueueAsyncOperation(SourceOp::OP_REQUEST_DATA);
00685         if (FAILED(hr))
00686         {
00687             goto done;
00688         }
00689     }
00690
00691 done:
00692     if (FAILED(hr) && (m_state != STATE_SHUTDOWN))
00693     {
00694         // An error occurred. Send an MEError even from the source,
00695         // unless the source is already shut down.
00696         m_pSource->QueueEvent(MEError, GUID_NULL, hr, NULL);
00697     }
00698
00699     SafeRelease(&pSample);
00700     SafeRelease(&pToken);
00701     return S_OK;
00702 }
00703
00704 #pragma warning( pop )
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML FlipView control/C++/common/suspensionmanager.cpp Source File

  • XAML FlipView control
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

EaseOutExponentialAnimation< T > Member List

This is the complete list of members for EaseOutExponentialAnimation< T >, including all inherited members.
Animation(T start, T end, T duration) | Animation< T > | [inline]
ComputeValue(T time) | EaseOutExponentialAnimation< T > | [inline, protected, virtual]
EaseOutExponentialAnimation(T start=0, T end=0, T duration=0) | EaseOutExponentialAnimation< T > | [inline]
GetDuration() | Animation< T > | [inline]
GetEnd() | Animation< T > | [inline]
GetStart() | Animation< T > | [inline]
GetValue(T time) | Animation< T > | [inline]
m_Duration | Animation< T > | [protected]
m_End | Animation< T > | [protected]
m_Start | Animation< T > | [protected]
SetDuration(T duration) | Animation< T > | [inline]
SetEnd(T end) | Animation< T > | [inline]
SetStart(T start) | Animation< T > | [inline]
Generated on Sat Nov 23 2024 16:09:12 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Touch keyboard/C++/MainPage.xaml.h Source File

  • Input Touch keyboard

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:46 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Scheduled notifications/C#,C++/ScenarioOutput2.xaml.cpp Source File

  • Scheduled notifications
  • C#,C++

ScenarioOutput2.xaml.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 //
00009 // Scenario2Output.xaml.cpp
00010 // Implementation of the Scenario2Output class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioOutput2.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace ScheduledNotificationsSampleCPP;
00018
00019 using namespace Platform;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Graphics::Display;
00023 using namespace Windows::UI::ViewManagement;
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 ScenarioOutput2::ScenarioOutput2()
00033 {
00034     InitializeComponent();
00035 }
00036
00037 ScenarioOutput2::~ScenarioOutput2()
00038 {
00039 }
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D 3D transform effect/C++/DirectXBase.h Source File

  • Direct2D 3D transform effect

DirectXBase.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 "DirectXSample.h"
00011
00012 // Helper class that initializes DirectX APIs for both 2D and 3D rendering.
00013 // Some of the code in this class may be omitted if only 2D or only 3D rendering is being used.
00014 ref class DirectXBase abstract
00015 {
00016 internal:
00017     DirectXBase();
00018
00019     virtual void Initialize(
00020         Windows::UI::Core::CoreWindow^ window,
00021         Windows::UI::Xaml::Controls::SwapChainBackgroundPanel^ swapChainPanel,
00022         float dpi
00023         );
00024
00025     virtual void HandleDeviceLost();
00026     virtual void CreateDeviceIndependentResources();
00027     virtual void CreateDeviceResources();
00028     virtual void SetDpi(float dpi);
00029     virtual void UpdateForWindowSizeChange();
00030     virtual void CreateWindowSizeDependentResources();
00031     virtual void Render() = 0;
00032     virtual void Present();
00033     void ValidateDevice();
00034
00035 protected private:
00036     Windows::UI::Xaml::Controls::SwapChainBackgroundPanel^  m_swapChainPanel;
00037     Platform::Agile<Windows::UI::Core::CoreWindow>          m_window;
00038
00039     // DirectWrite & Windows Imaging Component Objects.
00040     Microsoft::WRL::ComPtr<IDWriteFactory1>         m_dwriteFactory;
00041     Microsoft::WRL::ComPtr<IWICImagingFactory2>     m_wicFactory;
00042
00043     // DirectX Core Objects. Required for 2D and 3D.
00044     Microsoft::WRL::ComPtr<ID3D11Device1>           m_d3dDevice;
00045     Microsoft::WRL::ComPtr<ID3D11DeviceContext1>    m_d3dContext;
00046     Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00047     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00048
00049     // Direct2D Rendering Objects. Required for 2D.
00050     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00051     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00052     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00053     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmap;
00054
00055     // Direct3D Rendering Objects. Required for 3D.
00056     Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00057
00058     // Cached renderer properties.
00059     D3D_FEATURE_LEVEL                               m_featureLevel;
00060     Windows::Foundation::Size                       m_renderTargetSize;
00061     Windows::Foundation::Rect                       m_windowBounds;
00062     float                                           m_dpi;
00063 };
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CameraOptionsUI/C++/common/suspensionmanager.cpp Source File

  • CameraOptionsUI
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

WorldFloorMesh Member List

This is the complete list of members for WorldFloorMesh, including all inherited members.
__pad0__ WorldFloorMesh
Generated on Sat Nov 23 2024 16:09:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Connecting with WebSockets/C++/Scenario1.xaml.cpp Source File

  • Connecting with WebSockets

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 <strsafe.h>
00018 #include "Scenario1.xaml.h"
00019
00020 using namespace concurrency;
00021 using namespace SDKSample::WebSocket;
00022 using namespace Windows::UI::Core;
00023
00024 Scenario1::Scenario1()
00025 {
00026     InitializeComponent();
00027 }
00028
00029 Scenario1::~Scenario1()
00030 {
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 void SDKSample::WebSocket::Scenario1::Start_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00046 {
00047     // Make a local copy to avoid races with Closed events.
00048     MessageWebSocket^ webSocket = messageWebSocket;
00049
00050     if (InputField->Text == "")
00051     {
00052         rootPage->NotifyUser("Please specify text to send", NotifyType::ErrorMessage);
00053         return;
00054     }
00055
00056     // Have we connected yet?
00057     if (webSocket == nullptr)
00058     {
00059         // By default 'ServerAddressField' is disabled and URI validation is not required. When enabling the text box
00060         // validating the URI is required since it was received from an untrusted source (user input).
00061         // The URI is validated by calling TryGetUri() that will return 'false' for strings that are not
00062         // valid WebSocket URIs.
00063         // Note that when enabling the text box users may provide URIs to machines on the intrAnet or intErnet. In
00064         // these cases the app requires the "Home or Work Networking" or "Internet (Client)" capability respectively.
00065         Uri^ server;
00066         if (!rootPage->TryGetUri(ServerAddressField->Text, &server))
00067         {
00068             return;
00069         }
00070
00071         rootPage->NotifyUser("Connecting to: " + server->DisplayUri, NotifyType::StatusMessage);
00072
00073         webSocket = ref new MessageWebSocket();
00074         webSocket->Control->MessageType = SocketMessageType::Utf8;
00075         webSocket->MessageReceived += ref new TypedEventHandler<MessageWebSocket^, MessageWebSocketMessageReceivedEventArgs^>(this, &Scenario1::MessageReceived);
00076         webSocket->Closed += ref new TypedEventHandler<IWebSocket^, WebSocketClosedEventArgs^>(this, &Scenario1::Closed);
00077
00078         task<void>(webSocket->ConnectAsync(server)).then([this, webSocket] (task<void> previousTask)
00079         {
00080             try
00081             {
00082                 // Try getting all exceptions from the continuation chain above this point.
00083                 previousTask.get();
00084
00085                 messageWebSocket = webSocket; // Only store it after successfully connecting.
00086                 messageWriter = ref new DataWriter(webSocket->OutputStream);
00087
00088                 rootPage->NotifyUser("Connected", NotifyType::StatusMessage);
00089                 SendMessage();
00090             }
00091             catch (Exception^ exception)
00092             {
00093                 HandleException(exception);
00094             }
00095         });
00096     }
00097     else
00098     {
00099         rootPage->NotifyUser("Already connected", NotifyType::StatusMessage);
00100         SendMessage();
00101     }
00102 }
00103
00104 void SDKSample::WebSocket::Scenario1::HandleException(Exception^ exception)
00105 {
00106     WebErrorStatus status = WebSocketError::GetStatus(exception->HResult);
00107
00108     if (status == WebErrorStatus::CannotConnect ||
00109         status == WebErrorStatus::NotFound ||
00110         status == WebErrorStatus::RequestTimeout)
00111     {
00112         rootPage->NotifyUser("Cannot connect to the server. Please make sure "
00113             "to run the server setup script before running the sample.", NotifyType::ErrorMessage);
00114     }
00115     else
00116     {
00117         rootPage->NotifyUser("Error: " + status.ToString(), NotifyType::ErrorMessage);
00118     }
00119
00120     OutputField->Text += exception->Message + "\r\n";
00121 }
00122
00123 void SDKSample::WebSocket::Scenario1::SendMessage()
00124 {
00125     String^ message = InputField->Text;
00126
00127     OutputField->Text += "Sending Message:\r\n" + message + "\r\n";
00128
00129     // Buffer any data we want to send.
00130     messageWriter->WriteString(message);
00131
00132     // Send the data as one complete message.
00133     task<unsigned int>(messageWriter->StoreAsync()).then([this] (unsigned int)
00134     {
00135         rootPage->NotifyUser("Send Complete", NotifyType::StatusMessage);
00136     }).then([this] (task<void> previousTask)
00137     {
00138         try
00139         {
00140             // Try getting all exceptions from the continuation chain above this point.
00141             previousTask.get();
00142         }
00143         catch (Exception^ exception)
00144         {
00145             HandleException(exception);
00146         }
00147     });
00148 }
00149
00150 void SDKSample::WebSocket::Scenario1::MessageReceived(MessageWebSocket^ sender, MessageWebSocketMessageReceivedEventArgs^ args)
00151 {
00152     MarshalText(OutputField, "Message Received; Type: " + args->MessageType.ToString() + "\r\n");
00153     DataReader^ reader = args->GetDataReader();
00154     reader->UnicodeEncoding = UnicodeEncoding::Utf8;
00155
00156     String^ read = reader->ReadString(reader->UnconsumedBufferLength);
00157     MarshalText(OutputField, read + "\r\n");
00158 }
00159
00160 void SDKSample::WebSocket::Scenario1::Close_Click(Object^ sender, RoutedEventArgs^ e)
00161 {
00162     try
00163     {
00164         if (messageWebSocket != nullptr)
00165         {
00166             rootPage->NotifyUser("Closing", NotifyType::StatusMessage);
00167             messageWebSocket->Close(1000, "Closed due to user request.");
00168             messageWebSocket = nullptr;
00169         }
00170         else
00171         {
00172             rootPage->NotifyUser("No active WebSocket, send something first", NotifyType::StatusMessage);
00173         }
00174     }
00175     catch (Exception^ exception)
00176     {
00177         HandleException(exception);
00178     }
00179 }
00180
00181 void SDKSample::WebSocket::Scenario1::Closed(IWebSocket^ sender, WebSocketClosedEventArgs^ args)
00182 {
00183     // The method may be triggered remotely by the server sending unsolicited close frame or locally by Close()/delete operator.
00184     // Dispatch the event to the UI thread so we do not need to synchronize access to messageWebSocket.
00185     Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, args] ()
00186     {
00187         OutputField->Text += "Closed; Code: " + args->Code.ToString() + ", Reason: " + args->Reason + "\r\n";
00188
00189         if (messageWebSocket != nullptr)
00190         {
00191             delete messageWebSocket;
00192             messageWebSocket = nullptr;
00193         }
00194     }));
00195 }
00196
00197 void SDKSample::WebSocket::Scenario1::MarshalText(TextBox^ output, String^ value)
00198 {
00199     MarshalText(output, value, true);
00200 }
00201
00202 // When operations happen on a background thread we have to marshal UI updates back to the UI thread.
00203 void SDKSample::WebSocket::Scenario1::MarshalText(TextBox^ output, String^ value, bool append)
00204 {
00205     Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, output, value, append] ()
00206     {
00207         if (append)
00208         {
00209             output->Text += value;
00210         }
00211         else
00212         {
00213             output->Text = value;
00214         }
00215     }));
00216 }
00217
Generated on Sat Nov 23 2024 16:07:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media capture using capture device/C++/AudioCapture.xaml.cpp Source File

  • Media capture using capture device

AudioCapture.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 // AudioCapture.xaml.cpp
00013 // Implementation of the AudioCapture class
00014 //
00015
00016 #include "pch.h"
00017 #include "AudioCapture.xaml.h"
00018 #include <ppl.h>
00019 using namespace concurrency;
00020
00021 using namespace SDKSample::MediaCapture;
00022
00023 using namespace Windows::UI::Xaml;
00024 using namespace Windows::UI::Xaml::Navigation;
00025 using namespace Windows::UI::Xaml::Data;
00026 using namespace Windows::System;
00027 using namespace Windows::Foundation;
00028 using namespace Platform;
00029 using namespace Windows::UI;
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::Data;
00034 using namespace Windows::UI::Xaml::Media;
00035 using namespace Windows::Storage;
00036 using namespace Windows::Media::MediaProperties;
00037 using namespace Windows::Storage::Streams;
00038 using namespace Windows::System;
00039 using namespace Windows::UI::Xaml::Media::Imaging;
00040
00041
00042 AudioCapture::AudioCapture()
00043 {
00044     InitializeComponent();
00045     ScenarioInit();
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 AudioCapture::OnNavigatedTo(NavigationEventArgs^ e)
00054 {
00055     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00056     // as NotifyUser()
00057     rootPage = MainPage::Current;
00058     m_eventRegistrationToken = Windows::Media::MediaControl::SoundLevelChanged += ref new EventHandler<Object^>(this, &AudioCapture::SoundLevelChanged);
00059 }
00060
00061 void AudioCapture::OnNavigatedFrom(NavigationEventArgs^ e)
00062 {
00063     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00064     // as NotifyUser()
00065     Windows::Media::MediaControl::SoundLevelChanged -= m_eventRegistrationToken;
00066 }
00067
00068 void  AudioCapture::ScenarioInit()
00069 {
00070     try
00071     {
00072         rootPage = MainPage::Current;
00073         btnStartDevice3->IsEnabled = true;
00074         btnStartStopRecord3->IsEnabled = false;
00075         m_bRecording = false;
00076         playbackElement3->Source = nullptr;
00077         m_bSuspended = false;
00078         ShowStatusMessage("");
00079     }
00080     catch (Exception ^e)
00081     {
00082         ShowExceptionMessage(e);
00083     }
00084
00085 }
00086
00087 void AudioCapture::ScenarioReset()
00088 {
00089     ScenarioInit();
00090 }
00091
00092
00093 void AudioCapture::SoundLevelChanged(Object^ sender, Object^ e)
00094 {
00095     create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([this]()
00096     {
00097         if(Windows::Media::MediaControl::SoundLevel != Windows::Media::SoundLevel::Muted)
00098         {
00099             ScenarioReset();
00100         }
00101         else
00102         {
00103             if (m_bRecording)
00104             {
00105                 ShowStatusMessage("Stopping Record on invisibility");
00106
00107                 create_task(m_mediaCaptureMgr->StopRecordAsync()).then([this](task<void> recordTask)
00108                 {
00109                     try
00110                     {
00111                         recordTask.get();
00112                         m_bRecording = false;
00113                     }catch (Exception ^e)
00114                     {
00115                         ShowExceptionMessage(e);
00116                     }
00117                 });
00118             }
00119         }
00120     })));
00121 }
00122
00123 void AudioCapture::RecordLimitationExceeded(Windows::Media::Capture::MediaCapture ^currentCaptureObject)
00124 {
00125     try
00126     {
00127         if (m_bRecording)
00128         {
00129             create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([this](){
00130                 try
00131                 {
00132                     ShowStatusMessage("Stopping Record on exceeding max record duration");
00133                     EnableButton(false, "StartStopRecord");
00134                     create_task(m_mediaCaptureMgr->StopRecordAsync()).then([this](task<void> recordTask)
00135                     {
00136                         try
00137                         {
00138                             recordTask.get();
00139                             m_bRecording = false;
00140                             SwitchRecordButtonContent();
00141                             EnableButton(true, "StartStopRecord");
00142                             ShowStatusMessage("Stopped record on exceeding max record duration:" + m_recordStorageFile->Path);
00143                         }
00144                         catch (Exception ^e)
00145                         {
00146                             ShowExceptionMessage(e);
00147                             m_bRecording = false;
00148                             SwitchRecordButtonContent();
00149                             EnableButton(true, "StartStopRecord");
00150                         }
00151                     });
00152
00153                 }
00154                 catch (Exception ^e)
00155                 {
00156                     m_bRecording = false;
00157                     SwitchRecordButtonContent();
00158                     EnableButton(true, "StartStopRecord");
00159                     ShowExceptionMessage(e);
00160                 }
00161
00162             })));
00163         }
00164     }
00165     catch (Exception ^e)
00166     {
00167         m_bRecording = false;
00168         SwitchRecordButtonContent();
00169         EnableButton(true, "StartStopRecord");
00170         ShowExceptionMessage(e);
00171     }
00172 }
00173
00174 void AudioCapture::Failed(Windows::Media::Capture::MediaCapture ^currentCaptureObject, Windows::Media::Capture::MediaCaptureFailedEventArgs^ currentFailure)
00175 {
00176     String ^message = "Fatal error: " + currentFailure->Message;
00177     create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High,
00178         ref new Windows::UI::Core::DispatchedHandler([this, message]()
00179     {
00180         ShowStatusMessage(message);
00181     })));
00182 }
00183
00184 void AudioCapture::btnStartDevice_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00185 {
00186     try
00187     {
00188         EnableButton(false, "StartDevice");
00189         ShowStatusMessage("Starting device");
00190         auto mediaCapture = ref new Windows::Media::Capture::MediaCapture();
00191         m_mediaCaptureMgr = mediaCapture;
00192         auto settings = ref new Windows::Media::Capture::MediaCaptureInitializationSettings();
00193         settings->StreamingCaptureMode = Windows::Media::Capture::StreamingCaptureMode::Audio;
00194         create_task(mediaCapture->InitializeAsync()).then([this](task<void> initTask)
00195         {
00196             try
00197             {
00198                 initTask.get();
00199
00200                 auto mediaCapture = m_mediaCaptureMgr.Get();
00201                 EnableButton(true, "StartPreview");
00202                 EnableButton(true, "StartStopRecord");
00203                 EnableButton(true, "TakePhoto");
00204                 ShowStatusMessage("Device initialized successful");
00205                 mediaCapture->RecordLimitationExceeded += ref new Windows::Media::Capture::RecordLimitationExceededEventHandler(this, &AudioCapture::RecordLimitationExceeded);
00206                 mediaCapture->Failed += ref new Windows::Media::Capture::MediaCaptureFailedEventHandler(this, &AudioCapture::Failed);
00207             }
00208             catch (Exception ^ e)
00209             {
00210                 ShowExceptionMessage(e);
00211             }
00212         });
00213     }
00214     catch (Platform::Exception^ e)
00215     {
00216         ShowExceptionMessage(e);
00217     }
00218 }
00219
00220 void AudioCapture::btnStartStopRecord_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00221 {
00222     try
00223     {
00224         String ^fileName;
00225         EnableButton(false, "StartStopRecord");
00226
00227         if (!m_bRecording)
00228         {
00229             ShowStatusMessage("Starting Record");
00230
00231             fileName = AUDIO_FILE_NAME;
00232
00233             task<StorageFile^>(KnownFolders::VideosLibrary->CreateFileAsync(fileName, Windows::Storage::CreationCollisionOption::GenerateUniqueName)).then([this](task<StorageFile^> fileTask)
00234             {
00235                 try
00236                 {
00237                     this->m_recordStorageFile = fileTask.get();
00238                     ShowStatusMessage("Create record file successful");
00239
00240                     MediaEncodingProfile^ recordProfile= nullptr;
00241                     recordProfile = MediaEncodingProfile::CreateM4a(Windows::Media::MediaProperties::AudioEncodingQuality::Auto);
00242
00243                     create_task(m_mediaCaptureMgr->StartRecordToStorageFileAsync(recordProfile, this->m_recordStorageFile)).then([this](task<void> recordTask)
00244                     {
00245                         try
00246                         {
00247                             recordTask.get();
00248                             m_bRecording = true;
00249                             SwitchRecordButtonContent();
00250                             EnableButton(true, "StartStopRecord");
00251
00252                             ShowStatusMessage("Start Record successful");
00253
00254
00255                         }catch (Exception ^e)
00256                         {
00257                             ShowExceptionMessage(e);
00258                             m_bRecording = false;
00259                             SwitchRecordButtonContent();
00260                             EnableButton(true, "StartStopRecord");
00261                         }
00262                     });
00263                 }
00264                 catch (Exception ^e)
00265                 {
00266                     m_bRecording = false;
00267                     SwitchRecordButtonContent();
00268                     EnableButton(true, "StartStopRecord");
00269                     ShowExceptionMessage(e);
00270                 }
00271             }
00272             );
00273         }
00274         else
00275         {
00276             ShowStatusMessage("Stopping Record");
00277
00278             create_task(m_mediaCaptureMgr->StopRecordAsync()).then([this](task<void>)
00279             {
00280                 try
00281                 {
00282                     m_bRecording = false;
00283                     EnableButton(true, "StartStopRecord");
00284                     SwitchRecordButtonContent();
00285
00286                     ShowStatusMessage("Stop record successful");
00287                     if (!m_bSuspended)
00288                     {
00289                         task<IRandomAccessStream^>(this->m_recordStorageFile->OpenAsync(FileAccessMode::Read)).then([this](task<IRandomAccessStream^> streamTask)
00290                         {
00291                             try
00292                             {
00293                                 ShowStatusMessage("Record file opened");
00294                                 auto stream = streamTask.get();
00295                                 ShowStatusMessage(this->m_recordStorageFile->Path);
00296                                 playbackElement3->AutoPlay = true;
00297                                 playbackElement3->SetSource(stream, this->m_recordStorageFile->FileType);
00298                                 playbackElement3->Play();
00299                             }
00300                             catch (Exception ^e)
00301                             {
00302                                 ShowExceptionMessage(e);
00303                                 m_bRecording = false;
00304                                 SwitchRecordButtonContent();
00305                                 EnableButton(true, "StartStopRecord");
00306                             }
00307                         });
00308                     }
00309                 }
00310                 catch (Exception ^e)
00311                 {
00312                     m_bRecording = false;
00313                     SwitchRecordButtonContent();
00314                     EnableButton(true, "StartStopRecord");
00315                     ShowExceptionMessage(e);
00316                 }
00317             });
00318         }
00319     }
00320     catch (Platform::Exception^ e)
00321     {
00322         EnableButton(true, "StartStopRecord");
00323         ShowExceptionMessage(e);
00324         m_bRecording = false;
00325         SwitchRecordButtonContent();
00326     }
00327 }
00328
00329
00330 void AudioCapture::ShowStatusMessage(Platform::String^ text)
00331 {
00332     rootPage->NotifyUser(text, NotifyType::StatusMessage);
00333 }
00334
00335 void AudioCapture::ShowExceptionMessage(Platform::Exception^ ex)
00336 {
00337     rootPage->NotifyUser(ex->Message, NotifyType::ErrorMessage);
00338 }
00339
00340 void AudioCapture::SwitchRecordButtonContent()
00341 {
00342     {
00343         if (m_bRecording)
00344         {
00345             btnStartStopRecord3->Content="StopRecord";
00346         }
00347         else
00348         {
00349             btnStartStopRecord3->Content="StartRecord";
00350         }
00351     }
00352 }
00353 void AudioCapture::EnableButton(bool enabled, String^ name)
00354 {
00355     if (name->Equals("StartDevice"))
00356     {
00357         btnStartDevice3->IsEnabled = enabled;
00358     }
00359
00360     else if (name->Equals("StartStopRecord"))
00361     {
00362         btnStartStopRecord3->IsEnabled = enabled;
00363     }
00364
00365 }
00366
Generated on Sat Nov 23 2024 16:08:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Custom driver access/C++/app_cpp/Scenario1_DeviceConnect.xaml.h Source File

  • Custom driver access
  • app_cpp

Scenario1_DeviceConnect.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 // DeviceConnect.xaml.h
00013 // Declaration of the DeviceConnect class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario1_DeviceConnect.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace CustomDeviceAccess
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 DeviceConnect sealed
00031         {
00032         public:
00033             DeviceConnect();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void deviceConnectStart_Click_1(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040             void deviceConnectStop_Click_1(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041             void deviceConnectDevices_SelectionChanged_1(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00042
00043             void UpdateStartStopButtons(void);
00044
00045             void OpenFx2Device(Platform::String^ Id);
00046             void CloseFx2Device(void);
00047         };
00048     }
00049 }
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D convolve matrix effect/C++/pch.h Source File

  • Direct2D convolve matrix effect

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 <d3d11_1.h>
00012 #include <d2d1_1.h>
00013 #include <d2d1effects.h>
00014 #include <dwrite_1.h>
00015 #include <wincodec.h>
00016 #include <agile.h>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX marble maze game/C++/PersistentState.cpp Source File

  • DirectX marble maze game

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 Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Push and periodic notifications client-side/C++/MainPage.xaml.h Source File

  • Push and periodic notifications client-side

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D tutorial/C++/Lesson5.Components/DirectXApp.h Source File

  • Direct3D tutorial
  • Lesson5.Components

DirectXApp.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 "Direct3DTutorial.h"
00011
00012 ref class DirectXApp : public Windows::ApplicationModel::Core::IFrameworkView
00013 {
00014 internal:
00015     DirectXApp();
00016
00017 public:
00018     // IFrameworkView Methods
00019     virtual void Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00020     virtual void SetWindow(_In_ Windows::UI::Core::CoreWindow^ window);
00021     virtual void Load(_In_ Platform::String^ entryPoint);
00022     virtual void Run();
00023     virtual void Uninitialize();
00024
00025 private:
00026     // Event Handlers
00027     void OnWindowSizeChanged(
00028         _In_ Windows::UI::Core::CoreWindow^ sender,
00029         _In_ Windows::UI::Core::WindowSizeChangedEventArgs^ args
00030         );
00031
00032     void OnVisibilityChanged(
00033         _In_ Windows::UI::Core::CoreWindow^ sender,
00034         _In_ Windows::UI::Core::VisibilityChangedEventArgs^ args
00035         );
00036
00037     void OnLogicalDpiChanged(
00038         _In_ Platform::Object^ sender
00039         );
00040
00041     void OnActivated(
00042         _In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView,
00043         _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^ args
00044         );
00045
00046     void OnWindowClosed(
00047         _In_ Windows::UI::Core::CoreWindow^ sender,
00048         _In_ Windows::UI::Core::CoreWindowEventArgs^ args
00049         );
00050
00051     Direct3DTutorial^ m_renderer;
00052     bool m_windowClosed;
00053     bool m_windowVisible;
00054 };
00055
00056 ref class DirectXAppSource : Windows::ApplicationModel::Core::IFrameworkViewSource
00057 {
00058 public:
00059     virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00060 };
Generated on Sat Nov 23 2024 16:08:07 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX postcard app/C++/BasicReaderWriter.h Source File

  • DirectX postcard app

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     Platform::String^ m_locationPath;
00019
00020 internal:
00021     BasicReaderWriter();
00022     BasicReaderWriter(
00023         _In_ Windows::Storage::StorageFolder^ folder
00024         );
00025
00026     Platform::Array<byte>^ ReadData(
00027         _In_ Platform::String^ filename
00028         );
00029
00030     concurrency::task<Platform::Array<byte>^> ReadDataAsync(
00031         _In_ Platform::String^ filename
00032         );
00033
00034     uint32 WriteData(
00035         _In_ Platform::String^ filename,
00036         _In_ const Platform::Array<byte>^ fileData
00037         );
00038
00039     concurrency::task<void> WriteDataAsync(
00040         _In_ Platform::String^ filename,
00041         _In_ const Platform::Array<byte>^ fileData
00042         );
00043 };
Generated on Sat Nov 23 2024 16:08:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAudio2 audio file playback/C++/RandomAccessReader.h Source File

  • XAudio2 audio file playback

RandomAccessReader.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 class that provides support for random access to files.
00011 ref class RandomAccessReader
00012 {
00013 internal:
00014     RandomAccessReader(_In_ Platform::String^ fileName);
00015
00016     Platform::Array<byte>^ Read(_In_ size_t bytesToRead);
00017
00018     void SeekRelative(_In_ int64 offset);
00019     void SeekAbsolute(_In_ int64 position);
00020     void SeekToStart();
00021     void SeekToEnd();
00022
00023     uint64 GetFileSize();
00024     uint64 GetPosition();
00025
00026 private:
00027     Microsoft::WRL::Wrappers::FileHandle    m_file;
00028 };
Generated on Sat Nov 23 2024 16:08:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Mobile broadband account provisioning/C++/Constants.h Source File

  • Mobile broadband account provisioning

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"Provisioning Agent");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044
00045
00046 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML personality animations/C++/MainPage.xaml.cpp Source File

  • XAML personality animations

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Background Transfer/C++/common/suspensionmanager.h Source File

  • Background Transfer
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Hilo::RandomPhotoSelector Member List

This is the complete list of members for Hilo::RandomPhotoSelector, including all inherited members.
CreateRandomizedVector(unsigned int vectorSize, unsigned int sampleSize) | Hilo::RandomPhotoSelector | [static]
SelectFilesAsync(Windows::Foundation::Collections::IVectorView< Windows::Storage::StorageFile^>^photos, unsigned int count) | Hilo::RandomPhotoSelector | [static]
Generated on Sat Nov 23 2024 16:09:39 for Win8-Examples by doxygen 1.7.1


Win8-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 Sat Nov 23 2024 16:09:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D-Direct2D interop/C++/BasicLoader.cpp Source File

  • Direct3D-Direct2D interop

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 Sat Nov 23 2024 16:08:07 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Message dialog/C++/common/suspensionmanager.cpp Source File

  • Message dialog
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:37 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Device auto rotation preferences/C++/MainPage.xaml.cpp Source File

  • Device auto rotation preferences

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:41 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Scaling according to DPI/C++/Scenario1.xaml.cpp Source File

  • Scaling according to DPI

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::Scaling;
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     DisplayProperties::LogicalDpiChanged += ref new DisplayPropertiesEventHandler(this, &Scenario1::DisplayProperties_LogicalDpiChanged);
00034
00035     String^ baseUri = ManualLoadImage->BaseUri->AbsoluteUri;
00036     image100 = ref new BitmapImage(ref new Uri(baseUri, "Assets/projector.scale-100.png"));
00037     image140 = ref new BitmapImage(ref new Uri(baseUri, "Assets/projector.scale-140.png"));
00038     image180 = ref new BitmapImage(ref new Uri(baseUri, "Assets/projector.scale-180.png"));
00039 }
00040
00041 String^ Scenario1::GetMinDPI()
00042 {
00043     Platform::String^ minDPI = "";
00044     switch (DisplayProperties::ResolutionScale)
00045     {
00046     case ResolutionScale::Invalid:
00047         minDPI = "Unknown";
00048         break;
00049     case ResolutionScale::Scale100Percent:
00050         minDPI = "No minimum DPI for this scale";
00051         break;
00052     case ResolutionScale::Scale140Percent:
00053         minDPI = "174 DPI";
00054         break;
00055     case ResolutionScale::Scale180Percent:
00056         minDPI = "240 DPI";
00057         break;
00058     }
00059
00060     return minDPI;
00061 }
00062
00063 String^ Scenario1::GetMinResolution()
00064 {
00065     Platform::String^ minRes = "";
00066     switch (DisplayProperties::ResolutionScale)
00067     {
00068     case ResolutionScale::Invalid:
00069         minRes = "Unknown";
00070         break;
00071     case ResolutionScale::Scale100Percent:
00072         minRes = "1024x768 (min resolution needed to run apps)";
00073         break;
00074     case ResolutionScale::Scale140Percent:
00075         minRes = "1920x1080";
00076         break;
00077     case ResolutionScale::Scale180Percent:
00078         minRes = "2560x1440";
00079         break;
00080     }
00081
00082     return minRes;
00083 }
00084
00085 void Scenario1::SetManualLoadImage()
00086 {
00087     switch (DisplayProperties::ResolutionScale)
00088     {
00089     default:
00090     case ResolutionScale::Scale100Percent:
00091         ManualLoadImage->Source = image100;
00092         break;
00093     case ResolutionScale::Scale140Percent:
00094         ManualLoadImage->Source = image140;
00095         break;
00096     case ResolutionScale::Scale180Percent:
00097         ManualLoadImage->Source = image180;
00098         break;
00099     }
00100 }
00101
00102 void Scenario1::ResetOutput()
00103 {
00104     ScalingText->Text = (DisplayProperties::LogicalDpi * PERCENT / DEFAULT_LOGICALPPI).ToString() + "%";
00105     MinDPIText->Text = GetMinDPI();
00106     MinScreenResolutionText->Text = GetMinResolution();
00107     LogicalDPIText->Text = DisplayProperties::LogicalDpi.ToString() + " DPI";
00108     SetManualLoadImage();
00109 }
00110
00111 void Scenario1::OnNavigatedTo(NavigationEventArgs^ e)
00112 {
00113     ResetOutput();
00114 }
00115
00116 void Scenario1::DisplayProperties_LogicalDpiChanged(Object^ sender)
00117 {
00118     ResetOutput();
00119 }
Generated on Sat Nov 23 2024 16:07:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: AtomPub/C++/Scenario2.xaml.cpp Source File

  • AtomPub

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 SDKSample::AtomPub;
00020
00021 using namespace Windows::UI::Xaml::Controls;
00022 using namespace Windows::Foundation;
00023 using namespace Windows::Web::Syndication;
00024 using namespace Concurrency;
00025
00026 Scenario2::Scenario2()
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 Scenario2::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     CommonData::Restore(this);
00043 }
00044
00045 void Scenario2::OnNavigatingFrom(NavigatingCancelEventArgs^ e)
00046 {
00047     CommonData::Save(ServiceAddressField->Text, UserNameField->Text, PasswordField->Password);
00048 }
00049
00050 // Submit an item.
00051 void Scenario2::SubmitItem_Click(Object^ sender, RoutedEventArgs^ e)
00052 {
00053     OutputField->Text = "";
00054
00055     // The title cannot be an empty string or a string with white spaces only, since it is used also
00056     // as the resource description (Slug header).
00057     if (StringHelper::Trim(TitleField->Text) == "")
00058     {
00059         rootPage->NotifyUser("Post title cannot be blank.", NotifyType::ErrorMessage);
00060         return;
00061     }
00062
00063     // Since the value of 'ServiceAddressField' was provided by the user it is untrusted input. We'll validate it
00064     // by using TryGetUri().
00065     // Note that this app has both "Internet (Client)" and "Home and Work Networking" capabilities set, since
00066     // the user may provide URIs for servers located on the intErnet or intrAnet. If apps only communicate
00067     // with servers on the intErnet, only the "Internet (Client)" capability should be set. Similarly if an
00068     // app is only intended to communicate on the intrAnet, only the "Home and Work Networking" capability should be set.
00069     Uri^ serviceUri;
00070     if (!rootPage->TryGetUri(StringHelper::Trim(ServiceAddressField->Text) + CommonData::ServiceDocUri, &serviceUri))
00071     {
00072         return;
00073     }
00074
00075     rootPage->NotifyUser("Performing operation...", NotifyType::StatusMessage);
00076     OutputField->Text = "Fetching Service document: " + serviceUri->DisplayUri + "\r\n";
00077
00078     task<ServiceDocument^>(CommonData::GetClient()->RetrieveServiceDocumentAsync(serviceUri)).then([this] (ServiceDocument^ serviceDocument)
00079     {
00080         // The result here is usually the same as:
00081         // Uri resourceUri = new Uri(StringHelper::Trim(ServiceAddressField->Text) + Common->EditUri);
00082         // Note that this app has both "Internet (Client)" and "Home and Work Networking" capabilities set, since
00083         // the user may provide URIs for servers located on the intErnet or intrAnet. If apps only communicate
00084         // with servers on the intErnet, the "Home or Work Networking" capability should not be set.
00085         Uri^ resourceUri = FindEditUri(serviceDocument);
00086         if (resourceUri == nullptr)
00087         {
00088             cancel_current_task();
00089         }
00090
00091         OutputField->Text += "Uploading Post: " + resourceUri->DisplayUri + "\r\n";
00092
00093         SyndicationItem^ item = ref new SyndicationItem();
00094         item->Title = ref new SyndicationText(TitleField->Text, SyndicationTextType::Text);
00095         item->Content = ref new SyndicationContent(ContentField->Text, SyndicationTextType::Html);
00096
00097         return CommonData::GetClient()->CreateResourceAsync(resourceUri, item->Title->Text, item);
00098     }).then([this] (SyndicationItem^ result)
00099     {
00100         rootPage->NotifyUser("New post created.", NotifyType::StatusMessage);
00101         OutputField->Text += "Posted at " + result->ItemUri->DisplayUri + "\r\n";
00102     }).then([this] (task<void> t)
00103     {
00104         try
00105         {
00106             t.get();
00107         }
00108         catch (task_canceled&)
00109         {
00110             rootPage->NotifyUser("URI not found in service document.", NotifyType::ErrorMessage);
00111         }
00112         catch (Exception^ exception)
00113         {
00114             if (!rootPage->HandleException(exception, OutputField))
00115             {
00116                 throw;
00117             }
00118         }
00119     });
00120 }
00121
00122 // Read the service document to find the URI we're supposed to use when uploading content.
00123 Uri^ Scenario2::FindEditUri(ServiceDocument^ serviceDocument)
00124 {
00125     for (unsigned int i = 0; i < serviceDocument->Workspaces->Size; i++)
00126     {
00127         Workspace^ workspace = serviceDocument->Workspaces->GetAt(i);
00128
00129         for (unsigned int j = 0; j < workspace->Collections->Size; j++)
00130         {
00131             ResourceCollection^ collection = workspace->Collections->GetAt(j);
00132
00133             if (StringHelper::Join(";", collection->Accepts) == "application/atom+xml;type=entry")
00134             {
00135                 return collection->Uri;
00136             }
00137         }
00138     }
00139
00140     return nullptr;
00141 }
00142
00143 void Scenario2::UserNameField_TextChanged(Object^ sender, TextChangedEventArgs^ e)
00144 {
00145     CommonData::Save(ServiceAddressField->Text, UserNameField->Text, PasswordField->Password);
00146 }
00147
00148 void Scenario2::PasswordField_PasswordChanged(Object^ sender, RoutedEventArgs^ e)
00149 {
00150     CommonData::Save(ServiceAddressField->Text, UserNameField->Text, PasswordField->Password);
00151 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKANIMATION_DATA Member List

This is the complete list of members for SDKANIMATION_DATA, including all inherited members.
Orientation | SDKANIMATION_DATA
Scaling | SDKANIMATION_DATA
Translation | SDKANIMATION_DATA
Generated on Sat Nov 23 2024 16:09:21 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Portable device API/C++/common/LayoutAwarePage.h Source File

  • Portable device API
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: PlayToReceiver/C++/audiovideoptr.xaml.cpp Source File

  • PlayToReceiver

audiovideoptr.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 <string.h>
00018 #include "AudioVideoPTR.xaml.h"
00019
00020 using namespace SDKSample::PlayToreceiver;
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::Foundation;
00026 using namespace Windows::UI::Core;
00027 using namespace Platform;
00028 using namespace Windows::UI::Xaml::Media;
00029 Scenario1^ g_this;
00030
00031 Scenario1::Scenario1():receiver(nullptr)
00032 {
00033     InitializeComponent();
00034     g_this = this;
00035     IsReceiverStarted = false;
00036     IsSeeking = false;
00037     bufferedPlaybackRate = 0;
00038     IsMediaJustLoaded = false;
00039     currentType = MediaType::None;
00040     imageRecd = nullptr;
00041     IsPlayReceivedPreMediaLoaded = false;
00042     InitialisePlayToReceiver();
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 void Scenario1::OnNavigatedTo(NavigationEventArgs^ e)
00051 {
00052     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00053     // as NotifyUser()
00054     rootPage = MainPage::Current;
00055 }
00056
00057 void Scenario1::InitialisePlayToReceiver()
00058 {
00059     try
00060     {
00061         Windows::Media::PlayTo::PlayToReceiver^ localReceiver = ref new Windows::Media::PlayTo::PlayToReceiver();
00062         localReceiver->PlayRequested += ref new TypedEventHandler<PlayToReceiver^, Object^>(this, &Scenario1::receiver_PlayRequested);
00063         localReceiver->PauseRequested += ref new TypedEventHandler<PlayToReceiver^, Object^>(this, &Scenario1::receiver_PauseRequested);
00064         localReceiver->StopRequested += ref new TypedEventHandler<PlayToReceiver^, Object^>(this, &Scenario1::receiver_StopRequested);
00065         localReceiver->TimeUpdateRequested += ref new TypedEventHandler<PlayToReceiver^, Object^>(this, &Scenario1::receiver_TimeUpdateRequested);
00066         localReceiver->CurrentTimeChangeRequested += ref new TypedEventHandler<PlayToReceiver^, CurrentTimeChangeRequestedEventArgs^>(this, &Scenario1::receiver_CurrentTimeChangeRequested);
00067         localReceiver->SourceChangeRequested += ref new TypedEventHandler<PlayToReceiver^, SourceChangeRequestedEventArgs^>(this, &Scenario1::receiver_SourceChangeRequested);
00068         localReceiver->MuteChangeRequested += ref new TypedEventHandler<PlayToReceiver^, MuteChangeRequestedEventArgs^>(this, &Scenario1::receiver_MuteChangeRequested);
00069         localReceiver->PlaybackRateChangeRequested += ref new TypedEventHandler<PlayToReceiver^, PlaybackRateChangeRequestedEventArgs^>(this, &Scenario1::receiver_PlaybackRateChangeRequested);
00070         localReceiver->VolumeChangeRequested += ref new TypedEventHandler<PlayToReceiver^, VolumeChangeRequestedEventArgs^>(this, &Scenario1::receiver_VolumeChangeRequestedEvent);
00071
00072         localReceiver->SupportsAudio = true;
00073         localReceiver->SupportsVideo = true;
00074         localReceiver->SupportsImage = true;
00075
00076         localReceiver->FriendlyName = "SDK CPP Sample PlayToReceiver";
00077         receiver = localReceiver;
00078     }
00079     catch(Platform::Exception^ e)
00080     {
00081         startDMRButton->IsEnabled = false;
00082         stopDMRButton->IsEnabled = true;
00083         rootPage->NotifyUser("PlayToReceiver Initialization failed, Error: " + e->Message, NotifyType::ErrorMessage);
00084     }
00085 }
00086
00087 void Scenario1::startPlayToReceiver(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00088 {
00089     try
00090     {
00091         startDMRButton->IsEnabled = false;
00092         stopDMRButton->IsEnabled = true;
00093         IAsyncAction^ startoperation = receiver->StartAsync();
00094         startoperation->Completed = ref new AsyncActionCompletedHandler([=](IAsyncInfo^ asyncInfo, AsyncStatus /**/)
00095         {
00096             IsReceiverStarted = true;
00097             auto handler = ref new DispatchedHandler(
00098             []()
00099             {
00100                 g_this->rootPage->NotifyUser("PlayToReceiver started", NotifyType::StatusMessage);
00101             },CallbackContext::Any);
00102             g_this->Dispatcher->RunAsync(CoreDispatcherPriority::High,handler);
00103         });
00104     }
00105     catch(Platform::Exception^ e)
00106     {
00107         IsReceiverStarted = false;
00108         startDMRButton->IsEnabled = true;
00109         stopDMRButton->IsEnabled = false;
00110         rootPage->NotifyUser("PlayToReceiver start failed, Error: " + e->Message, NotifyType::ErrorMessage);
00111     }
00112 }
00113
00114 void Scenario1::stopPlayToReceiver(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00115 {
00116
00117     Windows::Media::PlayTo::PlayToReceiver^ localReceiver = receiver.Get();
00118     if(localReceiver != nullptr)
00119     {
00120         try
00121         {
00122             startDMRButton->IsEnabled = true;
00123             stopDMRButton->IsEnabled = false;
00124             IAsyncAction^ stopoperation = localReceiver->StopAsync();
00125             stopoperation->Completed = ref new AsyncActionCompletedHandler([=](IAsyncInfo^ asyncInfo, AsyncStatus /**/)
00126             {
00127                 g_this->IsReceiverStarted = true;
00128                 auto handler = ref new DispatchedHandler(
00129                 []()
00130                 {
00131                     g_this->rootPage->NotifyUser("PlayToReceiver stopped", NotifyType::StatusMessage);
00132                 },CallbackContext::Any);
00133                 g_this->Dispatcher->RunAsync(CoreDispatcherPriority::High,handler);
00134             });
00135         }
00136         catch(Platform::Exception^ e)
00137         {
00138             startDMRButton->IsEnabled = false;
00139             stopDMRButton->IsEnabled = true;
00140             rootPage->NotifyUser("PlayToReceiver stop failed, Error: " + e->Message, NotifyType::ErrorMessage);
00141         }
00142     }
00143 }
00144
00145 void Scenario1::dmrVideo_VolumeChanged(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00146 {
00147     if(IsReceiverStarted)
00148     {
00149         receiver->NotifyVolumeChange(dmrVideo->Volume, dmrVideo->IsMuted);
00150     }
00151 }
00152
00153
00154 void Scenario1::dmrVideo_RateChanged(Platform::Object^ sender, Windows::UI::Xaml::Media::RateChangedRoutedEventArgs^ e)
00155 {
00156     if(IsReceiverStarted)
00157     {
00158         receiver->NotifyRateChange(dmrVideo->PlaybackRate);
00159     }
00160 }
00161
00162
00163 void Scenario1::dmrVideo_MediaOpened(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00164 {
00165     if(IsReceiverStarted)
00166     {
00167         receiver->NotifyLoadedMetadata();
00168         receiver->NotifyDurationChange(dmrVideo->NaturalDuration.TimeSpan);
00169         if(IsPlayReceivedPreMediaLoaded == true)
00170         {
00171             dmrVideo->Play();
00172         }
00173     }
00174 }
00175
00176
00177 void Scenario1::dmrVideo_CurrentStateChanged(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00178 {
00179     if(IsReceiverStarted)
00180     {
00181         switch (dmrVideo->CurrentState)
00182         {
00183         case MediaElementState::Playing:
00184             receiver->NotifyPlaying();
00185             break;
00186         case MediaElementState::Paused:
00187             if(IsMediaJustLoaded)
00188             {
00189                 receiver->NotifyStopped();
00190                 IsMediaJustLoaded = false;
00191             }
00192             else
00193             {
00194                 receiver->NotifyPaused();
00195             }
00196             break;
00197         case MediaElementState::Stopped:
00198             receiver->NotifyStopped();
00199             break;
00200         default:
00201             break;
00202         }
00203     }
00204 }
00205
00206
00207 void Scenario1::dmrVideo_MediaEnded(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00208 {
00209     if(IsReceiverStarted)
00210     {
00211         receiver->NotifyEnded();
00212         if(dmrVideo != nullptr)
00213             dmrVideo->Stop();
00214     }
00215 }
00216
00217
00218 void Scenario1::dmrVideo_MediaFailed(Platform::Object^ sender, Windows::UI::Xaml::ExceptionRoutedEventArgs^ e)
00219 {
00220     if(IsReceiverStarted)
00221     {
00222         receiver->NotifyError();
00223     }
00224 }
00225
00226
00227 void Scenario1::dmrVideo_SeekCompleted(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00228 {
00229     if(IsReceiverStarted)
00230     {
00231         if(!IsSeeking)
00232             receiver->NotifySeeking();
00233         receiver->NotifySeeked();
00234         IsSeeking = false;
00235     }
00236 }
00237
00238 void Scenario1::receiver_PlayRequested(PlayToReceiver^ , Object^ args)
00239 {
00240     auto handler = ref new DispatchedHandler(
00241         [this, args]()
00242         {
00243             if(dmrVideo != nullptr && currentType == MediaType::AudioVisual)
00244             {
00245                 IsPlayReceivedPreMediaLoaded = true;
00246                 dmrVideo->Play();
00247             }
00248             else if(currentType == MediaType::Image && dmrImage != nullptr)
00249             {
00250                 dmrImage->Source = imageRecd;
00251                 receiver->NotifyPlaying();
00252             }
00253         },CallbackContext::Any);
00254
00255     Dispatcher->RunAsync(CoreDispatcherPriority::High,handler);
00256 }
00257
00258 void Scenario1::receiver_PauseRequested(PlayToReceiver^ , Object^ args)
00259 {
00260     auto handler = ref new DispatchedHandler(
00261         [this, args]()
00262         {
00263             if(dmrVideo != nullptr && currentType == MediaType::AudioVisual)
00264             {
00265                 if(dmrVideo->CurrentState == MediaElementState::Stopped)
00266                 {
00267                     receiver->NotifyPaused();
00268                 }
00269                 else
00270                 {
00271                     dmrVideo->Pause();
00272                 }
00273             }
00274         },CallbackContext::Any);
00275
00276     Dispatcher->RunAsync(CoreDispatcherPriority::High,handler);
00277 }
00278
00279 void Scenario1::receiver_StopRequested(PlayToReceiver^ , Object^ args)
00280 {
00281     auto handler = ref new DispatchedHandler(
00282         [this, args]()
00283         {
00284             if(dmrVideo != nullptr && currentType == MediaType::AudioVisual)
00285             {
00286                 receiver->NotifyStopped();
00287                 dmrVideo->Stop();
00288             }
00289             else if (dmrImage != nullptr && currentType == MediaType::Image)
00290             {
00291                 dmrImage->Source = nullptr;
00292                 receiver->NotifyStopped();
00293             }
00294         },CallbackContext::Any);
00295
00296     Dispatcher->RunAsync(CoreDispatcherPriority::High,handler);
00297 }
00298
00299 void Scenario1::receiver_TimeUpdateRequested(PlayToReceiver^ , Object^ args)
00300 {
00301     auto handler = ref new DispatchedHandler(
00302         [this, args]()
00303         {
00304             if(g_this->IsReceiverStarted)
00305             {
00306                 if(dmrVideo != nullptr && currentType == MediaType::AudioVisual)
00307                 {
00308                     receiver->NotifyTimeUpdate(dmrVideo->Position);
00309                 }
00310                 else if (currentType == MediaType::Image)
00311                 {
00312                     __int64 timeSpaninMilliseconds = 0;
00313                     TimeSpan ts = {0};
00314                     receiver->NotifyTimeUpdate(ts);
00315                 }
00316             }
00317         },CallbackContext::Any);
00318
00319     Dispatcher->RunAsync(CoreDispatcherPriority::High,handler);
00320 }
00321
00322 void Scenario1::receiver_CurrentTimeChangeRequested(PlayToReceiver^, CurrentTimeChangeRequestedEventArgs^ args)
00323 {
00324     auto handler = ref new DispatchedHandler(
00325         [this, args]()
00326         {
00327             if(g_this->IsReceiverStarted )
00328             {
00329                 if(dmrVideo != nullptr && currentType == MediaType::AudioVisual)
00330                 {
00331                     if(dmrVideo->CanSeek)
00332                     {
00333
00334                         dmrVideo->Position = args->Time;
00335                         receiver->NotifySeeking();
00336                         IsSeeking = true;
00337
00338                     }
00339                 }
00340                 else if(currentType == MediaType::Image)
00341                 {
00342                     receiver->NotifySeeking();
00343                     receiver->NotifySeeked();
00344                 }
00345             }
00346         },CallbackContext::Any);
00347
00348     Dispatcher->RunAsync(CoreDispatcherPriority::High,handler);
00349 }
00350
00351 void Scenario1::btmapImage_ImageOpened(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00352 {
00353     receiver->NotifyLoadedMetadata();
00354 }
00355
00356 void Scenario1::receiver_SourceChangeRequested(PlayToReceiver^, SourceChangeRequestedEventArgs^ args)
00357 {
00358     auto handler = ref new DispatchedHandler(
00359     [this, args]()
00360     {
00361         String^ imgstr = "image";
00362         IsPlayReceivedPreMediaLoaded = false;
00363         if(args->Stream == nullptr)
00364         {
00365             if(currentType == MediaType::AudioVisual)
00366             {
00367                 dmrVideo->Stop();
00368             }
00369             else if (currentType == MediaType::Image)
00370             {
00371                 dmrImage->Source = nullptr;
00372                 dmrImage->Opacity = 0;
00373             }
00374             currentType = MediaType::None;
00375         }
00376         else if(!FindStringOrdinal(FIND_FROMSTART,args->Stream->ContentType->Data(), args->Stream->ContentType->Length(), imgstr->Data(),imgstr->Length(),TRUE))
00377         {
00378             imageRecd = ref new BitmapImage();
00379             imageRecd->ImageOpened += ref new RoutedEventHandler(this, &Scenario1::btmapImage_ImageOpened);
00380             imageRecd->SetSource(args->Stream);
00381             if(currentType != MediaType::Image)
00382             {
00383                 if(currentType == MediaType::AudioVisual)
00384                 {
00385                     dmrVideo->Stop();
00386                 }
00387                 dmrImage->Opacity = 1;
00388                 dmrVideo->Opacity = 0;
00389             }
00390             currentType = MediaType::Image;
00391         }
00392         else
00393         {
00394             if(dmrVideo != nullptr)
00395             {
00396                 try
00397                 {
00398                     IsMediaJustLoaded = true;
00399                     dmrVideo->SetSource(args->Stream, args->Stream->ContentType);
00400                 }
00401                 catch(Exception^ e)
00402                 {
00403                     rootPage->NotifyUser(e->Message->ToString() + " Content Type: " + args->Stream->ContentType, NotifyType::ErrorMessage);
00404                 }
00405             }
00406             if(currentType == MediaType::Image)
00407             {
00408                 dmrImage->Opacity = 0;
00409                 if(dmrVideo != nullptr)
00410                 {
00411                     dmrVideo->Opacity = 1;
00412                 }
00413                 dmrImage->Source = nullptr;
00414             }
00415             currentType = MediaType::AudioVisual;
00416         }
00417     },CallbackContext::Any);
00418
00419     Dispatcher->RunAsync(CoreDispatcherPriority::High,handler);
00420 }
00421
00422
00423 void Scenario1::receiver_MuteChangeRequested(PlayToReceiver^, MuteChangeRequestedEventArgs^ args)
00424 {
00425     auto handler = ref new DispatchedHandler(
00426         [this, args]()
00427         {
00428             if(dmrVideo != nullptr && currentType == MediaType::AudioVisual)
00429             {
00430                 dmrVideo->IsMuted = args->Mute;
00431             }
00432             else if(currentType == MediaType::Image)
00433             {
00434                 receiver->NotifyVolumeChange(0, args->Mute);
00435             }
00436         },CallbackContext::Any);
00437
00438     Dispatcher->RunAsync(CoreDispatcherPriority::High,handler);
00439 }
00440
00441
00442 void Scenario1::receiver_PlaybackRateChangeRequested(PlayToReceiver^, PlaybackRateChangeRequestedEventArgs^ args)
00443 {
00444     auto handler = ref new DispatchedHandler(
00445         [this, args]()
00446         {
00447             if(dmrVideo != nullptr && MediaType::AudioVisual == currentType)
00448             {
00449                 if(dmrVideo->CurrentState != MediaElementState::Opening && dmrVideo->CurrentState != MediaElementState::Closed)
00450                 {
00451                     dmrVideo->PlaybackRate = args->Rate;
00452                 }
00453                 else
00454                 {
00455                     bufferedPlaybackRate = args->Rate;
00456                 }
00457             }
00458         },CallbackContext::Any);
00459
00460     Dispatcher->RunAsync(CoreDispatcherPriority::High,handler);
00461 }
00462
00463
00464 void Scenario1::receiver_VolumeChangeRequestedEvent(PlayToReceiver^, VolumeChangeRequestedEventArgs^ args)
00465 {
00466     auto handler = ref new DispatchedHandler(
00467         [this, args]()
00468         {
00469             if(dmrVideo != nullptr && currentType == MediaType::AudioVisual)
00470             {
00471                 dmrVideo->Volume = args->Volume;
00472             }
00473         },CallbackContext::Any);
00474
00475     Dispatcher->RunAsync(CoreDispatcherPriority::High,handler);
00476 }
00477
00478
00479
00480 void Scenario1::dmrImage_ImageFailed_1(Platform::Object^ sender, Windows::UI::Xaml::ExceptionRoutedEventArgs^ e)
00481 {
00482     if(IsReceiverStarted)
00483     {
00484         receiver->NotifyError();
00485     }
00486 }
00487
00488
00489 void Scenario1::dmrVideo_DownloadProgressChanged_1(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00490 {
00491     if(IsReceiverStarted)
00492     {
00493         if(dmrVideo->DownloadProgress == 1 && bufferedPlaybackRate > 0)
00494         {
00495             dmrVideo->PlaybackRate = bufferedPlaybackRate;
00496             bufferedPlaybackRate = 0;
00497         }
00498     }
00499 }
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Snap/C++/common/LayoutAwarePage.h Source File

  • Snap
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite custom text renderer/C++/DirectXSample.h Source File

  • DirectWrite custom text renderer

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
00010 // This header defines helper utilities to make DirectX APIs work with exceptions.
00011 namespace DX
00012 {
00013     inline void ThrowIfFailed(HRESULT hr)
00014     {
00015         if (FAILED(hr))
00016         {
00017             // Set a breakpoint on this line to catch DX API errors.
00018             throw Platform::Exception::CreateException(hr);
00019         }
00020     }
00021 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Network information/C++/Constants.cpp Source File

  • Network information

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
00021     { "Get Internet Connection Profile", "SDKSample.NetworkInformationApi.InternetConnectionProfile" },
00022     { "Get Local Data Usage for Internet Connection Profile", "SDKSample.NetworkInformationApi.ProfileLocalUsageData" },
00023     { "Get Connection Profile List", "SDKSample.NetworkInformationApi.ConnectionProfileList" },
00024     { "Get Lan Identifiers", "SDKSample.NetworkInformationApi.LanId" },
00025     { "Register for Network Status Change Notifications", "SDKSample.NetworkInformationApi.NetworkStatusChange" }
00026 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media Play To/C++/Scenario1.xaml.h Source File

  • Media Play To

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 SDKSample
00023 {
00024     namespace PlayTo
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 Scenario1 sealed
00031         {
00032         public:
00033             Scenario1();
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         private:
00039             MainPage^ rootPage;
00040         Windows::UI::Core::CoreDispatcher^ dispatcher;
00041         Windows::Media::PlayTo::PlayToManager^ playToManager;
00042         Windows::Storage::StorageFile^ localFile;
00043         Windows::Foundation::EventRegistrationToken sourceRequestedToken;
00044         void webContent_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00045         void videoFile_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00046         void playButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047         void pauseButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048         void playToManager_SourceRequested(Windows::Media::PlayTo::PlayToManager^ sender, Windows::Media::PlayTo::PlayToSourceRequestedEventArgs^ e);
00049       };
00050     }
00051 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: HttpClient/C++/pch.cpp Source File

  • HttpClient

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Scaling according to DPI/C++/MainPage.xaml.h Source File

  • Scaling according to DPI

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Credential picker/C++/pch.h Source File

  • Credential picker

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 //
00009 // pch.h
00010 // Header for standard system include files.
00011 //
00012
00013 #pragma once
00014 #define USE_PPLTASKS
00015 #include "CppSamplesUtils.h"
00016 #include <ppltasks.h>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: App package information/C++/common/LayoutAwarePage.h Source File

  • App package information
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media engine native C++ video playback/C++/d3dmanagerlock.hxx Source File

  • Media engine native C++ video playback

d3dmanagerlock.hxx

Go to the documentation of this file.
00001 //+-------------------------------------------------------------------------
00002 //
00003 //  Member:     d3dManagerLock.hxx
00004 //
00005 //  Synopsis:   Contains a class to aid aquiring a D3D9 or DXGI device from a
00006 //              device manager
00007 //
00008 //--------------------------------------------------------------------------
00009
00010 //+-----------------------------------------------------------------------------
00011 //
00012 //  Class:      CAutoDXDevLock
00013 //
00014 //  Synopsis:   Class to handle extracting a locked DX device from a
00015 //              a D3D9 or DXGI Device manager
00016 //
00017 //------------------------------------------------------------------------------
00018 template<class DevManager, class DevInterface>
00019 class CAutoDXDevLockBase
00020 {
00021 protected:
00022     Microsoft::WRL::ComPtr<DevManager> m_spDevManager;
00023     HANDLE m_hDev;
00024     bool m_locked;
00025
00026 public:
00027     //+-------------------------------------------------------------------------
00028     //
00029     //  Member:     CAutoDXDevLockBase
00030     //
00031     //  Synopsis:   Constructor
00032     //
00033     //--------------------------------------------------------------------------
00034     CAutoDXDevLockBase(
00035         _In_ Microsoft::WRL::ComPtr<DevManager> spDevManager
00036         ) :
00037         m_locked(false),
00038         m_hDev(NULL),
00039         m_spDevManager(spDevManager)
00040     {
00041         m_spDevManager->OpenDeviceHandle(&m_hDev);
00042     }
00043
00044     //+-------------------------------------------------------------------------
00045     //
00046     //  Member:     ~CAutoDXDevLockBase
00047     //
00048     //  Synopsis:   destructor
00049     //
00050     //--------------------------------------------------------------------------
00051     ~CAutoDXDevLockBase()
00052     {
00053         if (m_hDev != NULL)
00054         {
00055             if (m_locked)
00056             {
00057                 m_spDevManager->UnlockDevice(m_hDev, FALSE);
00058             }
00059             m_spDevManager->CloseDeviceHandle(m_hDev);
00060         }
00061     }
00062
00063     //+-------------------------------------------------------------------------
00064     //
00065     //  Member:     LockDevice
00066     //
00067     //  Synopsis:
00068     //
00069     //--------------------------------------------------------------------------
00070     virtual HRESULT LockDevice(
00071         _Out_ Microsoft::WRL::ComPtr<DevInterface>& spDev
00072         ) = 0;
00073 };
00074
00075 class CAutoDXGILock : public CAutoDXDevLockBase<IMFDXGIDeviceManager, ID3D11Device>
00076 {
00077
00078 public:
00079     CAutoDXGILock(_In_ Microsoft::WRL::ComPtr<IMFDXGIDeviceManager> spDevManager) :
00080         CAutoDXDevLockBase(spDevManager)
00081     {}
00082
00083     HRESULT LockDevice(
00084         _Out_ Microsoft::WRL::ComPtr<ID3D11Device>& spDev
00085         )
00086     {
00087     HRESULT hr = S_OK;
00088
00089         if (m_locked)
00090         {
00091             hr = E_FAIL;
00092         }
00093
00094         MEDIA::ThrowIfFailed(
00095       m_spDevManager->LockDevice(
00096       m_hDev,
00097       __uuidof(ID3D11Device),
00098       &spDev,
00099       TRUE)
00100       );
00101
00102         m_locked = true;
00103
00104         return hr;
00105     }
00106 };
Generated on Sat Nov 23 2024 16:08:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2Dapp printing/C++/DirectXSample.h Source File

  • Direct2Dapp printing

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
00010 // This header defines helper utilities to make DirectX APIs work with exceptions.
00011 namespace DX
00012 {
00013     inline void ThrowIfFailed(HRESULT hr)
00014     {
00015         if (FAILED(hr))
00016         {
00017             // Set a breakpoint on this line to catch DX API errors.
00018             throw Platform::Exception::CreateException(hr);
00019         }
00020     }
00021 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/GameObject.cpp Source File

  • DirectX 3D shooting game

GameObject.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 "GameObject.h"
00010 #include "ConstantBuffers.h"
00011 #include "GameConstants.h"
00012
00013 using namespace DirectX;
00014
00015 //--------------------------------------------------------------------------------
00016
00017 GameObject::GameObject() :
00018     m_normalMaterial(nullptr),
00019     m_hitMaterial(nullptr)
00020 {
00021     m_active          = false;
00022     m_target          = false;
00023     m_targetId        = 0;
00024     m_hit             = false;
00025     m_ground          = true;
00026
00027     m_position        = XMFLOAT3(0.0f, 0.0f, 0.0f);
00028     m_velocity        = XMFLOAT3(0.0f, 0.0f, 0.0f);
00029     m_defaultXAxis    = XMFLOAT3(1.0f, 0.0f, 0.0f);
00030     m_defaultYAxis    = XMFLOAT3(0.0f, 1.0f, 0.0f);
00031     m_defaultZAxis    = XMFLOAT3(0.0f, 0.0f, 1.0f);
00032     XMStoreFloat4x4(&m_modelMatrix, XMMatrixIdentity());
00033
00034     m_hitTime         = 0.0f;
00035
00036     m_animatePosition = nullptr;
00037 }
00038
00039 //----------------------------------------------------------------------
00040
00041 void GameObject::Render(
00042     _In_ ID3D11DeviceContext *context,
00043     _In_ ID3D11Buffer *primitiveConstantBuffer
00044     )
00045 {
00046     if (!m_active || (m_mesh == nullptr) || (m_normalMaterial == nullptr))
00047     {
00048         return;
00049     }
00050
00051     ConstantBufferChangesEveryPrim constantBuffer;
00052
00053     XMStoreFloat4x4(
00054         &constantBuffer.worldMatrix,
00055         XMMatrixTranspose(ModelMatrix())
00056         );
00057
00058     if (m_hit && m_hitMaterial != nullptr)
00059     {
00060         m_hitMaterial->RenderSetup(context, &constantBuffer);
00061     }
00062     else
00063     {
00064         m_normalMaterial->RenderSetup(context, &constantBuffer);
00065     }
00066     context->UpdateSubresource(primitiveConstantBuffer, 0, nullptr, &constantBuffer, 0, 0);
00067
00068     m_mesh->Render(context);
00069 }
00070
00071 //----------------------------------------------------------------------
00072
00073 void GameObject::PlaySound(float impactSpeed, XMFLOAT3 eyePoint)
00074 {
00075     if (m_hitSound != nullptr)
00076     {
00077         // Determine the sound volume adjustment based on velocity.
00078         float adjustment;
00079         if (impactSpeed < GameConstants::Sound::MinVelocity)
00080         {
00081             adjustment = 0.0f;  // Too soft.  Don't play sound.
00082         }
00083         else
00084         {
00085             adjustment = min(1.0f, impactSpeed / GameConstants::Sound::MaxVelocity);
00086             adjustment = GameConstants::Sound::MinAdjustment + adjustment * (1.0f - GameConstants::Sound::MinAdjustment);
00087         }
00088
00089         // Compute Distance to eyePoint to adjust the volume based on that distance.
00090         XMVECTOR cameraToPosition = XMLoadFloat3(&eyePoint) - VectorPosition();
00091         float distToPositionSquared = XMVectorGetX(XMVector3LengthSq(cameraToPosition));
00092
00093         float volume = min(distToPositionSquared, 1.0f);
00094         // Scale
00095         // Sound is proportional to how hard the ball is hitting.
00096         volume = adjustment * volume;
00097
00098         m_hitSound->PlaySound(volume);
00099     }
00100 }
00101
00102 //----------------------------------------------------------------------
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Credential locker/C++/MainPage.xaml.cpp Source File

  • Credential locker

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:41 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Cylinder Member List

This is the complete list of members for Cylinder, including all inherited members.
__pad0__ | Cylinder |
Active(bool active) | GameObject |
Active() | GameObject |
Active(bool active) | GameObject |
Active() | GameObject |
AnimatePosition(_In_opt_ Animate^animate) | GameObject |
AnimatePosition() | GameObject |
AnimatePosition(_In_opt_ Animate^animate) | GameObject |
AnimatePosition() | GameObject |
Cylinder(DirectX::XMFLOAT3 position, float radius, DirectX::XMFLOAT3 direction) | Cylinder |
Cylinder(DirectX::XMFLOAT3 position, float radius, DirectX::XMFLOAT3 direction) | Cylinder |
Hit(bool hit) | GameObject |
Hit() | GameObject |
Hit(bool hit) | GameObject |
Hit() | GameObject |
HitMaterial(_In_ Material^material) | GameObject |
HitMaterial() | GameObject |
HitMaterial(_In_ Material^material) | GameObject |
HitMaterial() | GameObject |
HitSound(_In_ SoundEffect^hitSound) | GameObject |
HitSound() | GameObject |
HitSound(_In_ SoundEffect^hitSound) | GameObject |
HitSound() | GameObject |
HitTime(float t) | GameObject |
HitTime() | GameObject |
HitTime(float t) | GameObject |
HitTime() | GameObject |
Initialize(DirectX::XMFLOAT3 position, float radius, DirectX::XMFLOAT3 direction) | Cylinder | [private]
Initialize(DirectX::XMFLOAT3 position, float radius, DirectX::XMFLOAT3 direction) | Cylinder | [private]
IsTouching(DirectX::XMFLOAT3 point, float radius, _Out_ DirectX::XMFLOAT3 *contact, _Out_ DirectX::XMFLOAT3 *normal) override | Cylinder | [virtual]
IsTouching(DirectX::XMFLOAT3 point, float radius, _Out_ DirectX::XMFLOAT3 *contact, _Out_ DirectX::XMFLOAT3 *normal) override | Cylinder | [virtual]
m_axis | Cylinder | [private]
m_length | Cylinder | [private]
m_radius | Cylinder | [private]
m_rotationMatrix | Cylinder | [private]
Mesh(_In_ MeshObject^mesh) | GameObject |
Mesh(_In_ MeshObject^mesh) | GameObject |
ModelMatrix() | GameObject |
ModelMatrix() | GameObject |
NormalMaterial(_In_ Material^material) | GameObject |
NormalMaterial() | GameObject |
NormalMaterial(_In_ Material^material) | GameObject |
NormalMaterial() | GameObject |
OnGround(bool ground) | GameObject |
OnGround() | GameObject |
OnGround(bool ground) | GameObject |
OnGround() | GameObject |
PlaySound(float impactSpeed, DirectX::XMFLOAT3 eyePoint) | GameObject |
PlaySound(float impactSpeed, DirectX::XMFLOAT3 eyePoint) | GameObject |
Position(DirectX::XMFLOAT3 position) | GameObject |
Position(DirectX::XMVECTOR position) | GameObject |
Position() | GameObject |
Position(DirectX::XMFLOAT3 position) | GameObject |
Position(DirectX::XMVECTOR position) | GameObject |
Position() | GameObject |
Render(_In_ ID3D11DeviceContext *context, _In_ ID3D11Buffer *primitiveConstantBuffer) | GameObject |
Render(_In_ ID3D11DeviceContext *context, _In_ ID3D11Buffer *primitiveConstantBuffer) | GameObject |
Target(bool target) | GameObject |
Target() | GameObject |
Target(bool target) | GameObject |
Target() | GameObject |
TargetId(int targetId) | GameObject |
TargetId() | GameObject |
TargetId(int targetId) | GameObject |
TargetId() | GameObject |
UpdatePosition() override | Cylinder | [protected, virtual]
UpdatePosition() override | Cylinder | [protected, virtual]
VectorPosition() | GameObject |
VectorPosition() | GameObject |
VectorVelocity() | GameObject |
VectorVelocity() | GameObject |
Velocity(DirectX::XMFLOAT3 velocity) | GameObject |
Velocity(DirectX::XMVECTOR velocity) | GameObject |
Velocity() | GameObject |
Velocity(DirectX::XMFLOAT3 velocity) | GameObject |
Velocity(DirectX::XMVECTOR velocity) | GameObject |
Velocity() | GameObject |
Generated on Sat Nov 23 2024 16:09:10 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Portable device API/C++/common/SuspensionManager.h Source File

  • Portable device API
  • common

SuspensionManager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Touch keyboard text input/C++/common/suspensionmanager.h Source File

  • Input Touch keyboard text input
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML user and custom controls/C++/ImageWithLabelControl.h Source File

  • XAML user and custom controls

ImageWithLabelControl.h

Go to the documentation of this file.
00001 ﻿//
00002 // ImageWithLabelControl.h
00003 // Declaration of the ImageWithLabelControl class.
00004 //
00005
00006 using namespace Windows::UI::Xaml::Controls;
00007 using namespace Windows::UI::Xaml::Interop;
00008 using namespace Windows::UI::Xaml;
00009 using namespace Windows::UI::Xaml::Media;
00010 using namespace Platform;
00011 #pragma once
00012
00013 #include "pch.h"
00014
00015 namespace SDKSample
00016 {
00017     namespace UserAndCustomControls
00018     {
00019       [Windows::Foundation::Metadata::WebHostHidden]
00020       public ref class ImageWithLabelControl sealed : public Control
00021       {
00022       private:
00023         static DependencyProperty^ _LabelProperty;
00024         static DependencyProperty^ _ImagePathProperty;
00025
00026       public:
00027         ImageWithLabelControl();
00028         static property DependencyProperty^ LabelProperty
00029         {
00030           DependencyProperty^ get() { return _LabelProperty; }
00031         }
00032
00033         static property DependencyProperty^ ImagePathProperty
00034         {
00035           DependencyProperty^ get() { return _ImagePathProperty; }
00036         }
00037
00038         property String^ Label
00039         {
00040           String^ get() { return (String^)GetValue(LabelProperty); }
00041           void set(String^ value) { SetValue(LabelProperty, value); }
00042         }
00043         property ImageSource^ ImagePath
00044         {
00045           ImageSource^ get() { return (ImageSource^)GetValue(ImagePathProperty); }
00046           void set(ImageSource^ value) { SetValue(ImagePathProperty, value); }
00047         }
00048       };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:08:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Inclinometer sensor/C++/Constants.h Source File

  • Inclinometer sensor

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"Inclinometer Sensor Raw Data");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044
00045
00046 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File picker contracts/C++/App.xaml.h Source File

  • File picker contracts

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020
00021 namespace SDKSample
00022 {
00023     ref class App
00024     {
00025     internal:
00026         App();
00027         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00028         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00029
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032         virtual void OnFileOpenPickerActivated(Windows::ApplicationModel::Activation::FileOpenPickerActivatedEventArgs^ pArgs) override;
00033         virtual void OnFileSavePickerActivated(Windows::ApplicationModel::Activation::FileSavePickerActivatedEventArgs^ pArgs) override;
00034         virtual void OnCachedFileUpdaterActivated(Windows::ApplicationModel::Activation::CachedFileUpdaterActivatedEventArgs^ pArgs) override;
00035
00036     private:
00037         void App::EnsureMainPageActivated(Windows::ApplicationModel::Activation::IActivatedEventArgs^ pArgs);
00038         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00039     };
00040 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Background Transfer/C++/Scenario1.xaml.cpp Source File

  • Background Transfer

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::BackgroundTransfer;
00021
00022 using namespace Concurrency;
00023 using namespace Platform;
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::Networking::BackgroundTransfer;
00029 using namespace Windows::Web;
00030 using namespace Windows::Foundation;
00031 using namespace Windows::Foundation::Collections;
00032 using namespace Windows::Storage;
00033
00034 Scenario1::Scenario1()
00035 {
00036     InitializeComponent();
00037     cancellationToken = new cancellation_token_source();
00038 }
00039
00040 Scenario1::~Scenario1()
00041 {
00042     if (cancellationToken != nullptr)
00043     {
00044         delete cancellationToken;
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::OnNavigatedTo(NavigationEventArgs^ e)
00054 {
00055     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00056     // as NotifyUser()
00057     rootPage = MainPage::Current;
00058     DiscoverActiveDownloads();
00059 }
00060
00061 // Enumerate the downloads that were going on in the background while the app was closed.
00062 void Scenario1::DiscoverActiveDownloads()
00063 {
00064     task<IVectorView<DownloadOperation^>^>(BackgroundDownloader::GetCurrentDownloadsAsync()).then([this] (IVectorView<DownloadOperation^>^ downloads)
00065     {
00066         Log("Loading background downloads: " + downloads->Size);
00067
00068         for (unsigned int i = 0; i < downloads->Size; i++)
00069         {
00070             DownloadOperation^ download = downloads->GetAt(i);
00071             Log("Discovered background download: " + download->Guid + ", Status: " + download->Progress.Status.ToString());
00072
00073             // Attach progress and completion handlers.
00074             HandleDownloadAsync(download, false);
00075         }
00076     }).then([this] (task<void> previousTask)
00077     {
00078         try
00079         {
00080             previousTask.get();
00081         }
00082         catch (Exception^ ex)
00083         {
00084             LogException("Discovery error", ex);
00085         }
00086     });
00087 }
00088
00089 void Scenario1::HandleDownloadAsync(DownloadOperation^ download, boolean start)
00090 {
00091     IAsyncOperationWithProgress<DownloadOperation^, DownloadOperation^>^ async;
00092     activeDownloads[download->Guid.GetHashCode()] = download;
00093
00094     LogStatus("Running: " + download->Guid, NotifyType::StatusMessage);
00095
00096     if (start)
00097     {
00098         async = download->StartAsync();
00099     }
00100     else
00101     {
00102         async = download->AttachAsync();
00103     }
00104
00105     async->Progress = ref new AsyncOperationProgressHandler<DownloadOperation^, DownloadOperation^>(this, &Scenario1::DownloadProgress);
00106     task<DownloadOperation^>(async, cancellationToken->get_token()).then([this] (DownloadOperation^ download)
00107     {
00108         ResponseInformation^ response = download->GetResponseInformation();
00109         LogStatus("Completed: " + download->Guid + ", Status Code: " + response->StatusCode, NotifyType::StatusMessage);
00110     }).then([this, download] (task<void> previousTask)
00111     {
00112         try
00113         {
00114             previousTask.get();
00115         }
00116         catch (Exception^ ex)
00117         {
00118             LogException("Handle download", ex);
00119         }
00120
00121         // It is important to note, that this method executes on UI thread. This guarantees that
00122         // access to the activeDownloads is synchronized.
00123         activeDownloads.erase(download->Guid.GetHashCode());
00124     });
00125 }
00126
00127 void Scenario1::DownloadProgress(IAsyncOperationWithProgress<DownloadOperation^, DownloadOperation^>^ operation, DownloadOperation^ download)
00128 {
00129     MarshalLog("Progress: " + download->Guid + ", Status: " + download->Progress.Status.ToString());
00130
00131     double percent = 0;
00132     if (download->Progress.TotalBytesToReceive > 0)
00133     {
00134         double percent = (double)(download->Progress.BytesReceived / download->Progress.TotalBytesToReceive) * 100;
00135     }
00136
00137     MarshalLog(" - Transfered bytes: " + download->Progress.BytesReceived + " of " +
00138         download->Progress.TotalBytesToReceive + ", " + percent + "%");
00139
00140     if (download->Progress.HasRestarted)
00141     {
00142         MarshalLog(" - Download restarted");
00143     }
00144
00145     if (download->Progress.HasResponseChanged)
00146     {
00147         // We've received new response headers from the server.
00148         MarshalLog(" - Response updated; Header count: " + download->GetResponseInformation()->Headers->Size);
00149
00150         // If you want to stream the response data this is a good time to start.
00151         // download->GetResultStreamAt(0);
00152     }
00153 }
00154
00155 void Scenario1::StartDownload_Click(Object^ sender, RoutedEventArgs^ e)
00156 {
00157     // By default 'serverAddressField' is disabled and URI validation is not required. When enabling the text box
00158     // validating the URI is required since it was received from an untrusted source (user input).
00159     // The URI is validated by calling TryGetUri() that will return 'false' for strings that are not valid URIs.
00160     // Note that when enabling the text box users may provide URIs to machines on the intrAnet that require the
00161     // "Home or Work Networking" capability.
00162     Uri^ source;
00163     if (!rootPage->TryGetUri(serverAddressField->Text, &source))
00164     {
00165         return;
00166     }
00167
00168     String^ destination = StringTrimmer::Trim(fileNameField->Text);
00169
00170     if (destination == "")
00171     {
00172         rootPage->NotifyUser("A local file name is required.", NotifyType::ErrorMessage);
00173         return;
00174     }
00175
00176     task<StorageFile^>(KnownFolders::PicturesLibrary->CreateFileAsync(destination, CreationCollisionOption::GenerateUniqueName)).then([this, source] (StorageFile^ destinationFile)
00177     {
00178         BackgroundDownloader^ downloader = ref new BackgroundDownloader();
00179         DownloadOperation^ download = downloader->CreateDownload(source, destinationFile);
00180
00181         Log("Downloading " + source->AbsoluteUri + " to " + destinationFile->Name + ", " + download->Guid);
00182
00183         // Attach progress and completion handlers.
00184         HandleDownloadAsync(download, true);
00185     }).then([this] (task<void> previousTask)
00186     {
00187         try
00188         {
00189             previousTask.get();
00190         }
00191         catch (Exception^ ex)
00192         {
00193             LogException("Error", ex);
00194         }
00195     });
00196 }
00197
00198 void Scenario1::PauseAll_Click(Object^ sender, RoutedEventArgs^ e)
00199 {
00200     Log("Downloads: " + activeDownloads.size());
00201     for (auto iterator = activeDownloads.begin(); iterator != activeDownloads.end(); iterator++)
00202     {
00203         DownloadOperation^ download = iterator->second;
00204         if (download->Progress.Status == BackgroundTransferStatus::Running)
00205         {
00206             download->Pause();
00207             Log("Paused: " + download->Guid);
00208         }
00209         else
00210         {
00211             Log("Skipped: " + download->Guid + ", Status: " + download->Progress.Status.ToString());
00212         }
00213     }
00214 }
00215
00216 void Scenario1::ResumeAll_Click(Object^ sender, RoutedEventArgs^ e)
00217 {
00218     Log("Downloads: " + activeDownloads.size());
00219     for (auto iterator = activeDownloads.begin(); iterator != activeDownloads.end(); iterator++)
00220     {
00221         DownloadOperation^ download = iterator->second;
00222         if (download->Progress.Status == BackgroundTransferStatus::PausedByApplication)
00223         {
00224             download->Resume();
00225             Log("Resumed: " + download->Guid);
00226         }
00227         else
00228         {
00229             Log("Skipped: " + download->Guid + ", Status: " + download->Progress.Status.ToString());
00230         }
00231     }
00232 }
00233
00234 void Scenario1::CancelAll_Click(Object^ sender, RoutedEventArgs^ e)
00235 {
00236     Log("Cancelling Downloads: " + activeDownloads.size());
00237
00238     cancellationToken->cancel();
00239     cancellationToken = new cancellation_token_source();
00240     activeDownloads.clear();
00241 }
00242
00243 void Scenario1::LogException(String^ title, Exception^ ex)
00244 {
00245     WebErrorStatus error = BackgroundTransferError::GetStatus(ex->HResult);
00246     if (error == WebErrorStatus::Unknown)
00247     {
00248         LogStatus(title + ": " + ex, NotifyType::ErrorMessage);
00249     }
00250     else
00251     {
00252         LogStatus(title + ": " + error.ToString(), NotifyType::ErrorMessage);
00253     }
00254 }
00255
00256 // When operations happen on a background thread we have to marshal UI updates back to the UI thread.
00257 void Scenario1::MarshalLog(String^ value)
00258 {
00259     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, value] ()
00260     {
00261         Log(value);
00262     }));
00263 }
00264
00265 void Scenario1::Log(String^ message)
00266 {
00267     outputField->Text += message + "\r\n";
00268 }
00269
00270 void Scenario1::LogStatus(String^ message, NotifyType type)
00271 {
00272     rootPage->NotifyUser(message, type);
00273     outputField->Text += message + "\r\n";
00274 }
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D HLSL fractal generator/C++/SampleOverlay.cpp Source File

  • Direct3D HLSL fractal generator

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 Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::UI::ViewManagement;
00015 using namespace Windows::Graphics::Display;
00016 using namespace D2D1;
00017
00018 SampleOverlay::SampleOverlay() :
00019     m_drawOverlay(true)
00020 {
00021 }
00022
00023 void SampleOverlay::Initialize(
00024     _In_ ID2D1Device*         d2dDevice,
00025     _In_ ID2D1DeviceContext*  d2dContext,
00026     _In_ IWICImagingFactory*  wicFactory,
00027     _In_ IDWriteFactory*      dwriteFactory,
00028     _In_ Platform::String^    caption
00029     )
00030 {
00031     m_wicFactory = wicFactory;
00032     m_dwriteFactory = dwriteFactory;
00033     m_sampleName = caption;
00034     m_d2dDevice = d2dDevice;
00035     m_d2dContext = d2dContext;
00036     m_padding = 3.0f;
00037     m_textVerticalOffset = 5.0f;
00038     m_logoSize = D2D1::SizeF(0.0f, 0.0f);
00039     m_overlayWidth = 0.0f;
00040
00041     ComPtr<ID2D1Factory> factory;
00042     d2dDevice->GetFactory(&factory);
00043
00044     DX::ThrowIfFailed(
00045         factory.As(&m_d2dFactory)
00046         );
00047
00048     ResetDirectXResources();
00049 }
00050
00051 void SampleOverlay::ResetDirectXResources()
00052 {
00053     DX::ThrowIfFailed(
00054         m_d2dContext->CreateSolidColorBrush(ColorF(ColorF::White), &m_whiteBrush)
00055         );
00056
00057     ComPtr<IWICBitmapDecoder> wicBitmapDecoder;
00058     DX::ThrowIfFailed(
00059         m_wicFactory->CreateDecoderFromFilename(
00060             L"windowsbig-sdk.png",
00061             nullptr,
00062             GENERIC_READ,
00063             WICDecodeMetadataCacheOnDemand,
00064             &wicBitmapDecoder
00065             )
00066         );
00067
00068     ComPtr<IWICBitmapFrameDecode> wicBitmapFrame;
00069     DX::ThrowIfFailed(
00070         wicBitmapDecoder->GetFrame(0, &wicBitmapFrame)
00071         );
00072
00073     ComPtr<IWICFormatConverter> wicFormatConverter;
00074     DX::ThrowIfFailed(
00075         m_wicFactory->CreateFormatConverter(&wicFormatConverter)
00076         );
00077
00078     DX::ThrowIfFailed(
00079         wicFormatConverter->Initialize(
00080             wicBitmapFrame.Get(),
00081             GUID_WICPixelFormat32bppPBGRA,
00082             WICBitmapDitherTypeNone,
00083             nullptr,
00084             0.0,
00085             WICBitmapPaletteTypeCustom  // the BGRA format has no palette so this value is ignored
00086             )
00087         );
00088
00089     double dpiX = 96.0f;
00090     double dpiY = 96.0f;
00091     DX::ThrowIfFailed(
00092         wicFormatConverter->GetResolution(&dpiX, &dpiY)
00093         );
00094
00095     DX::ThrowIfFailed(
00096         m_d2dContext->CreateBitmapFromWicBitmap(
00097             wicFormatConverter.Get(),
00098             BitmapProperties(
00099                 PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00100                 static_cast<float>(dpiX),
00101                 static_cast<float>(dpiY)
00102                 ),
00103             &m_logoBitmap
00104             )
00105         );
00106
00107     m_logoSize = m_logoBitmap->GetSize();
00108
00109     ComPtr<IDWriteTextFormat> nameTextFormat;
00110     DX::ThrowIfFailed(
00111         m_dwriteFactory->CreateTextFormat(
00112             L"Segoe UI",
00113             nullptr,
00114             DWRITE_FONT_WEIGHT_LIGHT,
00115             DWRITE_FONT_STYLE_NORMAL,
00116             DWRITE_FONT_STRETCH_NORMAL,
00117             36.0f,
00118             L"en-US",
00119             &nameTextFormat
00120             )
00121         );
00122
00123     DX::ThrowIfFailed(
00124         nameTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)
00125         );
00126
00127     DX::ThrowIfFailed(
00128         nameTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)
00129         );
00130
00131     DX::ThrowIfFailed(
00132         m_dwriteFactory->CreateTextLayout(
00133             m_sampleName->Data(),
00134             m_sampleName->Length(),
00135             nameTextFormat.Get(),
00136             4096.0f,
00137             4096.0f,
00138             &m_textLayout
00139             )
00140         );
00141
00142     DWRITE_TEXT_METRICS metrics = {0};
00143     DX::ThrowIfFailed(
00144         m_textLayout->GetMetrics(&metrics)
00145         );
00146
00147     m_overlayWidth = m_padding * 3.0f + m_logoSize.width + metrics.width;
00148
00149     DX::ThrowIfFailed(
00150         m_d2dFactory->CreateDrawingStateBlock(&m_stateBlock)
00151         );
00152
00153     UpdateForWindowSizeChange();
00154 }
00155
00156 void SampleOverlay::UpdateForWindowSizeChange()
00157 {
00158     if (CoreWindow::GetForCurrentThread()->Bounds.Width < m_overlayWidth)
00159     {
00160         m_drawOverlay = false;
00161     }
00162     else
00163     {
00164         m_drawOverlay = true;
00165     }
00166 }
00167
00168 void SampleOverlay::Render()
00169 {
00170     if (m_drawOverlay)
00171     {
00172         m_d2dContext->SaveDrawingState(m_stateBlock.Get());
00173
00174         m_d2dContext->BeginDraw();
00175         m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00176         m_d2dContext->DrawBitmap(
00177             m_logoBitmap.Get(),
00178             D2D1::RectF(m_padding, 0.0f, m_logoSize.width + m_padding, m_logoSize.height)
00179             );
00180
00181         m_d2dContext->DrawTextLayout(
00182             Point2F(m_logoSize.width + 2.0f * m_padding, m_textVerticalOffset),
00183             m_textLayout.Get(),
00184             m_whiteBrush.Get()
00185             );
00186
00187         // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00188         // is lost. It will be handled during the next call to Present.
00189         HRESULT hr = m_d2dContext->EndDraw();
00190         if (hr != D2DERR_RECREATE_TARGET)
00191         {
00192             DX::ThrowIfFailed(hr);
00193         }
00194
00195         m_d2dContext->RestoreDrawingState(m_stateBlock.Get());
00196     }
00197 }
00198
00199 float SampleOverlay::GetTitleHeightInDips()
00200 {
00201     return m_logoSize.height;
00202 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Reading and writing data/C++/ReadBytes.xaml.h Source File

  • Reading and writing data

ReadBytes.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 // ReadBytes.xaml.h
00013 // Declaration of the ReadBytes class
00014 //
00015
00016 #pragma once
00017
00018 #include <cstring>
00019 #include "pch.h"
00020 #include "ReadBytes.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKSample
00024 {
00025     namespace DataReaderWriter
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 ReadBytes sealed
00032         {
00033         public:
00034             ReadBytes();
00035
00036         protected:
00037             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00038         private:
00039             MainPage^ rootPage;
00040             void HexDump(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041             void ReadLoop(Windows::Storage::Streams::DataReader^ dataReader);
00042             void PrintRow(Platform::Array<byte>^ bytes, int i);
00043             Platform::String^ GetAddress(int i);
00044             Platform::String^ ToHex(byte value);
00045             int static const bytesPerRow = 16;
00046             int static const bytesPerSegment = 2;
00047             int static const chunkSize = 4096;
00048             int currChunk;
00049         };
00050     }
00051 }
Generated on Sat Nov 23 2024 16:08:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XInput audio controller playback/C++/AudioController.h Source File

  • XInput audio controller playback

AudioController.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 "DirectXBase.h"
00011 #include "SampleOverlay.h"
00012
00013 #include <xaudio2.h>
00014 #include <xaudio2fx.h>
00015 #include "MediaStreamer.h"
00016
00017 ref class AudioController : public DirectXBase
00018 {
00019 internal:
00020     AudioController();
00021
00022     // Overrides from DirectXBase
00023     virtual void CreateDeviceResources() override;
00024     virtual void CreateWindowSizeDependentResources() override;
00025     virtual void Render() override;
00026
00027     void OnSuspending();
00028     void OnResuming();
00029
00030     void Update(float TimeTotal, float TimeDelta);
00031
00032     // Audio Functionality
00033     void CreateAudioVoices(_In_ const char16* deviceEndpointId);
00034     void ReleaseAudioResources();
00035     void TriggerSoundEffect();
00036
00037     // Input functionality
00038     void FetchControllerInput();
00039
00040 private:
00041     ~AudioController();
00042
00043     // Overlay for Graphics
00044     SampleOverlay^              m_sampleOverlay;
00045
00046     // Audio Related Members
00047     IXAudio2*                   m_audioEngine;
00048     IXAudio2MasteringVoice*     m_masteringVoice;
00049     IXAudio2SourceVoice*        m_sourceVoice;
00050     std::vector<byte>           m_soundEffectBuffer;
00051
00052     // Input related members
00053     bool                    m_isControllerConnected;  // Do we have a controller connected
00054     bool                    m_isHeadsetConnected;     // Does the controller have a headset
00055     XINPUT_CAPABILITIES     m_xinputCaps;             // Capabilites of the controller
00056     XINPUT_STATE            m_xinputState;            // The current state of the controller
00057     uint64                  m_lastEnumTime;           // Last time a new controller connection was checked
00058     uint64                  m_lastHeadsetCheckTime;   // Last time the headset was re-checked for connectivity
00059     bool                    m_aButtonWasPressed;
00060
00061     // Members for drawing
00062     Microsoft::WRL::ComPtr<IDWriteTextFormat>       m_dataTextFormat;
00063     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_textBrush;
00064 };
Generated on Sat Nov 23 2024 16:08:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D magazine app/C++/Element.h Source File

  • Direct2D magazine app

Element.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 ref class Document;
00011 ref class Renderer;
00012
00013 //  A node in the element tree created by parsing a content markup. Element measures
00014 //  and draws its content to a destination surface as well as responds to the user's
00015 //  input gestures.
00016 //
00017 //  Element accepts the following markup attributes:
00018 //      name = "<string>"
00019 //          Name string used to identified the element
00020 //      x = "<float>"
00021 //          Horizontal offset of the element relative to parent in design unit
00022 //      y = "<float>"
00023 //          Vertical offset of the element relative to parent in design unit
00024 //      width = "<float>"
00025 //          Width of the element in design unit
00026 //      height = "<float>"
00027 //          Height of the element in design unit
00028 //
00029 ref class Element
00030 {
00031 internal:
00032     Element();
00033
00034     virtual void ReleaseParent();
00035
00036     template <typename T>
00037     static T^ Create(
00038         _In_ Document^ document,
00039         _In_ Windows::Data::Xml::Dom::IXmlNode^ xmlNode
00040         );
00041
00042     virtual bool Initialize(
00043         _In_ Document^ document,
00044         _In_ Windows::Data::Xml::Dom::XmlElement^ xmlElement
00045         );
00046
00047     virtual bool AcceptChildNode(
00048         _In_ Document^ document,
00049         _In_ Windows::Data::Xml::Dom::IXmlNode^ childXmlNode
00050         );
00051
00052     virtual bool BindResource(_In_ Element^ rootElement);
00053
00054     virtual void Measure(
00055         _In_ Document^ document,
00056         D2D1_SIZE_F const& parentSize,
00057         _Out_ D2D1_RECT_F* bounds
00058         );
00059
00060     virtual bool PrepareToDraw(
00061         _In_ Document^ document,
00062         D2D1::Matrix3x2F const& transform
00063         );
00064
00065     virtual bool Draw(
00066         _In_ Document^ document,
00067         D2D1::Matrix3x2F const& transform
00068         );
00069
00070     virtual float GetOpacity()
00071     {
00072         return 1.0f;
00073     }
00074
00075     inline D2D1_SIZE_F GetSize()
00076     {
00077         return m_size;
00078     }
00079
00080     inline Platform::String^ GetName()
00081     {
00082         return m_name;
00083     }
00084
00085     void AddChild(_In_ Element^ element);
00086
00087     void AddSibling(_In_ Element^ element);
00088
00089     inline Element^ GetParent()
00090     {
00091         return m_parent;
00092     }
00093
00094     inline Element^ GetFirstChild()
00095     {
00096         return m_firstChild;
00097     }
00098
00099     inline Element^ GetNextSibling()
00100     {
00101         return m_nextSibling;
00102     }
00103
00104 protected private:
00105     bool PrepareToDrawChildren(
00106         _In_ Document^ document,
00107         D2D1::Matrix3x2F const& transform
00108         );
00109
00110     bool DrawChildren(
00111         _In_ Document^ document,
00112         D2D1::Matrix3x2F const& transform
00113         );
00114
00115     // Parse color string of the form "#RRGGBB" of the "color" attribute
00116     uint32 ParseColor(_In_ Platform::String^ value);
00117
00118     // Parse resource's name identifier of the form "#name"
00119     Platform::String^ ParseNameIdentifier(_In_ Platform::String^ value);
00120
00121     // Name identifier of the element
00122     Platform::String^ m_name;
00123
00124     // Positioning offset relative to parent.
00125     D2D1_POINT_2F m_offset;
00126
00127     // Element size
00128     D2D1_SIZE_F m_size;
00129
00130     // Reference to the parent element. This dependency needs to be explicitly
00131     // released to avoid cycle dependency.
00132     Element^ m_parent;
00133
00134     // Reference to the next element of the same parent
00135     Element^ m_nextSibling;
00136
00137     // Reference to the first child element
00138     Element^ m_firstChild;
00139 };
00140
00141 //  Element creation wrapper, which instantiates and initializes a element as well as
00142 //  all its children. The process stops when all element are created or when a element
00143 //  is rejected due to parsing error.
00144 //
00145 template <typename T>
00146 T^ Element::Create(
00147     _In_ Document^ document,
00148     _In_ Windows::Data::Xml::Dom::IXmlNode^ xmlNode
00149     )
00150 {
00151     T^ element = nullptr;
00152
00153     if (xmlNode->NodeType == NodeType::ElementNode)
00154     {
00155         Windows::Data::Xml::Dom::XmlElement^ xmlElement = dynamic_cast<Windows::Data::Xml::Dom::XmlElement^>(xmlNode);
00156
00157         element = ref new T();
00158
00159         if (element)
00160         {
00161             if (element->Initialize(document, xmlElement))
00162             {
00163                 if (xmlNode->HasChildNodes())
00164                 {
00165                     Windows::Data::Xml::Dom::IXmlNode^ childXmlNode = xmlNode->FirstChild;
00166
00167                     while (childXmlNode != nullptr)
00168                     {
00169                         if (!element->AcceptChildNode(document, childXmlNode))
00170                         {
00171                             break;
00172                         }
00173
00174                         childXmlNode = childXmlNode->NextSibling;
00175                     }
00176                 }
00177             }
00178             else
00179             {
00180                 element = nullptr;
00181             }
00182         }
00183     }
00184
00185     return element;
00186 }
Generated on Sat Nov 23 2024 16:08:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/Level3.cpp Source File

  • DirectX 3D shooting game

Level3.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 "Level3.h"
00010 #include "Face.h"
00011 #include "Animate.h"
00012
00013 using namespace DirectX;
00014
00015 //----------------------------------------------------------------------
00016
00017 Level3::Level3()
00018 {
00019     m_timeLimit = 30.0f;
00020     m_objective = "Hit each of the moving targets before time runs out.";
00021 }
00022
00023 //----------------------------------------------------------------------
00024
00025 void Level3::Initialize(std::vector<GameObject^> objects)
00026 {
00027     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     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     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     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     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     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     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.begin(); object != objects.end(); object++)
00090     {
00091         if (Face^ target = dynamic_cast<Face^>(*object))
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(ref new AnimateLineListPosition(4, LineList1, 10.0f, true));
00103                     break;
00104                 case 1:
00105                     target->AnimatePosition(ref new AnimateLineListPosition(6, LineList2, 15.0f, true));
00106                     break;
00107                 case 2:
00108                     target->AnimatePosition(ref new AnimateLineListPosition(4, LineList3, 15.0f, true));
00109                     break;
00110                 case 3:
00111                     target->AnimatePosition(ref new AnimateLineListPosition(5, LineList4, 15.0f, true));
00112                     break;
00113                 case 4:
00114                     target->AnimatePosition(ref new AnimateLineListPosition(6, LineList5, 15.0f, true));
00115                     break;
00116                 case 5:
00117                     target->AnimatePosition(ref new AnimateLineListPosition(5, LineList6, 15.0f, true));
00118                     break;
00119                 case 6:
00120                     target->AnimatePosition(
00121                         ref new 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                         ref new 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                         ref new 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 }
00171
00172 //----------------------------------------------------------------------
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File access/C++/Scenario8.xaml.cpp Source File

  • File access

Scenario8.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 // Scenario8.xaml.cpp
00013 // Implementation of the Scenario8 class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario8.xaml.h"
00018
00019 using namespace SDKSample::FileAccess;
00020
00021 using namespace concurrency;
00022 using namespace Platform;
00023 using namespace Windows::Storage;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Controls;
00026 using namespace Windows::UI::Xaml::Navigation;
00027
00028 Scenario8::Scenario8()
00029 {
00030     InitializeComponent();
00031     rootPage = MainPage::Current;
00032     DeleteFileButton->Click += ref new RoutedEventHandler(this, &Scenario8::DeleteFileButton_Click);
00033 }
00034
00035 void Scenario8::DeleteFileButton_Click(Object^ sender, RoutedEventArgs^ e)
00036 {
00037     rootPage->ResetScenarioOutput(OutputTextBlock);
00038     StorageFile^ sampleFile = rootPage->SampleFile;
00039     if (sampleFile != nullptr)
00040     {
00041         String^ filename = sampleFile->Name;
00042         // Get the returned file and displays basic file properties
00043         create_task(sampleFile->DeleteAsync()).then([this, filename](task<void> task)
00044         {
00045             try
00046             {
00047                 task.get();
00048                 rootPage->SampleFile = nullptr;
00049                 OutputTextBlock->Text = "The file '" + filename + "' was deleted";
00050             }
00051             catch(COMException^ ex)
00052             {
00053                 rootPage->HandleFileNotFoundException(ex);
00054             }
00055         });
00056     }
00057 }
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Search contract/C++/Constants.h Source File

  • Search contract

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"Search contract C++ sample");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041
00042     internal:
00043         void ProcessQueryText(Platform::String^ queryText);
00044         static Platform::String^ ReplaceUrlSearchTerms(Platform::String^ strUrl, Platform::String^ queryText);
00045         static const int SearchPaneMaxSuggestions = 5;
00046         Windows::Foundation::EventRegistrationToken token;
00047
00048     private:
00049         static Platform::Array<Scenario>^ scenariosInner;
00050     };
00051
00052     class Finally
00053     {
00054     public:
00055         Finally(std::function<void()> f) : finallyClause(f) {}
00056         ~Finally()
00057         {
00058             finallyClause();
00059         }
00060
00061     private:
00062         std::function<void()> finallyClause;
00063     };
00064 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Date and time formatting/C++/pch.cpp Source File

  • Date and time formatting

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 Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playback Manager Companion/C++/App.xaml.cpp Source File

  • Playback Manager Companion

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D convolve matrix effect/C++/pch.cpp Source File

  • Direct2D convolve matrix effect

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite inline object/C++/DWriteInlineObject.cpp Source File

  • DirectWrite inline object

DWriteInlineObject.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 "DWriteInlineObject.h"
00010
00011 using namespace Microsoft::WRL;
00012 using namespace Windows::ApplicationModel;
00013 using namespace Windows::ApplicationModel::Core;
00014 using namespace Windows::ApplicationModel::Activation;
00015 using namespace Windows::UI::Core;
00016 using namespace Windows::System;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Graphics::Display;
00019
00020 DWriteInlineObject::DWriteInlineObject()
00021 {
00022 }
00023
00024 void DWriteInlineObject::HandleDeviceLost()
00025 {
00026     // Release window size-dependent resources prior to creating a new device and swap chain.
00027     m_inlineImage = nullptr;
00028     m_textLayout = nullptr;
00029
00030     DirectXBase::HandleDeviceLost();
00031 }
00032
00033 void DWriteInlineObject::CreateDeviceIndependentResources()
00034 {
00035     DirectXBase::CreateDeviceIndependentResources();
00036
00037     // Create a DirectWrite text format object.
00038     DX::ThrowIfFailed(
00039         m_dwriteFactory->CreateTextFormat(
00040             L"Segoe UI",
00041             nullptr,
00042             DWRITE_FONT_WEIGHT_LIGHT,
00043             DWRITE_FONT_STYLE_NORMAL,
00044             DWRITE_FONT_STRETCH_NORMAL,
00045             64.0f,
00046             L"en-US", // locale
00047             &m_textFormat
00048             )
00049         );
00050
00051     // Center the text horizontally.
00052     DX::ThrowIfFailed(
00053         m_textFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER)
00054         );
00055
00056     // Center the text vertically.
00057     DX::ThrowIfFailed(
00058         m_textFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER)
00059         );
00060 }
00061
00062 void DWriteInlineObject::CreateDeviceResources()
00063 {
00064     DirectXBase::CreateDeviceResources();
00065
00066     m_sampleOverlay = ref new SampleOverlay();
00067
00068     m_sampleOverlay->Initialize(
00069         m_d2dDevice.Get(),
00070         m_d2dContext.Get(),
00071         m_wicFactory.Get(),
00072         m_dwriteFactory.Get(),
00073         "DirectWrite inline object sample"
00074         );
00075
00076     DX::ThrowIfFailed(
00077         m_d2dContext->CreateSolidColorBrush(
00078             D2D1::ColorF(D2D1::ColorF::Black),
00079             &m_blackBrush
00080             )
00081         );
00082 }
00083
00084 void DWriteInlineObject::CreateWindowSizeDependentResources()
00085 {
00086     DirectXBase::CreateWindowSizeDependentResources();
00087
00088     Platform::String^ text = "Inline object * sample";
00089
00090     D2D1_SIZE_F size = m_d2dContext->GetSize();
00091
00092     // Create a DirectWrite Text Layout object
00093     DX::ThrowIfFailed(
00094         m_dwriteFactory->CreateTextLayout(
00095             text->Data(),                       // Text to be displayed
00096             text->Length(),                     // Length of the text
00097             m_textFormat.Get(),                 // DirectWrite Text Format object
00098             size.width,                         // Width of the Text Layout
00099             size.height,                        // Height of the Text Layout
00100             &m_textLayout
00101             )
00102         );
00103
00104     m_inlineImage = new InlineImage(m_d2dContext.Get(), m_wicFactory.Get(), L"img1.jpg");
00105
00106     DWRITE_TEXT_RANGE textRange = {14, 1};
00107
00108     DX::ThrowIfFailed(
00109         m_textLayout->SetInlineObject(m_inlineImage.Get(), textRange)
00110         );
00111 }
00112
00113 void DWriteInlineObject::Render()
00114 {
00115     m_d2dContext->BeginDraw();
00116
00117     m_d2dContext->Clear(D2D1::ColorF(D2D1::ColorF::CornflowerBlue));
00118     m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00119
00120     m_d2dContext->DrawTextLayout(
00121         D2D1::Point2F(0.0f, 0.0f),
00122         m_textLayout.Get(),
00123         m_blackBrush.Get()
00124         );
00125
00126     // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00127     // is lost. It will be handled during the next call to Present.
00128     HRESULT hr = m_d2dContext->EndDraw();
00129     if (hr != D2DERR_RECREATE_TARGET)
00130     {
00131         DX::ThrowIfFailed(hr);
00132     }
00133
00134     m_sampleOverlay->Render();
00135 }
00136
00137 void DWriteInlineObject::Initialize(
00138     _In_ CoreApplicationView^ applicationView
00139     )
00140 {
00141     applicationView->Activated +=
00142         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &DWriteInlineObject::OnActivated);
00143
00144     CoreApplication::Suspending +=
00145         ref new EventHandler<SuspendingEventArgs^>(this, &DWriteInlineObject::OnSuspending);
00146
00147     CoreApplication::Resuming +=
00148         ref new EventHandler<Platform::Object^>(this, &DWriteInlineObject::OnResuming);
00149 }
00150
00151 void DWriteInlineObject::SetWindow(
00152     _In_ CoreWindow^ window
00153     )
00154 {
00155     window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
00156
00157     window->SizeChanged +=
00158         ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &DWriteInlineObject::OnWindowSizeChanged);
00159
00160     DisplayProperties::LogicalDpiChanged +=
00161         ref new DisplayPropertiesEventHandler(this, &DWriteInlineObject::OnLogicalDpiChanged);
00162
00163     DisplayProperties::DisplayContentsInvalidated +=
00164         ref new DisplayPropertiesEventHandler(this, &DWriteInlineObject::OnDisplayContentsInvalidated);
00165
00166     DirectXBase::Initialize(window, DisplayProperties::LogicalDpi);
00167 }
00168
00169 void DWriteInlineObject::Load(
00170     _In_ Platform::String^ entryPoint
00171     )
00172 {
00173 }
00174
00175 void DWriteInlineObject::Run()
00176 {
00177     Render();
00178     Present();
00179
00180     m_window->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessUntilQuit);
00181 }
00182
00183 void DWriteInlineObject::Uninitialize()
00184 {
00185 }
00186
00187 void DWriteInlineObject::OnWindowSizeChanged(
00188     _In_ CoreWindow^ sender,
00189     _In_ WindowSizeChangedEventArgs^ args
00190     )
00191 {
00192     UpdateForWindowSizeChange();
00193     m_sampleOverlay->UpdateForWindowSizeChange();
00194     Render();
00195     Present();
00196 }
00197
00198 void DWriteInlineObject::OnLogicalDpiChanged(
00199     _In_ Platform::Object^ sender
00200     )
00201 {
00202     SetDpi(DisplayProperties::LogicalDpi);
00203     Render();
00204     Present();
00205 }
00206
00207 void DWriteInlineObject::OnDisplayContentsInvalidated(
00208     _In_ Platform::Object^ sender
00209     )
00210 {
00211     // Ensure the D3D Device is available for rendering.
00212     ValidateDevice();
00213
00214     Render();
00215     Present();
00216 }
00217
00218 void DWriteInlineObject::OnActivated(
00219     _In_ CoreApplicationView^ applicationView,
00220     _In_ IActivatedEventArgs^ args
00221     )
00222 {
00223     m_window->Activate();
00224 }
00225
00226 void DWriteInlineObject::OnSuspending(
00227     _In_ Platform::Object^ sender,
00228     _In_ SuspendingEventArgs^ args
00229     )
00230 {
00231 }
00232
00233 void DWriteInlineObject::OnResuming(
00234     _In_ Platform::Object^ sender,
00235     _In_ Platform::Object^ args
00236     )
00237 {
00238 }
00239
00240 IFrameworkView^ DirectXAppSource::CreateView()
00241 {
00242     return ref new DWriteInlineObject();
00243 }
00244
00245 [Platform::MTAThread]
00246 int main(Platform::Array<Platform::String^>^)
00247 {
00248     auto directXAppSource = ref new DirectXAppSource();
00249     CoreApplication::Run(directXAppSource);
00250     return 0;
00251 }
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CryptoWinRT/C++/MainPage.xaml.h Source File

  • CryptoWinRT

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Lock screen apps/C#,C++/ScenarioInput1.xaml.cpp Source File

  • Lock screen apps
  • C#,C++

ScenarioInput1.xaml.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 //
00009 // Scenario1Input.xaml.cpp
00010 // Implementation of the Scenario1Input class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioInput1.xaml.h"
00015
00016 using namespace LockScreenAppsCPP;
00017
00018 using namespace concurrency;
00019 using namespace Platform;
00020 using namespace Windows::ApplicationModel::Background;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 ScenarioInput1::ScenarioInput1()
00026 {
00027     InitializeComponent();
00028     RequestLockScreenAccess->Click += ref new RoutedEventHandler(this, &ScenarioInput1::RequestLockScreenAccess_Click);
00029     RemoveLockScreenAccess->Click += ref new RoutedEventHandler(this, &ScenarioInput1::RemoveLockScreenAccess_Click);
00030     QueryLockScreenAccess->Click += ref new RoutedEventHandler(this, &ScenarioInput1::QueryLockScreenAccess_Click);
00031 }
00032
00033 ScenarioInput1::~ScenarioInput1()
00034 {
00035 }
00036
00037 void ScenarioInput1::RequestLockScreenAccess_Click(Object^ sender, RoutedEventArgs^ e)
00038 {
00039     task<BackgroundAccessStatus> statusTask(BackgroundExecutionManager::RequestAccessAsync());
00040     statusTask.then([this](BackgroundAccessStatus backgroundStatus)
00041     {
00042         switch (backgroundStatus)
00043         {
00044         case BackgroundAccessStatus::AllowedWithAlwaysOnRealTimeConnectivity:
00045             rootPage->NotifyUser("This app is on the lock screen and has access to Always-On Real Time Connectivity.", NotifyType::StatusMessage);
00046             break;
00047         case BackgroundAccessStatus::AllowedMayUseActiveRealTimeConnectivity:
00048             rootPage->NotifyUser("This app is on the lock screen and has access to Active Real Time Connectivity.", NotifyType::StatusMessage);
00049             break;
00050         case BackgroundAccessStatus::Denied:
00051             rootPage->NotifyUser("This app is not on the lock screen.", NotifyType::StatusMessage);
00052             break;
00053         case BackgroundAccessStatus::Unspecified:
00054             rootPage->NotifyUser("The user has not yet taken any action. This is the default setting and the app is not on the lock screen.", NotifyType::StatusMessage);
00055         }
00056     });
00057 }
00058
00059 void ScenarioInput1::RemoveLockScreenAccess_Click(Object^ sender, RoutedEventArgs^ e)
00060 {
00061     BackgroundExecutionManager::RemoveAccess();
00062     rootPage->NotifyUser("This app has been removed from the lock screen.", NotifyType::StatusMessage);
00063 }
00064
00065 void ScenarioInput1::QueryLockScreenAccess_Click(Object^ sender, RoutedEventArgs^ e)
00066 {
00067     switch (BackgroundExecutionManager::GetAccessStatus())
00068     {
00069     case BackgroundAccessStatus::AllowedWithAlwaysOnRealTimeConnectivity:
00070         rootPage->NotifyUser("This app is on the lock screen and has access to Always-On Real Time Connectivity.", NotifyType::StatusMessage);
00071         break;
00072     case BackgroundAccessStatus::AllowedMayUseActiveRealTimeConnectivity:
00073         rootPage->NotifyUser("This app is on the lock screen and has access to Active Real Time Connectivity.", NotifyType::StatusMessage);
00074         break;
00075     case BackgroundAccessStatus::Denied:
00076         rootPage->NotifyUser("This app is not on the lock screen.", NotifyType::StatusMessage);
00077         break;
00078     case BackgroundAccessStatus::Unspecified:
00079         rootPage->NotifyUser("The user has not yet taken any action. This is the default setting and the app is not on the lock screen.", NotifyType::StatusMessage);
00080         break;
00081     default:
00082         break;
00083     }
00084 }
00085
00086 void ScenarioInput1::OnNavigatedTo(NavigationEventArgs^ e)
00087 {
00088     // Get a pointer to our main page.
00089     rootPage = dynamic_cast<MainPage^>(e->Parameter);
00090 }
Generated on Sat Nov 23 2024 16:07:59 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML FlipView control/C++/SampleDataSource.h Source File

  • XAML FlipView control

SampleDataSource.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 using namespace Windows::ApplicationModel::Resources::Core;
00014 using namespace Windows::Foundation;
00015 using namespace Windows::Foundation::Collections;
00016 using namespace Windows::UI::Xaml::Data;
00017 using namespace Windows::UI::Xaml::Media;
00018 using namespace Windows::UI::Xaml::Media::Imaging;
00019
00020 namespace SDKSample
00021 {
00022     namespace FlipViewData // namespace Controls_FlipView.Data in C#
00023     {
00024         [Windows::UI::Xaml::Data::Bindable]
00025         [Windows::Foundation::Metadata::WebHostHiddenAttribute]
00026         public ref class SampleDataItem sealed
00027         {
00028             Platform::String^ _title;
00029             Platform::String^ _type;
00030             Platform::String^ _picture;
00031             ImageSource^ _image;
00032             static Uri _baseUri;
00033
00034             event PropertyChangedEventHandler^ _PropertyChanged;
00035
00036         public:
00037             SampleDataItem(Platform::String^ title,Platform::String^ type,Platform::String^ picture);
00038
00039             void OnPropertyChanged(Platform::String^ propertyName)
00040             {
00041                 PropertyChangedEventArgs^ pcea = ref new  PropertyChangedEventArgs(propertyName);
00042                 _PropertyChanged(this,pcea);
00043             }
00044
00045
00046             //Title
00047             property Platform::String^ Title
00048             {
00049                 Platform::String^ get()
00050                 {
00051                     return _title;
00052                 }
00053                 void set(Platform::String^ value)
00054                 {
00055                     _title = value;
00056                     OnPropertyChanged("Title");
00057                 }
00058             }
00059
00060             //Type
00061             property Platform::String^ Type
00062             {
00063                 Platform::String^ get()
00064                 {
00065                     return _type;
00066                 }
00067                 void set(Platform::String^ value)
00068                 {
00069                     _type = value;
00070                     OnPropertyChanged("Type");
00071                 }
00072             }
00073
00074             //Picture, _picture is the path to Image
00075             property Platform::String^ Picture
00076             {
00077                 Platform::String^ get()
00078                 {
00079                     return _picture;
00080                 }
00081                 void set(Platform::String^ value)
00082                 {
00083                     _picture = value;
00084                     OnPropertyChanged("Picture");
00085                 }
00086             }
00087
00088             //Image
00089             property ImageSource^ Image
00090             {
00091                 ImageSource^ get()
00092                 {
00093                     if(_image==nullptr && _picture!=nullptr)
00094                     {
00095                         Windows::Foundation::Uri^ uri = ref new Windows::Foundation::Uri("ms-appx:///" + _picture);
00096                         _image = ref new BitmapImage(uri);
00097                     }
00098                     return _image;
00099                 }
00100                 void set(ImageSource^ value)
00101                 {
00102                     _image = value;
00103                     OnPropertyChanged("Image");
00104                 }
00105             }
00106         };
00107
00108         // Workaround: data binding works best with an enumeration of objects that does not implement IList
00109         [Windows::Foundation::Metadata::WebHostHiddenAttribute]
00110         public ref class ItemCollection sealed
00111         {
00112         private:
00113             Windows::Foundation::Collections::IObservableVector<SampleDataItem^>^ itemCollection;
00114             UINT count;
00115
00116         public:
00117             ItemCollection():count(0)
00118             {
00119                 itemCollection = ref new Platform::Collections::Vector<SampleDataItem^>();
00120             };
00121
00122             void Add(SampleDataItem^ item)
00123             {
00124                 itemCollection->Append(item);
00125                 count++;
00126             }
00127
00128             SampleDataItem^ GetItemAt(UINT i)
00129             {
00130                 return itemCollection->GetAt(i);
00131             }
00132
00133             UINT GetCollectionCount()
00134             {
00135                 return count;
00136             }
00137         };
00138
00139         /// <summary>
00140         /// Creates a collection of groups and items with hard-coded content.
00141         /// </summary>
00142         [Windows::Foundation::Metadata::WebHostHiddenAttribute]
00143         public ref class SampleDataSource sealed
00144         {
00145             Windows::UI::Xaml::Interop::IBindableObservableVector^ _items;
00146
00147         public:
00148             SampleDataSource()
00149             {
00150                 _items = ref new Platform::Collections::Vector<Object^>();
00151
00152                 SampleDataItem^ item;
00153                 item = ref new SampleDataItem("Cliff", "item", "Assets/Cliff.jpg");
00154                 _items->Append(item);
00155
00156                 item = ref new SampleDataItem("Grapes", "item", "Assets/Grapes.jpg");
00157                 _items->Append(item);
00158
00159                 item = ref new SampleDataItem("Rainier", "item", "Assets/Rainier.jpg");
00160                 _items->Append(item);
00161
00162                 item = ref new SampleDataItem("Sunset", "item", "Assets/Sunset.jpg");
00163                 _items->Append(item);
00164
00165                 item = ref new SampleDataItem("Valley", "item", "Assets/Valley.jpg");
00166                 _items->Append(item);
00167             }
00168
00169             property Windows::UI::Xaml::Interop::IBindableObservableVector^ Items
00170             {
00171                 Windows::UI::Xaml::Interop::IBindableObservableVector^ get()
00172                 {
00173                     return _items;
00174                 }
00175
00176             }
00177         };
00178     }
00179 }
Generated on Sat Nov 23 2024 16:08:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Network information/C++/MainPage.xaml.cpp Source File

  • Network information

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:43 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML vector-based drawing/C++/common/LayoutAwarePage.cpp Source File

  • XAML vector-based drawing
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

CPolarEffect Member List

This is the complete list of members for CPolarEffect, including all inherited members.
AddInputStreams(DWORD cStreams, DWORD *adwStreamIDs) | CPolarEffect | [private]
AddInputStreams(DWORD cStreams, DWORD *adwStreamIDs) | CPolarEffect | [private]
BeginStreaming() | CPolarEffect | [private]
BeginStreaming() | CPolarEffect | [private]
DefaultRadius(DOUBLE r, DOUBLE R, DOUBLE theta) | CPolarEffect | [inline, private, static]
DefaultRadius(DOUBLE r, DOUBLE R, DOUBLE theta) | CPolarEffect | [inline, private, static]
DefaultTheta(DOUBLE r, DOUBLE R, DOUBLE theta) | CPolarEffect | [inline, private, static]
DefaultTheta(DOUBLE r, DOUBLE R, DOUBLE theta) | CPolarEffect | [inline, private, static]
DeleteInputStream(DWORD dwStreamID) | CPolarEffect | [private]
DeleteInputStream(DWORD dwStreamID) | CPolarEffect | [private]
EndStreaming() | CPolarEffect | [private]
EndStreaming() | CPolarEffect | [private]
FisheyeRadius(DOUBLE r, DOUBLE R, DOUBLE theta) | CPolarEffect | [inline, private, static]
FisheyeRadius(DOUBLE r, DOUBLE R, DOUBLE theta) | CPolarEffect | [inline, private, static]
GeneratePolarLookup(UINT32 unWidth, UINT32 unHeight, UINT32 *pIndexLookup) | CPolarEffect | [private]
GeneratePolarLookup(UINT32 unWidth, UINT32 unHeight, UINT32 *pIndexLookup) | CPolarEffect | [private]
GetAttributes(IMFAttributes **pAttributes) | CPolarEffect | [private]
GetAttributes(IMFAttributes **pAttributes) | CPolarEffect | [private]
GetInputAvailableType(DWORD dwInputStreamID, DWORD dwTypeIndex, IMFMediaType **ppType) | CPolarEffect | [private]
GetInputAvailableType(DWORD dwInputStreamID, DWORD dwTypeIndex, IMFMediaType **ppType) | CPolarEffect | [private]
GetInputCurrentType(DWORD dwInputStreamID, IMFMediaType **ppType) | CPolarEffect | [private]
GetInputCurrentType(DWORD dwInputStreamID, IMFMediaType **ppType) | CPolarEffect | [private]
GetInputStatus(DWORD dwInputStreamID, DWORD *pdwFlags) | CPolarEffect | [private]
GetInputStatus(DWORD dwInputStreamID, DWORD *pdwFlags) | CPolarEffect | [private]
GetInputStreamAttributes(DWORD dwInputStreamID, IMFAttributes **ppAttributes) | CPolarEffect | [private]
GetInputStreamAttributes(DWORD dwInputStreamID, IMFAttributes **ppAttributes) | CPolarEffect | [private]
GetInputStreamInfo(DWORD dwInputStreamID, MFT_INPUT_STREAM_INFO *pStreamInfo) | CPolarEffect | [private]
GetInputStreamInfo(DWORD dwInputStreamID, MFT_INPUT_STREAM_INFO *pStreamInfo) | CPolarEffect | [private]
GetOutputAvailableType(DWORD dwOutputStreamID, DWORD dwTypeIndex, IMFMediaType **ppType) | CPolarEffect | [private]
GetOutputAvailableType(DWORD dwOutputStreamID, DWORD dwTypeIndex, IMFMediaType **ppType) | CPolarEffect | [private]
GetOutputCurrentType(DWORD dwOutputStreamID, IMFMediaType **ppType) | CPolarEffect | [private]
GetOutputCurrentType(DWORD dwOutputStreamID, IMFMediaType **ppType) | CPolarEffect | [private]
GetOutputStatus(DWORD *pdwFlags) | CPolarEffect | [private]
GetOutputStatus(DWORD *pdwFlags) | CPolarEffect | [private]
GetOutputStreamAttributes(DWORD dwOutputStreamID, IMFAttributes **ppAttributes) | CPolarEffect | [private]
GetOutputStreamAttributes(DWORD dwOutputStreamID, IMFAttributes **ppAttributes) | CPolarEffect | [private]
GetOutputStreamInfo(DWORD dwOutputStreamID, MFT_OUTPUT_STREAM_INFO *pStreamInfo) | CPolarEffect | [private]
GetOutputStreamInfo(DWORD dwOutputStreamID, MFT_OUTPUT_STREAM_INFO *pStreamInfo) | CPolarEffect | [private]
GetStreamCount(DWORD *pcInputStreams, DWORD *pcOutputStreams) | CPolarEffect | [private]
GetStreamCount(DWORD *pcInputStreams, DWORD *pcOutputStreams) | CPolarEffect | [private]
GetStreamIDs(DWORD dwInputIDArraySize, DWORD *pdwInputIDs, DWORD dwOutputIDArraySize, DWORD *pdwOutputIDs) | CPolarEffect | [private]
GetStreamIDs(DWORD dwInputIDArraySize, DWORD *pdwInputIDs, DWORD dwOutputIDArraySize, DWORD *pdwOutputIDs) | CPolarEffect | [private]
GetStreamLimits(DWORD *pdwInputMinimum, DWORD *pdwInputMaximum, DWORD *pdwOutputMinimum, DWORD *pdwOutputMaximum) | CPolarEffect | [private]
GetStreamLimits(DWORD *pdwInputMinimum, DWORD *pdwInputMaximum, DWORD *pdwOutputMinimum, DWORD *pdwOutputMaximum) | CPolarEffect | [private]
HasPendingOutput() const | CPolarEffect | [inline, private]
HasPendingOutput() const | CPolarEffect | [inline, private]
IsValidInputStream(DWORD dwInputStreamID) const | CPolarEffect | [inline, private]
IsValidInputStream(DWORD dwInputStreamID) const | CPolarEffect | [inline, private]
IsValidOutputStream(DWORD dwOutputStreamID) const | CPolarEffect | [inline, private]
IsValidOutputStream(DWORD dwOutputStreamID) const | CPolarEffect | [inline, private]
m_bStreamingInitialized | CPolarEffect | [private]
m_cbImageSize | CPolarEffect | [private]
m_critSec | CPolarEffect | [private]
m_imageHeightInPixels | CPolarEffect | [private]
m_imageWidthInPixels | CPolarEffect | [private]
m_pAttributes | CPolarEffect | [private]
m_pIndexLookup | CPolarEffect | [private]
m_pInputType | CPolarEffect | [private]
m_pOutputType | CPolarEffect | [private]
m_pRadiusTransformFn | CPolarEffect | [private]
m_pSample | CPolarEffect | [private]
m_pThetaTransformFn | CPolarEffect | [private]
m_pTransformFn | CPolarEffect | [private]
OnCheckInputType(IMFMediaType *pmt) | CPolarEffect | [private]
OnCheckInputType(IMFMediaType *pmt) | CPolarEffect | [private]
OnCheckMediaType(IMFMediaType *pmt) | CPolarEffect | [private]
OnCheckMediaType(IMFMediaType *pmt) | CPolarEffect | [private]
OnCheckOutputType(IMFMediaType *pmt) | CPolarEffect | [private]
OnCheckOutputType(IMFMediaType *pmt) | CPolarEffect | [private]
OnFlush() | CPolarEffect | [private]
OnFlush() | CPolarEffect | [private]
OnGetPartialType(DWORD dwTypeIndex, IMFMediaType **ppmt) | CPolarEffect | [private]
OnGetPartialType(DWORD dwTypeIndex, IMFMediaType **ppmt) | CPolarEffect | [private]
OnProcessOutput(IMFMediaBuffer *pIn, IMFMediaBuffer *pOut) | CPolarEffect | [private]
OnProcessOutput(IMFMediaBuffer *pIn, IMFMediaBuffer *pOut) | CPolarEffect | [private]
OnSetInputType(IMFMediaType *pmt) | CPolarEffect | [private]
OnSetInputType(IMFMediaType *pmt) | CPolarEffect | [private]
OnSetOutputType(IMFMediaType *pmt) | CPolarEffect | [private]
OnSetOutputType(IMFMediaType *pmt) | CPolarEffect | [private]
PinchRadius(DOUBLE r, DOUBLE R, DOUBLE theta) | CPolarEffect | [inline, private, static]
PinchRadius(DOUBLE r, DOUBLE R, DOUBLE theta) | CPolarEffect | [inline, private, static]
ProcessEvent(DWORD dwInputStreamID, IMFMediaEvent *pEvent) | CPolarEffect | [private]
ProcessEvent(DWORD dwInputStreamID, IMFMediaEvent *pEvent) | CPolarEffect | [private]
ProcessInput(DWORD dwInputStreamID, IMFSample *pSample, DWORD dwFlags) | CPolarEffect | [private]
ProcessInput(DWORD dwInputStreamID, IMFSample *pSample, DWORD dwFlags) | CPolarEffect | [private]
ProcessMessage(MFT_MESSAGE_TYPE eMessage, ULONG_PTR ulParam) | CPolarEffect | [private]
ProcessMessage(MFT_MESSAGE_TYPE eMessage, ULONG_PTR ulParam) | CPolarEffect | [private]
ProcessOutput(DWORD dwFlags, DWORD cOutputBufferCount, MFT_OUTPUT_DATA_BUFFER *pOutputSamples, DWORD *pdwStatus) | CPolarEffect | [private]
ProcessOutput(DWORD dwFlags, DWORD cOutputBufferCount, MFT_OUTPUT_DATA_BUFFER *pOutputSamples, DWORD *pdwStatus) | CPolarEffect | [private]
RuntimeClassInitialize() | CPolarEffect | [private]
RuntimeClassInitialize() | CPolarEffect | [private]
SetInputType(DWORD dwInputStreamID, IMFMediaType *pType, DWORD dwFlags) | CPolarEffect | [private]
SetInputType(DWORD dwInputStreamID, IMFMediaType *pType, DWORD dwFlags) | CPolarEffect | [private]
SetOutputBounds(LONGLONG hnsLowerBound, LONGLONG hnsUpperBound) | CPolarEffect | [private]
SetOutputBounds(LONGLONG hnsLowerBound, LONGLONG hnsUpperBound) | CPolarEffect | [private]
SetOutputType(DWORD dwOutputStreamID, IMFMediaType *pType, DWORD dwFlags) | CPolarEffect | [private]
SetOutputType(DWORD dwOutputStreamID, IMFMediaType *pType, DWORD dwFlags) | CPolarEffect | [private]
SetProperties(ABI::Windows::Foundation::Collections::IPropertySet *pConfiguration) | CPolarEffect | [private]
SetProperties(ABI::Windows::Foundation::Collections::IPropertySet *pConfiguration) | CPolarEffect | [private]
UpdateFormatInfo() | CPolarEffect | [private]
UpdateFormatInfo() | CPolarEffect | [private]
WarpTheta(DOUBLE r, DOUBLE R, DOUBLE theta) | CPolarEffect | [inline, private, static]
WarpTheta(DOUBLE r, DOUBLE R, DOUBLE theta) | CPolarEffect | [inline, private, static]
~CPolarEffect() | CPolarEffect | [private]
~CPolarEffect() | CPolarEffect | [private]
Generated on Sat Nov 23 2024 16:09:10 for Win8-Examples by doxygen 1.7.1


Win8-Examples: User domain name/C++/App.xaml.cpp Source File

  • User domain name

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:28 for Win8-Examples by doxygen 1.7.1


Win8-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.
__pad0__ | Program |
AddShape(_In_reads_(numPoints) Windows::Foundation::Point const *points, _In_ int numPoints, _In_ D2D1::ColorF color) | Program | [private]
CreateWindowSizeDependentResources() | Program |
DrawBackward(_In_ std::shared_ptr< ShapeRecord > const &shapeRec) | Program | [private]
Initialize(_In_ Windows::UI::Core::CoreWindow^window) | Program |
m_d2dContext | Program | [private]
m_height | Program | [private]
m_shapes | Program | [private]
m_width | Program | [private]
m_window | Program | [private]
MoveToFront(_Inout_ std::shared_ptr< ShapeRecord > &shapeRec) | Program | [private]
OnPointerMoved(_In_ Windows::UI::Core::PointerEventArgs^args) | Program |
OnPointerPressed(_In_ Windows::UI::Core::PointerEventArgs^args) | Program |
OnPointerReleased(_In_ Windows::UI::Core::PointerEventArgs^args) | Program |
OnTouchHitTesting(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::TouchHitTestingEventArgs^args) | Program | [private]
PointHitTest(_In_ Windows::Foundation::Point pt) | Program | [private]
RenderObjects() | Program |
SetD2DContext(_In_ ID2D1DeviceContext *d2dContext) | Program |
SetupControls() | Program | [private]
~Program() | Program | [private]
Generated on Sat Nov 23 2024 16:09:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Simple3DTouch Member List

This is the complete list of members for Simple3DTouch, including all inherited members.
__pad0__ | Simple3DTouch |
CreateDeviceIndependentResources() override | Simple3DTouch | [virtual]
CreateDeviceResources() override | Simple3DTouch | [virtual]
CreateWindowSizeDependentResources() override | Simple3DTouch | [virtual]
LoadInternalState(_In_ Windows::Foundation::Collections::IPropertySet^state) | Simple3DTouch |
m_camera | Simple3DTouch | [private]
m_constantBuffer | Simple3DTouch | [private]
m_constantBufferData | Simple3DTouch | [private]
m_controller | Simple3DTouch | [private]
m_indexBuffer | Simple3DTouch | [private]
m_indexCount | Simple3DTouch | [private]
m_inputLayout | Simple3DTouch | [private]
m_lookControlLayout | Simple3DTouch | [private]
m_lookMetrics | Simple3DTouch | [private]
m_moveControlLayout | Simple3DTouch | [private]
m_moveMetrics | Simple3DTouch | [private]
m_pixelShader | Simple3DTouch | [private]
m_sampleOverlay | Simple3DTouch | [private]
m_sampler | Simple3DTouch | [private]
m_textBrush | Simple3DTouch | [private]
m_textFormat | Simple3DTouch | [private]
m_texture | Simple3DTouch | [private]
m_textureSRV | Simple3DTouch | [private]
m_vertexBuffer | Simple3DTouch | [private]
m_vertexShader | Simple3DTouch | [private]
Render() override | Simple3DTouch | [virtual]
SaveInternalState(_In_ Windows::Foundation::Collections::IPropertySet^state) | Simple3DTouch |
Update(float TimeTotal, float TimeDelta) | Simple3DTouch |
Generated on Sat Nov 23 2024 16:09:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XInput game controller/C++/pch.cpp Source File

  • XInput game controller

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Compass sensor/C++/Scenario1.xaml.cpp Source File

  • Compass sensor

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::CompassCPP;
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::Devices::Sensors;
00025 using namespace Windows::Foundation;
00026 using namespace Windows::UI::Core;
00027 using namespace Platform;
00028
00029 Scenario1::Scenario1() : rootPage(MainPage::Current), desiredReportInterval(0)
00030 {
00031     InitializeComponent();
00032
00033     compass = Compass::GetDefault();
00034     if (compass != nullptr)
00035     {
00036         // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
00037         // This value will be used later to activate the sensor.
00038         uint32 minReportInterval = compass->MinimumReportInterval;
00039         desiredReportInterval = minReportInterval > 16 ? minReportInterval : 16;
00040     }
00041     else
00042     {
00043         rootPage->NotifyUser("No compass found", NotifyType::ErrorMessage);
00044     }
00045 }
00046
00047 /// <summary>
00048 /// Invoked when this page is about to be displayed in a Frame.
00049 /// </summary>
00050 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00051 /// property is typically used to configure the page.</param>
00052 void Scenario1::OnNavigatedTo(NavigationEventArgs^ e)
00053 {
00054     ScenarioEnableButton->IsEnabled = true;
00055     ScenarioDisableButton->IsEnabled = false;
00056 }
00057
00058 /// <summary>
00059 /// Invoked when this page is no longer displayed.
00060 /// </summary>
00061 /// <param name="e"></param>
00062 void Scenario1::OnNavigatedFrom(NavigationEventArgs^ e)
00063 {
00064     if (ScenarioDisableButton->IsEnabled)
00065     {
00066         Window::Current->VisibilityChanged::remove(visibilityToken);
00067         compass->ReadingChanged::remove(readingToken);
00068
00069         // Restore the default report interval to release resources while the sensor is not in use
00070         compass->ReportInterval = 0;
00071     }
00072 }
00073
00074 /// <summary>
00075 /// This is the event handler for VisibilityChanged events. You would register for these notifications
00076 /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00077 /// </summary>
00078 /// <param name="sender"></param>
00079 /// <param name="e">
00080 /// Event data that can be examined for the current visibility state.
00081 /// </param>
00082 void Scenario1::VisibilityChanged(Object^ sender, VisibilityChangedEventArgs^ e)
00083 {
00084     // The app should watch for VisibilityChanged events to disable and re-enable sensor input as appropriate
00085     if (ScenarioDisableButton->IsEnabled)
00086     {
00087         if (e->Visible)
00088         {
00089             // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00090             readingToken = compass->ReadingChanged::add(ref new TypedEventHandler<Compass^, CompassReadingChangedEventArgs^>(this, &Scenario1::ReadingChanged));
00091         }
00092         else
00093         {
00094             // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00095             compass->ReadingChanged::remove(readingToken);
00096         }
00097     }
00098 }
00099
00100 void Scenario1::ReadingChanged(Compass^ sender, CompassReadingChangedEventArgs^ e)
00101 {
00102     // We need to dispatch to the UI thread to display the output
00103     Dispatcher->RunAsync(
00104         CoreDispatcherPriority::Normal,
00105         ref new DispatchedHandler(
00106             [this, e]()
00107             {
00108                 CompassReading^ reading = e->Reading;
00109
00110                 ScenarioOutput_MagneticNorth->Text = reading->HeadingMagneticNorth.ToString();
00111                 if (reading->HeadingTrueNorth != nullptr)
00112                 {
00113                     ScenarioOutput_TrueNorth->Text = reading->HeadingTrueNorth->Value.ToString();
00114                 }
00115                 else
00116                 {
00117                     ScenarioOutput_TrueNorth->Text = "No data";
00118                 }
00119             },
00120             CallbackContext::Any
00121             )
00122         );
00123 }
00124
00125 void Scenario1::ScenarioEnable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00126 {
00127     if (compass != nullptr)
00128     {
00129         // Establish the report interval
00130         compass->ReportInterval = desiredReportInterval;
00131
00132         visibilityToken = Window::Current->VisibilityChanged::add(ref new WindowVisibilityChangedEventHandler(this, &Scenario1::VisibilityChanged));
00133         readingToken = compass->ReadingChanged::add(ref new TypedEventHandler<Compass^, CompassReadingChangedEventArgs^>(this, &Scenario1::ReadingChanged));
00134
00135         ScenarioEnableButton->IsEnabled = false;
00136         ScenarioDisableButton->IsEnabled = true;
00137     }
00138     else
00139     {
00140         rootPage->NotifyUser("No compass found", NotifyType::ErrorMessage);
00141     }
00142 }
00143
00144 void Scenario1::ScenarioDisable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00145 {
00146     Window::Current->VisibilityChanged::remove(visibilityToken);
00147     compass->ReadingChanged::remove(readingToken);
00148
00149     // Restore the default report interval to release resources while the sensor is not in use
00150     compass->ReportInterval = 0;
00151
00152     ScenarioEnableButton->IsEnabled = true;
00153     ScenarioDisableButton->IsEnabled = false;
00154 }
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML user and custom controls/C++/Scenario4.xaml.h Source File

  • XAML user and custom controls

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
00022 namespace SDKSample
00023 {
00024     namespace UserAndCustomControls
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 Scenario4 sealed
00031         {
00032         public:
00033             Scenario4();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040             void Other_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         void NavigateToLink(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00042         };
00043     }
00044 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File picker/C++/Scenario6.xaml.h Source File

  • File picker

Scenario6.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 // Scenario6.xaml.h
00013 // Declaration of the Scenario6 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario6.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace FilePicker
00025     {
00026         /// <summary>
00027         /// An empty page that can be used on its own or navigated to within a Frame.
00028         /// </summary>
00029         public ref class Scenario6 sealed
00030         {
00031         public:
00032             Scenario6();
00033
00034         private:
00035             MainPage^ rootPage;
00036             Platform::String^ fileToken;
00037
00038             void SaveFileButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039             void WriteFileButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040             void OutputFileAsync(Windows::Storage::StorageFile^ file);
00041         };
00042     }
00043 }
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Configure keys for media/C++/common/LayoutAwarePage.cpp Source File

  • Configure keys for media
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:30 for Win8-Examples by doxygen 1.7.1


Win8-Examples: StreamSocket/C++/Common/LayoutAwarePage.h Source File

  • StreamSocket
  • Common

LayoutAwarePage.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 #include <collection.h>
00015
00016 namespace StreamSocketSample
00017 {
00018     namespace Common
00019     {
00020         // Suppress class "not consumable from JavaScript because it's not marked 'sealed'" warning
00021         // currently emitted despite the WebHostHidden attribute
00022         #pragma warning(push)
00023         #pragma warning(disable: 4449)
00024         /// <summary>
00025         /// Typical implementation of Page that provides several important conveniences: application
00026         /// view state to visual state mapping, GoBack and GoHome event handlers, and a default view
00027         /// model.
00028         /// </summary>
00029         [Windows::Foundation::Metadata::WebHostHidden]
00030         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00031         {
00032         internal:
00033             LayoutAwarePage();
00034         public:
00035             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00036             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00037             void InvalidateVisualState();
00038             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00039             {
00040                 Windows::UI::Xaml::DependencyProperty^ get();
00041             };
00042             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Object^>^ DefaultViewModel
00043             {
00044                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Object^>^ get();
00045                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Object^>^ value);
00046             }
00047
00048         protected:
00049             virtual void GoHome(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00050             virtual void GoBack(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00051             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00052
00053         private:
00054             Platform::Collections::Map<Platform::String^, Object^>^ _defaultViewModel;
00055             Windows::Foundation::EventRegistrationToken _windowSizeEventToken;
00056             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00057             void WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00058         };
00059         #pragma warning(pop)
00060     }
00061 }
Generated on Sat Nov 23 2024 16:07:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Custom driver access/C++/app_cpp/Scenario4_DeviceAsync.xaml.h Source File

  • Custom driver access
  • app_cpp

Scenario4_DeviceAsync.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 // DeviceAsync.xaml.h
00013 // Declaration of the DeviceAsync class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario4_DeviceAsync.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace CustomDeviceAccess
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 DeviceAsync sealed
00031         {
00032         public:
00033             DeviceAsync();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void deviceAsyncSet_Click_1(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040             void deviceAsyncGet_Click_1(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041             void ClearBarGraphTable(void);
00042             void UpdateBarGraphTable(Platform::Array<bool>^ BarGraphArray);
00043         };
00044     }
00045 }
Generated on Sat Nov 23 2024 16:08:02 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D magazine app/C++/App.xaml.cpp Source File

  • Direct2D magazine app

App.xaml.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
00010 using namespace Magazine;
00011 using namespace Windows::ApplicationModel;
00012 using namespace Windows::ApplicationModel::Activation;
00013 using namespace Windows::Foundation;
00014 using namespace Windows::UI::Input;
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::Xaml::Interop;
00023 using namespace Windows::Storage;
00024
00025 App::App()
00026 {
00027     InitializeComponent();
00028 }
00029
00030 App::~App()
00031 {
00032 }
00033
00034 void App::OnLaunched(
00035     _In_ LaunchActivatedEventArgs^ args
00036     )
00037 {
00038     Window::Current->Content = ref new MainPage();
00039     Window::Current->Activate();
00040
00041     Suspending += ref new SuspendingEventHandler(this, &App::OnSuspending);
00042     Resuming += ref new EventHandler<Object^>(this, &App::OnResuming);
00043 }
00044
00045 void App::OnSuspending(
00046     _In_ Platform::Object^ sender,
00047     _In_ SuspendingEventArgs^ args
00048     )
00049 {
00050     // This is a good time to save your application's state in case the process gets terminated.
00051     // That way, when the user relaunches the application, they will return to the position they left.
00052     auto mainPage = dynamic_cast<MainPage^>(Window::Current->Content);
00053     mainPage->SaveState(ApplicationData::Current->LocalSettings->Values);
00054 }
00055
00056 void App::OnResuming(
00057     _In_ Platform::Object^ sender,
00058     _In_ Platform::Object^ args
00059     )
00060 {
00061     // No extra operation required on resume as the application is only visually updated.
00062     // If the application is suspended for a longer period and is eventually terminated,
00063     // the application's activation logic will ensure that the application saved state is
00064     // properly restored.
00065 }
Generated on Sat Nov 23 2024 16:07:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Language font mapping/C++/ScenarioList.xaml.cpp Source File

  • Language font mapping

ScenarioList.xaml.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 //
00009 // ScenarioList.xaml.cpp
00010 // Implementation of the ScenarioList class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioList.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace LanguageFontCPP;
00018
00019 using namespace Platform;
00020 using namespace CppSamplesUtils;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Foundation::Collections;
00023 using namespace Windows::Graphics::Display;
00024 using namespace Windows::UI::ViewManagement;
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 using namespace Windows::UI::Xaml::Interop;
00033
00034 ScenarioList::ScenarioList()
00035 {
00036     InitializeComponent();
00037 }
00038
00039 ScenarioList::~ScenarioList()
00040 {
00041 }
00042
00043 void ScenarioList::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00044 {
00045     if(Scenarios->SelectedItem != nullptr)
00046     {
00047         rootPage->NotifyUser("", NotifyType::StatusMessage);
00048
00049         ListBoxItem^ selectedListBoxItem = dynamic_cast<ListBoxItem^>(Scenarios->SelectedItem);
00050         SuspensionManager::SessionState()->Insert("SelectedScenario", selectedListBoxItem->Name);
00051
00052         if (rootPage->InputFrame != nullptr && rootPage->OutputFrame != nullptr)
00053         {
00054              //Load the input and output pages for the current scenario into their respective frames
00055             TypeName inputPage = { "LanguageFontCPP" + "." + "ScenarioInput" + ((Scenarios->SelectedIndex + 1).ToString()), TypeKind::Custom };
00056             TypeName outputPage = { "LanguageFontCPP" + "." + "ScenarioOutput" + ((Scenarios->SelectedIndex + 1).ToString()), TypeKind::Custom };
00057             rootPage->DoNavigation(inputPage, rootPage->InputFrame, outputPage, rootPage->OutputFrame);
00058         }
00059     }
00060 }
00061
00062 void ScenarioList::OnNavigatedTo(NavigationEventArgs^ e)
00063 {
00064     rootPage = dynamic_cast<MainPage^>(e->Parameter);
00065
00066     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &ScenarioList::Scenarios_SelectionChanged);
00067     ListBoxItem^ startingScenario = nullptr;
00068
00069     auto ps = SuspensionManager::SessionState();
00070     if (ps->HasKey("SelectedScenario"))
00071     {
00072         String^ item = dynamic_cast<String^>(ps->Lookup("SelectedScenario"));
00073         startingScenario = dynamic_cast<ListBoxItem^>(this->FindName(item));
00074     }
00075
00076     Scenarios->SelectedItem = startingScenario != nullptr ? startingScenario : Scenario1;
00077 }
Generated on Sat Nov 23 2024 16:07:57 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

GameObject Member List

This is the complete list of members for GameObject, including all inherited members.
__pad0__ | GameObject |
Active(bool active) | GameObject |
Active() | GameObject |
Active(bool active) | GameObject |
Active() | GameObject |
AnimatePosition(_In_opt_ Animate^animate) | GameObject |
AnimatePosition() | GameObject |
AnimatePosition(_In_opt_ Animate^animate) | GameObject |
AnimatePosition() | GameObject |
Hit(bool hit) | GameObject |
Hit() | GameObject |
Hit(bool hit) | GameObject |
Hit() | GameObject |
HitMaterial(_In_ Material^material) | GameObject |
HitMaterial() | GameObject |
HitMaterial(_In_ Material^material) | GameObject |
HitMaterial() | GameObject |
HitSound(_In_ SoundEffect^hitSound) | GameObject |
HitSound() | GameObject |
HitSound(_In_ SoundEffect^hitSound) | GameObject |
HitSound() | GameObject |
HitTime(float t) | GameObject |
HitTime() | GameObject |
HitTime(float t) | GameObject |
HitTime() | GameObject |
IsTouching(DirectX::XMFLOAT3, float, _Out_ DirectX::XMFLOAT3 *contact, _Out_ DirectX::XMFLOAT3 *normal) | GameObject | [inline, virtual]
IsTouching(DirectX::XMFLOAT3, float, _Out_ DirectX::XMFLOAT3 *contact, _Out_ DirectX::XMFLOAT3 *normal) | GameObject | [inline, virtual]
m_active | GameObject | [private]
m_animatePosition | GameObject | [private]
m_defaultXAxis | GameObject | [private]
m_defaultYAxis | GameObject | [private]
m_defaultZAxis | GameObject | [private]
m_ground | GameObject | [private]
m_hit | GameObject | [private]
m_hitMaterial | GameObject | [private]
m_hitSound | GameObject | [private]
m_hitTime | GameObject | [private]
m_mesh | GameObject | [private]
m_modelMatrix | GameObject | [private]
m_normalMaterial | GameObject | [private]
m_position | GameObject | [private]
m_target | GameObject | [private]
m_targetId | GameObject | [private]
m_velocity | GameObject | [private]
Mesh(_In_ MeshObject^mesh) | GameObject |
Mesh(_In_ MeshObject^mesh) | GameObject |
ModelMatrix() | GameObject |
ModelMatrix() | GameObject |
NormalMaterial(_In_ Material^material) | GameObject |
NormalMaterial() | GameObject |
NormalMaterial(_In_ Material^material) | GameObject |
NormalMaterial() | GameObject |
OnGround(bool ground) | GameObject |
OnGround() | GameObject |
OnGround(bool ground) | GameObject |
OnGround() | GameObject |
PlaySound(float impactSpeed, DirectX::XMFLOAT3 eyePoint) | GameObject |
PlaySound(float impactSpeed, DirectX::XMFLOAT3 eyePoint) | GameObject |
Position(DirectX::XMFLOAT3 position) | GameObject |
Position(DirectX::XMVECTOR position) | GameObject |
Position() | GameObject |
Position(DirectX::XMFLOAT3 position) | GameObject |
Position(DirectX::XMVECTOR position) | GameObject |
Position() | GameObject |
Render(_In_ ID3D11DeviceContext *context, _In_ ID3D11Buffer *primitiveConstantBuffer) | GameObject |
Render(_In_ ID3D11DeviceContext *context, _In_ ID3D11Buffer *primitiveConstantBuffer) | GameObject |
Target(bool target) | GameObject |
Target() | GameObject |
Target(bool target) | GameObject |
Target() | GameObject |
TargetId(int targetId) | GameObject |
TargetId() | GameObject |
TargetId(int targetId) | GameObject |
TargetId() | GameObject |
UpdatePosition() | GameObject | [inline, private, virtual]
UpdatePosition() | GameObject | [inline, private, virtual]
VectorPosition() | GameObject |
VectorPosition() | GameObject |
VectorVelocity() | GameObject |
VectorVelocity() | GameObject |
Velocity(DirectX::XMFLOAT3 velocity) | GameObject |
Velocity(DirectX::XMVECTOR velocity) | GameObject |
Velocity() | GameObject |
Velocity(DirectX::XMFLOAT3 velocity) | GameObject |
Velocity(DirectX::XMVECTOR velocity) | GameObject |
Velocity() | GameObject |
Generated on Sat Nov 23 2024 16:09:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Gyrometer sensor/C++/common/LayoutAwarePage.cpp Source File

  • Gyrometer sensor
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:31 for Win8-Examples by doxygen 1.7.1


Win8-Examples: OrientationSensor/C++/Scenario2.xaml.cpp Source File

  • OrientationSensor

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 SDKSample::OrientationSensorCPP;
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::Devices::Sensors;
00025 using namespace Windows::Foundation;
00026 using namespace Windows::UI::Core;
00027 using namespace Platform;
00028
00029 Scenario2::Scenario2() : rootPage(MainPage::Current), desiredReportInterval(0)
00030 {
00031     InitializeComponent();
00032
00033     sensor = OrientationSensor::GetDefault();
00034     if (sensor != nullptr)
00035     {
00036         // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
00037         // This value will be used later to activate the sensor.
00038         uint32 minReportInterval = sensor->MinimumReportInterval;
00039         desiredReportInterval = minReportInterval > 16 ? minReportInterval : 16;
00040
00041         // Set up a DispatchTimer
00042         TimeSpan span;
00043         span.Duration = static_cast<int32>(desiredReportInterval) * 10000;   // convert to 100ns ticks
00044         dispatcherTimer = ref new DispatcherTimer();
00045         dispatcherTimer->Interval = span;
00046         dispatcherTimer->Tick += ref new Windows::Foundation::EventHandler<Object^>(this, &Scenario2::DisplayCurrentReading);
00047     }
00048     else
00049     {
00050         rootPage->NotifyUser("No orientation sensor found", NotifyType::ErrorMessage);
00051     }
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 void Scenario2::OnNavigatedTo(NavigationEventArgs^ e)
00060 {
00061     ScenarioEnableButton->IsEnabled = true;
00062     ScenarioDisableButton->IsEnabled = false;
00063 }
00064
00065 /// <summary>
00066 /// Invoked when this page is no longer displayed.
00067 /// </summary>
00068 /// <param name="e"></param>
00069 void Scenario2::OnNavigatedFrom(NavigationEventArgs^ e)
00070 {
00071     if (ScenarioDisableButton->IsEnabled)
00072     {
00073         Window::Current->VisibilityChanged::remove(visibilityToken);
00074         dispatcherTimer->Stop();
00075
00076         // Restore the default report interval to release resources while the sensor is not in use
00077         sensor->ReportInterval = 0;
00078     }
00079 }
00080
00081 /// <summary>
00082 /// This is the event handler for VisibilityChanged events. You would register for these notifications
00083 /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00084 /// </summary>
00085 /// <param name="sender"></param>
00086 /// <param name="e">
00087 /// Event data that can be examined for the current visibility state.
00088 /// </param>
00089 void Scenario2::VisibilityChanged(Object^ sender, VisibilityChangedEventArgs^ e)
00090 {
00091     // The app should watch for VisibilityChanged events to disable and re-enable sensor input as appropriate
00092     if (ScenarioDisableButton->IsEnabled)
00093     {
00094         if (e->Visible)
00095         {
00096             // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00097             dispatcherTimer->Start();
00098         }
00099         else
00100         {
00101             // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00102             dispatcherTimer->Stop();
00103         }
00104     }
00105 }
00106
00107 void Scenario2::DisplayCurrentReading(Object^ sender, Object^ e)
00108 {
00109     OrientationSensorReading^ reading = sensor->GetCurrentReading();
00110     if (reading != nullptr)
00111     {
00112         // Quaternion values
00113         SensorQuaternion^ quaternion = reading->Quaternion; // get a reference to the object to avoid re-creating it for each access
00114         ScenarioOutput_X->Text = quaternion->X.ToString();
00115         ScenarioOutput_Y->Text = quaternion->Y.ToString();
00116         ScenarioOutput_Z->Text = quaternion->Z.ToString();
00117         ScenarioOutput_W->Text = quaternion->W.ToString();
00118
00119         // Rotation Matrix values
00120         SensorRotationMatrix^ rotationMatrix = reading->RotationMatrix;
00121         ScenarioOutput_M11->Text = rotationMatrix->M11.ToString();
00122         ScenarioOutput_M12->Text = rotationMatrix->M12.ToString();
00123         ScenarioOutput_M13->Text = rotationMatrix->M13.ToString();
00124         ScenarioOutput_M21->Text = rotationMatrix->M21.ToString();
00125         ScenarioOutput_M22->Text = rotationMatrix->M22.ToString();
00126         ScenarioOutput_M23->Text = rotationMatrix->M23.ToString();
00127         ScenarioOutput_M31->Text = rotationMatrix->M31.ToString();
00128         ScenarioOutput_M32->Text = rotationMatrix->M32.ToString();
00129         ScenarioOutput_M33->Text = rotationMatrix->M33.ToString();
00130     }
00131 }
00132
00133 void Scenario2::ScenarioEnable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00134 {
00135     if (sensor != nullptr)
00136     {
00137         visibilityToken = Window::Current->VisibilityChanged::add(ref new WindowVisibilityChangedEventHandler(this, &Scenario2::VisibilityChanged));
00138
00139         // Set the report interval to enable the sensor for polling
00140         sensor->ReportInterval = desiredReportInterval;
00141
00142         dispatcherTimer->Start();
00143
00144         ScenarioEnableButton->IsEnabled = false;
00145         ScenarioDisableButton->IsEnabled = true;
00146     }
00147     else
00148     {
00149         rootPage->NotifyUser("No orientation sensor found", NotifyType::ErrorMessage);
00150     }
00151 }
00152
00153 void Scenario2::ScenarioDisable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00154 {
00155     Window::Current->VisibilityChanged::remove(visibilityToken);
00156
00157     dispatcherTimer->Stop();
00158
00159     // Restore the default report interval to release resources while the sensor is not in use
00160     sensor->ReportInterval = 0;
00161
00162     ScenarioEnableButton->IsEnabled = true;
00163     ScenarioDisableButton->IsEnabled = false;
00164 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: App tiles and badges/C#,C++/SendLocalImageTile.xaml.cpp Source File

  • App tiles and badges
  • C#,C++

SendLocalImageTile.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 // SendLocalImageTile.xaml.cpp
00013 // Implementation of the SendLocalImageTile class
00014 //
00015
00016 #include "pch.h"
00017 #include "SendLocalImageTile.xaml.h"
00018
00019 using namespace SDKSample::Tiles;
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::UI::Notifications;
00025 using namespace NotificationsExtensions::TileContent;
00026
00027 SendLocalImageTile::SendLocalImageTile()
00028 {
00029   InitializeComponent();
00030 }
00031
00032 void SendLocalImageTile::OnNavigatedTo(NavigationEventArgs^ e)
00033 {
00034   rootPage = MainPage::Current;
00035 }
00036
00037 void SendLocalImageTile::UpdateTileWithImage_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00038 {
00039   // Note: This sample contains an additional project, NotificationsExtensions.
00040   // NotificationsExtensions exposes an object model for creating notifications, but you can also modify the xml
00041   // of the notification directly via TileUpdateManager::GetTemplateContent(TileTemplateType)
00042
00043   // create the wide template
00044   auto tileContent = TileContentFactory::CreateTileWideImageAndText01();
00045
00046   tileContent->TextCaptionWrap->Text = "This tile notification uses ms-appx images";
00047   tileContent->Image->Src = "ms-appx:///redWide.png";
00048   tileContent->Image->Alt = "Red image";
00049
00050   // Users can resize tiles to square or wide.
00051   // Apps can choose to include only square assets (meaning the app's tile can never be wide), or
00052   // include both wide and square assets (the user can resize the tile to square or wide).
00053   // Apps cannot include only wide assets.
00054
00055   // Apps that support being wide should include square tile notifications since users
00056   // determine the size of the tile.
00057
00058   // create the square template and attach it to the wide template
00059   auto squareContent = TileContentFactory::CreateTileSquareImage();
00060   squareContent->Image->Src = "ms-appx:///graySquare.png";
00061   squareContent->Image->Alt = "Gray image";
00062   tileContent->SquareContent = squareContent;
00063
00064   // Send the notification to the app's application tile
00065   TileUpdateManager::CreateTileUpdaterForApplication()->Update(tileContent->CreateNotification());
00066
00067   OutputTextBlock->Text = tileContent->GetContent();
00068 }
00069
00070 void SendLocalImageTile::UpdateTileWithImageWithStringManipulation_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00071 {
00072   // create a string with the tile template xml
00073   auto tileXmlString = "<tile>"
00074     + "<visual>"
00075     + "<binding template='TileWideImageAndText01'>"
00076     + "<text id='1'>This tile notification uses ms-appx images</text>"
00077     + "<image id='1' src='ms-appx:///redWide.png'/>"
00078     + "</binding>"
00079     + "<binding template='TileSquareImage'>"
00080     + "<image id='1' src='ms-appx:///graySquare.png'/>"
00081     + "</binding>"
00082     + "</visual>"
00083     + "</tile>";
00084
00085   // create a DOM
00086   auto tileDOM = ref new Windows::Data::Xml::Dom::XmlDocument();
00087
00088   // load the xml string into the DOM, catching any invalid xml characters
00089   tileDOM->LoadXml(tileXmlString);
00090
00091   // create a tile notification
00092   auto tile = ref new TileNotification(tileDOM);
00093
00094   // Send the notification to the app's application tile
00095   TileUpdateManager::CreateTileUpdaterForApplication()->Update(tile);
00096
00097   OutputTextBlock->Text = tileDOM->GetXml();
00098 }
00099
00100 void SendLocalImageTile::ClearTile_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00101 {
00102   // A TileUpdater is also used to clear the tile
00103   TileUpdateManager::CreateTileUpdaterForApplication()->Clear();
00104   OutputTextBlock->Text = "Tile cleared";
00105 }
Generated on Sat Nov 23 2024 16:07:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D custom image effects/C++/VertexShader/DirectXSample.h Source File

  • Direct2D custom image effects
  • VertexShader

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
00010 // This header defines helper utilities to make DirectX APIs work with exceptions.
00011 namespace DX
00012 {
00013     inline void ThrowIfFailed(HRESULT hr)
00014     {
00015         if (FAILED(hr))
00016         {
00017             // Set a breakpoint on this line to catch DX API errors.
00018             throw Platform::Exception::CreateException(hr);
00019         }
00020     }
00021 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-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.
__pad0__ WorldCeilingMesh
Generated on Sat Nov 23 2024 16:09:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Display orientation/C++/pch.cpp Source File

  • Display orientation

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/Level.h Source File

  • XAML DirectX 3D shooting game

Level.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 // Level:
00011 // This is an abstract class from which all of the levels of the game are derived.
00012 // Each level potentially overrides up to four methods:
00013 //     Initialize - (required) takes a list of objects and enables the objects that
00014 //         are active for the level as well as setting their positions and
00015 //         any animations associated with the objects.
00016 //     Update - this method is called once per time step and is expected to
00017 //         determine if the level has been completed.  The Level class provides
00018 //         a 'standard' Update method which checks each object that is a target
00019 //         and disables any active targets that have been hit.  It returns true
00020 //         once there are no active targets remaining.
00021 //     SaveState - method to save any Level specific state.  Default is defined as
00022 //         not saving any state.
00023 //     LoadState - method to restore any Level specific state.  Default is defined
00024 //         as not restoring any state.
00025
00026 #include "GameObject.h"
00027 #include "PersistentState.h"
00028
00029 ref class Level abstract
00030 {
00031 internal:
00032     virtual void Initialize(
00033         std::vector<GameObject^> objects
00034         ) = 0;
00035
00036     virtual bool Update(
00037         float time,
00038         float elapsedTime,
00039         float timeRemaining,
00040         std::vector<GameObject^> objects
00041         );
00042
00043     virtual void SaveState(PersistentState^ state);
00044     virtual void LoadState(PersistentState^ state);
00045
00046     Platform::String^ Objective();
00047     float TimeLimit();
00048
00049 protected private:
00050     Platform::String^ m_objective;
00051     float             m_timeLimit;
00052 };
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Toast notifications/C#,C++/ScenarioInput4.xaml.cpp Source File

  • Toast notifications
  • C#,C++

ScenarioInput4.xaml.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 //
00009 // Scenario1Input.xaml.cpp
00010 // Implementation of the Scenario1Input class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioInput4.xaml.h"
00015
00016 using namespace ToastsSampleCPP;
00017
00018 using namespace NotificationsExtensions::ToastContent;
00019 using namespace Platform;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Graphics::Display;
00023 using namespace Windows::UI::Notifications;
00024 using namespace Windows::UI::ViewManagement;
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 ScenarioInput4::ScenarioInput4()
00034 {
00035   InitializeComponent();
00036
00037   Scenario4DisplayToastSilent->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00038     Scenario4DisplayToastWithSound(ToastAudioContent::Silent, "Silent");
00039   });
00040   Scenario4DisplayToastDefault->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00041     Scenario4DisplayToastWithSound(ToastAudioContent::Default, "Default");
00042   });
00043   Scenario4DisplayToastMail->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00044     Scenario4DisplayToastWithSound(ToastAudioContent::Mail, "Mail");
00045   });
00046   Scenario4DisplayToastSMS->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00047     Scenario4DisplayToastWithSound(ToastAudioContent::SMS, "SMS");
00048   });
00049   Scenario4DisplayToastIM->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00050     Scenario4DisplayToastWithSound(ToastAudioContent::IM, "IM");
00051   });
00052   Scenario4DisplayToastReminder->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00053     Scenario4DisplayToastWithSound(ToastAudioContent::Reminder, "Reminder");
00054   });
00055
00056
00057   Scenario4DisplayToastSilentString->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00058     Scenario4DisplayToastWithSoundWithStringManipulation(ToastAudioContent::Silent, "Silent");
00059   });
00060   Scenario4DisplayToastDefaultString->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00061     Scenario4DisplayToastWithSoundWithStringManipulation(ToastAudioContent::Default, "Default");
00062   });
00063   Scenario4DisplayToastMailString->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00064     Scenario4DisplayToastWithSoundWithStringManipulation(ToastAudioContent::Mail, "Mail");
00065   });
00066 }
00067
00068 ScenarioInput4::~ScenarioInput4()
00069 {
00070 }
00071
00072 #pragma region Template-Related Code - Do not remove
00073 void ScenarioInput4::OnNavigatedTo(NavigationEventArgs^ e)
00074 {
00075   // Get a pointer to our main page.
00076   rootPage = dynamic_cast<MainPage^>(e->Parameter);
00077 }
00078
00079 void ScenarioInput4::OnNavigatedFrom(NavigationEventArgs^ e)
00080 {
00081 }
00082
00083 #pragma endregion
00084
00085 void ScenarioInput4::OutputText(String^ text) {
00086   if (outputText == nullptr)
00087   {
00088     // Get a pointer to the content within the OutputFrame.
00089     Page^ outputFrame = dynamic_cast<Page^>(rootPage->OutputFrame->Content);
00090
00091     // Go find the elements that we need for this scenario
00092     outputText = dynamic_cast<TextBlock^>(outputFrame->FindName("Scenario4OutputText"));
00093   }
00094
00095   outputText->Text = text;
00096 }
00097
00098 void ScenarioInput4::Scenario4DisplayToastWithSound(ToastAudioContent audioContent, String^ audioSrc)
00099 {
00100   IToastText02^ toastContent = ToastContentFactory::CreateToastText02();
00101   toastContent->TextHeading->Text = "Sound:";
00102   toastContent->TextBodyWrap->Text = audioSrc;
00103
00104   toastContent->Audio->Content = audioContent;
00105
00106   OutputText(toastContent->GetContent());
00107
00108   // Create a toast, then create a ToastNotifier object to show
00109   // the toast
00110   auto toast = toastContent->CreateNotification();
00111
00112   // If you have other applications in your package, you can specify the AppId of
00113   // the app to create a ToastNotifier for that application
00114   ToastNotificationManager::CreateToastNotifier()->Show(toast);
00115 }
00116
00117 void ScenarioInput4::Scenario4DisplayToastWithSoundWithStringManipulation(ToastAudioContent audioContent, String^ audioSrc)
00118 {
00119   String^ toastXmlString = nullptr;
00120
00121   if (audioSrc->Equals("Silent"))
00122   {
00123     toastXmlString = "<toast>"
00124       + "<visual version='1'>"
00125       + "<binding template='ToastText02'>"
00126       + "<text id='1'>Sound:</text>"
00127       + "<text id='2'>" + audioSrc + "</text>"
00128       + "</binding>"
00129       + "</visual>"
00130       + "<audio silent='true'/>"
00131       + "</toast>";
00132
00133   }
00134   else if (audioSrc->Equals("Default"))
00135   {
00136     toastXmlString = "<toast>"
00137       + "<visual version='1'>"
00138       + "<binding template='ToastText02'>"
00139       + "<text id='1'>Sound:</text>"
00140       + "<text id='2'>" + audioSrc + "</text>"
00141       + "</binding>"
00142       + "</visual>"
00143       + "</toast>";
00144
00145   }
00146   else
00147   {
00148     toastXmlString = "<toast>"
00149       + "<visual version='1'>"
00150       + "<binding template='ToastText02'>"
00151       + "<text id='1'>Sound:</text>"
00152       + "<text id='2'>" + audioSrc + "</text>"
00153       + "</binding>"
00154       + "</visual>"
00155       + "<audio src='ms-winsoundevent:Notification." + audioSrc + "'/>"
00156       + "</toast>";
00157   }
00158
00159   auto toastDOM = ref new Windows::Data::Xml::Dom::XmlDocument();
00160   try
00161   {
00162     toastDOM->LoadXml(toastXmlString);
00163
00164     OutputText(toastDOM->GetXml());
00165
00166     // Create a toast, then create a ToastNotifier object to show
00167     // the toast
00168     auto toast = ref new ToastNotification(toastDOM);
00169
00170     // If you have other applications in your package, you can specify the AppId of
00171     // the app to create a ToastNotifier for that application
00172     ToastNotificationManager::CreateToastNotifier()->Show(toast);
00173   }
00174   catch (Exception^ e)
00175   {
00176     rootPage->NotifyUser("Error loading the xml, check for invalid characters in the input", NotifyType::ErrorMessage);
00177   }
00178 }
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Compass sensor/C++/Scenario1.xaml.h Source File

  • Compass sensor

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 SDKSample
00023 {
00024     namespace CompassCPP
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 Scenario1 sealed
00031         {
00032         public:
00033             Scenario1();
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             MainPage^ rootPage;
00041             Windows::Devices::Sensors::Compass^ compass;
00042             Windows::Foundation::EventRegistrationToken visibilityToken;
00043             Windows::Foundation::EventRegistrationToken readingToken;
00044             uint32 desiredReportInterval;
00045
00046             void VisibilityChanged(Platform::Object^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ e);
00047             void ReadingChanged(Windows::Devices::Sensors::Compass^ sender, Windows::Devices::Sensors::CompassReadingChangedEventArgs^ 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     }
00052 }
Generated on Sat Nov 23 2024 16:07:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Proximity/C++/PeerFinderScenario.xaml.h Source File

  • Proximity

PeerFinderScenario.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 // PeerFinderScenario.xaml.h
00013 // Declaration of the PeerFinderScenario class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "PeerFinderScenario.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace ProximityCPP
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 PeerFinderScenario sealed
00029     {
00030     public:
00031         PeerFinderScenario();
00032
00033     protected:
00034         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00035         virtual void OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs ^ e) override;
00036     private:
00037
00038         void TriggeredConnectionStateChangedEventHandler(Object^ sender, Windows::Networking::Proximity::TriggeredConnectionStateChangedEventArgs^ e);
00039         void ConnectionRequestedEventHandler(Object^ sender, Windows::Networking::Proximity::ConnectionRequestedEventArgs^ e);
00040         void PeerFinder_StartFindingPeers(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         void PeerFinder_BrowsePeers(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00042         void PeerFinder_Accept(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00043         void PeerFinder_Connect(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00044         void SocketError(Platform::String^ errMessage);
00045         void CloseSocket();
00046         void PeerFinder_Send(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047
00048         void PeerFinderInit();
00049         void PeerFinderReset();
00050         void Scenario2Reset();
00051         void PeerFinder_StartSendReceive(Windows::Networking::Sockets::StreamSocket^ socket);
00052         void PeerFinder_StartReader(Windows::Storage::Streams::DataReader^ socketReader);
00053
00054         //members
00055         MainPage^ m_rootPage;
00056         Windows::UI::Core::CoreDispatcher^ m_coreDispatcher;
00057         bool m_peerFinderStarted;
00058         Windows::Foundation::Collections::IVectorView<Windows::Networking::Proximity::PeerInformation^>^ m_peerInformationList;
00059         Windows::Networking::Proximity::PeerInformation^ m_requestingPeer;
00060         Windows::Networking::Sockets::StreamSocket^ m_socket;
00061         Windows::Storage::Streams::DataWriter^ m_dataWriter;
00062         bool m_triggeredConnectSupported;
00063         bool m_browseConnectSupported;
00064         bool m_startPeerFinderImmediately;
00065         bool m_socketClosed;
00066         Windows::Foundation::EventRegistrationToken m_triggerToken;
00067         Windows::Foundation::EventRegistrationToken m_connectionRequestedToken;
00068
00069         //connection states
00070         Platform::Collections::Vector<Platform::String^>^ m_ConnectStateArray;
00071     };
00072 }
Generated on Sat Nov 23 2024 16:08:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Lock screen personalization/C++/Constants.cpp Source File

  • Lock screen personalization

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016 using namespace Windows::UI::ViewManagement;
00017
00018 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00019 {
00020     { "Set lock screen image", "SDKSample.Personalization.SetLockscreenImage" }
00021 };
00022
00023 bool MainPage::EnsureUnsnapped()
00024 {
00025     // FilePicker APIs will not work if the application is in a snapped state. If an app wants to show a FilePicker while snapped,
00026     // it must attempt to unsnap first.
00027     bool unsnapped = ((ApplicationView::Value != ApplicationViewState::Snapped) || ApplicationView::TryUnsnap());
00028     if (!unsnapped)
00029     {
00030         NotifyUser("Cannot unsnap the sample application.", NotifyType::StatusMessage);
00031     }
00032
00033     return unsnapped;
00034 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Lock screen personalization/C++/MainPage.xaml.h Source File

  • Lock screen personalization

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:46 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/GameConstants.h Source File

  • DirectX 3D shooting game

GameConstants.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 GameConstants
00011 {
00012     static const int MaxAmmo                    = 10;
00013     static const int MaxCylinders               = 5;
00014     static const int MaxTargets                 = 10;
00015     static const float AmmoSize                 = 0.2f;
00016     static const float AmmoRadius               = AmmoSize * 0.5f;
00017     static const float TouchRectangleSize       = 300.0f;
00018     static const int MaxBackgroundTextures      = 3;
00019
00020     static const float CrossHairHalfSize        = 20.0f;
00021     static const float HudSafeWidth             = 300.0f;
00022     static const float HudRightOffset           = 250.0f;
00023     static const float HudTopOffset             = 50.0f;
00024     static const float Margin                   = 5.0f;
00025     static const float HudBodyPointSize         = 24.0f;
00026     static const float HudTitleHeaderPointSize  = 16.0f;
00027     static const float HudTitleBodyPointSize    = 36.0f;
00028     static const float HudLicensePointSize      = 20.0f;
00029
00030     static const int InitialLoadingDelay        = 2000;     // Number of ms to wait before completion of initial load.
00031     static const int LevelLoadingDelay          = 500;      // Number of ms to wait before completion of level load.
00032
00033     static const int WorldFloorId               = 80001;
00034     static const int WorldCeilingId             = 80002;
00035     static const int WorldWallsId               = 80003;
00036
00037     namespace Physics
00038     {
00039         static const float GroundRestitution    = 0.8f;     // Percentage of the velocity transmitted by ground and walls when an ammo hit.
00040         static const float Friction             = 0.9f;     // The amount of velocity retained after friction is applied.
00041         static const float AutoFireDelay        = 0.2f;     // The period between two successive ammo firing.
00042         static const float Gravity              = 5.0f;     // The magnitude of the downward force applied to ammos.
00043         static const float BounceTransfer       = 0.8f;     // The proportion of velocity transferred during a collision between 2 ammos.
00044         static const float BounceLost           = 0.1f;     // The proportion of velocity lost during a collision between 2 ammos.
00045         static const float RestThreshold        = 0.02f;    // The energy below which the ball is flagged as laying on ground.
00046                                                             // It is defined as Gravity * Height_above_ground + 0.5 * Velocity * Velocity.
00047         static const float FrameLength          = 0.003f;   // The duration of a frame for physics handling when the graphics frame length is too long.
00048     }
00049
00050     namespace Sound
00051     {
00052         static const float MaxVelocity          = 10.0f;    // The velocity at which the bouncing sound is played at maximum volume.
00053         static const float MinVelocity          = 0.05f;    // The minimum contact velocity required to make a sound.
00054         static const float MinAdjustment        = 0.2f;     // The minimum volume adjustment based on contact velocity.
00055     }
00056 };
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Document Member List

This is the complete list of members for Document, including all inherited members.
__pad0__ | Document |
DesignToDisplayHeight(float designHeight) | Document |
DesignToDisplayWidth(float designWidth) | Document |
DisplayToDesignHeight(float displayHeight) | Document |
DisplayToDesignWidth(float displayWidth) | Document |
fileName | Document |
GetContentRoot() | Document |
GetDWriteFactory(_Outptr_ IDWriteFactory **dwriteFactory) | Document |
GetFontCollection(_Outptr_result_maybenull_ IDWriteFontCollection **fontCollection) | Document |
GetLocation() | Document | [inline]
GetPageSize() | Document |
GetRenderer() | Document | [inline]
LoadAsync() | Document |
m_design | Document | [private]
m_dwriteFactory | Document | [private]
m_fileName | Document | [private]
m_fontCollection | Document | [private]
m_fontLoader | Document | [private]
m_location | Document | [private]
m_renderer | Document | [private]
m_rootElement | Document | [private]
m_rootXml | Document | [private]
Parse() | Document |
renderer | Document |
UpdateDesign() | Document | [private]
~Document() | Document | [private]
Generated on Sat Nov 23 2024 16:09:12 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::TileContent::TileWideText06 Member List

This is the complete list of members for NotificationsExtensions::TileContent::TileWideText06, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
Branding | NotificationsExtensions::TileContent::TileNotificationBase |
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
RequireSquareContent | NotificationsExtensions::TileContent::TileWideBase |
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SquareContent | NotificationsExtensions::TileContent::TileWideBase |
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextColumn1Row1 | NotificationsExtensions::TileContent::TileWideText06 |
TextColumn1Row2 | NotificationsExtensions::TileContent::TileWideText06 |
TextColumn1Row3 | NotificationsExtensions::TileContent::TileWideText06 |
TextColumn1Row4 | NotificationsExtensions::TileContent::TileWideText06 |
TextColumn1Row5 | NotificationsExtensions::TileContent::TileWideText06 |
TextColumn2Row1 | NotificationsExtensions::TileContent::TileWideText06 |
TextColumn2Row2 | NotificationsExtensions::TileContent::TileWideText06 |
TextColumn2Row3 | NotificationsExtensions::TileContent::TileWideText06 |
TextColumn2Row4 | NotificationsExtensions::TileContent::TileWideText06 |
TextColumn2Row5 | NotificationsExtensions::TileContent::TileWideText06 |
TextFields | NotificationsExtensions::NotificationBase |
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWideText06() | NotificationsExtensions::TileContent::TileWideText06 | [inline]
TileWideText06() | NotificationsExtensions::TileContent::TileWideText06 | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:44 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Audio Session (WASAPI)/C++/common/suspensionmanager.cpp Source File

  • Windows Audio Session (WASAPI)
  • C++
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML ListView and GridView essentials/C++/App.xaml.h Source File

  • XAML ListView and GridView essentials

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::CoTaskMemFreeArray Member List

This is the complete list of members for SDKSample::CoTaskMemFreeArray, including all inherited members.
_count | SDKSample::CoTaskMemFreeArray |
_ptr | SDKSample::CoTaskMemFreeArray |
CoTaskMemFreeArray(_Inout_updates_(count) void **ptr, size_t count) | SDKSample::CoTaskMemFreeArray | [inline]
~CoTaskMemFreeArray() | SDKSample::CoTaskMemFreeArray | [inline]
Generated on Sat Nov 23 2024 16:09:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Syndication/C++/Constants.h Source File

  • Syndication

Constants.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
00017 namespace SDKSample
00018 {
00019     public value struct Scenario
00020     {
00021         Platform::String^ Title;
00022         Platform::String^ ClassName;
00023     };
00024
00025     partial ref class MainPage
00026     {
00027     public:
00028         static property Platform::String^ FEATURE_NAME
00029         {
00030             Platform::String^ get()
00031             {
00032                 return ref new Platform::String(L"Syndication (CPP)");
00033             }
00034         }
00035
00036         static property Platform::Array<Scenario>^ scenarios
00037         {
00038             Platform::Array<Scenario>^ get()
00039             {
00040                 return scenariosInner;
00041             }
00042         }
00043
00044         bool TryGetUri(Platform::String^ uriString, Windows::Foundation::Uri^* uri)
00045         {
00046             // Create a Uri instance and catch exceptions related to invalid input. This method returns 'true'
00047             // if the Uri instance was successfully created and 'false' otherwise.
00048             try
00049             {
00050                 *uri = ref new Windows::Foundation::Uri(StringTrimmer::Trim(uriString));
00051                 return true;
00052             }
00053             catch (Platform::NullReferenceException^ exception)
00054             {
00055                 NotifyUser("Error: URI must not be null or empty.", NotifyType::ErrorMessage);
00056             }
00057             catch (Platform::InvalidArgumentException^ exception)
00058             {
00059                 NotifyUser("Error: Invalid URI", NotifyType::ErrorMessage);
00060             }
00061
00062             return false;
00063         }
00064
00065     private:
00066         static Platform::Array<Scenario>^ scenariosInner;
00067     };
00068
00069     class StringTrimmer
00070     {
00071     public:
00072         static Platform::String^ Trim(Platform::String^ s)
00073         {
00074             const WCHAR* first = s->Begin();
00075             const WCHAR* last = s->End();
00076
00077             while (first != last && iswspace(*first))
00078             {
00079                 ++first;
00080             }
00081
00082             while (first != last && iswspace(last[-1]))
00083             {
00084                 --last;
00085             }
00086
00087             return ref new Platform::String(first, last - first);
00088         }
00089     };
00090
00091     [Windows::UI::Xaml::Data::Bindable]
00092     public ref class BindableNode sealed
00093     {
00094     public:
00095         BindableNode(String^ nodeName, String^ nodeNamespace, String^ nodeValue)
00096         {
00097             this->NodeName = nodeName;
00098             this->NodeNamespace = nodeNamespace;
00099             this->NodeValue = nodeValue;
00100         }
00101
00102         property String^ NodeName
00103         {
00104             String^ get()
00105             {
00106                 return nodeName;
00107             }
00108             void set(String^ value)
00109             {
00110                 nodeName = value;
00111             }
00112         }
00113
00114         property String^ NodeNamespace
00115         {
00116             String^ get()
00117             {
00118                 return nodeNamespace;
00119             }
00120             void set(String^ value)
00121             {
00122                 nodeNamespace = value;
00123             }
00124         }
00125
00126         property String^ NodeValue
00127         {
00128             String^ get()
00129             {
00130                 return nodeValue;
00131             }
00132             void set(String^ value)
00133             {
00134                 nodeValue = value;
00135             }
00136         }
00137
00138     private:
00139         String^ nodeName;
00140         String^ nodeNamespace;
00141         String^ nodeValue;
00142     };
00143 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/texconv/DirectXTexWIC.cpp Source File

  • Direct3D resource loading
  • texconv

DirectXTexWIC.cpp

Go to the documentation of this file.
00001 //-------------------------------------------------------------------------------------
00002 // DirectXTexWIC.cpp
00003 //
00004 // DirectX Texture Library - WIC-based file reader/writer
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 #include "directxtexp.h"
00015
00016 //-------------------------------------------------------------------------------------
00017 // WIC Pixel Format nearest conversion table
00018 //-------------------------------------------------------------------------------------
00019
00020 struct WICConvert
00021 {
00022     GUID        source;
00023     GUID        target;
00024 };
00025
00026 static WICConvert g_WICConvert[] =
00027 {
00028     // Directly support the formats listed in XnaTexUtil::g_WICFormats, so no conversion required
00029     // Note target GUID in this conversion table must be one of those directly supported formats.
00030
00031     { GUID_WICPixelFormat1bppIndexed,           GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM
00032     { GUID_WICPixelFormat2bppIndexed,           GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM
00033     { GUID_WICPixelFormat4bppIndexed,           GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM
00034     { GUID_WICPixelFormat8bppIndexed,           GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM
00035
00036     { GUID_WICPixelFormat2bppGray,              GUID_WICPixelFormat8bppGray }, // DXGI_FORMAT_R8_UNORM
00037     { GUID_WICPixelFormat4bppGray,              GUID_WICPixelFormat8bppGray }, // DXGI_FORMAT_R8_UNORM
00038
00039     { GUID_WICPixelFormat16bppGrayFixedPoint,   GUID_WICPixelFormat16bppGrayHalf }, // DXGI_FORMAT_R16_FLOAT
00040     { GUID_WICPixelFormat32bppGrayFixedPoint,   GUID_WICPixelFormat32bppGrayFloat }, // DXGI_FORMAT_R32_FLOAT
00041
00042     { GUID_WICPixelFormat16bppBGR555,           GUID_WICPixelFormat16bppBGRA5551 }, // DXGI_FORMAT_B5G5R5A1_UNORM
00043     { GUID_WICPixelFormat32bppBGR101010,        GUID_WICPixelFormat32bppRGBA1010102 }, // DXGI_FORMAT_R10G10B10A2_UNORM
00044
00045     { GUID_WICPixelFormat24bppBGR,              GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM
00046     { GUID_WICPixelFormat24bppRGB,              GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM
00047     { GUID_WICPixelFormat32bppPBGRA,            GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM
00048     { GUID_WICPixelFormat32bppPRGBA,            GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM
00049
00050     { GUID_WICPixelFormat48bppRGB,              GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM
00051     { GUID_WICPixelFormat48bppBGR,              GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM
00052     { GUID_WICPixelFormat64bppBGRA,             GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM
00053     { GUID_WICPixelFormat64bppPRGBA,            GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM
00054     { GUID_WICPixelFormat64bppPBGRA,            GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM
00055
00056     { GUID_WICPixelFormat48bppRGBFixedPoint,    GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT
00057     { GUID_WICPixelFormat48bppBGRFixedPoint,    GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT
00058     { GUID_WICPixelFormat64bppRGBAFixedPoint,   GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT
00059     { GUID_WICPixelFormat64bppBGRAFixedPoint,   GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT
00060     { GUID_WICPixelFormat64bppRGBFixedPoint,    GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT
00061     { GUID_WICPixelFormat64bppRGBHalf,          GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT
00062     { GUID_WICPixelFormat48bppRGBHalf,          GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT
00063
00064     { GUID_WICPixelFormat128bppPRGBAFloat,      GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT
00065     { GUID_WICPixelFormat128bppRGBFloat,        GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT
00066     { GUID_WICPixelFormat128bppRGBAFixedPoint,  GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT
00067     { GUID_WICPixelFormat128bppRGBFixedPoint,   GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT
00068
00069     { GUID_WICPixelFormat32bppCMYK,             GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM
00070     { GUID_WICPixelFormat64bppCMYK,             GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM
00071     { GUID_WICPixelFormat40bppCMYKAlpha,        GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM
00072     { GUID_WICPixelFormat80bppCMYKAlpha,        GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM
00073
00074 #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8)
00075     { GUID_WICPixelFormat32bppRGB,              GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM
00076     { GUID_WICPixelFormat64bppRGB,              GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM
00077     { GUID_WICPixelFormat64bppPRGBAHalf,        GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT
00078     { GUID_WICPixelFormat96bppRGBFixedPoint,    GUID_WICPixelFormat96bppRGBFloat }, // DXGI_FORMAT_R32G32B32_FLOAT
00079 #else
00080     { GUID_WICPixelFormat96bppRGBFixedPoint,    GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT
00081 #endif
00082
00083     // We don't support n-channel formats
00084 };
00085
00086 namespace DirectX
00087 {
00088
00089 //-------------------------------------------------------------------------------------
00090 // Returns the DXGI format and optionally the WIC pixel GUID to convert to
00091 //-------------------------------------------------------------------------------------
00092 static DXGI_FORMAT _DetermineFormat( _In_ const WICPixelFormatGUID& pixelFormat, _In_ DWORD flags,
00093                                      _Out_opt_ WICPixelFormatGUID* pConvert )
00094 {
00095     if ( pConvert )
00096         memset( pConvert, 0, sizeof(WICPixelFormatGUID) );
00097
00098     DXGI_FORMAT format = _WICToDXGI( pixelFormat );
00099
00100     if ( format == DXGI_FORMAT_UNKNOWN )
00101     {
00102         for( size_t i=0; i < _countof(g_WICConvert); ++i )
00103         {
00104             if ( memcmp( &g_WICConvert[i].source, &pixelFormat, sizeof(WICPixelFormatGUID) ) == 0 )
00105             {
00106                 if ( pConvert )
00107                     memcpy( pConvert, &g_WICConvert[i].target, sizeof(WICPixelFormatGUID) );
00108
00109                 format = _WICToDXGI( g_WICConvert[i].target );
00110                 assert( format != DXGI_FORMAT_UNKNOWN );
00111                 break;
00112             }
00113         }
00114     }
00115
00116     // Handle special cases based on flags
00117     switch (format)
00118     {
00119     case DXGI_FORMAT_B8G8R8A8_UNORM:    // BGRA
00120     case DXGI_FORMAT_B8G8R8X8_UNORM:    // BGRX
00121         if ( flags & WIC_FLAGS_FORCE_RGB )
00122         {
00123             format = DXGI_FORMAT_R8G8B8A8_UNORM;
00124             if ( pConvert )
00125                 memcpy( pConvert, &GUID_WICPixelFormat32bppRGBA, sizeof(WICPixelFormatGUID) );
00126         }
00127         break;
00128
00129     case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM:
00130         if ( flags & WIC_FLAGS_NO_X2_BIAS )
00131         {
00132             format = DXGI_FORMAT_R10G10B10A2_UNORM;
00133             if ( pConvert )
00134                 memcpy( pConvert, &GUID_WICPixelFormat32bppRGBA1010102, sizeof(WICPixelFormatGUID) );
00135         }
00136         break;
00137
00138     case DXGI_FORMAT_B5G5R5A1_UNORM:
00139     case DXGI_FORMAT_B5G6R5_UNORM:
00140         if ( flags & WIC_FLAGS_NO_16BPP )
00141         {
00142             format = DXGI_FORMAT_R8G8B8A8_UNORM;
00143             if ( pConvert )
00144                 memcpy( pConvert, &GUID_WICPixelFormat32bppRGBA, sizeof(WICPixelFormatGUID) );
00145         }
00146         break;
00147
00148     case DXGI_FORMAT_R1_UNORM:
00149         if ( !(flags & WIC_FLAGS_ALLOW_MONO ) )
00150         {
00151             // By default we want to promote a black & white to gresycale since R1 is not a generally supported D3D format
00152             format = DXGI_FORMAT_R8_UNORM;
00153             if ( pConvert )
00154                 memcpy( pConvert, &GUID_WICPixelFormat8bppGray, sizeof(WICPixelFormatGUID) );
00155         }
00156     }
00157
00158     return format;
00159 }
00160
00161
00162 //-------------------------------------------------------------------------------------
00163 // Determines metadata for image
00164 //-------------------------------------------------------------------------------------
00165 static HRESULT _DecodeMetadata( _In_ DWORD flags,
00166                                 _In_ IWICBitmapDecoder *decoder, _In_ IWICBitmapFrameDecode *frame,
00167                                 _Out_ TexMetadata& metadata, _Out_opt_ WICPixelFormatGUID* pConvert )
00168 {
00169     if ( !decoder || !frame )
00170         return E_POINTER;
00171
00172     memset( &metadata, 0, sizeof(TexMetadata) );
00173     metadata.depth = 1;
00174     metadata.mipLevels = 1;
00175     metadata.dimension = TEX_DIMENSION_TEXTURE2D;
00176
00177     UINT w, h;
00178     HRESULT hr = frame->GetSize( &w, &h );
00179     if ( FAILED(hr) )
00180         return hr;
00181
00182     metadata.width = w;
00183     metadata.height = h;
00184
00185     if ( flags & WIC_FLAGS_ALL_FRAMES )
00186     {
00187         UINT fcount;
00188         hr = decoder->GetFrameCount( &fcount );
00189         if ( FAILED(hr) )
00190             return hr;
00191
00192         metadata.arraySize = fcount;
00193     }
00194     else
00195         metadata.arraySize = 1;
00196
00197     WICPixelFormatGUID pixelFormat;
00198     hr = frame->GetPixelFormat( &pixelFormat );
00199     if ( FAILED(hr) )
00200         return hr;
00201
00202     metadata.format = _DetermineFormat( pixelFormat, flags, pConvert );
00203     if ( metadata.format == DXGI_FORMAT_UNKNOWN )
00204         return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
00205
00206     return S_OK;
00207 }
00208
00209
00210 //-------------------------------------------------------------------------------------
00211 // Decodes a single frame
00212 //-------------------------------------------------------------------------------------
00213 static HRESULT _DecodeSingleFrame( _In_ DWORD flags, _In_ const TexMetadata& metadata, _In_ const WICPixelFormatGUID& convertGUID,
00214                                    _In_ IWICBitmapFrameDecode *frame, _Inout_ ScratchImage& image )
00215 {
00216     if ( !frame )
00217         return E_POINTER;
00218
00219     HRESULT hr = image.Initialize2D( metadata.format, metadata.width, metadata.height, 1, 1 );
00220     if ( FAILED(hr) )
00221         return hr;
00222
00223     const Image *img = image.GetImage( 0, 0, 0 );
00224     if ( !img )
00225         return E_POINTER;
00226
00227     IWICImagingFactory* pWIC = _GetWIC();
00228     if ( !pWIC )
00229         return E_NOINTERFACE;
00230
00231     if ( memcmp( &convertGUID, &GUID_NULL, sizeof(GUID) ) == 0 )
00232     {
00233         hr = frame->CopyPixels( 0, static_cast<UINT>( img->rowPitch ), static_cast<UINT>( img->slicePitch ), img->pixels );
00234         if ( FAILED(hr) )
00235             return hr;
00236     }
00237     else
00238     {
00239         ScopedObject<IWICFormatConverter> FC;
00240         hr = pWIC->CreateFormatConverter( &FC );
00241         if ( FAILED(hr) )
00242             return hr;
00243
00244         hr = FC->Initialize( frame, convertGUID, _GetWICDither( flags ), 0, 0, WICBitmapPaletteTypeCustom );
00245         if ( FAILED(hr) )
00246             return hr;
00247
00248         hr = FC->CopyPixels( 0, static_cast<UINT>( img->rowPitch ), static_cast<UINT>( img->slicePitch ), img->pixels );
00249         if ( FAILED(hr) )
00250             return hr;
00251     }
00252
00253     return S_OK;
00254 }
00255
00256
00257 //-------------------------------------------------------------------------------------
00258 // Decodes an image array, resizing/format converting as needed
00259 //-------------------------------------------------------------------------------------
00260 static HRESULT _DecodeMultiframe( _In_ DWORD flags, _In_ const TexMetadata& metadata,
00261                                   _In_ IWICBitmapDecoder *decoder, _Inout_ ScratchImage& image )
00262 {
00263     if ( !decoder )
00264         return E_POINTER;
00265
00266     HRESULT hr = image.Initialize2D( metadata.format, metadata.width, metadata.height, metadata.arraySize, 1 );
00267     if ( FAILED(hr) )
00268         return hr;
00269
00270     IWICImagingFactory* pWIC = _GetWIC();
00271     if ( !pWIC )
00272         return E_NOINTERFACE;
00273
00274     WICPixelFormatGUID sourceGUID;
00275     if ( !_DXGIToWIC( metadata.format, sourceGUID ) )
00276         return E_FAIL;
00277
00278     for( size_t index = 0; index < metadata.arraySize; ++index )
00279     {
00280         const Image* img = image.GetImage( 0, index, 0 );
00281         if ( !img )
00282             return E_POINTER;
00283
00284         ScopedObject<IWICBitmapFrameDecode> frame;
00285         hr = decoder->GetFrame( static_cast<UINT>( index ), &frame );
00286         if ( FAILED(hr) )
00287             return hr;
00288
00289         WICPixelFormatGUID pfGuid;
00290         hr = frame->GetPixelFormat( &pfGuid );
00291         if ( FAILED(hr) )
00292             return hr;
00293
00294         UINT w, h;
00295         hr = frame->GetSize( &w, &h );
00296         if ( FAILED(hr) )
00297             return hr;
00298
00299         if ( memcmp( &pfGuid, &sourceGUID, sizeof(WICPixelFormatGUID) ) == 0 )
00300         {
00301             if ( w == metadata.width && h == metadata.height )
00302             {
00303                 // This frame does not need resized or format converted, just copy...
00304                 hr = frame->CopyPixels( 0, static_cast<UINT>( img->rowPitch ), static_cast<UINT>( img->slicePitch ), img->pixels );
00305                 if ( FAILED(hr) )
00306                     return hr;
00307             }
00308             else
00309             {
00310                 // This frame needs resizing, but not format converted
00311                 ScopedObject<IWICBitmapScaler> scaler;
00312                 hr = pWIC->CreateBitmapScaler( &scaler );
00313                 if ( FAILED(hr) )
00314                     return hr;
00315
00316                 hr = scaler->Initialize( frame.Get(), static_cast<UINT>( metadata.width ), static_cast<UINT>( metadata.height ), _GetWICInterp( flags ) );
00317                 if ( FAILED(hr) )
00318                     return hr;
00319
00320                 hr = scaler->CopyPixels( 0, static_cast<UINT>( img->rowPitch ), static_cast<UINT>( img->slicePitch ), img->pixels );
00321                 if ( FAILED(hr) )
00322                     return hr;
00323             }
00324         }
00325         else
00326         {
00327             // This frame required format conversion
00328             ScopedObject<IWICFormatConverter> FC;
00329             hr = pWIC->CreateFormatConverter( &FC );
00330             if ( FAILED(hr) )
00331                 return hr;
00332
00333             hr = FC->Initialize( frame.Get(), pfGuid, _GetWICDither( flags ), 0, 0, WICBitmapPaletteTypeCustom );
00334             if ( FAILED(hr) )
00335                 return hr;
00336
00337             if ( w == metadata.width && h == metadata.height )
00338             {
00339                 // This frame is the same size, no need to scale
00340                 hr = FC->CopyPixels( 0, static_cast<UINT>( img->rowPitch ), static_cast<UINT>( img->slicePitch ), img->pixels );
00341                 if ( FAILED(hr) )
00342                     return hr;
00343             }
00344             else
00345             {
00346                 // This frame needs resizing and format converted
00347                 ScopedObject<IWICBitmapScaler> scaler;
00348                 hr = pWIC->CreateBitmapScaler( &scaler );
00349                 if ( FAILED(hr) )
00350                     return hr;
00351
00352                 hr = scaler->Initialize( FC.Get(), static_cast<UINT>( metadata.width ), static_cast<UINT>( metadata.height ), _GetWICInterp( flags ) );
00353                 if ( FAILED(hr) )
00354                     return hr;
00355
00356                 hr = scaler->CopyPixels( 0, static_cast<UINT>( img->rowPitch ), static_cast<UINT>( img->slicePitch ), img->pixels );
00357                 if ( FAILED(hr) )
00358                     return hr;
00359             }
00360         }
00361     }
00362
00363     return S_OK;
00364 }
00365
00366
00367 //-------------------------------------------------------------------------------------
00368 // Encodes a single frame
00369 //-------------------------------------------------------------------------------------
00370 static HRESULT _EncodeImage( _In_ const Image& image, _In_ DWORD flags, _In_ IWICBitmapFrameEncode* frame, _In_opt_ IPropertyBag2* props )
00371 {
00372     if ( !frame )
00373         return E_INVALIDARG;
00374
00375     if ( !image.pixels )
00376         return E_POINTER;
00377
00378     WICPixelFormatGUID pfGuid;
00379     if ( !_DXGIToWIC( image.format, pfGuid ) )
00380         return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
00381
00382     HRESULT hr = frame->Initialize( props );
00383     if ( FAILED(hr) )
00384         return hr;
00385
00386 #ifdef _AMD64_
00387     if ( (image.width > 0xFFFFFFFF) || (image.height > 0xFFFFFFFF) )
00388         return E_INVALIDARG;
00389 #endif
00390
00391     hr = frame->SetSize( static_cast<UINT>( image.width ), static_cast<UINT>( image.height ) );
00392     if ( FAILED(hr) )
00393         return hr;
00394
00395     hr = frame->SetResolution( 72, 72 );
00396     if ( FAILED(hr) )
00397         return hr;
00398
00399     WICPixelFormatGUID targetGuid = pfGuid;
00400     hr = frame->SetPixelFormat( &targetGuid );
00401     if ( FAILED(hr) )
00402         return hr;
00403
00404     if ( memcmp( &targetGuid, &pfGuid, sizeof(WICPixelFormatGUID) ) != 0 )
00405     {
00406         // Conversion required to write
00407         IWICImagingFactory* pWIC = _GetWIC();
00408         if ( !pWIC )
00409             return E_NOINTERFACE;
00410
00411         ScopedObject<IWICBitmap> source;
00412         hr = pWIC->CreateBitmapFromMemory( static_cast<UINT>( image.width ), static_cast<UINT>( image.height ), pfGuid,
00413                                            static_cast<UINT>( image.rowPitch ), static_cast<UINT>( image.slicePitch ),
00414                                            image.pixels, &source );
00415         if ( FAILED(hr) )
00416             return hr;
00417
00418         ScopedObject<IWICFormatConverter> FC;
00419         hr = pWIC->CreateFormatConverter( &FC );
00420         if ( FAILED(hr) )
00421             return hr;
00422
00423         hr = FC->Initialize( source.Get(), targetGuid, _GetWICDither( flags ), 0, 0, WICBitmapPaletteTypeCustom );
00424         if ( FAILED(hr) )
00425             return hr;
00426
00427         size_t bpp = _WICBitsPerPixel( targetGuid );
00428         if ( bpp == 0 )
00429             return E_FAIL;
00430
00431         size_t rowPitch = ( image.width * bpp + 7 ) / 8;
00432         size_t slicePitch = rowPitch * image.height;
00433
00434         std::unique_ptr<uint8_t[]> temp( new uint8_t[ slicePitch ] );
00435         if ( !temp )
00436             return E_OUTOFMEMORY;
00437
00438         hr = FC->CopyPixels( 0, static_cast<UINT>( rowPitch ), static_cast<UINT>( slicePitch ), temp.get() );
00439         if ( FAILED(hr) )
00440             return hr;
00441
00442         hr = frame->WritePixels( static_cast<UINT>( image.height ), static_cast<UINT>( rowPitch ), static_cast<UINT>( slicePitch ), temp.get() );
00443         if ( FAILED(hr) )
00444             return hr;
00445     }
00446     else
00447     {
00448         // No conversion required
00449         hr = frame->WritePixels( static_cast<UINT>( image.height ), static_cast<UINT>( image.rowPitch ), static_cast<UINT>( image.slicePitch ),
00450                                  reinterpret_cast<uint8_t*>( image.pixels ) );
00451         if ( FAILED(hr) )
00452             return hr;
00453     }
00454
00455     hr = frame->Commit();
00456     if ( FAILED(hr) )
00457         return hr;
00458
00459     return S_OK;
00460 }
00461
00462 static HRESULT _EncodeSingleFrame( _In_ const Image& image, _In_ DWORD flags,
00463                                    _In_ REFGUID guidContainerFormat, _Inout_ IStream* stream )
00464 {
00465     if ( !stream )
00466         return E_INVALIDARG;
00467
00468     // Initialize WIC
00469     IWICImagingFactory* pWIC = _GetWIC();
00470     if ( !pWIC )
00471         return E_NOINTERFACE;
00472
00473     ScopedObject<IWICBitmapEncoder> encoder;
00474     HRESULT hr = pWIC->CreateEncoder( guidContainerFormat, 0, &encoder );
00475     if ( FAILED(hr) )
00476         return hr;
00477
00478     hr = encoder->Initialize( stream, WICBitmapEncoderNoCache );
00479     if ( FAILED(hr) )
00480         return hr;
00481
00482     ScopedObject<IWICBitmapFrameEncode> frame;
00483     ScopedObject<IPropertyBag2> props;
00484     hr = encoder->CreateNewFrame( &frame, &props );
00485     if ( FAILED(hr) )
00486         return hr;
00487
00488     if ( memcmp( &guidContainerFormat, &GUID_ContainerFormatBmp, sizeof(WICPixelFormatGUID) ) == 0  )
00489     {
00490         // Opt-in to the Windows 8 support for writing 32-bit Windows BMP files with an alpha channel if supported
00491         PROPBAG2 option = { 0 };
00492         option.pstrName = L"EnableV5Header32bppBGRA";
00493
00494         VARIANT varValue;
00495         varValue.vt = VT_BOOL;
00496         varValue.boolVal = VARIANT_TRUE;
00497         hr = props->Write( 1, &option, &varValue );
00498         if ( FAILED(hr) )
00499         {
00500             // Fails on older versions of WIC, so we default to the null property bag
00501             props.Reset();
00502         }
00503     }
00504
00505     hr = _EncodeImage( image, flags, frame.Get(), props.Get() );
00506     if ( FAILED(hr) )
00507         return hr;
00508
00509     hr = encoder->Commit();
00510     if ( FAILED(hr) )
00511         return hr;
00512
00513     return S_OK;
00514 }
00515
00516
00517 //-------------------------------------------------------------------------------------
00518 // Encodes an image array
00519 //-------------------------------------------------------------------------------------
00520 static HRESULT _EncodeMultiframe( _In_reads_(nimages) const Image* images, _In_ size_t nimages, _In_ DWORD flags,
00521                                   _In_ REFGUID guidContainerFormat, _Inout_ IStream* stream )
00522 {
00523     if ( !stream || nimages < 2 )
00524         return E_INVALIDARG;
00525
00526     if ( !images )
00527         return E_POINTER;
00528
00529     // Initialize WIC
00530     IWICImagingFactory* pWIC = _GetWIC();
00531     if ( !pWIC )
00532         return E_NOINTERFACE;
00533
00534     ScopedObject<IWICBitmapEncoder> encoder;
00535     HRESULT hr = pWIC->CreateEncoder( guidContainerFormat, 0, &encoder );
00536     if ( FAILED(hr) )
00537         return hr;
00538
00539     ScopedObject<IWICBitmapEncoderInfo> einfo;
00540     hr = encoder->GetEncoderInfo( &einfo );
00541     if ( FAILED(hr) )
00542         return hr;
00543
00544     BOOL mframe = FALSE;
00545     hr = einfo->DoesSupportMultiframe( &mframe );
00546     if ( FAILED(hr) )
00547         return hr;
00548
00549     if ( !mframe )
00550         return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
00551
00552     hr = encoder->Initialize( stream, WICBitmapEncoderNoCache );
00553     if ( FAILED(hr) )
00554         return hr;
00555
00556     for( size_t index=0; index < nimages; ++index )
00557     {
00558         ScopedObject<IWICBitmapFrameEncode> frame;
00559         hr = encoder->CreateNewFrame( &frame, nullptr );
00560         if ( FAILED(hr) )
00561             return hr;
00562
00563         hr = _EncodeImage( images[index], flags, frame.Get(), nullptr );
00564         if ( FAILED(hr) )
00565             return hr;
00566     }
00567
00568     hr = encoder->Commit();
00569     if ( FAILED(hr) )
00570         return hr;
00571
00572     return S_OK;
00573 }
00574
00575
00576 //=====================================================================================
00577 // Entry-points
00578 //=====================================================================================
00579
00580 //-------------------------------------------------------------------------------------
00581 // Obtain metadata from WIC-supported file in memory
00582 //-------------------------------------------------------------------------------------
00583 _Use_decl_annotations_
00584 HRESULT GetMetadataFromWICMemory( LPCVOID pSource, size_t size, DWORD flags, TexMetadata& metadata )
00585 {
00586     if ( !pSource || size == 0 )
00587         return E_INVALIDARG;
00588
00589 #ifdef _AMD64_
00590     if ( size > 0xFFFFFFFF )
00591         return HRESULT_FROM_WIN32( ERROR_FILE_TOO_LARGE );
00592 #endif
00593
00594     IWICImagingFactory* pWIC = _GetWIC();
00595     if ( !pWIC )
00596         return E_NOINTERFACE;
00597
00598     // Create input stream for memory
00599     ScopedObject<IWICStream> stream;
00600     HRESULT hr = pWIC->CreateStream( &stream );
00601     if ( FAILED(hr) )
00602         return hr;
00603
00604     hr = stream->InitializeFromMemory( reinterpret_cast<BYTE*>( const_cast<void*>( pSource ) ),
00605                                        static_cast<UINT>( size ) );
00606     if ( FAILED(hr) )
00607         return hr;
00608
00609     // Initialize WIC
00610     ScopedObject<IWICBitmapDecoder> decoder;
00611     hr = pWIC->CreateDecoderFromStream( stream.Get(), 0, WICDecodeMetadataCacheOnDemand, &decoder );
00612     if ( FAILED(hr) )
00613         return hr;
00614
00615     ScopedObject<IWICBitmapFrameDecode> frame;
00616     hr = decoder->GetFrame( 0, &frame );
00617     if ( FAILED(hr) )
00618         return hr;
00619
00620     // Get metadata
00621     hr = _DecodeMetadata( flags, decoder.Get(), frame.Get(), metadata, 0 );
00622     if ( FAILED(hr) )
00623         return hr;
00624
00625     return S_OK;
00626 }
00627
00628
00629 //-------------------------------------------------------------------------------------
00630 // Obtain metadata from WIC-supported file on disk
00631 //-------------------------------------------------------------------------------------
00632 _Use_decl_annotations_
00633 HRESULT GetMetadataFromWICFile( LPCWSTR szFile, DWORD flags, TexMetadata& metadata )
00634 {
00635     if ( !szFile )
00636         return E_INVALIDARG;
00637
00638     IWICImagingFactory* pWIC = _GetWIC();
00639     if ( !pWIC )
00640         return E_NOINTERFACE;
00641
00642     // Initialize WIC
00643     ScopedObject<IWICBitmapDecoder> decoder;
00644     HRESULT hr = pWIC->CreateDecoderFromFilename( szFile, 0, GENERIC_READ, WICDecodeMetadataCacheOnDemand, &decoder );
00645     if ( FAILED(hr) )
00646         return hr;
00647
00648     ScopedObject<IWICBitmapFrameDecode> frame;
00649     hr = decoder->GetFrame( 0, &frame );
00650     if ( FAILED(hr) )
00651         return hr;
00652
00653     // Get metadata
00654     hr = _DecodeMetadata( flags, decoder.Get(), frame.Get(), metadata, 0 );
00655     if ( FAILED(hr) )
00656         return hr;
00657
00658     return S_OK;
00659 }
00660
00661
00662 //-------------------------------------------------------------------------------------
00663 // Load a WIC-supported file in memory
00664 //-------------------------------------------------------------------------------------
00665 _Use_decl_annotations_
00666 HRESULT LoadFromWICMemory( LPCVOID pSource, size_t size, DWORD flags, TexMetadata* metadata, ScratchImage& image )
00667 {
00668     if ( !pSource || size == 0 )
00669         return E_INVALIDARG;
00670
00671 #ifdef _AMD64_
00672     if ( size > 0xFFFFFFFF )
00673         return HRESULT_FROM_WIN32( ERROR_FILE_TOO_LARGE );
00674 #endif
00675
00676     IWICImagingFactory* pWIC = _GetWIC();
00677     if ( !pWIC )
00678         return E_NOINTERFACE;
00679
00680     image.Release();
00681
00682     // Create input stream for memory
00683     ScopedObject<IWICStream> stream;
00684     HRESULT hr = pWIC->CreateStream( &stream );
00685     if ( FAILED(hr) )
00686         return hr;
00687
00688     hr = stream->InitializeFromMemory( reinterpret_cast<uint8_t*>( const_cast<void*>( pSource ) ), static_cast<DWORD>( size ) );
00689     if ( FAILED(hr) )
00690         return hr;
00691
00692     // Initialize WIC
00693     ScopedObject<IWICBitmapDecoder> decoder;
00694     hr = pWIC->CreateDecoderFromStream( stream.Get(), 0, WICDecodeMetadataCacheOnDemand, &decoder );
00695     if ( FAILED(hr) )
00696         return hr;
00697
00698     ScopedObject<IWICBitmapFrameDecode> frame;
00699     hr = decoder->GetFrame( 0, &frame );
00700     if ( FAILED(hr) )
00701         return hr;
00702
00703     // Get metadata
00704     TexMetadata mdata;
00705     WICPixelFormatGUID convertGUID = {0};
00706     hr = _DecodeMetadata( flags, decoder.Get(), frame.Get(), mdata, &convertGUID );
00707     if ( FAILED(hr) )
00708         return hr;
00709
00710     if ( (mdata.arraySize > 1) && (flags & WIC_FLAGS_ALL_FRAMES) )
00711     {
00712         hr = _DecodeMultiframe( flags, mdata, decoder.Get(), image );
00713     }
00714     else
00715     {
00716         hr = _DecodeSingleFrame( flags, mdata, convertGUID, frame.Get(), image );
00717     }
00718
00719     if ( FAILED(hr) )
00720     {
00721         image.Release();
00722         return hr;
00723     }
00724
00725     if ( metadata )
00726         memcpy( metadata, &mdata, sizeof(TexMetadata) );
00727
00728     return S_OK;
00729 }
00730
00731
00732 //-------------------------------------------------------------------------------------
00733 // Load a WIC-supported file from disk
00734 //-------------------------------------------------------------------------------------
00735 _Use_decl_annotations_
00736 HRESULT LoadFromWICFile( LPCWSTR szFile, DWORD flags, TexMetadata* metadata, ScratchImage& image )
00737 {
00738     if ( !szFile )
00739         return E_INVALIDARG;
00740
00741     IWICImagingFactory* pWIC = _GetWIC();
00742     if ( !pWIC )
00743         return E_NOINTERFACE;
00744
00745     image.Release();
00746
00747     // Initialize WIC
00748     ScopedObject<IWICBitmapDecoder> decoder;
00749     HRESULT hr = pWIC->CreateDecoderFromFilename( szFile, 0, GENERIC_READ, WICDecodeMetadataCacheOnDemand, &decoder );
00750     if ( FAILED(hr) )
00751         return hr;
00752
00753     ScopedObject<IWICBitmapFrameDecode> frame;
00754     hr = decoder->GetFrame( 0, &frame );
00755     if ( FAILED(hr) )
00756         return hr;
00757
00758     // Get metadata
00759     TexMetadata mdata;
00760     WICPixelFormatGUID convertGUID = {0};
00761     hr = _DecodeMetadata( flags, decoder.Get(), frame.Get(), mdata, &convertGUID );
00762     if ( FAILED(hr) )
00763         return hr;
00764
00765     if ( (mdata.arraySize > 1) && (flags & WIC_FLAGS_ALL_FRAMES) )
00766     {
00767         hr = _DecodeMultiframe( flags, mdata, decoder.Get(), image );
00768     }
00769     else
00770     {
00771         hr = _DecodeSingleFrame( flags, mdata, convertGUID, frame.Get(), image );
00772     }
00773
00774     if ( FAILED(hr) )
00775     {
00776         image.Release();
00777         return hr;
00778     }
00779
00780     if ( metadata )
00781         memcpy( metadata, &mdata, sizeof(TexMetadata) );
00782
00783     return S_OK;
00784 }
00785
00786
00787 //-------------------------------------------------------------------------------------
00788 // Save a WIC-supported file to memory
00789 //-------------------------------------------------------------------------------------
00790 _Use_decl_annotations_
00791 HRESULT SaveToWICMemory( const Image& image, DWORD flags, REFGUID guidContainerFormat, Blob& blob )
00792 {
00793     if ( !image.pixels )
00794         return E_POINTER;
00795
00796     blob.Release();
00797
00798     ScopedObject<IStream> stream;
00799     HRESULT hr = CreateStreamOnHGlobal( 0, TRUE, &stream );
00800     if ( FAILED(hr) )
00801         return hr;
00802
00803     hr = _EncodeSingleFrame( image, flags, guidContainerFormat, stream.Get() );
00804     if ( FAILED(hr) )
00805         return hr;
00806
00807     // Copy stream data into blob
00808     STATSTG stat;
00809     hr = stream->Stat( &stat, STATFLAG_NONAME );
00810     if ( FAILED(hr) )
00811         return hr;
00812
00813     if ( stat.cbSize.HighPart > 0 )
00814         return HRESULT_FROM_WIN32( ERROR_FILE_TOO_LARGE );
00815
00816     hr = blob.Initialize( stat.cbSize.LowPart );
00817     if ( FAILED(hr) )
00818         return hr;
00819
00820     LARGE_INTEGER li = { 0 };
00821     hr = stream->Seek( li, STREAM_SEEK_SET, 0 );
00822     if ( FAILED(hr) )
00823         return hr;
00824
00825     DWORD bytesRead;
00826     hr = stream->Read( blob.GetBufferPointer(), static_cast<ULONG>( blob.GetBufferSize() ), &bytesRead );
00827     if ( FAILED(hr) )
00828         return hr;
00829
00830     if ( bytesRead != blob.GetBufferSize() )
00831         return E_FAIL;
00832
00833     return S_OK;
00834 }
00835
00836 _Use_decl_annotations_
00837 HRESULT SaveToWICMemory( const Image* images, size_t nimages, DWORD flags, REFGUID guidContainerFormat, Blob& blob )
00838 {
00839     if ( !images || nimages == 0 )
00840         return E_INVALIDARG;
00841
00842     blob.Release();
00843
00844     ScopedObject<IStream> stream;
00845     HRESULT hr = CreateStreamOnHGlobal( 0, TRUE, &stream );
00846     if ( FAILED(hr) )
00847         return hr;
00848
00849     if ( nimages > 1 )
00850         hr = _EncodeMultiframe( images, nimages, flags, guidContainerFormat, stream.Get() );
00851     else
00852         hr = _EncodeSingleFrame( images[0], flags, guidContainerFormat, stream.Get() );
00853
00854     if ( FAILED(hr) )
00855         return hr;
00856
00857     // Copy stream data into blob
00858     STATSTG stat;
00859     hr = stream->Stat( &stat, STATFLAG_NONAME );
00860     if ( FAILED(hr) )
00861         return hr;
00862
00863     if ( stat.cbSize.HighPart > 0 )
00864         return HRESULT_FROM_WIN32( ERROR_FILE_TOO_LARGE );
00865
00866     hr = blob.Initialize( stat.cbSize.LowPart );
00867     if ( FAILED(hr) )
00868         return hr;
00869
00870     LARGE_INTEGER li = { 0 };
00871     hr = stream->Seek( li, STREAM_SEEK_SET, 0 );
00872     if ( FAILED(hr) )
00873         return hr;
00874
00875     DWORD bytesRead;
00876     hr = stream->Read( blob.GetBufferPointer(), static_cast<ULONG>( blob.GetBufferSize() ), &bytesRead );
00877     if ( FAILED(hr) )
00878         return hr;
00879
00880     if ( bytesRead != blob.GetBufferSize() )
00881         return E_FAIL;
00882
00883     return S_OK;
00884 }
00885
00886
00887 //-------------------------------------------------------------------------------------
00888 // Save a WIC-supported file to disk
00889 //-------------------------------------------------------------------------------------
00890 _Use_decl_annotations_
00891 HRESULT SaveToWICFile( const Image& image, DWORD flags, REFGUID guidContainerFormat, LPCWSTR szFile )
00892 {
00893     if ( !szFile )
00894         return E_INVALIDARG;
00895
00896     if ( !image.pixels )
00897         return E_POINTER;
00898
00899     IWICImagingFactory* pWIC = _GetWIC();
00900     if ( !pWIC )
00901         return E_NOINTERFACE;
00902
00903     ScopedObject<IWICStream> stream;
00904     HRESULT hr = pWIC->CreateStream( &stream );
00905     if ( FAILED(hr) )
00906         return hr;
00907
00908     hr = stream->InitializeFromFilename( szFile, GENERIC_WRITE );
00909     if ( FAILED(hr) )
00910         return hr;
00911
00912     hr = _EncodeSingleFrame( image, flags, guidContainerFormat, stream.Get() );
00913     if ( FAILED(hr) )
00914         return hr;
00915
00916     return S_OK;
00917 }
00918
00919 _Use_decl_annotations_
00920 HRESULT SaveToWICFile( const Image* images, size_t nimages, DWORD flags, REFGUID guidContainerFormat, LPCWSTR szFile )
00921 {
00922     if ( !szFile || !images || nimages == 0 )
00923         return E_INVALIDARG;
00924
00925     IWICImagingFactory* pWIC = _GetWIC();
00926     if ( !pWIC )
00927         return E_NOINTERFACE;
00928
00929     ScopedObject<IWICStream> stream;
00930     HRESULT hr = pWIC->CreateStream( &stream );
00931     if ( FAILED(hr) )
00932         return hr;
00933
00934     hr = stream->InitializeFromFilename( szFile, GENERIC_WRITE );
00935     if ( FAILED(hr) )
00936         return hr;
00937
00938     if ( nimages > 1 )
00939         hr = _EncodeMultiframe( images, nimages, flags, guidContainerFormat, stream.Get() );
00940     else
00941         hr = _EncodeSingleFrame( images[0], flags, guidContainerFormat, stream.Get() );
00942
00943     if ( FAILED(hr) )
00944         return hr;
00945
00946     return S_OK;
00947 }
00948
00949 }; // namespace
Generated on Sat Nov 23 2024 16:08:12 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Portable device API/C++/S3_SendToDevice.xaml.cpp Source File

  • Portable device API

S3_SendToDevice.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 // S3_SendToDevice.xaml.cpp
00013 // Implementation of the S3_SendToDevice class
00014 //
00015
00016 #include "pch.h"
00017 #include "S3_SendToDevice.xaml.h"
00018
00019 using namespace SDKSample::PortableDeviceCPP;
00020
00021 using namespace concurrency;
00022 using namespace Microsoft::WRL;
00023 using namespace Platform;
00024 using namespace Platform::Collections;
00025 using namespace Windows::Devices::Enumeration;
00026 using namespace Windows::Storage;
00027 using namespace Windows::Storage::FileProperties;
00028 using namespace Windows::Storage::Pickers;
00029 using namespace Windows::Storage::Streams;
00030 using namespace Windows::UI::Xaml;
00031 using namespace Windows::UI::Xaml::Controls;
00032 using namespace Windows::UI::Xaml::Navigation;
00033
00034 S3_SendToDevice::S3_SendToDevice() : rootPage(MainPage::Current)
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 S3_SendToDevice::OnNavigatedTo(NavigationEventArgs^ e)
00045 {
00046     DeviceSelector->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00047 }
00048
00049 /// <summary>
00050 /// This is the click handler for the 'Run' button.
00051 /// </summary>
00052 /// <param name="sender"></param>
00053 /// <param name="e"></param>
00054 void S3_SendToDevice::Run_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00055 {
00056     ShowDeviceSelectorAsync();
00057 }
00058
00059 /// <summary>
00060 /// Enumerates all portable devices and populates the device selection list.
00061 /// </summary>
00062 void S3_SendToDevice::ShowDeviceSelectorAsync()
00063 {
00064     _deviceInfoCollection = nullptr;
00065
00066     // Find all portable devices
00067     String^ aqsFilter = "System.Devices.InterfaceClassGuid:=\"{6AC27878-A6FA-4155-BA85-F98F491D4F33}\" AND System.Devices.InterfaceEnabled:=System.StructuredQueryType.Boolean#True";
00068     create_task(DeviceInformation::FindAllAsync(aqsFilter)).then([this] (DeviceInformationCollection^ deviceInfoCollection)
00069     {
00070         _deviceInfoCollection = deviceInfoCollection;
00071         if (_deviceInfoCollection->Size > 0)
00072         {
00073             auto items = ref new Vector<String^>();
00074             std::for_each(begin(_deviceInfoCollection), end(_deviceInfoCollection), [items](IDeviceInformation^ deviceInfoElement)
00075             {
00076                 items->Append(ref new String(deviceInfoElement->Name->Begin()));
00077             });
00078             cvs->Source = items;
00079             DeviceSelector->Visibility = Windows::UI::Xaml::Visibility::Visible;
00080         }
00081         else
00082         {
00083             rootPage->NotifyUser("No portable devices were found. Please attach a portable device to the system (e.g. a camera, music player, or cellular phone)", NotifyType::ErrorMessage);
00084         }
00085     });
00086 }
00087
00088 /// <summary>
00089 /// This is the tapped handler for the device selection list. It runs the scenario
00090 /// for the selected portable device.
00091 /// </summary>
00092 /// <param name="sender"></param>
00093 /// <param name="e"></param>
00094 void S3_SendToDevice::DeviceList_Tapped(Platform::Object^ sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^ e)
00095 {
00096     DeviceSelector->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00097     if (_deviceInfoCollection == nullptr)
00098     {
00099         return; // not yet populated
00100     }
00101
00102     auto deviceInfo = _deviceInfoCollection->GetAt(DeviceList->SelectedIndex);
00103     SendContentToDeviceAsync(deviceInfo);
00104 }
00105
00106 /// <summary>
00107 /// Launches the picker to select a file and then calls TransferFileToDevice to send
00108 /// the file to the selected portable device.
00109 /// </summary>
00110 /// <param name="deviceInfoElement">Contains information about a selected device.</param>
00111 void S3_SendToDevice::SendContentToDeviceAsync(DeviceInformation^ deviceInfoElement)
00112 {
00113     ComPtr<IPortableDevice> device;
00114     ThrowIfFailed(CoCreateInstance(CLSID_PortableDeviceFTM, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&device)));
00115
00116     auto clientInfo = GetClientInfo();
00117     HRESULT hr = device->Open(deviceInfoElement->Id->Begin(), clientInfo.Get());
00118     if (hr == E_ACCESSDENIED)
00119     {
00120         rootPage->NotifyUser("Access to " + deviceInfoElement->Name + " is denied. Only a Privileged Application may access this device.", NotifyType::ErrorMessage);
00121         return;
00122     }
00123     ThrowIfFailed(hr);
00124
00125     // Verify that we are currently not snapped, or that we can unsnap to open the file picker
00126     auto currentState = Windows::UI::ViewManagement::ApplicationView::Value;
00127     if (currentState == Windows::UI::ViewManagement::ApplicationViewState::Snapped && !Windows::UI::ViewManagement::ApplicationView::TryUnsnap())
00128     {
00129         rootPage->NotifyUser("Could not unsnap (required to launch the file open picker). Please unsnap this app before proceeding", NotifyType::ErrorMessage);
00130         return;
00131     }
00132
00133     auto picker = ref new FileOpenPicker();
00134     picker->FileTypeFilter->Append(".jpg");
00135     picker->FileTypeFilter->Append(".png");
00136     picker->FileTypeFilter->Append(".gif");
00137     picker->SuggestedStartLocation = PickerLocationId::PicturesLibrary;
00138
00139     create_task(picker->PickSingleFileAsync()).then([this, device](StorageFile^ sourceFile)
00140     {
00141         if (sourceFile != nullptr)
00142         {
00143             rootPage->NotifyUser("Selected file to send to device: " + sourceFile->Name, NotifyType::StatusMessage);
00144             TransferFileToDeviceAsync(sourceFile, device.Get());
00145         }
00146         else
00147         {
00148             rootPage->NotifyUser("No file was selected", NotifyType::StatusMessage);
00149         }
00150     });
00151 }
00152
00153 /// <summary>
00154 /// Sends a file to the device using the Windows.Storage and Portable Device COM APIs.
00155 /// </summary>
00156 /// <param name="file">The file to send to the device.</param>
00157 /// <param name="device">Pointer to the IPortableDevice for a portable device.</param>
00158 void S3_SendToDevice::TransferFileToDeviceAsync(StorageFile^ file, _In_ IPortableDevice* device)
00159 {
00160     if (file == nullptr) throw ref new Platform::NullReferenceException;
00161
00162     // Allows the random access stream pointer to be shared between tasks and task continuations
00163     auto randomAccessStream = std::make_shared<IRandomAccessStream^>(nullptr);
00164
00165     auto storageId = GetFirstStorageId(device);
00166     if (storageId != nullptr)
00167     {
00168         ComPtr<IPortableDevice> deviceRef = device; // for capturing in the completion lambda
00169
00170         create_task(file->OpenAsync(FileAccessMode::Read)).then([this, file, randomAccessStream] (IRandomAccessStream^ rastream)
00171         {
00172             if (rastream == nullptr) throw ref new Platform::NullReferenceException;
00173             *randomAccessStream = rastream;
00174             return file->GetBasicPropertiesAsync();
00175
00176         }).then([this, file, deviceRef, storageId, randomAccessStream] (BasicProperties^ basicProperties)
00177         {
00178             ComPtr<IStream> sourceStream, destStream;
00179             DWORD optimalTransferSizeBytes = 0;
00180
00181             ComPtr<IPortableDeviceContent> content;
00182             ThrowIfFailed(deviceRef->Content(&content));
00183
00184             // Create a new object with properties and data
00185             auto imageProperties = FillInPropertiesForImage(file, storageId, basicProperties->Size);
00186             HRESULT hr = content->CreateObjectWithPropertiesAndData(imageProperties.Get(), // Properties describing the object data
00187                                                             &destStream,                    // Returned object data stream (to transfer the data to)
00188                                                             &optimalTransferSizeBytes,      // Returned optimal buffer size to use during transfer
00189                                                             nullptr);
00190             if (hr == HRESULT_FROM_WIN32(ERROR_FILE_EXISTS))
00191             {
00192                 rootPage->NotifyUser("The file '" + file->Name + "' already exists on the device, please try a different file or remove the existing one from the device.",
00193                     NotifyType::ErrorMessage);
00194                 return;
00195             }
00196             ThrowIfFailed(hr);
00197
00198             // Transfer the object data
00199             ThrowIfFailed(CreateStreamOverRandomAccessStream(*randomAccessStream, IID_PPV_ARGS(&sourceStream)));
00200             ULONGLONG totalTransferredBytes = StreamCopy(destStream.Get(), sourceStream.Get(), optimalTransferSizeBytes);
00201             if (totalTransferredBytes >= basicProperties->Size)
00202             {
00203                 // Commit the object data to save it
00204                 ComPtr<IPortableDeviceDataStream> dataStream;
00205                 ThrowIfFailed(destStream.As(&dataStream));
00206                 ThrowIfFailed(dataStream->Commit(STGC_DEFAULT));
00207
00208                 // Get the object Id of the newly created object
00209                 PWSTR newlyCreatedObjectId = nullptr;
00210                 HRESULT hr = dataStream->GetObjectID(&newlyCreatedObjectId);
00211                 CoTaskMemString objectIdPtr(newlyCreatedObjectId); // Ensure that the object Id is properly freed upon an exception
00212                 ThrowIfFailed(hr);
00213
00214                 rootPage->NotifyUser("The file '" + file->Path + "' was transferred to the device (" + totalTransferredBytes.ToString()
00215                     + " bytes).\nThe newly created object's ID is '" + ref new String(newlyCreatedObjectId), NotifyType::StatusMessage);
00216             }
00217             else
00218             {
00219                 rootPage->NotifyUser("The file '" + file->Path + "' was not completely transferred to the device (only "
00220                     + totalTransferredBytes.ToString() + " bytes were transferred).", NotifyType::ErrorMessage);
00221             }
00222         });
00223     }
00224     else
00225     {
00226         rootPage->NotifyUser("No storages were found on the device. Please attach a device with at least 1 storage", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 /// <summary>
00231 /// Returns an IPortableDeviceValues containing properties used for creating an image object on the device.
00232 /// </summary>
00233 /// <param name="file">The image file that will be transferred to the new image object.</param>
00234 /// <param name="parentId">The parent object identifier for the new image object.</param>
00235 /// <param name="size">The size of the new image object.</param>
00236 /// <returns>IPortableDeviceValues ComPtr containing the image object property keys and values.</returns>
00237 #define COMPILETIMESTRLEN(A) ARRAYSIZE(A) - 1
00238 ComPtr<IPortableDeviceValues> S3_SendToDevice::FillInPropertiesForImage(StorageFile^ file, String^ parentId, ULONGLONG size)
00239 {
00240     ComPtr<IPortableDeviceValues> result;
00241     ThrowIfFailed(CoCreateInstance(CLSID_PortableDeviceValues, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&result)));
00242
00243     ThrowIfFailed(result->SetStringValue(WPD_OBJECT_PARENT_ID, parentId->Begin()));
00244     ThrowIfFailed(result->SetUnsignedLargeIntegerValue(WPD_OBJECT_SIZE, size));
00245     ThrowIfFailed(result->SetStringValue(WPD_OBJECT_NAME, file->DisplayName->Begin()));
00246     ThrowIfFailed(result->SetStringValue(WPD_OBJECT_ORIGINAL_FILE_NAME, file->Name->Begin()));
00247     ThrowIfFailed(result->SetGuidValue(WPD_OBJECT_CONTENT_TYPE, WPD_CONTENT_TYPE_IMAGE));
00248
00249     // using culture-insensitive, case-insensitive comparison for the file extensions
00250     if (0 == CompareStringOrdinal(file->FileType->Data(), file->FileType->Length(), L".gif", COMPILETIMESTRLEN(L".gif"), TRUE))
00251     {
00252         ThrowIfFailed(result->SetGuidValue(WPD_OBJECT_FORMAT, WPD_OBJECT_FORMAT_GIF));
00253     }
00254     else if (0 == CompareStringOrdinal(file->FileType->Data(), file->FileType->Length(), L".png", COMPILETIMESTRLEN(L".png"), TRUE))
00255     {
00256         ThrowIfFailed(result->SetGuidValue(WPD_OBJECT_FORMAT, WPD_OBJECT_FORMAT_PNG));
00257     }
00258     else
00259     {
00260         // since we already filtered the file types in the file picker, we can fall back to jpg
00261         ThrowIfFailed(result->SetGuidValue(WPD_OBJECT_FORMAT, WPD_OBJECT_FORMAT_EXIF));
00262     }
00263     return result;
00264 }
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: App package information/C++/Constants.cpp Source File

  • App package information

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
00021     { "Identity",           "SDKSample.PackageSample.Scenario1" },
00022     { "Installed Location", "SDKSample.PackageSample.Scenario2" },
00023     { "Dependencies",       "SDKSample.PackageSample.Scenario3" },
00024 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Scheduled notifications/C#,C++/ScenarioOutput1.xaml.h Source File

  • Scheduled notifications
  • C#,C++

ScenarioOutput1.xaml.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 //
00009 // Scenario1Output.xaml.h
00010 // Declaration of the Scenario1Output class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioOutput1.g.h"
00017 #include "MainPage.xaml.h"
00018
00019 namespace ScheduledNotificationsSampleCPP
00020 {
00021   [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class ScenarioOutput1 sealed
00023     {
00024     public:
00025         ScenarioOutput1();
00026   private:
00027     ~ScenarioOutput1();
00028     };
00029 }
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML AppBar control/C++/Page1.xaml.h Source File

  • XAML AppBar control

Page1.xaml.h

Go to the documentation of this file.
00001 ﻿//
00002 // Page1.xaml.h
00003 // Declaration of the Page1 class
00004 //
00005
00006 #pragma once
00007
00008 #include "pch.h"
00009 #include "GlobalPage.xaml.h"
00010 #include "Page1.g.h"
00011
00012 namespace AppBarControl
00013 {
00014   /// <summary>
00015   /// An empty page that can be used on its own or navigated to within a Frame.
00016   /// </summary>
00017   [Windows::Foundation::Metadata::WebHostHidden]
00018   public ref class Page1 sealed
00019   {
00020   public:
00021     Page1();
00022
00023   protected:
00024     virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00025   private:
00026     void PageTwo_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00027     static GlobalPage^ rootPage;
00028   };
00029 }
Generated on Sat Nov 23 2024 16:08:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

AnimateLineListPosition Member List

This is the complete list of members for AnimateLineListPosition, including all inherited members.
__pad0__ | AnimateLineListPosition |
Evaluate(_In_ float t) override | AnimateLineListPosition | [virtual]
Evaluate(_In_ float t) override | AnimateLineListPosition | [virtual]
m_count | AnimateLineListPosition | [private]
m_segment | AnimateLineListPosition | [private]
m_totalLength | AnimateLineListPosition | [private]
Generated on Sat Nov 23 2024 16:09:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Audio Session (WASAPI)/C++/Scenario3.xaml.h Source File

  • Windows Audio Session (WASAPI)
  • C++

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 "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 Scenario3 sealed
00034         {
00035
00036         public:
00037             Scenario3();
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             ~Scenario3();
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_Oscilliscope;
00066
00067             Windows::Foundation::EventRegistrationToken     m_deviceStateChangeToken;
00068             Windows::Foundation::EventRegistrationToken     m_plotDataReadyToken;
00069
00070             int                         m_DiscontinuityCount;
00071             Platform::Boolean           m_IsMFLoaded;
00072             DeviceStateChangedEvent^    m_StateChangedEvent;
00073             ComPtr<WASAPICapture>       m_spCapture;
00074         };
00075     }
00076 }
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/IMonthBlock.h Source File

  • Hilo C++
  • Hilo

IMonthBlock.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
00009 namespace Hilo
00010 {
00011     interface class IYearGroup;
00012
00013     // The IMonthBlock class defines the signature of per-month data used by the
00014     // image browser's zoomed-out view of the user's picture library. XAML controls
00015     // bind to objects of this type.
00016     public interface class IMonthBlock
00017     {
00018         property Platform::String^ Name
00019         {
00020             Platform::String^ get();
00021         }
00022
00023         property bool HasPhotos
00024         {
00025             bool get();
00026         }
00027
00028         property unsigned int Month
00029         {
00030             unsigned int get();
00031         }
00032
00033         property IYearGroup^ Group
00034         {
00035             IYearGroup^ get();
00036         }
00037     };
00038 }
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/MonthBlock.cpp Source File

  • Hilo C++
  • Hilo

MonthBlock.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 #include "MonthBlock.h"
00009 #include "ExceptionPolicy.h"
00010 #include "IYearGroup.h"
00011 #include "IResourceLoader.h"
00012 #include "TaskExceptionsExtensions.h"
00013 #include "Repository.h"
00014 #include "CalendarExtensions.h"
00015 using namespace concurrency;
00016 using namespace std;
00017 using namespace Hilo;
00018 using namespace Platform;
00019 using namespace Windows::Globalization;
00020 using namespace Windows::Globalization::DateTimeFormatting;
00021 using namespace Windows::System::UserProfile;
00022 using namespace Windows::Storage::Search;
00023
00024 MonthBlock::MonthBlock(IYearGroup^ yearGroup, int month, IStorageFolderQueryOperations^ folderQuery, shared_ptr<Repository> repository, shared_ptr<ExceptionPolicy> exceptionPolicy) :
00025     m_weakYearGroup(yearGroup), m_month(month), m_name(nullptr), m_folderQuery(folderQuery),
00026     m_repository(repository), m_exceptionPolicy(exceptionPolicy), m_count(0ul), m_runOperation(false), m_runningOperation(false)
00027 {
00028 }
00029
00030 void MonthBlock::OnPropertyChanged(String^ propertyName)
00031 {
00032     assert(IsMainThread());
00033     PropertyChanged(this, ref new Windows::UI::Xaml::Data::PropertyChangedEventArgs(propertyName));
00034 }
00035
00036 unsigned int MonthBlock::Month::get()
00037 {
00038     return m_month;
00039 }
00040
00041 String^ MonthBlock::Name::get()
00042 {
00043     if (nullptr == m_name)
00044     {
00045         m_name = CalendarExtensions::GetLocalizedAbbreviatedMonthName(Group->Year, m_month);
00046     }
00047     return m_name;
00048 }
00049
00050 IYearGroup^ MonthBlock::Group::get()
00051 {
00052     return m_weakYearGroup.Resolve<IYearGroup>();
00053 }
00054
00055 bool MonthBlock::HasPhotos::get()
00056 {
00057     if (!m_runOperation && !m_runningOperation)
00058     {
00059         m_runningOperation = true;
00060         run_async_non_interactive([this]()
00061         {
00062             QueryPhotoCount().then([this]
00063             {
00064                 assert(IsMainThread());
00065                 OnPropertyChanged("HasPhotos");
00066             }, task_continuation_context::use_current())
00067                 .then(ObserveException<void>(m_exceptionPolicy));
00068         });
00069     }
00070     return (m_count > 0);
00071 }
00072
00073 task<void> MonthBlock::QueryPhotoCount()
00074 {
00075     auto t = create_task_from_result(true);
00076
00077     if (Group != nullptr)
00078     {
00079         // If there is a valid group we can actually build a query to get the real count.
00080         auto dateRangeQuery = BuildDateQuery();
00081         t = m_repository->HasPhotosInRangeAsync(dateRangeQuery, m_folderQuery);
00082     }
00083
00084     return t.then([this](task<bool> priorTask)
00085     {
00086         assert(IsMainThread());
00087         m_runningOperation = false;
00088         m_count = priorTask.get() ? 1u : 0u;
00089         m_runOperation = true;
00090     }, task_continuation_context::use_current());
00091 }
00092
00093 String^ MonthBlock::BuildDateQuery()
00094 {
00095     return CalendarExtensions::CreateMonthRangeFromYearAndMonth(Group->Year, m_month);
00096 }
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Gyrometer sensor/C++/Constants.cpp Source File

  • Gyrometer sensor

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     { "Gyrometer data events", "SDKSample.GyrometerCPP.Scenario1" },
00020     { "Poll gyrometer readings", "SDKSample.GyrometerCPP.Scenario2" }
00021 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/VariableGridView.cpp Source File

  • Hilo C++
  • Hilo

VariableGridView.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 #include "VariableGridView.h"
00009 #include "IResizable.h"
00010
00011 using namespace Hilo;
00012 using namespace Platform;
00013 using namespace Windows::UI::Xaml::Controls;
00014
00015 void VariableGridView::PrepareContainerForItemOverride(DependencyObject^ element, Object^ item)
00016 {
00017     auto model = dynamic_cast<IResizable^>(item);
00018
00019     if (model != nullptr)
00020     {
00021         element->SetValue(VariableSizedWrapGrid::ColumnSpanProperty, model->ColumnSpan);
00022         element->SetValue(VariableSizedWrapGrid::RowSpanProperty, model->RowSpan);
00023     }
00024
00025     GridView::PrepareContainerForItemOverride(element, item);
00026 }
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Proximity/C++/common/LayoutAwarePage.h Source File

  • Proximity
  • common

LayoutAwarePage.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 #include <collection.h>
00015
00016 namespace ProximityCPP
00017 {
00018     namespace Common
00019     {
00020         /// <summary>
00021         /// Typical implementation of Page that provides several important conveniences: application
00022         /// view state to visual state mapping, GoBack and GoHome event handlers, and a default view
00023         /// model.
00024         /// </summary>
00025         [Windows::Foundation::Metadata::WebHostHidden]
00026         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00027         {
00028         internal:
00029             LayoutAwarePage();
00030
00031         public:
00032             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00033             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00034             void InvalidateVisualState();
00035             property bool UseFilledStateForNarrowWindow
00036             {
00037                 bool get();
00038                 void set(bool value);
00039             }
00040             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Object^>^ DefaultViewModel
00041             {
00042                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Object^>^ get();
00043             }
00044
00045         protected:
00046             virtual void GoHome(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             virtual void GoBack(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00049
00050         private:
00051             bool _useFilledStateForNarrowWindow;
00052             Platform::Collections::Map<Platform::String^, Object^>^ _defaultViewModel;
00053             Windows::Foundation::EventRegistrationToken _windowSizeEventToken;
00054             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00055             void WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00056         };
00057     }
00058 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C#,C++/MediaExtensions/Grayscale/Grayscale.h Source File

  • Media extensions
  • C#,C++
  • MediaExtensions
  • Grayscale

Grayscale.h

Go to the documentation of this file.
00001 // Defines the transform class.
00002 //
00003 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00004 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00005 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00006 // PARTICULAR PURPOSE.
00007 //
00008 // Copyright (c) Microsoft Corporation. All rights reserved.
00009
00010 #ifndef GRAYSCALE_H
00011 #define GRAYSCALE_H
00012
00013 #include <new>
00014 #include <mfapi.h>
00015 #include <mftransform.h>
00016 #include <mfidl.h>
00017 #include <mferror.h>
00018 #include <strsafe.h>
00019 #include <assert.h>
00020
00021 // Note: The Direct2D helper library is included for its 2D matrix operations.
00022 #include <D2d1helper.h>
00023
00024 #include <wrl\implements.h>
00025 #include <wrl\module.h>
00026 #include <windows.media.h>
00027
00028 #include "GrayscaleTransform.h"
00029
00030 // CLSID of the MFT.
00031 DEFINE_GUID(CLSID_GrayscaleMFT,
00032 0x2f3dbc05, 0xc011, 0x4a8f, 0xb2, 0x64, 0xe4, 0x2e, 0x35, 0xc6, 0x7b, 0xf4);
00033
00034 //
00035 // * IMPORTANT: If you implement your own MFT, create a new GUID for the CLSID. *
00036 //
00037
00038
00039 // Configuration attributes
00040
00041 // {7BBBB051-133B-41F5-B6AA-5AFF9B33A2CB}
00042 DEFINE_GUID(MFT_GRAYSCALE_DESTINATION_RECT,
00043 0x7bbbb051, 0x133b, 0x41f5, 0xb6, 0xaa, 0x5a, 0xff, 0x9b, 0x33, 0xa2, 0xcb);
00044
00045
00046 // {14782342-93E8-4565-872C-D9A2973D5CBF}
00047 DEFINE_GUID(MFT_GRAYSCALE_SATURATION,
00048 0x14782342, 0x93e8, 0x4565, 0x87, 0x2c, 0xd9, 0xa2, 0x97, 0x3d, 0x5c, 0xbf);
00049
00050 // {E0BADE5D-E4B9-4689-9DBA-E2F00D9CED0E}
00051 DEFINE_GUID(MFT_GRAYSCALE_CHROMA_ROTATION,
00052 0xe0bade5d, 0xe4b9, 0x4689, 0x9d, 0xba, 0xe2, 0xf0, 0xd, 0x9c, 0xed, 0xe);
00053
00054
00055 template <class T> void SafeRelease(T **ppT)
00056 {
00057     if (*ppT)
00058     {
00059         (*ppT)->Release();
00060         *ppT = NULL;
00061     }
00062 }
00063
00064 // Function pointer for the function that transforms the image.
00065 typedef void (*IMAGE_TRANSFORM_FN)(
00066     const D2D1::Matrix3x2F& mat,             // Chroma transform matrix.
00067     const D2D_RECT_U&       rcDest,          // Destination rectangle for the transformation.
00068     BYTE*                   pDest,           // Destination buffer.
00069     LONG                    lDestStride,     // Destination stride.
00070     const BYTE*             pSrc,            // Source buffer.
00071     LONG                    lSrcStride,      // Source stride.
00072     DWORD                   dwWidthInPixels, // Image width in pixels.
00073     DWORD                   dwHeightInPixels // Image height in pixels.
00074     );
00075
00076 // CGrayscale class:
00077 // Implements a grayscale video effect.
00078
00079 class CGrayscale
00080     : public Microsoft::WRL::RuntimeClass<
00081            Microsoft::WRL::RuntimeClassFlags< Microsoft::WRL::RuntimeClassType::WinRtClassicComMix >,
00082            ABI::Windows::Media::IMediaExtension,
00083            IMFTransform >
00084 {
00085     InspectableClass(RuntimeClass_GrayscaleTransform_GrayscaleEffect, BaseTrust)
00086
00087 public:
00088     CGrayscale();
00089
00090     ~CGrayscale();
00091
00092     STDMETHOD(RuntimeClassInitialize)();
00093
00094     // IMediaExtension
00095     STDMETHODIMP SetProperties(ABI::Windows::Foundation::Collections::IPropertySet *pConfiguration);
00096
00097     // IMFTransform
00098     STDMETHODIMP GetStreamLimits(
00099         DWORD   *pdwInputMinimum,
00100         DWORD   *pdwInputMaximum,
00101         DWORD   *pdwOutputMinimum,
00102         DWORD   *pdwOutputMaximum
00103     );
00104
00105     STDMETHODIMP GetStreamCount(
00106         DWORD   *pcInputStreams,
00107         DWORD   *pcOutputStreams
00108     );
00109
00110     STDMETHODIMP GetStreamIDs(
00111         DWORD   dwInputIDArraySize,
00112         DWORD   *pdwInputIDs,
00113         DWORD   dwOutputIDArraySize,
00114         DWORD   *pdwOutputIDs
00115     );
00116
00117     STDMETHODIMP GetInputStreamInfo(
00118         DWORD                     dwInputStreamID,
00119         MFT_INPUT_STREAM_INFO *   pStreamInfo
00120     );
00121
00122     STDMETHODIMP GetOutputStreamInfo(
00123         DWORD                     dwOutputStreamID,
00124         MFT_OUTPUT_STREAM_INFO *  pStreamInfo
00125     );
00126
00127     STDMETHODIMP GetAttributes(IMFAttributes** pAttributes);
00128
00129     STDMETHODIMP GetInputStreamAttributes(
00130         DWORD           dwInputStreamID,
00131         IMFAttributes   **ppAttributes
00132     );
00133
00134     STDMETHODIMP GetOutputStreamAttributes(
00135         DWORD           dwOutputStreamID,
00136         IMFAttributes   **ppAttributes
00137     );
00138
00139     STDMETHODIMP DeleteInputStream(DWORD dwStreamID);
00140
00141     STDMETHODIMP AddInputStreams(
00142         DWORD   cStreams,
00143         DWORD   *adwStreamIDs
00144     );
00145
00146     STDMETHODIMP GetInputAvailableType(
00147         DWORD           dwInputStreamID,
00148         DWORD           dwTypeIndex, // 0-based
00149         IMFMediaType    **ppType
00150     );
00151
00152     STDMETHODIMP GetOutputAvailableType(
00153         DWORD           dwOutputStreamID,
00154         DWORD           dwTypeIndex, // 0-based
00155         IMFMediaType    **ppType
00156     );
00157
00158     STDMETHODIMP SetInputType(
00159         DWORD           dwInputStreamID,
00160         IMFMediaType    *pType,
00161         DWORD           dwFlags
00162     );
00163
00164     STDMETHODIMP SetOutputType(
00165         DWORD           dwOutputStreamID,
00166         IMFMediaType    *pType,
00167         DWORD           dwFlags
00168     );
00169
00170     STDMETHODIMP GetInputCurrentType(
00171         DWORD           dwInputStreamID,
00172         IMFMediaType    **ppType
00173     );
00174
00175     STDMETHODIMP GetOutputCurrentType(
00176         DWORD           dwOutputStreamID,
00177         IMFMediaType    **ppType
00178     );
00179
00180     STDMETHODIMP GetInputStatus(
00181         DWORD           dwInputStreamID,
00182         DWORD           *pdwFlags
00183     );
00184
00185     STDMETHODIMP GetOutputStatus(DWORD *pdwFlags);
00186
00187     STDMETHODIMP SetOutputBounds(
00188         LONGLONG        hnsLowerBound,
00189         LONGLONG        hnsUpperBound
00190     );
00191
00192     STDMETHODIMP ProcessEvent(
00193         DWORD              dwInputStreamID,
00194         IMFMediaEvent      *pEvent
00195     );
00196
00197     STDMETHODIMP ProcessMessage(
00198         MFT_MESSAGE_TYPE    eMessage,
00199         ULONG_PTR           ulParam
00200     );
00201
00202     STDMETHODIMP ProcessInput(
00203         DWORD               dwInputStreamID,
00204         IMFSample           *pSample,
00205         DWORD               dwFlags
00206     );
00207
00208     STDMETHODIMP ProcessOutput(
00209         DWORD                   dwFlags,
00210         DWORD                   cOutputBufferCount,
00211         MFT_OUTPUT_DATA_BUFFER  *pOutputSamples, // one per stream
00212         DWORD                   *pdwStatus
00213     );
00214
00215
00216 private:
00217     // HasPendingOutput: Returns TRUE if the MFT is holding an input sample.
00218     BOOL HasPendingOutput() const { return m_pSample != NULL; }
00219
00220     // IsValidInputStream: Returns TRUE if dwInputStreamID is a valid input stream identifier.
00221     BOOL IsValidInputStream(DWORD dwInputStreamID) const
00222     {
00223         return dwInputStreamID == 0;
00224     }
00225
00226     // IsValidOutputStream: Returns TRUE if dwOutputStreamID is a valid output stream identifier.
00227     BOOL IsValidOutputStream(DWORD dwOutputStreamID) const
00228     {
00229         return dwOutputStreamID == 0;
00230     }
00231
00232     HRESULT OnGetPartialType(DWORD dwTypeIndex, IMFMediaType **ppmt);
00233     HRESULT OnCheckInputType(IMFMediaType *pmt);
00234     HRESULT OnCheckOutputType(IMFMediaType *pmt);
00235     HRESULT OnCheckMediaType(IMFMediaType *pmt);
00236     void    OnSetInputType(IMFMediaType *pmt);
00237     void    OnSetOutputType(IMFMediaType *pmt);
00238     HRESULT BeginStreaming();
00239     HRESULT EndStreaming();
00240     HRESULT OnProcessOutput(IMFMediaBuffer *pIn, IMFMediaBuffer *pOut);
00241     HRESULT OnFlush();
00242     HRESULT UpdateFormatInfo();
00243
00244     CRITICAL_SECTION            m_critSec;
00245
00246     // Transformation parameters
00247     D2D1::Matrix3x2F            m_transform;                // Chroma transform matrix.
00248     D2D_RECT_U                  m_rcDest;                   // Destination rectangle for the effect.
00249
00250     // Streaming
00251     bool                        m_bStreamingInitialized;
00252     IMFSample                   *m_pSample;                 // Input sample.
00253     IMFMediaType                *m_pInputType;              // Input media type.
00254     IMFMediaType                *m_pOutputType;             // Output media type.
00255
00256     // Fomat information
00257     UINT32                      m_imageWidthInPixels;
00258     UINT32                      m_imageHeightInPixels;
00259     DWORD                       m_cbImageSize;              // Image size, in bytes.
00260
00261     IMFAttributes               *m_pAttributes;
00262
00263     // Image transform function. (Changes based on the media type.)
00264     IMAGE_TRANSFORM_FN          m_pTransformFn;
00265 };
00266 #endif
Generated on Sat Nov 23 2024 16:08:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DirectX::DDS_HEADER Member List

This is the complete list of members for DirectX::DDS_HEADER, including all inherited members.
ddspf | DirectX::DDS_HEADER
dwCaps | DirectX::DDS_HEADER
dwCaps2 | DirectX::DDS_HEADER
dwCaps3 | DirectX::DDS_HEADER
dwCaps4 | DirectX::DDS_HEADER
dwDepth | DirectX::DDS_HEADER
dwFlags | DirectX::DDS_HEADER
dwHeight | DirectX::DDS_HEADER
dwMipMapCount | DirectX::DDS_HEADER
dwPitchOrLinearSize | DirectX::DDS_HEADER
dwReserved1 | DirectX::DDS_HEADER
dwReserved2 | DirectX::DDS_HEADER
dwSize | DirectX::DDS_HEADER
dwWidth | DirectX::DDS_HEADER
Generated on Sat Nov 23 2024 16:09:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML vector-based drawing/C++/Constants.cpp Source File

  • XAML vector-based drawing

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 using namespace Windows::UI;
00018
00019 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00020 {
00021     // The format here is the following:
00022     //     { "Description for the sample", "Fully qualified name for the class that implements the scenario" }
00023     { "Shape", "SDKSample.Drawing.Scenario1" },
00024     { "Strokes and fills", "SDKSample.Drawing.Scenario2" },
00025     { "Gradient", "SDKSample.Drawing.Scenario3" },
00026   { "Clipping", "SDKSample.Drawing.Scenario4" }
00027 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Store device app for camera/C++/Wrapper/pch.h Source File

  • Windows Store device app for camera
  • Wrapper

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
00009 // pch.h : include file for standard system include files, or project specific
00010 // include files that are used frequently, but are changed infrequently
00011
00012 #pragma once
00013
00014 #include <winstring.h>
00015 #include <wrl\client.h>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

ProximityCPP::Common::LayoutAwarePage Member List

This is the complete list of members for ProximityCPP::Common::LayoutAwarePage, including all inherited members.
__pad0__ | ProximityCPP::Common::LayoutAwarePage |
_defaultViewModel | ProximityCPP::Common::LayoutAwarePage | [private]
_layoutAwareControls | ProximityCPP::Common::LayoutAwarePage | [private]
_useFilledStateForNarrowWindow | ProximityCPP::Common::LayoutAwarePage | [private]
_windowSizeEventToken | ProximityCPP::Common::LayoutAwarePage | [private]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | ProximityCPP::Common::LayoutAwarePage | [virtual]
GoBack(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | ProximityCPP::Common::LayoutAwarePage | [virtual]
InvalidateVisualState() | ProximityCPP::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | ProximityCPP::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | ProximityCPP::Common::LayoutAwarePage |
WindowSizeChanged(Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | ProximityCPP::Common::LayoutAwarePage | [private]
Generated on Sat Nov 23 2024 16:09:46 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML animation library/C++/Scenario3.xaml.h Source File

  • XAML animation library

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 SDKSample
00023 {
00024     namespace Animation
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         void Scenario3EasingFunctionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00040         void PlotEasingFunctionGraph(Windows::UI::Xaml::Media::Animation::EasingFunctionBase^ easingFunction, double samplingInterval);
00041       };
00042     }
00043 }
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/MeshObject.cpp Source File

  • XAML DirectX 3D shooting game

MeshObject.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 "MeshObject.h"
00010 #include "DirectXSample.h"
00011 #include "ConstantBuffers.h"
00012
00013 using namespace Microsoft::WRL;
00014 using namespace DirectX;
00015
00016 MeshObject::MeshObject():
00017     m_vertexCount(0),
00018     m_indexCount(0)
00019 {
00020 }
00021
00022 //--------------------------------------------------------------------------------
00023
00024 void MeshObject::Render(_In_ ID3D11DeviceContext *context)
00025 {
00026     uint32 stride = sizeof(PNTVertex);
00027     uint32 offset = 0;
00028
00029     context->IASetVertexBuffers(0, 1, m_vertexBuffer.GetAddressOf(), &stride, &offset);
00030     context->IASetIndexBuffer(m_indexBuffer.Get(), DXGI_FORMAT_R16_UINT, 0);
00031     context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
00032     context->DrawIndexed(m_indexCount, 0, 0);
00033 }
00034
00035 //--------------------------------------------------------------------------------
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML scrolling, panning, and zooming/C++/App.xaml.cpp Source File

  • XAML scrolling, panning, and zooming

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Globalization preferences/C++/Language.xaml.cpp Source File

  • Globalization preferences

Language.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 // LanguageScenario.xaml.cpp
00013 // Implementation of the LanguageScenario class
00014 //
00015
00016 #include "pch.h"
00017 #include "Language.xaml.h"
00018
00019 using namespace SDKSample::GlobalizationPreferencesSample;
00020
00021 using namespace Platform;
00022 using namespace Windows::Foundation;
00023 using namespace Windows::Foundation::Collections;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Controls;
00026 using namespace Windows::UI::Xaml::Navigation;
00027 using namespace Windows::System::UserProfile;
00028 using namespace Windows::Globalization;
00029
00030 LanguageScenario::LanguageScenario()
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 void LanguageScenario::OnNavigatedTo(NavigationEventArgs^ e)
00041 {
00042     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00043     // as NotifyUser()
00044     rootPage = MainPage::Current;
00045 }
00046
00047 void LanguageScenario::Display_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00048 {
00049   // This scenario uses the Windows.System.UserProfile.GlobalizationPreferences class to
00050   // obtains the user's preferred language characteristics.
00051   auto userLanguage = ref new Windows::Globalization::Language(GlobalizationPreferences::Languages->GetAt(0));
00052
00053   // This obtains the language characteristics by providing a BCP47 tag.
00054   auto exampleLanguage = ref new Windows::Globalization::Language("en-AU");
00055
00056   // Generate the results
00057   String^ userLanguageCharacteristics = "User's Preferred Language\n" +
00058     "Display Name: " + userLanguage->DisplayName + "\n" +
00059     "Language Tag: "  + userLanguage->LanguageTag + "\n" +
00060     "Native Name: "  + userLanguage->NativeName + "\n" +
00061     "Script Code: "  + userLanguage->Script;
00062
00063   String^ exampleLanguageCharacteristics = "Example Language by BCP47 tag (en-AU)\n" +
00064     "Display Name: " + exampleLanguage->DisplayName + "\n" +
00065     "Language Tag: "  + exampleLanguage->LanguageTag + "\n" +
00066     "Native Name: "  + exampleLanguage->NativeName + "\n" +
00067     "Script Code: "  + exampleLanguage->Script;
00068
00069   String^ results = userLanguageCharacteristics + "\n\n" + exampleLanguageCharacteristics;
00070
00071     // Display the results
00072   rootPage->NotifyUser(results, NotifyType::StatusMessage);
00073 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Background task/C++/BackgroundTask/ServicingCompleteTask.xaml.h Source File

  • Background task
  • BackgroundTask

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 // ServicingCompleteTask.xaml.h
00013 // Declaration of the ServicingCompleteTask class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "ServicingCompleteTask.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace BackgroundTask
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 ServicingCompleteTask sealed
00031         {
00032         public:
00033             ServicingCompleteTask();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
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 UpdateUI();
00044         };
00045     }
00046 }
Generated on Sat Nov 23 2024 16:07:58 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

TextAnalysis Member List

This is the complete list of members for TextAnalysis, including all inherited members.
AnalyzeBidi(Microsoft::WRL::ComPtr< IDWriteTextAnalyzer1 > textAnalyzer, IDWriteTextAnalysisSource1 *analysisSource, UINT32 firstPosition, UINT32 textLength, IDWriteTextAnalysisSink1 *analysisSink) | TextAnalysis |
AnalyzeGlyphOrientation(Microsoft::WRL::ComPtr< IDWriteTextAnalyzer1 > textAnalyzer, IDWriteTextAnalysisSource1 *analysisSource, UINT32 textPosition, UINT32 textLength, IDWriteTextAnalysisSink1 *analysisSink) | TextAnalysis |
ComBase() | ComBase< QiList< IDWriteTextAnalysisSource1, QiList< IDWriteTextAnalysisSink1, QiList< IUnknown > > > > | [inline, explicit]
FetchNextRun(_Inout_ UINT32 *textLength) | TextAnalysis | [protected]
GenerateResults(Microsoft::WRL::ComPtr< IDWriteTextAnalyzer1 > textAnalyzer, _Out_ std::vector< Run > &runs, _Out_ std::vector< DWRITE_LINE_BREAKPOINT > &breakpoints_) | TextAnalysis |
GetLocaleName(UINT32 textPosition, _Out_ UINT32 *textLength, _Out_ WCHAR const **localeName) | TextAnalysis |
GetNumberSubstitution(UINT32 textPosition, _Out_ UINT32 *textLength, _Out_ IDWriteNumberSubstitution **numberSubstitution) | TextAnalysis |
GetTextAtPosition(UINT32 textPosition, _Out_ WCHAR const **textString, _Out_ UINT32 *textLength) | TextAnalysis |
GetTextBeforePosition(UINT32 textPosition, _Out_ WCHAR const **textString, _Out_ UINT32 *textLength) | TextAnalysis |
GetVerticalGlyphOrientation(UINT32 textPosition, _Out_ UINT32 *textLength, _Out_ DWRITE_VERTICAL_GLYPH_ORIENTATION *glyphOrientation, _Out_ UINT8 *bidiLevel) | TextAnalysis |
IFACEMETHOD_(ULONG, AddRef)() | ComBase< QiList< IDWriteTextAnalysisSource1, QiList< IDWriteTextAnalysisSink1, QiList< IUnknown > > > > | [inline]
IFACEMETHOD_(ULONG, Release)() | ComBase< QiList< IDWriteTextAnalysisSource1, QiList< IDWriteTextAnalysisSink1, QiList< IUnknown > > > > | [inline]
IFACEMETHODIMP_(DWRITE_READING_DIRECTION) GetParagraphReadingDirection() | TextAnalysis |
m_breakpoints | TextAnalysis | [protected]
m_currentPosition | TextAnalysis | [protected]
m_currentRunIndex | TextAnalysis | [protected]
m_glyphOrientationMode | TextAnalysis | [protected]
m_localeName | TextAnalysis | [protected]
m_numberSubstitution | TextAnalysis | [protected]
m_readingDirection | TextAnalysis | [protected]
m_runs | TextAnalysis | [protected]
m_text | TextAnalysis | [protected]
m_textLength | TextAnalysis | [protected]
QueryInterface(IID const &iid, OUT void **ppObject) | ComBase< QiList< IDWriteTextAnalysisSource1, QiList< IDWriteTextAnalysisSink1, QiList< IUnknown > > > > | [inline]
QueryInterfaceInternal(IID const &iid, OUT void **ppObject) | QiList< IDWriteTextAnalysisSource1, QiList< IDWriteTextAnalysisSink1, QiList< IUnknown > > > | [inline]
refValue_ | ComBase< QiList< IDWriteTextAnalysisSource1, QiList< IDWriteTextAnalysisSink1, QiList< IUnknown > > > > | [protected]
SetBidiLevel(UINT32 textPosition, UINT32 textLength, UINT8 explicitLevel, UINT8 resolvedLevel) | TextAnalysis |
SetCurrentRun(UINT32 textPosition) | TextAnalysis | [protected]
SetGlyphOrientation(UINT32 textPosition, UINT32 textLength, DWRITE_GLYPH_ORIENTATION_ANGLE glyphOrientationAngle, UINT8 adjustedBidiLevel, BOOL isSideways, BOOL isRightToLeft) | TextAnalysis |
SetLineBreakpoints(UINT32 textPosition, UINT32 textLength, const DWRITE_LINE_BREAKPOINT *lineBreakpoints) | TextAnalysis |
SetNumberSubstitution(UINT32 textPosition, UINT32 textLength, IDWriteNumberSubstitution *numberSubstitution) | TextAnalysis |
SetScriptAnalysis(UINT32 textPosition, UINT32 textLength, DWRITE_SCRIPT_ANALYSIS const *scriptAnalysis) | TextAnalysis |
SplitCurrentRun(UINT32 splitPosition) | TextAnalysis | [protected]
TextAnalysis(const wchar_t *text, UINT32 textLength, const wchar_t *localeName, IDWriteNumberSubstitution *numberSubstitution, ReadingDirection readingDirection, GlyphOrientationMode glyphOrientationMode) | TextAnalysis |
~ComBase() | ComBase< QiList< IDWriteTextAnalysisSource1, QiList< IDWriteTextAnalysisSink1, QiList< IUnknown > > > > | [inline, virtual]
Generated on Sat Nov 23 2024 16:09:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

XAudio2SoundPlayer Member List

This is the complete list of members for XAudio2SoundPlayer, including all inherited members.
AddSound(_In_ WAVEFORMATEX *format, _In_ Platform::Array< byte >^data) | XAudio2SoundPlayer |
GetSoundCount() const | XAudio2SoundPlayer |
IsSoundPlaying(size_t index) const | XAudio2SoundPlayer |
m_audioEngine | XAudio2SoundPlayer | [private]
m_masteringVoice | XAudio2SoundPlayer | [private]
m_soundList | XAudio2SoundPlayer | [private]
PlaySound(size_t index) | XAudio2SoundPlayer |
Resume() | XAudio2SoundPlayer |
StopSound(size_t index) | XAudio2SoundPlayer |
Suspend() | XAudio2SoundPlayer |
XAudio2SoundPlayer(uint32 sampleRate) | XAudio2SoundPlayer |
~XAudio2SoundPlayer() | XAudio2SoundPlayer |
Generated on Sat Nov 23 2024 16:09:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: App package information/C++/common/suspensionmanager.h Source File

  • App package information
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/DDSTextureLoader.h Source File

  • Direct3D resource loading

DDSTextureLoader.h

Go to the documentation of this file.
00001 //--------------------------------------------------------------------------------------
00002 // File: DDSTextureLoader.h
00003 //
00004 // Function for loading a DDS texture and creating a Direct3D 11 runtime resource for it
00005 //
00006 // Note this function is 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
00018 #pragma once
00019
00020 void CreateDDSTextureFromMemory(
00021     _In_ ID3D11Device* d3dDevice,
00022     _In_reads_bytes_(ddsDataSize) const byte* ddsData,
00023     _In_ size_t ddsDataSize,
00024     _Out_opt_ ID3D11Resource** texture,
00025     _Out_opt_ ID3D11ShaderResourceView** textureView,
00026     _In_ size_t maxsize = 0
00027     );
Generated on Sat Nov 23 2024 16:08:11 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/MediaReader.cpp Source File

  • XAML DirectX 3D shooting game

MediaReader.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 "MediaReader.h"
00010 #include "DirectXSample.h"
00011
00012 using namespace Microsoft::WRL;
00013 using namespace Windows::Storage;
00014 using namespace Windows::Storage::Streams;
00015 using namespace Windows::Foundation;
00016 using namespace Windows::ApplicationModel;
00017
00018 MediaReader::MediaReader()
00019 {
00020     ZeroMemory(&m_waveFormat, sizeof(m_waveFormat));
00021     m_installedLocation = Package::Current->InstalledLocation;
00022     m_installedLocationPath = Platform::String::Concat(m_installedLocation->Path, "\\");
00023 }
00024
00025 WAVEFORMATEX *MediaReader::GetOutputWaveFormatEx()
00026 {
00027     return &m_waveFormat;
00028 }
00029
00030 Platform::Array<byte>^ MediaReader::LoadMedia(_In_ Platform::String^ filename)
00031 {
00032     DX::ThrowIfFailed(
00033         MFStartup(MF_VERSION)
00034         );
00035
00036     ComPtr<IMFSourceReader> reader;
00037     DX::ThrowIfFailed(
00038         MFCreateSourceReaderFromURL(
00039             Platform::String::Concat(m_installedLocationPath, filename)->Data(),
00040             nullptr,
00041             &reader
00042             )
00043         );
00044
00045     // Set the decoded output format as PCM.
00046     // XAudio2 on Windows can process PCM and ADPCM-encoded buffers.
00047     // When using MediaFoundation, this sample always decodes into PCM.
00048     Microsoft::WRL::ComPtr<IMFMediaType> mediaType;
00049     DX::ThrowIfFailed(
00050         MFCreateMediaType(&mediaType)
00051         );
00052
00053     DX::ThrowIfFailed(
00054         mediaType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Audio)
00055         );
00056
00057     DX::ThrowIfFailed(
00058         mediaType->SetGUID(MF_MT_SUBTYPE, MFAudioFormat_PCM)
00059         );
00060
00061     DX::ThrowIfFailed(
00062         reader->SetCurrentMediaType(static_cast<uint32>(MF_SOURCE_READER_FIRST_AUDIO_STREAM), 0, mediaType.Get())
00063         );
00064
00065     // Get the complete WAVEFORMAT from the Media Type.
00066     Microsoft::WRL::ComPtr<IMFMediaType> outputMediaType;
00067     DX::ThrowIfFailed(
00068         reader->GetCurrentMediaType(static_cast<uint32>(MF_SOURCE_READER_FIRST_AUDIO_STREAM), &outputMediaType)
00069         );
00070
00071     UINT32 size = 0;
00072     WAVEFORMATEX* waveFormat;
00073     DX::ThrowIfFailed(
00074         MFCreateWaveFormatExFromMFMediaType(outputMediaType.Get(), &waveFormat, &size)
00075         );
00076
00077     CopyMemory(&m_waveFormat, waveFormat, sizeof(m_waveFormat));
00078     CoTaskMemFree(waveFormat);
00079
00080     PROPVARIANT propVariant;
00081     DX::ThrowIfFailed(
00082         reader->GetPresentationAttribute(static_cast<uint32>(MF_SOURCE_READER_MEDIASOURCE), MF_PD_DURATION, &propVariant)
00083         );
00084     // 'duration' is in 100ns units; convert to seconds, and round up
00085     // to the nearest whole byte.
00086     LONGLONG duration = propVariant.uhVal.QuadPart;
00087     unsigned int maxStreamLengthInBytes =
00088         static_cast<unsigned int>(
00089             ((duration * static_cast<ULONGLONG>(m_waveFormat.nAvgBytesPerSec)) + 10000000) /
00090             10000000
00091             );
00092
00093     Platform::Array<byte>^ fileData = ref new Platform::Array<byte>(maxStreamLengthInBytes);
00094
00095     ComPtr<IMFSample> sample;
00096     ComPtr<IMFMediaBuffer> mediaBuffer;
00097     DWORD flags = 0;
00098
00099     int positionInData = 0;
00100     bool done = false;
00101     while (!done)
00102     {
00103         DX::ThrowIfFailed(
00104             reader->ReadSample(static_cast<uint32>(MF_SOURCE_READER_FIRST_AUDIO_STREAM), 0, nullptr, &flags, nullptr, &sample)
00105             );
00106
00107         if (sample != nullptr)
00108         {
00109             DX::ThrowIfFailed(
00110                 sample->ConvertToContiguousBuffer(&mediaBuffer)
00111                 );
00112
00113             BYTE *audioData = nullptr;
00114             DWORD sampleBufferLength = 0;
00115             DX::ThrowIfFailed(
00116                 mediaBuffer->Lock(&audioData, nullptr, &sampleBufferLength)
00117                 );
00118
00119             for (DWORD i = 0; i < sampleBufferLength; i++)
00120             {
00121                 fileData[positionInData++] = audioData[i];
00122             }
00123         }
00124         if (flags & MF_SOURCE_READERF_ENDOFSTREAM)
00125         {
00126             done = true;
00127         }
00128     }
00129
00130     return fileData;
00131 }
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Touch keyboard/C++/Launch.xaml.cpp Source File

  • Input Touch keyboard

Launch.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 // Launch.xaml.cpp
00013 // Implementation of the Launch class
00014 //
00015
00016 #include "pch.h"
00017 #include "Launch.xaml.h"
00018
00019 using namespace SDKSample::TouchKeyboard;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 Launch::Launch()
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 Launch::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 Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML two-dimensional transforms/C++/pch.cpp Source File

  • XAML two-dimensional transforms

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D printing images and effects/C++/DocSource.h Source File

  • Direct2D printing images and effects

DocSource.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 <windows.graphics.printing.h>
00010 #include <printpreview.h>
00011 #include <documentsource.h>
00012 #include "D2DPageRenderer.h"
00013
00014 class CDocumentSource : public Microsoft::WRL::RuntimeClass<Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::WinRtClassicComMix>,
00015                                                             IPrintDocumentPageSource,
00016                                                             IPrintPreviewPageCollection,
00017                                                             ABI::Windows::Graphics::Printing::IPrintDocumentSource>
00018 {
00019 private:
00020     InspectableClass(L"Windows.Graphics.Printing.IPrintDocumentSource", BaseTrust);
00021
00022 public:
00023     HRESULT RuntimeClassInitialize(
00024         _In_ IUnknown* pageRenderer
00025         )
00026     {
00027         HRESULT hr = (pageRenderer != nullptr) ? S_OK : E_INVALIDARG;
00028
00029         if (SUCCEEDED(hr))
00030         {
00031             m_paginateCalled = false;
00032             m_totalPages     = 1;
00033             m_height         = 0.f;
00034             m_width          = 0.f;
00035
00036             // Cast d2dRender back to PageRenderer object.
00037             m_renderer = reinterpret_cast<PageRenderer^>(pageRenderer);
00038         }
00039
00040         return hr;
00041     }
00042
00043     //
00044     // classic COM interface IDocumentPageSource methods
00045     //
00046     IFACEMETHODIMP
00047     GetPreviewPageCollection(
00048         _In_  IPrintDocumentPackageTarget*  docPackageTarget,
00049         _Out_ IPrintPreviewPageCollection** docPageCollection
00050         );
00051
00052     IFACEMETHODIMP
00053     MakeDocument(
00054         _In_ IInspectable*                  docOptions,
00055         _In_ IPrintDocumentPackageTarget*   docPackageTarget
00056         );
00057
00058     //
00059     // classic COM interface IPrintPreviewPageCollection methods
00060     //
00061     IFACEMETHODIMP
00062     Paginate(
00063         _In_   uint32           currentJobPage,
00064         _In_   IInspectable*    docOptions
00065         );
00066
00067     IFACEMETHODIMP
00068     MakePage(
00069         _In_ uint32 desiredJobPage,
00070         _In_ float  width,
00071         _In_ float  height
00072         );
00073
00074 private:
00075     float
00076     TransformedPageSize(
00077         _In_  float                         desiredWidth,
00078         _In_  float                         desiredHeight,
00079         _Out_ Windows::Foundation::Size*    previewSize
00080         );
00081
00082     uint32                                                  m_totalPages;
00083     bool                                                    m_paginateCalled;
00084     float                                                   m_height;
00085     float                                                   m_width;
00086     D2D1_RECT_F                                             m_imageableRect;
00087     PageRenderer^                                           m_renderer;
00088     Microsoft::WRL::ComPtr<IPrintPreviewDxgiPackageTarget>  m_dxgiPreviewTarget;
00089 };
Generated on Sat Nov 23 2024 16:08:07 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML AppBar control/C++/pch.h Source File

  • XAML AppBar control

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include "Sample-Utils\CppSamplesUtils.h"
00019 #include <ppltasks.h>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D tutorial/C++/Lesson4.Textures/BasicReaderWriter.h Source File

  • Direct3D tutorial
  • Lesson4.Textures

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     Platform::String^ m_locationPath;
00019
00020 internal:
00021     BasicReaderWriter();
00022     BasicReaderWriter(
00023         _In_ Windows::Storage::StorageFolder^ folder
00024         );
00025
00026     Platform::Array<byte>^ ReadData(
00027         _In_ Platform::String^ filename
00028         );
00029
00030     concurrency::task<Platform::Array<byte>^> ReadDataAsync(
00031         _In_ Platform::String^ filename
00032         );
00033
00034     uint32 WriteData(
00035         _In_ Platform::String^ filename,
00036         _In_ const Platform::Array<byte>^ fileData
00037         );
00038
00039     concurrency::task<void> WriteDataAsync(
00040         _In_ Platform::String^ filename,
00041         _In_ const Platform::Array<byte>^ fileData
00042         );
00043 };
Generated on Sat Nov 23 2024 16:08:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: PlayToReceiver/C++/common/suspensionmanager.h Source File

  • PlayToReceiver
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

InkRenderer Member List

This is the complete list of members for InkRenderer, including all inherited members.
__pad0__ | InkRenderer |
ConvertStrokeToGeometry(_In_ Windows::UI::Input::Inking::IInkStroke^stroke, _Outptr_result_maybenull_ ID2D1PathGeometry **geometry) | InkRenderer | [private]
CreateDeviceIndependentResources(Microsoft::WRL::ComPtr< ID2D1Factory1 > d2dFactory) | InkRenderer |
CreateDeviceResources(Microsoft::WRL::ComPtr< ID2D1DeviceContext > d2dContext) | InkRenderer |
CreateWindowSizeDependentResources(float dpi) | InkRenderer |
DeleteAllStrokes() | InkRenderer | [private]
DrawInk() | InkRenderer |
m_blackBrush | InkRenderer | [private]
m_currentStroke | InkRenderer | [private]
m_d2dContext | InkRenderer | [private]
m_d2dFactory | InkRenderer | [private]
m_dpi | InkRenderer | [private]
m_inkManager | InkRenderer | [private]
m_inkState | InkRenderer | [private]
m_pointerId | InkRenderer | [private]
m_strokes | InkRenderer | [private]
OnPointerMoved(_In_ Windows::UI::Xaml::Input::PointerRoutedEventArgs^args) | InkRenderer |
OnPointerPressed(_In_ Windows::UI::Xaml::Input::PointerRoutedEventArgs^args) | InkRenderer |
OnPointerReleased(_In_ Windows::UI::Xaml::Input::PointerRoutedEventArgs^args) | InkRenderer |
Reset() | InkRenderer |
StartSignature() | InkRenderer |
Generated on Sat Nov 23 2024 16:09:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D animated text/C++/DirectXBase.h Source File

  • Direct2D animated text

DirectXBase.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 "DirectXSample.h"
00011
00012 // Helper class that initializes DirectX APIs for both 2D and 3D rendering.
00013 // Some of the code in this class may be omitted if only 2D or only 3D rendering is being used.
00014 ref class DirectXBase abstract
00015 {
00016 internal:
00017     DirectXBase();
00018
00019     virtual void Initialize(Windows::UI::Core::CoreWindow^ window, float dpi);
00020     virtual void HandleDeviceLost();
00021     virtual void CreateDeviceIndependentResources();
00022     virtual void CreateDeviceResources();
00023     virtual void SetDpi(float dpi);
00024     virtual void UpdateForWindowSizeChange();
00025     virtual void CreateWindowSizeDependentResources();
00026     virtual void Render() = 0;
00027     virtual void Present();
00028     void ValidateDevice();
00029
00030 protected private:
00031     Platform::Agile<Windows::UI::Core::CoreWindow>  m_window;
00032
00033     // DirectWrite & Windows Imaging Component Objects.
00034     Microsoft::WRL::ComPtr<IDWriteFactory1>         m_dwriteFactory;
00035     Microsoft::WRL::ComPtr<IWICImagingFactory2>     m_wicFactory;
00036
00037     // DirectX Core Objects. Required for 2D and 3D.
00038     Microsoft::WRL::ComPtr<ID3D11Device1>           m_d3dDevice;
00039     Microsoft::WRL::ComPtr<ID3D11DeviceContext1>    m_d3dContext;
00040     Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00041     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00042
00043     // Direct2D Rendering Objects. Required for 2D.
00044     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00046     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00047     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmap;
00048
00049     // Direct3D Rendering Objects. Required for 3D.
00050     Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00051
00052     // Cached renderer properties.
00053     D3D_FEATURE_LEVEL                               m_featureLevel;
00054     Windows::Foundation::Size                       m_renderTargetSize;
00055     Windows::Foundation::Rect                       m_windowBounds;
00056     float                                           m_dpi;
00057     bool                                            m_windowSizeChangeInProgress;
00058 };
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C#,C++/MediaExtensions/Common/OpQueue.h Source File

  • Media extensions
  • C#,C++
  • MediaExtensions
  • Common

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 Sat Nov 23 2024 16:08:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Device enumeration/C++/MainPage.xaml.cpp Source File

  • Device enumeration

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:41 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/texconv/DirectXTexMisc.cpp Source File

  • Direct3D resource loading
  • texconv

DirectXTexMisc.cpp

Go to the documentation of this file.
00001 //-------------------------------------------------------------------------------------
00002 // DirectXTexMisc.cpp
00003 //
00004 // DirectX Texture Library - Misc image operations
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 #include "directxtexp.h"
00015
00016 namespace DirectX
00017 {
00018
00019 //-------------------------------------------------------------------------------------
00020 static HRESULT _ComputeMSE( _In_ const Image& image1, _In_ const Image& image2,
00021                             _Out_ float& mse, _Out_writes_opt_(4) float* mseV )
00022 {
00023     if ( !image1.pixels || !image2.pixels )
00024         return E_POINTER;
00025
00026     assert( image1.width == image2.width && image1.height == image2.height );
00027     assert( !IsCompressed( image1.format ) && !IsCompressed( image2.format )  );
00028
00029     const size_t width = image1.width;
00030
00031     ScopedAlignedArrayXMVECTOR scanline( reinterpret_cast<XMVECTOR*>( _aligned_malloc( (sizeof(XMVECTOR)*width)*2, 16 ) ) );
00032     if ( !scanline )
00033         return E_OUTOFMEMORY;
00034
00035     const uint8_t *pSrc1 = image1.pixels;
00036     const size_t rowPitch1 = image1.rowPitch;
00037
00038     const uint8_t *pSrc2 = image2.pixels;
00039     const size_t rowPitch2 = image2.rowPitch;
00040
00041     XMVECTOR acc = XMVectorZero();
00042
00043     for( size_t h = 0; h < image1.height; ++h )
00044     {
00045         XMVECTOR* ptr1 = scanline.get();
00046         if ( !_LoadScanline( ptr1, width, pSrc1, rowPitch1, image1.format ) )
00047             return E_FAIL;
00048
00049         XMVECTOR* ptr2 = scanline.get() + width;
00050         if ( !_LoadScanline( ptr2, width, pSrc2, rowPitch2, image2.format ) )
00051             return E_FAIL;
00052
00053         for( size_t i = 0; i < width; ++i, ++ptr1, ++ptr2 )
00054         {
00055             // sum[ (I1 - I2)^2 ]
00056             XMVECTOR v = XMVectorSubtract( *ptr1, *ptr2 );
00057             acc = XMVectorMultiplyAdd( v, v, acc );
00058         }
00059
00060         pSrc1 += rowPitch1;
00061         pSrc2 += rowPitch2;
00062     }
00063
00064     // MSE = sum[ (I1 - I2)^2 ] / w*h
00065     XMVECTOR d = XMVectorReplicate( float(image1.width * image1.height) );
00066     XMVECTOR v = XMVectorDivide( acc, d );
00067     if ( mseV )
00068     {
00069         XMStoreFloat4( reinterpret_cast<XMFLOAT4*>( mseV ), v );
00070         mse = mseV[0] + mseV[1] + mseV[2] + mseV[3];
00071     }
00072     else
00073     {
00074         XMFLOAT4 _mseV;
00075         XMStoreFloat4( &_mseV, v );
00076         mse = _mseV.x + _mseV.y + _mseV.z + _mseV.w;
00077     }
00078
00079     return S_OK;
00080 }
00081
00082
00083 //=====================================================================================
00084 // Entry points
00085 //=====================================================================================
00086
00087 //-------------------------------------------------------------------------------------
00088 // Copies a rectangle from one image into another
00089 //-------------------------------------------------------------------------------------
00090 _Use_decl_annotations_
00091 HRESULT CopyRectangle( const Image& srcImage, const Rect& srcRect, const Image& dstImage, DWORD filter, size_t xOffset, size_t yOffset )
00092 {
00093     if ( !srcImage.pixels || !dstImage.pixels )
00094         return E_POINTER;
00095
00096     if ( IsCompressed( srcImage.format ) || IsCompressed( dstImage.format ) )
00097         return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
00098
00099     // Validate rectangle/offset
00100     if ( !srcRect.w || !srcRect.h || ( (srcRect.x + srcRect.w) > srcImage.width ) || ( (srcRect.y + srcRect.h) > srcImage.height ) )
00101     {
00102         return E_INVALIDARG;
00103     }
00104
00105     if ( ( (xOffset + srcRect.w) > dstImage.width ) || ( (yOffset + srcRect.h) > dstImage.height ) )
00106     {
00107         return E_INVALIDARG;
00108     }
00109
00110     // Compute source bytes-per-pixel
00111     size_t sbpp = BitsPerPixel( srcImage.format );
00112     if ( !sbpp )
00113         return E_FAIL;
00114
00115     if ( sbpp < 8 )
00116     {
00117         // We don't support monochrome (DXGI_FORMAT_R1_UNORM)
00118         return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
00119     }
00120
00121     const uint8_t* pEndSrc = srcImage.pixels + srcImage.rowPitch*srcImage.height;
00122     const uint8_t* pEndDest = dstImage.pixels + dstImage.rowPitch*dstImage.height;
00123
00124     // Round to bytes
00125     sbpp = ( sbpp + 7 ) / 8;
00126
00127     const uint8_t* pSrc = srcImage.pixels + (srcRect.y * srcImage.rowPitch) + (srcRect.x * sbpp);
00128
00129     if ( srcImage.format == dstImage.format )
00130     {
00131         // Direct copy case (avoid intermediate conversions)
00132         uint8_t* pDest = dstImage.pixels + (yOffset * dstImage.rowPitch) + (xOffset * sbpp);
00133         const size_t copyW = srcRect.w * sbpp;
00134         for( size_t h=0; h < srcRect.h; ++h )
00135         {
00136             if ( ( (pSrc+copyW) > pEndSrc ) || (pDest > pEndDest) )
00137                 return E_FAIL;
00138
00139             memcpy_s( pDest, pEndDest - pDest, pSrc, copyW );
00140
00141             pSrc += srcImage.rowPitch;
00142             pDest += dstImage.rowPitch;
00143         }
00144
00145         return S_OK;
00146     }
00147
00148     // Compute destination bytes-per-pixel (not the same format as source)
00149     size_t dbpp = BitsPerPixel( dstImage.format );
00150     if ( !dbpp )
00151         return E_FAIL;
00152
00153     if ( dbpp < 8 )
00154     {
00155         // We don't support monochrome (DXGI_FORMAT_R1_UNORM)
00156         return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
00157     }
00158
00159     // Round to bytes
00160     dbpp = ( dbpp + 7 ) / 8;
00161
00162     uint8_t* pDest = dstImage.pixels + (yOffset * dstImage.rowPitch) + (xOffset * dbpp);
00163
00164     ScopedAlignedArrayXMVECTOR scanline( reinterpret_cast<XMVECTOR*>( _aligned_malloc( (sizeof(XMVECTOR)*srcRect.w), 16 ) ) );
00165     if ( !scanline )
00166         return E_OUTOFMEMORY;
00167
00168     const size_t copyS = srcRect.w * sbpp;
00169     const size_t copyD = srcRect.w * dbpp;
00170
00171     for( size_t h=0; h < srcRect.h; ++h )
00172     {
00173         if ( ( (pSrc+copyS) > pEndSrc) || ((pDest+copyD) > pEndDest) )
00174             return E_FAIL;
00175
00176         if ( !_LoadScanline( scanline.get(), srcRect.w, pSrc, copyS, srcImage.format ) )
00177             return E_FAIL;
00178
00179         _ConvertScanline( scanline.get(), srcRect.w, dstImage.format, srcImage.format, filter );
00180
00181         if ( !_StoreScanline( pDest, copyD, dstImage.format, scanline.get(), srcRect.w ) )
00182             return E_FAIL;
00183
00184         pSrc += srcImage.rowPitch;
00185         pDest += dstImage.rowPitch;
00186     }
00187
00188     return S_OK;
00189 }
00190
00191
00192 //-------------------------------------------------------------------------------------
00193 // Computes the Mean-Squared-Error (MSE) between two images
00194 //-------------------------------------------------------------------------------------
00195 _Use_decl_annotations_
00196 HRESULT ComputeMSE( const Image& image1, const Image& image2, float& mse, float* mseV  )
00197 {
00198     if ( !image1.pixels || !image2.pixels )
00199         return E_POINTER;
00200
00201     if ( image1.width != image2.width || image1.height != image2.height )
00202         return E_INVALIDARG;
00203
00204     if ( IsCompressed(image1.format) )
00205     {
00206         if ( IsCompressed(image2.format) )
00207         {
00208             // Case 1: both images are compressed, expand to RGBA32F
00209             ScratchImage temp1;
00210             HRESULT hr = Decompress( image1, DXGI_FORMAT_R32G32B32A32_FLOAT, temp1 );
00211             if ( FAILED(hr) )
00212                 return hr;
00213
00214             ScratchImage temp2;
00215             hr = Decompress(  image2, DXGI_FORMAT_R32G32B32A32_FLOAT, temp2 );
00216             if ( FAILED(hr) )
00217                 return hr;
00218
00219             const Image* img1 = temp1.GetImage(0,0,0);
00220             const Image* img2 = temp2.GetImage(0,0,0);
00221             if ( !img1 || !img2 )
00222                 return E_POINTER;
00223
00224             return _ComputeMSE( *img1, *img2, mse, mseV );
00225         }
00226         else
00227         {
00228             // Case 2: image1 is compressed, expand to RGBA32F
00229             ScratchImage temp;
00230             HRESULT hr = Decompress( image1, DXGI_FORMAT_R32G32B32A32_FLOAT, temp );
00231             if ( FAILED(hr) )
00232                 return hr;
00233
00234             const Image* img = temp.GetImage(0,0,0);
00235             if ( !img )
00236                 return E_POINTER;
00237
00238             return _ComputeMSE( *img, image2, mse, mseV );
00239         }
00240     }
00241     else
00242     {
00243         if ( IsCompressed(image2.format) )
00244         {
00245             // Case 3: image2 is compressed, expand to RGBA32F
00246             ScratchImage temp;
00247             HRESULT hr = Decompress( image2, DXGI_FORMAT_R32G32B32A32_FLOAT, temp );
00248             if ( FAILED(hr) )
00249                 return hr;
00250
00251             const Image* img = temp.GetImage(0,0,0);
00252             if ( !img )
00253                 return E_POINTER;
00254
00255             return _ComputeMSE( image1, *img, mse, mseV );
00256         }
00257         else
00258         {
00259             // Case 4: neither image is compressed
00260             return _ComputeMSE( image1, image2, mse, mseV );
00261         }
00262     }
00263 }
00264
00265 }; // namespace
Generated on Sat Nov 23 2024 16:08:12 for Win8-Examples by doxygen 1.7.1


Win8-Examples: StreamSocket/C++/Scenario4.xaml.h Source File

  • StreamSocket

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
00022 namespace StreamSocketSample
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 Scenario4 sealed
00029     {
00030     public:
00031         Scenario4();
00032
00033     protected:
00034         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00035     private:
00036         MainPage^ rootPage;
00037         void CloseSockets_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038     };
00039 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Print/C++/ScenarioInput2.xaml.cpp Source File

  • Print

ScenarioInput2.xaml.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 //
00009 // Scenario2Input.xaml.cpp
00010 // Implementation of the Scenario2Input class.
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioInput2.xaml.h"
00015 #include "ScenarioOutput2.xaml.h"
00016 #include "MainPage.xaml.h"
00017
00018 using namespace PrintSample;
00019
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Graphics::Display;
00023 using namespace Windows::Graphics::Printing;
00024 using namespace Windows::UI;
00025 using namespace Windows::UI::Text;
00026 using namespace Windows::UI::Xaml::Controls;
00027 using namespace Windows::UI::Xaml::Documents;
00028 using namespace Windows::UI::Xaml::Media;
00029 using namespace Windows::UI::Xaml::Media::Imaging;
00030 using namespace Windows::UI::Xaml::Navigation;
00031
00032 ScenarioInput2::ScenarioInput2()
00033 {
00034     InitializeComponent();
00035 }
00036
00037 /// <summary>
00038 /// button click handlers
00039 /// </summary>
00040 void ScenarioInput2::InvokePrintButtonClick(Object^ sender, RoutedEventArgs^ e)
00041 {
00042     // Don't act when in snapped mode
00043     if (ApplicationView::Value != ApplicationViewState::Snapped)
00044     {
00045         Windows::Graphics::Printing::PrintManager::ShowPrintUIAsync();
00046     }
00047 }
00048
00049 /// <summary>
00050 /// Provide print content for scenario 2 first page
00051 /// </summary>
00052 void ScenarioInput2::PreparetPrintContent()
00053 {
00054     if (FirstPage == nullptr)
00055     {
00056         FirstPage = ref new ScenarioOutput2();
00057         StackPanel^ header = safe_cast<StackPanel^>(FirstPage->FindName("header"));
00058         header->Visibility = Windows::UI::Xaml::Visibility::Visible;
00059     }
00060
00061     // Add the (newley created) page to the printing root which is part of the visual tree and force it to go
00062     // through layout so that the linked containers correctly distribute the content inside them.
00063     PrintingRoot->Children->Append(FirstPage);
00064     PrintingRoot->InvalidateMeasure();
00065     PrintingRoot->UpdateLayout();
00066 }
00067
00068 void ScenarioInput2::OnNavigatedTo(NavigationEventArgs^ e)
00069 {
00070     BasePrintPage::OnNavigatedTo(e);
00071
00072     RegisterForPrinting();
00073 }
00074
00075 void ScenarioInput2::OnNavigatedFrom(NavigationEventArgs^ e)
00076 {
00077     UnregisterForPrinting() ;
00078 }
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Accelerometer sensor/C++/Scenario1.xaml.h Source File

  • Accelerometer sensor

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 SDKSample
00023 {
00024     namespace AccelerometerCPP
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 Scenario1 sealed
00031         {
00032         public:
00033             Scenario1();
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             MainPage^ rootPage;
00041             Windows::Devices::Sensors::Accelerometer^ accelerometer;
00042             Windows::Foundation::EventRegistrationToken visibilityToken;
00043             Windows::Foundation::EventRegistrationToken readingToken;
00044             uint32 desiredReportInterval;
00045
00046             void VisibilityChanged(Platform::Object^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ e);
00047             void ReadingChanged(Windows::Devices::Sensors::Accelerometer^ sender, Windows::Devices::Sensors::AccelerometerReadingChangedEventArgs^ 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     }
00052 }
Generated on Sat Nov 23 2024 16:07:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/ScenarioInput3.xaml.cpp Source File

  • Media extensions

ScenarioInput3.xaml.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 //
00009 // Scenario3Input.xaml.cpp
00010 // Implementation of the Scenario3Input class.
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioInput3.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace MediaExtensionsCPP;
00018
00019 using namespace Platform;
00020 using namespace Platform::Collections;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Foundation::Collections;
00023 using namespace Windows::Graphics::Display;
00024 using namespace Windows::UI::ViewManagement;
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 ScenarioInput3::ScenarioInput3()
00034 {
00035     InitializeComponent();
00036 }
00037
00038 ScenarioInput3::~ScenarioInput3()
00039 {
00040 }
00041
00042 #pragma region Template-Related Code - Do not remove
00043 void ScenarioInput3::OnNavigatedTo(NavigationEventArgs^ e)
00044 {
00045     // Get a pointer to our main page.
00046     rootPage = dynamic_cast<MainPage^>(e->Parameter);
00047
00048     // We want to be notified with the OutputFrame is loaded so we can get to the content.
00049     _frameLoadedToken = rootPage->OutputFrameLoaded += ref new Windows::Foundation::EventHandler<Platform::Object^>(this, &ScenarioInput3::rootPage_OutputFrameLoaded);
00050 }
00051
00052 void ScenarioInput3::OnNavigatedFrom(NavigationEventArgs^ e)
00053 {
00054     rootPage->OutputFrameLoaded -= _frameLoadedToken;
00055 }
00056
00057 #pragma endregion
00058
00059 #pragma region Event handlers
00060 void ScenarioInput3::rootPage_OutputFrameLoaded(Object^ sender, Object^ e)
00061 {
00062     // Get a pointer to the content within the OutputFrame.
00063     Page^ outputFrame = dynamic_cast<Page^>(rootPage->OutputFrame->Content);
00064
00065     // Go find the elements that we need for this scenario.
00066     outputVideo = dynamic_cast<MediaElement^>(outputFrame->FindName("Video"));
00067     outputVideoStabilized = dynamic_cast<MediaElement^>(outputFrame->FindName("VideoStabilized"));
00068 }
00069
00070 void ScenarioInput3::Open_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00071 {
00072     outputVideoStabilized->RemoveAllEffects();
00073     outputVideoStabilized->AddVideoEffect(Windows::Media::VideoEffects::VideoStabilization, true, nullptr);
00074
00075     auto v = ref new Vector<String^>();
00076     v->Append(".mp4");
00077     v->Append(".wmv");
00078     v->Append(".avi");
00079     auto me = ref new Vector<MediaElement^>();
00080     me->Append(outputVideo);
00081     me->Append(outputVideoStabilized);
00082     rootPage->PickSingleFileAndSet(v, me);
00083 }
00084
00085 void ScenarioInput3::Stop_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00086 {
00087     outputVideo->Source = nullptr;
00088     outputVideoStabilized->Source = nullptr;
00089 }
00090 #pragma endregion
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: App tiles and badges/C#,C++/Constants.cpp Source File

  • App tiles and badges
  • C#,C++

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 using namespace Windows::UI::ViewManagement;
00018
00019 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00020 {
00021     { "Send tile notification with text", "SDKSample.Tiles.SendTextTile" },
00022     { "Send tile notification with local images", "SDKSample.Tiles.SendLocalImageTile" },
00023     { "Send tile notification with web images", "SDKSample.Tiles.SendWebImageTile" },
00024     { "Send badge notification", "SDKSample.Tiles.SendBadge" },
00025     { "Enable notification queue and tags", "SDKSample.Tiles.EnableNotificationQueue" },
00026     { "Use notification expiration", "SDKSample.Tiles.NotificationExpiration" },
00027     { "Image protocols and baseUri", "SDKSample.Tiles.ImageProtocols" },
00028     { "Globalization, localization, scale, and accessibility", "SDKSample.Tiles.Globalization" }
00029 };
00030
00031 bool MainPage::EnsureUnsnapped()
00032 {
00033     // FilePicker APIs will not work if the application is in a snapped state. If an app wants to show a FilePicker while snapped,
00034     // it must attempt to unsnap first.
00035     return ((ApplicationView::Value != ApplicationViewState::Snapped) || ApplicationView::TryUnsnap());
00036 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Secondary tiles/C#,C++/pch.cpp Source File

  • Secondary tiles
  • C#,C++

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Animation metrics/C++/common/LayoutAwarePage.h Source File

  • Animation metrics
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Secondary tiles/C#,C++/Sample-Utils/cppsamplesutils.h Source File

  • Secondary tiles
  • C#,C++
  • Sample-Utils

cppsamplesutils.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 <string>
00014 #include <sstream>
00015 #include <algorithm>
00016 #include <collection.h>
00017 #include <ppltasks.h>
00018
00019 namespace CppSamplesUtils
00020 {
00021     namespace Details
00022     {
00023         static Windows::Foundation::Collections::PropertySet^ sessionState = nullptr;
00024         static Platform::String^ sessionStateFileName = ref new Platform::String(L"_cppSessionState.xml");
00025
00026         concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file);
00027         concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file);
00028     }
00029
00030     class SuspensionManager
00031     {
00032     public:
00033         static Windows::Foundation::Collections::PropertySet^ SessionState()
00034         {
00035             using namespace Windows::Foundation::Collections;
00036             using namespace Details;
00037
00038             if (sessionState == nullptr)
00039             {
00040                 sessionState = ref new PropertySet();
00041             }
00042             return sessionState;
00043         }
00044
00045         static concurrency::task<void> StartRestoreTask()
00046         {
00047             using namespace Windows::Foundation;
00048             using namespace Windows::Storage;
00049             using namespace Windows::Storage::Streams;
00050             using namespace Details;
00051
00052             auto state = SessionState();
00053             state->Clear();
00054
00055             concurrency::task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFileName));
00056             return getFileTask.then([=](StorageFile^ file)
00057             {
00058                 return DeserializeSessionState(file);
00059             });
00060         }
00061
00062         static concurrency::task<void> StartSaveTask()
00063         {
00064             using namespace Windows::Foundation;
00065             using namespace Windows::Storage;
00066             using namespace Windows::Storage::Streams;
00067             using namespace Details;
00068
00069             concurrency::task<StorageFile^> createFileTask(ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFileName, CreationCollisionOption::ReplaceExisting));
00070             return createFileTask.then([=](StorageFile^ file)
00071             {
00072                 return SerializeSessionState(file);
00073             });
00074         }
00075     };
00076
00077     namespace Details
00078     {
00079         template <class T>
00080         inline Platform::String^ ToString(T value)
00081         {
00082             std::wstringstream wss;
00083             wss << value;
00084             return ref new Platform::String(wss.str().c_str());
00085         }
00086
00087         template <class T>
00088         inline T FromStringTo(Platform::String^ str)
00089         {
00090             std::wistringstream wiss(str->Data());
00091             T value = 0;
00092             wiss >> value;
00093             return value;
00094         }
00095
00096         template <class T>
00097         inline T FromHexStringTo(Platform::String^ str)
00098         {
00099             std::wistringstream wiss(str->Data());
00100             T value = 0;
00101             wiss >> std::hex >> value;
00102             return value;
00103         }
00104
00105         template <>
00106         inline Platform::Guid FromStringTo<Platform::Guid>(Platform::String^ str)
00107         {
00108             using namespace Platform;
00109
00110             if (str->Length() != 38)
00111             {
00112                 throw ref new InvalidArgumentException;
00113             }
00114             std::wstring ws(str->Data());
00115             if (ws[0] != L'{' || ws[37] != L'}' || ws[9] != L'-' || ws[14] != L'-' || ws[19] != L'-' || ws[24] != L'-')
00116             {
00117                 throw ref new InvalidArgumentException;
00118             }
00119             ws[0] = ws[37] = ws[9] = ws[14] = ws[19] =ws[24] = L' ';
00120             std::wistringstream wiss(ws);
00121             unsigned int a = 0;
00122             unsigned short b = 0;
00123             unsigned short c = 0;
00124             unsigned short d = 0;
00125             unsigned long long e = 0;
00126             static_assert(sizeof(d) == sizeof(char) * 2, "sizeof(d) == sizeof(char) * 2");
00127             static_assert(sizeof(e) == sizeof(char) * 8, "sizeof(e) == sizeof(char) * 8");
00128             wiss >> std::hex >> a >> b >> c >> d >> e;
00129             unsigned char *ad = (unsigned char*)(&d);
00130             unsigned char *ae = (unsigned char*)(&e);
00131             return Platform::Guid(a, b, c, ad[1], ad[0], ae[5], ae[4], ae[3], ae[2], ae[1], ae[0]);
00132         }
00133
00134         inline Platform::Object^ ConvertStringToObject(Windows::Foundation::PropertyType type, Platform::String^ str)
00135         {
00136             using namespace Platform;
00137             using namespace Windows::Foundation;
00138
00139             if (type == PropertyType::String)
00140             {
00141                 return PropertyValue::CreateString(str);
00142             }
00143
00144             switch (type)
00145             {
00146             case PropertyType::UInt8:
00147                 return PropertyValue::CreateUInt8((unsigned char)FromStringTo<unsigned short>(str));
00148             case PropertyType::UInt16:
00149                 return PropertyValue::CreateUInt16(FromStringTo<unsigned short>(str));
00150             case PropertyType::UInt32:
00151                 return PropertyValue::CreateUInt32(FromStringTo<unsigned int>(str));
00152             case PropertyType::UInt64:
00153                 return PropertyValue::CreateUInt64(FromStringTo<unsigned long long>(str));
00154             case PropertyType::Int16:
00155                 return PropertyValue::CreateInt16(FromStringTo<short>(str));
00156             case PropertyType::Int32:
00157                 return PropertyValue::CreateInt32(FromStringTo<int>(str));
00158             case PropertyType::Int64:
00159                 return PropertyValue::CreateInt64(FromStringTo<long long>(str));
00160             case PropertyType::Single:
00161                 return PropertyValue::CreateSingle(FromStringTo<float>(str));
00162             case PropertyType::Double:
00163                 return PropertyValue::CreateDouble(FromStringTo<double>(str));
00164             case PropertyType::Boolean:
00165                 return PropertyValue::CreateBoolean(FromStringTo<bool>(str));
00166             case PropertyType::Char16:
00167                 return PropertyValue::CreateChar16(str->Data()[0]);
00168             case PropertyType::Guid:
00169                 return PropertyValue::CreateGuid(FromStringTo<Guid>(str));
00170             default:
00171                 throw ref new Platform::InvalidCastException;
00172             }
00173         }
00174
00175         inline Platform::String^ ConvertPropertyValueToString(Windows::Foundation::IPropertyValue^ pv)
00176         {
00177             using namespace Platform;
00178             using namespace Windows::Foundation;
00179
00180             String^ valueString;
00181
00182             switch (pv->Type)
00183             {
00184             case PropertyType::String:
00185                 valueString = pv->GetString();
00186                 break;
00187
00188             case PropertyType::UInt8:
00189             case PropertyType::UInt16:
00190             case PropertyType::UInt32:
00191             case PropertyType::UInt64:
00192                 valueString = ToString(pv->GetUInt64());
00193                 break;
00194
00195             case PropertyType::Int16:
00196             case PropertyType::Int32:
00197             case PropertyType::Int64:
00198                 valueString = ToString(pv->GetInt64());
00199                 break;
00200
00201             case PropertyType::Single:
00202                 valueString = ToString(pv->GetSingle());
00203                 break;
00204
00205             case PropertyType::Double:
00206                 valueString = ToString(pv->GetDouble());
00207                 break;
00208
00209             case PropertyType::Boolean:
00210                 valueString = ToString(pv->GetBoolean());
00211                 break;
00212
00213             case PropertyType::Char16:
00214                 wchar_t buffer[2];
00215                 buffer[0] = pv->GetChar16();
00216                 buffer[1] = 0;
00217                 valueString = ref new String(buffer);
00218                 break;
00219
00220             case PropertyType::Guid:
00221                 valueString = pv->GetGuid().ToString();
00222                 break;
00223
00224             default:
00225                 throw ref new InvalidCastException;
00226             }
00227
00228             return valueString;
00229         }
00230
00231         inline Windows::Data::Xml::Dom::XmlElement^ CreateXmlElementFromObject(Windows::Data::Xml::Dom::XmlDocument^ doc, Platform::String^ name, Platform::Object^ value)
00232         {
00233             using namespace Platform;
00234             using namespace Windows::Foundation;
00235             using namespace Windows::Data::Xml::Dom;
00236
00237             XmlElement^ element = doc->CreateElement("item");
00238             element->SetAttribute("name", name);
00239
00240             IPropertyValue^ pv = (IPropertyValue^)value;
00241             element->SetAttribute("type", ToString((int)pv->Type));
00242             element->SetAttribute("value", ConvertPropertyValueToString(pv));
00243
00244             return element;
00245         }
00246
00247         inline concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file)
00248         {
00249             using namespace Windows::Data::Xml::Dom;
00250             using namespace Windows::Foundation;
00251             namespace WFC = Windows::Foundation::Collections;
00252             typedef Windows::Foundation::Collections::IKeyValuePair<Platform::String^, Platform::Object^> KVPair;
00253
00254             XmlDocument^ doc = ref new XmlDocument;
00255             doc->AppendChild(doc->CreateElement("items"));
00256             auto sessionState = SuspensionManager::SessionState();
00257
00258             std::for_each(WFC::begin(sessionState), WFC::end(sessionState), [doc](KVPair^ item)
00259             {
00260                 doc->DocumentElement->AppendChild(CreateXmlElementFromObject(doc, item->Key, item->Value));
00261             });
00262
00263             return concurrency::task<void>(doc->SaveToFileAsync(file));
00264         }
00265
00266         inline Windows::Foundation::PropertyType PropertyTypeFromString(Platform::String^ str)
00267         {
00268             int value = FromStringTo<int>(str);
00269             return (Windows::Foundation::PropertyType)value;
00270         }
00271
00272         inline concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file)
00273         {
00274             using namespace Platform;
00275             using namespace Windows::Foundation;
00276             using namespace Windows::Data::Xml::Dom;
00277             namespace WFC = Windows::Foundation::Collections;
00278
00279             concurrency::task<XmlDocument^> loadFileTask(XmlDocument::LoadFromFileAsync(file));
00280             return loadFileTask.then([=](concurrency::task<XmlDocument^> docTask)
00281             {
00282                 try
00283                 {
00284                     auto doc = docTask.get();
00285                     auto items = doc->SelectNodes("/items/item");
00286                     auto sessionState = SuspensionManager::SessionState();
00287
00288                     std::for_each(WFC::begin(items), WFC::end(items), [sessionState](IXmlNode^ node)
00289                     {
00290                         auto element = (IXmlElement^)node;
00291                         String^ name = element->GetAttribute("name");
00292                         String^ value = element->GetAttribute("value");
00293                         PropertyType type = PropertyTypeFromString(element->GetAttribute("type"));
00294
00295                         Object^ valueObject = ConvertStringToObject(type, value);
00296                         sessionState->Insert(name, valueObject);
00297                     });
00298
00299                 }
00300                 catch (Platform::Exception^)
00301                 {
00302                     // Restoring is best effort
00303                 }
00304             });
00305         }
00306     } // namespace Details
00307 } // namespace CppSamplesUtils
Generated on Sat Nov 23 2024 16:07:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: EAS policies for mail clients/C++/Scenario1.xaml.cpp Source File

  • EAS policies for mail clients

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::EAS;
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::Security::ExchangeActiveSyncProvisioning;
00025
00026 Scenario1::Scenario1()
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 Scenario1::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 void SDKSample::EAS::Scenario1::Launch_Click1(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00044 {
00045   DeviceID ->Text= "";
00046   FriendlyName -> Text= "";
00047   SystemManufacturer ->Text= "";
00048   SystemProductName ->Text= "";
00049   SystemSku ->Text= "";
00050   OperatingSystem ->Text= "";
00051   try
00052   {
00053
00054     EasClientDeviceInformation^ CurrentDeviceInfor = ref new EasClientDeviceInformation();
00055
00056     auto id = CurrentDeviceInfor->Id;
00057     OperatingSystem->Text = CurrentDeviceInfor->OperatingSystem;
00058     FriendlyName->Text = CurrentDeviceInfor ->FriendlyName;
00059     SystemManufacturer->Text = CurrentDeviceInfor->SystemManufacturer;
00060     SystemProductName->Text = CurrentDeviceInfor->SystemProductName;
00061     SystemSku->Text = CurrentDeviceInfor->SystemSku;
00062
00063   }
00064   catch (Platform::Exception^ ex)
00065   {
00066     DebugArea->Text += "Error: " +ex->Message;
00067   }
00068
00069 }
00070
00071 void SDKSample::EAS::Scenario1::Reset_Click1(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00072 {
00073   try
00074   {
00075     DeviceID ->Text= "";
00076     FriendlyName -> Text= "";
00077     SystemManufacturer ->Text= "";
00078     SystemProductName ->Text= "";
00079     SystemSku ->Text= "";
00080     OperatingSystem ->Text= "";
00081   }
00082   catch(Platform::Exception^ ex)
00083   {
00084     DebugArea->Text += "Error: " +ex->Message;
00085   }
00086 }
Generated on Sat Nov 23 2024 16:07:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX touch input/C++/BasicLoader.h Source File

  • DirectX touch input

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 Sat Nov 23 2024 16:08:08 for Win8-Examples by doxygen 1.7.1


Win8-Examples: UI contrast and settings/C++/Accessibility.xaml.cpp Source File

  • UI contrast and settings

Accessibility.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 // Accessibility.xaml.cpp
00013 // Implementation of the Accessibility class
00014 //
00015
00016 #include "pch.h"
00017 #include "Accessibility.xaml.h"
00018
00019 using namespace SDKSample::HighContrast;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 using namespace Windows::UI::ViewManagement;
00026
00027 Accessibility::Accessibility()
00028 {
00029     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 void Accessibility::OnNavigatedTo(NavigationEventArgs^ e)
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     rootPage = MainPage::Current;
00042 }
00043
00044 void SDKSample::HighContrast::Accessibility::AccessibilityGetSettings_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00045 {
00046     Button^ b = safe_cast<Button^>(sender);
00047     if (b != nullptr)
00048     {
00049         AccessibilitySettings^ pAccessibilitySettings = ref new AccessibilitySettings();
00050         Platform::String^ Buffer;
00051
00052         Buffer = "High Contrast " + (pAccessibilitySettings->HighContrast ? "true" : "false") + "\n";
00053         Buffer += "High Contrast Scheme " + (pAccessibilitySettings->HighContrast ? pAccessibilitySettings->HighContrastScheme : "undefined") + "\n";
00054
00055         AccessibilityOutputTextBlock->Text = Buffer;
00056     }
00057 }
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Search contract/C++/Scenario7.xaml.cpp Source File

  • Search contract

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 SDKSample::SearchContract;
00020
00021 using namespace Windows::ApplicationModel::Search;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Navigation;
00025
00026 Scenario7::Scenario7()
00027 {
00028     InitializeComponent();
00029 }
00030
00031 void Scenario7::OnNavigatedTo(NavigationEventArgs^ e)
00032 {
00033     // Turn on type to search.
00034     SearchPane::GetForCurrentView()->ShowOnKeyboardInput = true;
00035 }
00036
00037 void Scenario7::OnNavigatedFrom(NavigationEventArgs^ e)
00038 {
00039     // Turn off type to search.
00040     SearchPane::GetForCurrentView()->ShowOnKeyboardInput = false;
00041 }
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Display orientation/C++/MainPage.xaml.h Source File

  • Display orientation

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:46 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D custom image effects/C++/PixelShader/SampleOverlay.cpp Source File

  • Direct2D custom image effects
  • PixelShader

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 Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::UI::ViewManagement;
00015 using namespace Windows::Graphics::Display;
00016 using namespace D2D1;
00017
00018 SampleOverlay::SampleOverlay() :
00019     m_drawOverlay(true)
00020 {
00021 }
00022
00023 void SampleOverlay::Initialize(
00024     _In_ ID2D1Device*         d2dDevice,
00025     _In_ ID2D1DeviceContext*  d2dContext,
00026     _In_ IWICImagingFactory*  wicFactory,
00027     _In_ IDWriteFactory*      dwriteFactory,
00028     _In_ Platform::String^    caption
00029     )
00030 {
00031     m_wicFactory = wicFactory;
00032     m_dwriteFactory = dwriteFactory;
00033     m_sampleName = caption;
00034     m_d2dDevice = d2dDevice;
00035     m_d2dContext = d2dContext;
00036     m_padding = 3.0f;
00037     m_textVerticalOffset = 5.0f;
00038     m_logoSize = D2D1::SizeF(0.0f, 0.0f);
00039     m_overlayWidth = 0.0f;
00040
00041     ComPtr<ID2D1Factory> factory;
00042     d2dDevice->GetFactory(&factory);
00043
00044     DX::ThrowIfFailed(
00045         factory.As(&m_d2dFactory)
00046         );
00047
00048     ResetDirectXResources();
00049 }
00050
00051 void SampleOverlay::ResetDirectXResources()
00052 {
00053     DX::ThrowIfFailed(
00054         m_d2dContext->CreateSolidColorBrush(ColorF(ColorF::White), &m_whiteBrush)
00055         );
00056
00057     ComPtr<IWICBitmapDecoder> wicBitmapDecoder;
00058     DX::ThrowIfFailed(
00059         m_wicFactory->CreateDecoderFromFilename(
00060             L"windowsbig-sdk.png",
00061             nullptr,
00062             GENERIC_READ,
00063             WICDecodeMetadataCacheOnDemand,
00064             &wicBitmapDecoder
00065             )
00066         );
00067
00068     ComPtr<IWICBitmapFrameDecode> wicBitmapFrame;
00069     DX::ThrowIfFailed(
00070         wicBitmapDecoder->GetFrame(0, &wicBitmapFrame)
00071         );
00072
00073     ComPtr<IWICFormatConverter> wicFormatConverter;
00074     DX::ThrowIfFailed(
00075         m_wicFactory->CreateFormatConverter(&wicFormatConverter)
00076         );
00077
00078     DX::ThrowIfFailed(
00079         wicFormatConverter->Initialize(
00080             wicBitmapFrame.Get(),
00081             GUID_WICPixelFormat32bppPBGRA,
00082             WICBitmapDitherTypeNone,
00083             nullptr,
00084             0.0,
00085             WICBitmapPaletteTypeCustom  // the BGRA format has no palette so this value is ignored
00086             )
00087         );
00088
00089     double dpiX = 96.0f;
00090     double dpiY = 96.0f;
00091     DX::ThrowIfFailed(
00092         wicFormatConverter->GetResolution(&dpiX, &dpiY)
00093         );
00094
00095     DX::ThrowIfFailed(
00096         m_d2dContext->CreateBitmapFromWicBitmap(
00097             wicFormatConverter.Get(),
00098             BitmapProperties(
00099                 PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00100                 static_cast<float>(dpiX),
00101                 static_cast<float>(dpiY)
00102                 ),
00103             &m_logoBitmap
00104             )
00105         );
00106
00107     m_logoSize = m_logoBitmap->GetSize();
00108
00109     ComPtr<IDWriteTextFormat> nameTextFormat;
00110     DX::ThrowIfFailed(
00111         m_dwriteFactory->CreateTextFormat(
00112             L"Segoe UI",
00113             nullptr,
00114             DWRITE_FONT_WEIGHT_LIGHT,
00115             DWRITE_FONT_STYLE_NORMAL,
00116             DWRITE_FONT_STRETCH_NORMAL,
00117             36.0f,
00118             L"en-US",
00119             &nameTextFormat
00120             )
00121         );
00122
00123     DX::ThrowIfFailed(
00124         nameTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)
00125         );
00126
00127     DX::ThrowIfFailed(
00128         nameTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)
00129         );
00130
00131     DX::ThrowIfFailed(
00132         m_dwriteFactory->CreateTextLayout(
00133             m_sampleName->Data(),
00134             m_sampleName->Length(),
00135             nameTextFormat.Get(),
00136             4096.0f,
00137             4096.0f,
00138             &m_textLayout
00139             )
00140         );
00141
00142     DWRITE_TEXT_METRICS metrics = {0};
00143     DX::ThrowIfFailed(
00144         m_textLayout->GetMetrics(&metrics)
00145         );
00146
00147     m_overlayWidth = m_padding * 3.0f + m_logoSize.width + metrics.width;
00148
00149     DX::ThrowIfFailed(
00150         m_d2dFactory->CreateDrawingStateBlock(&m_stateBlock)
00151         );
00152
00153     UpdateForWindowSizeChange();
00154 }
00155
00156 void SampleOverlay::UpdateForWindowSizeChange()
00157 {
00158     if (CoreWindow::GetForCurrentThread()->Bounds.Width < m_overlayWidth)
00159     {
00160         m_drawOverlay = false;
00161     }
00162     else
00163     {
00164         m_drawOverlay = true;
00165     }
00166 }
00167
00168 void SampleOverlay::Render()
00169 {
00170     if (m_drawOverlay)
00171     {
00172         m_d2dContext->SaveDrawingState(m_stateBlock.Get());
00173
00174         m_d2dContext->BeginDraw();
00175         m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00176         m_d2dContext->DrawBitmap(
00177             m_logoBitmap.Get(),
00178             D2D1::RectF(m_padding, 0.0f, m_logoSize.width + m_padding, m_logoSize.height)
00179             );
00180
00181         m_d2dContext->DrawTextLayout(
00182             Point2F(m_logoSize.width + 2.0f * m_padding, m_textVerticalOffset),
00183             m_textLayout.Get(),
00184             m_whiteBrush.Get()
00185             );
00186
00187         // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00188         // is lost. It will be handled during the next call to Present.
00189         HRESULT hr = m_d2dContext->EndDraw();
00190         if (hr != D2DERR_RECREATE_TARGET)
00191         {
00192             DX::ThrowIfFailed(hr);
00193         }
00194
00195         m_d2dContext->RestoreDrawingState(m_stateBlock.Get());
00196     }
00197 }
00198
00199 float SampleOverlay::GetTitleHeightInDips()
00200 {
00201     return m_logoSize.height;
00202 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D effects on primitives/C++/SampleOverlay.h Source File

  • Direct2D effects on primitives

SampleOverlay.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 "DirectXSample.h"
00011
00012 // This class is responsible for initializing and rendering the title overlay visible
00013 // at the top of the DirectX SDK samples.
00014 ref class SampleOverlay
00015 {
00016 internal:
00017     SampleOverlay();
00018
00019     void Initialize(
00020         _In_ ID2D1Device*         d2dDevice,
00021         _In_ ID2D1DeviceContext*  d2dContext,
00022         _In_ IWICImagingFactory*  wicFactory,
00023         _In_ IDWriteFactory*      dwriteFactory,
00024         _In_ Platform::String^    caption
00025         );
00026
00027     void ResetDirectXResources();
00028
00029     void UpdateForWindowSizeChange();
00030
00031     void Render();
00032
00033     float GetTitleHeightInDips();
00034
00035 private:
00036
00037     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00038     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00039     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00040     Microsoft::WRL::ComPtr<IDWriteFactory>          m_dwriteFactory;
00041     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_whiteBrush;
00042     Microsoft::WRL::ComPtr<ID2D1DrawingStateBlock>  m_stateBlock;
00043
00044     Microsoft::WRL::ComPtr<IWICImagingFactory>      m_wicFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Bitmap>             m_logoBitmap;
00046     Microsoft::WRL::ComPtr<IDWriteTextLayout>       m_textLayout;
00047
00048     UINT                                            m_idIncrement;
00049     bool                                            m_drawOverlay;
00050     Platform::String^                               m_sampleName;
00051     float                                           m_padding;
00052     float                                           m_textVerticalOffset;
00053     D2D1_SIZE_F                                     m_logoSize;
00054     float                                           m_overlayWidth;
00055 };
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::PlayToreceiver::sealed Member List

This is the complete list of members for SDKSample::PlayToreceiver::sealed, including all inherited members.
AudioVisual enum value | SDKSample::PlayToreceiver::sealed | [private]
btmapImage_ImageOpened(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::PlayToreceiver::sealed | [private]
bufferedPlaybackRate | SDKSample::PlayToreceiver::sealed | [private]
currentType | SDKSample::PlayToreceiver::sealed | [private]
dmrImage_ImageFailed_1(Platform::Object^sender, Windows::UI::Xaml::ExceptionRoutedEventArgs^e) | SDKSample::PlayToreceiver::sealed | [private]
dmrVideo_CurrentStateChanged(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::PlayToreceiver::sealed | [private]
dmrVideo_DownloadProgressChanged_1(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::PlayToreceiver::sealed | [private]
dmrVideo_MediaEnded(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::PlayToreceiver::sealed | [private]
dmrVideo_MediaFailed(Platform::Object^sender, Windows::UI::Xaml::ExceptionRoutedEventArgs^e) | SDKSample::PlayToreceiver::sealed | [private]
dmrVideo_MediaOpened(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::PlayToreceiver::sealed | [private]
dmrVideo_RateChanged(Platform::Object^sender, Windows::UI::Xaml::Media::RateChangedRoutedEventArgs^e) | SDKSample::PlayToreceiver::sealed | [private]
dmrVideo_SeekCompleted(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::PlayToreceiver::sealed | [private]
dmrVideo_VolumeChanged(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::PlayToreceiver::sealed | [private]
Image enum value | SDKSample::PlayToreceiver::sealed | [private]
imageRecd | SDKSample::PlayToreceiver::sealed | [private]
InitialisePlayToReceiver() | SDKSample::PlayToreceiver::sealed | [private]
IsMediaJustLoaded | SDKSample::PlayToreceiver::sealed | [private]
IsPlayReceivedPreMediaLoaded | SDKSample::PlayToreceiver::sealed | [private]
IsReceiverStarted | SDKSample::PlayToreceiver::sealed | [private]
IsSeeking | SDKSample::PlayToreceiver::sealed | [private]
MediaType enum name | SDKSample::PlayToreceiver::sealed | [private]
None enum value | SDKSample::PlayToreceiver::sealed | [private]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::PlayToreceiver::sealed | [protected, virtual]
receiver | SDKSample::PlayToreceiver::sealed | [private]
receiver_CurrentTimeChangeRequested(PlayToReceiver^, CurrentTimeChangeRequestedEventArgs^) | SDKSample::PlayToreceiver::sealed | [private]
receiver_MuteChangeRequested(PlayToReceiver^, MuteChangeRequestedEventArgs^) | SDKSample::PlayToreceiver::sealed | [private]
receiver_PauseRequested(PlayToReceiver^, Object^) | SDKSample::PlayToreceiver::sealed | [private]
receiver_PlaybackRateChangeRequested(PlayToReceiver^, PlaybackRateChangeRequestedEventArgs^) | SDKSample::PlayToreceiver::sealed | [private]
receiver_PlayRequested(PlayToReceiver^, Object^) | SDKSample::PlayToreceiver::sealed | [private]
receiver_SourceChangeRequested(PlayToReceiver^, SourceChangeRequestedEventArgs^) | SDKSample::PlayToreceiver::sealed | [private]
receiver_StopRequested(PlayToReceiver^, Object^) | SDKSample::PlayToreceiver::sealed | [private]
receiver_TimeUpdateRequested(PlayToReceiver^, Object^) | SDKSample::PlayToreceiver::sealed | [private]
receiver_VolumeChangeRequestedEvent(PlayToReceiver^, VolumeChangeRequestedEventArgs^) | SDKSample::PlayToreceiver::sealed | [private]
rootPage | SDKSample::PlayToreceiver::sealed | [private]
Scenario1() | SDKSample::PlayToreceiver::sealed |
startPlayToReceiver(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::PlayToreceiver::sealed | [private]
stopPlayToReceiver(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::PlayToreceiver::sealed | [private]
Generated on Sat Nov 23 2024 16:09:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Secondary tiles/C#,C++/common/LayoutAwarePage.h Source File

  • Secondary tiles
  • C#,C++
  • common

LayoutAwarePage.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 #include <collection.h>
00015
00016 namespace SecondaryTiles
00017 {
00018     namespace Common
00019     {
00020         /// <summary>
00021         /// Typical implementation of Page that provides several important conveniences: application
00022         /// view state to visual state mapping, GoBack and GoHome event handlers, and a default view
00023         /// model.
00024         /// </summary>
00025         [Windows::Foundation::Metadata::WebHostHidden]
00026         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00027         {
00028         internal:
00029             LayoutAwarePage();
00030
00031         public:
00032             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00033             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00034             void InvalidateVisualState();
00035             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00036             {
00037                 Windows::UI::Xaml::DependencyProperty^ get();
00038             };
00039             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Object^>^ DefaultViewModel
00040             {
00041                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Object^>^ get();
00042                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Object^>^ value);
00043             }
00044
00045         protected:
00046             virtual void GoHome(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             virtual void GoBack(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00049
00050         private:
00051             Platform::Collections::Map<Platform::String^, Object^>^ _defaultViewModel;
00052             Windows::Foundation::EventRegistrationToken _windowSizeEventToken;
00053             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00054             void WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00055         };
00056     }
00057 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: PlayToReceiver/C++/common/LayoutAwarePage.h Source File

  • PlayToReceiver
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Association launching/C++/App.xaml.h Source File

  • Association launching

App.xaml.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 //
00009 // App.xaml.h
00010 // Declaration of the App.xaml class.
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "App.g.h"
00017
00018 namespace AssociationLaunching
00019 {
00020     ref class App sealed
00021     {
00022     public:
00023         App();
00024
00025         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ args) override;
00026         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00027         virtual void App::OnFileActivated(Windows::ApplicationModel::Activation::FileActivatedEventArgs^ args) override;
00028         virtual void App::OnActivated(Windows::ApplicationModel::Activation::IActivatedEventArgs^ args) override;
00029
00030   private:
00031         ~App();
00032     };
00033 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Sharing content source app/C++/Constants.cpp Source File

  • Sharing content source app

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 using namespace Windows::UI::ViewManagement;
00018
00019 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00020 {
00021     { "Share text",                 "SDKSample.ShareSource.ShareText" },
00022     { "Share link",                 "SDKSample.ShareSource.ShareLink" },
00023     { "Share image",                "SDKSample.ShareSource.ShareImage" },
00024     { "Share files",                "SDKSample.ShareSource.ShareFiles" },
00025     { "Share delay rendered files", "SDKSample.ShareSource.ShareDelayRenderedFiles" },
00026     { "Share HTML content",         "SDKSample.ShareSource.ShareHtml" },
00027     { "Share custom data",          "SDKSample.ShareSource.ShareCustomData" },
00028     { "Fail with display text",     "SDKSample.ShareSource.SetErrorMessage" }
00029 };
00030
00031 bool MainPage::EnsureUnsnapped()
00032 {
00033     // FilePicker APIs will not work if the application is in a snapped state. If an app wants to show a FilePicker while snapped,
00034     // it must attempt to unsnap first.
00035     bool unsnapped = ((ApplicationView::Value != ApplicationViewState::Snapped) || ApplicationView::TryUnsnap());
00036     if (!unsnapped)
00037     {
00038         NotifyUser("Cannot unsnap the sample application", NotifyType::StatusMessage);
00039     }
00040
00041     return unsnapped;
00042 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Device capabilities/C++/pch.h Source File

  • Input Device capabilities

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Device enumeration/C++/common/LayoutAwarePage.h Source File

  • Device enumeration
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Touch hit testing/C++/pch.cpp Source File

  • Input Touch hit testing

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Extended Linguistic Services (ELS)/C++/Constants.cpp Source File

  • Extended Linguistic Services (ELS)
  • C++

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
00021     { "Language Detection", "SDKSample.ELS.LanguageDetection" },
00022     { "Script Detection", "SDKSample.ELS.ScriptDetection" },
00023     { "Transliteration", "SDKSample.ELS.Transliteration" }
00024 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Account picture name/C++/GetUserFirstAndLastName.xaml.h Source File

  • Account picture name

GetUserFirstAndLastName.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 // GetUserFirstAndLastName.xaml.h
00013 // Declaration of the GetUserFirstAndLastName class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "GetUserFirstAndLastName.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace AccountPictureName
00023 {
00024     [Windows::Foundation::Metadata::WebHostHidden]
00025     public ref class GetUserFirstAndLastName sealed
00026     {
00027     public:
00028         GetUserFirstAndLastName();
00029
00030     protected:
00031         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00032
00033     private:
00034         MainPage^ rootPage;
00035         void GetFirstNameButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00036         void GetLastNameButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00037     };
00038 }
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML high contrast style/C++/TargetButton.xaml.h Source File

  • XAML high contrast style

TargetButton.xaml.h

Go to the documentation of this file.
00001 ﻿//
00002 // TargetButton.xaml.h
00003 // Declaration of the TargetButton class
00004 //
00005
00006 #pragma once
00007
00008 #include "TargetButton.g.h"
00009
00010 namespace SDKSample
00011 {
00012   namespace HighContrast
00013   {
00014     /// <summary>
00015     /// An empty page that can be used on its own or navigated to within a Frame.
00016     /// </summary>
00017     [Windows::Foundation::Metadata::WebHostHiddenAttribute]
00018     public ref class TargetButton sealed
00019     {
00020     public:
00021       TargetButton();
00022
00023     protected:
00024       virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e);
00025       virtual void OnApplyTemplate() override;
00026     };
00027   }
00028 }
Generated on Sat Nov 23 2024 16:08:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/Level5.cpp Source File

  • XAML DirectX 3D shooting game

Level5.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 "Level5.h"
00010 #include "Cylinder.h"
00011 #include "Animate.h"
00012
00013 using namespace DirectX;
00014
00015 //----------------------------------------------------------------------
00016
00017 Level5::Level5()
00018 {
00019     m_timeLimit = 30.0f;
00020     m_objective = "Hit each of the moving targets while avoiding the obstacles before time runs out.";
00021 }
00022
00023 //----------------------------------------------------------------------
00024
00025 void Level5::Initialize(std::vector<GameObject^> objects)
00026 {
00027     Level3::Initialize(objects);
00028
00029     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     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     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.begin(); object != objects.end(); object++)
00056     {
00057         if (Cylinder^ obstacle = dynamic_cast<Cylinder^>(*object))
00058         {
00059             if (obstacleCount < 5)
00060             {
00061                 obstacle->Active(true);
00062                 obstacle->Position(obstacleStartPosition[obstacleCount]);
00063                 obstacle->AnimatePosition(
00064                     ref new AnimateLinePosition(
00065                         obstacleStartPosition[obstacleCount],
00066                         obstacleEndPosition[obstacleCount],
00067                         10.0,
00068                         false
00069                         )
00070                     );
00071                 obstacle->AnimatePosition()->Start(obstacleStartTime[obstacleCount]);
00072                 obstacleCount ++;
00073             }
00074         }
00075     }
00076 }
00077
00078 //----------------------------------------------------------------------
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D post-processing effects/C++/DirectXSample.h Source File

  • Direct3D post-processing effects

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
00010 // This header defines helper utilities to make DirectX APIs work with exceptions.
00011 namespace DX
00012 {
00013     inline void ThrowIfFailed(HRESULT hr)
00014     {
00015         if (FAILED(hr))
00016         {
00017             // Set a breakpoint on this line to catch DX API errors.
00018             throw Platform::Exception::CreateException(hr);
00019         }
00020     }
00021 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playback Manager Companion/C++/StreamTypeOther.xaml.h Source File

  • Playback Manager Companion

StreamTypeOther.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 // StreamTypeOther.xaml.h
00013 // Declaration of the StreamTypeOther class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "StreamTypeOther.g.h"
00020 #include "MainPage.xaml.h"
00021 #include "PlaybackControl.xaml.h"
00022
00023 namespace SDKSample
00024 {
00025     namespace PlaybackManager2
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 StreamTypeOther sealed
00032         {
00033         public:
00034             StreamTypeOther();
00035
00036         protected:
00037             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00038         private:
00039             MainPage^ rootPage;
00040             void Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         };
00042     }
00043 }
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Audio Session (WASAPI)/C++/ToneSampleGenerator.h Source File

  • Windows Audio Session (WASAPI)
  • C++

ToneSampleGenerator.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 // ToneSampleGenerator.h
00013 //
00014
00015 #pragma once
00016
00017 #define _USE_MATH_DEFINES
00018 #include <math.h>
00019 #include <limits.h>
00020 #include "MainPage.xaml.h"
00021
00022 template<typename T> T Convert(double Value);
00023
00024 namespace SDKSample
00025 {
00026     namespace WASAPIAudio
00027     {
00028         class ToneSampleGenerator
00029         {
00030         public:
00031             ToneSampleGenerator();
00032             ~ToneSampleGenerator();
00033
00034             Platform::Boolean IsEOF(){ return (m_SampleQueue == nullptr); };
00035             UINT32 GetBufferLength(){ return ( m_SampleQueue != nullptr ? m_SampleQueue->BufferSize : 0 ); };
00036             void Flush();
00037
00038             HRESULT GenerateSampleBuffer( DWORD Frequency, UINT32 FramesPerPeriod, WAVEFORMATEX *wfx );
00039             HRESULT FillSampleBuffer( UINT32 BytesToRead, BYTE *Data );
00040
00041         private:
00042             template <typename T>
00043                 void GenerateSineSamples(BYTE *Buffer, size_t BufferLength, DWORD Frequency, WORD ChannelCount, DWORD SamplesPerSecond, double Amplitude, double *InitialTheta);
00044
00045         private:
00046             RenderBuffer    *m_SampleQueue;
00047             RenderBuffer    **m_SampleQueueTail;
00048         };
00049     }
00050 }
00051
Generated on Sat Nov 23 2024 16:08:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Trial app and in-app purchase/C++/pch.cpp Source File

  • Trial app and in-app purchase

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Display orientation/C++/common/LayoutAwarePage.cpp Source File

  • Display orientation
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:31 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML personality animations/C++/Scenario1.xaml.h Source File

  • XAML personality animations

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 SDKSample
00023 {
00024   namespace PersonalityAnimations
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::WebHostHiddenAttribute]
00030     public ref class Scenario1 sealed
00031     {
00032     public:
00033       Scenario1();
00034
00035     protected:
00036       virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037       void PopInClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038       void PopOutClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039     private:
00040       MainPage^ rootPage;
00041     };
00042   }
00043 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Manipulations and gestures (C++)/C++/DirectXSample.h Source File

  • Input Manipulations and gestures (C++)
  • C++

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
00010 // This header defines helper utilities to make DirectX APIs work with exceptions.
00011 namespace DX
00012 {
00013     inline void ThrowIfFailed(HRESULT hr)
00014     {
00015         if (FAILED(hr))
00016         {
00017             // Set a breakpoint on this line to catch DX API errors.
00018             throw Platform::Exception::CreateException(hr);
00019         }
00020     }
00021 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Accelerometer sensor/C++/Constants.h Source File

  • Accelerometer sensor

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"Accelerometer Sensor Raw Data");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044
00045
00046 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Sharing content source app/C++/MainPage.xaml.h Source File

  • Sharing content source app

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

WaveEffect Member List

This is the complete list of members for WaveEffect, including all inherited members.
Clamp(float v, float low, float high) | WaveEffect | [inline, private, static]
CreateWaveImpl(_Outptr_ IUnknown **ppEffectImpl) | WaveEffect | [static]
GenerateMesh(_Outptr_ Vertex **ppMesh) | WaveEffect | [private]
GetSkewX() const | WaveEffect |
GetSkewY() const | WaveEffect |
GetWaveOffset() const | WaveEffect |
IFACEMETHODIMP_(UINT32) GetInputCount() const | WaveEffect | [inline]
IFACEMETHODIMP_(ULONG) AddRef() | WaveEffect |
IFACEMETHODIMP_(ULONG) Release() | WaveEffect |
Initialize(_In_ ID2D1EffectContext *pEffectContext, _In_ ID2D1TransformGraph *pTransformGraph) | WaveEffect |
m_constants | WaveEffect | [private]
m_drawInfo | WaveEffect | [private]
m_inputRect | WaveEffect | [private]
m_numVertices | WaveEffect | [private]
m_refCount | WaveEffect | [private]
m_sizeX | WaveEffect | [private]
m_sizeY | WaveEffect | [private]
m_skewX | WaveEffect | [private]
m_skewY | WaveEffect | [private]
m_vertexBuffer | WaveEffect | [private]
m_waveOffset | WaveEffect | [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) | WaveEffect |
MapInvalidRect(UINT32 inputIndex, D2D1_RECT_L invalidInputRect, _Out_ D2D1_RECT_L *pInvalidOutputRect) const | WaveEffect |
MapOutputRectToInputRects(_In_ const D2D1_RECT_L *pOutputRect, _Out_writes_(inputRectCount) D2D1_RECT_L *pInputRects, UINT32 inputRectCount) const | WaveEffect |
matrix | WaveEffect |
PrepareForRender(D2D1_CHANGE_TYPE changeType) | WaveEffect |
QueryInterface(_In_ REFIID riid, _Outptr_ void **ppOutput) | WaveEffect |
Register(_In_ ID2D1Factory1 *pFactory) | WaveEffect | [static]
SetDrawInfo(_In_ ID2D1DrawInfo *pDrawInfo) | WaveEffect |
SetGraph(_In_ ID2D1TransformGraph *pTransformGraph) | WaveEffect | [inline]
SetSkewX(float skew) | WaveEffect |
SetSkewY(float skew) | WaveEffect |
SetWaveOffset(float waveOffset) | WaveEffect |
sizeX | WaveEffect |
sizeY | WaveEffect |
skewX | WaveEffect |
skewY | WaveEffect |
UpdateConstants() | WaveEffect | [private]
WaveEffect() | WaveEffect | [private]
waveOffset | WaveEffect |
Generated on Sat Nov 23 2024 16:09:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D animation/C++/DirectXBase.h Source File

  • Direct2D animation

DirectXBase.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 "DirectXSample.h"
00011
00012 // Helper class that initializes DirectX APIs for both 2D and 3D rendering.
00013 // Some of the code in this class may be omitted if only 2D or only 3D rendering is being used.
00014 ref class DirectXBase abstract
00015 {
00016 internal:
00017     DirectXBase();
00018
00019     virtual void Initialize(Windows::UI::Core::CoreWindow^ window, float dpi);
00020     virtual void HandleDeviceLost();
00021     virtual void CreateDeviceIndependentResources();
00022     virtual void CreateDeviceResources();
00023     virtual void SetDpi(float dpi);
00024     virtual void UpdateForWindowSizeChange();
00025     virtual void CreateWindowSizeDependentResources();
00026     virtual void Render() = 0;
00027     virtual void Present();
00028     void ValidateDevice();
00029
00030 protected private:
00031     Platform::Agile<Windows::UI::Core::CoreWindow>  m_window;
00032
00033     // DirectWrite & Windows Imaging Component Objects.
00034     Microsoft::WRL::ComPtr<IDWriteFactory1>         m_dwriteFactory;
00035     Microsoft::WRL::ComPtr<IWICImagingFactory2>     m_wicFactory;
00036
00037     // DirectX Core Objects. Required for 2D and 3D.
00038     Microsoft::WRL::ComPtr<ID3D11Device1>           m_d3dDevice;
00039     Microsoft::WRL::ComPtr<ID3D11DeviceContext1>    m_d3dContext;
00040     Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00041     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00042
00043     // Direct2D Rendering Objects. Required for 2D.
00044     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00046     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00047     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmap;
00048
00049     // Direct3D Rendering Objects. Required for 3D.
00050     Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00051
00052     // Cached renderer properties.
00053     D3D_FEATURE_LEVEL                               m_featureLevel;
00054     Windows::Foundation::Size                       m_renderTargetSize;
00055     Windows::Foundation::Rect                       m_windowBounds;
00056     float                                           m_dpi;
00057     bool                                            m_windowSizeChangeInProgress;
00058 };
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

TangentVertex Member List

This is the complete list of members for TangentVertex, including all inherited members.
pos | TangentVertex
tex | TangentVertex
uTan | TangentVertex
vTan | TangentVertex
Generated on Sat Nov 23 2024 16:09:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Syndication/C++/Scenario1.xaml.h Source File

  • Syndication

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 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Navigation;
00024 using namespace Windows::Web::Syndication;
00025 using namespace Platform;
00026
00027 namespace SDKSample
00028 {
00029     namespace Syndication
00030     {
00031         /// <summary>
00032         /// An empty page that can be used on its own or navigated to within a Frame.
00033         /// </summary>
00034       [Windows::Foundation::Metadata::WebHostHidden]
00035         public ref class Scenario1 sealed
00036         {
00037         public:
00038             Scenario1();
00039
00040         protected:
00041             virtual void OnNavigatedTo(NavigationEventArgs^ e) override;
00042         private:
00043             MainPage^ rootPage;
00044             SyndicationFeed^ currentFeed;
00045             unsigned int currentItemIndex;
00046
00047             void GetFeed_Click(Object^ sender, RoutedEventArgs^ e);
00048             void PreviousItem_Click(Object^ sender, RoutedEventArgs^ e);
00049             void NextItem_Click(Object^ sender, RoutedEventArgs^ e);
00050             void LinkField_Click(Object^ sender, RoutedEventArgs^ e);
00051             void DisplayFeed();
00052             void DisplayCurrentItem();
00053         };
00054     }
00055 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Calendar details and math/C++/CalendarEnumerationAndMath.xaml.h Source File

  • Calendar details and math

CalendarEnumerationAndMath.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 // CalendarEnumerationAndMath.xaml.h
00013 // Declaration of the CalendarEnumerationAndMath class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "CalendarEnumerationAndMath.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace CalendarSample
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 CalendarEnumerationAndMath sealed
00031         {
00032         public:
00033             CalendarEnumerationAndMath();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void Display_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:07:58 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Number formatting and parsing/C++/common/suspensionmanager.cpp Source File

  • Number formatting and parsing
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:37 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Real-time communication/C++/MainPage.xaml.h Source File

  • Real-time communication

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SimpleCommunication
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051   [Windows::Foundation::Metadata::WebHostHidden]
00052     public ref class MainPage sealed
00053     {
00054     public:
00055         MainPage();
00056
00057         property bool AutoSizeInputSectionWhenSnapped
00058         {
00059             bool get()
00060             {
00061                 return autoSizeInputSectionWhenSnapped;
00062             }
00063
00064             void set(bool value)
00065             {
00066                 autoSizeInputSectionWhenSnapped = value;
00067             }
00068         }
00069
00070         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00071
00072         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00073         void LoadScenario(Platform::String^ scenarioName);
00074         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00075         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00076
00077         void LockScenarioChange();
00078         void UnlockScenarioChange();
00079         void SetCurrentScenario(Platform::String^ scenario);
00080         bool NavigatingPrevented();
00081
00082     private:
00083         void SetFeatureName(Platform::String^ strFeature);
00084         void PopulateScenarios();
00085         void InvalidateSize();
00086         void InvalidateViewState();
00087         ~MainPage();
00088
00089         Platform::Collections::Vector<Object^>^ ScenarioList;
00090         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00091         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00092         bool autoSizeInputSectionWhenSnapped;
00093
00094         long volatile _navigationDisabled;
00095         Platform::String^ _currentScenario;
00096
00097         Windows::UI::Core::CoreDispatcher^ _dispatcher;
00098         Windows::Media::MediaExtensionManager^ _mediaExtensionMgr;
00099
00100     protected:
00101         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00102         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00103         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00104
00105     internal:
00106         static MainPage^ Current;
00107
00108     };
00109
00110 }
Generated on Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-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 Sat Nov 23 2024 16:09:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows account authorization/C++/MainPage.xaml.cpp Source File

  • Windows account authorization

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:44 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/ScenarioOutput2.xaml.cpp Source File

  • Media extensions

ScenarioOutput2.xaml.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 //
00009 // Scenario2Output.xaml.cpp
00010 // Implementation of the Scenario2Output class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioOutput2.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace MediaExtensionsCPP;
00018
00019 using namespace Platform;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Graphics::Display;
00023 using namespace Windows::UI::ViewManagement;
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 ScenarioOutput2::ScenarioOutput2()
00033 {
00034     InitializeComponent();
00035 }
00036
00037 ScenarioOutput2::~ScenarioOutput2()
00038 {
00039 }
00040
00041 #pragma region Template-Related Code - Do not remove
00042 void ScenarioOutput2::OnNavigatedTo(NavigationEventArgs^ e)
00043 {
00044     // Get a pointer to our main page.
00045     rootPage = dynamic_cast<MainPage^>(e->Parameter);
00046
00047     _mediaFailedToken = Video->MediaFailed += ref new ExceptionRoutedEventHandler(rootPage, &MediaExtensionsCPP::MainPage::VideoOnError);
00048 }
00049
00050 void ScenarioOutput2::OnNavigatedFrom(NavigationEventArgs^ e)
00051 {
00052     Video->MediaFailed -= _mediaFailedToken;
00053     Video->Source = nullptr;
00054 }
00055 #pragma endregion
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/ImageNavigationData.h Source File

  • Hilo C++
  • Hilo

ImageNavigationData.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
00009 namespace Hilo
00010 {
00011     interface class IPhoto;
00012
00013     // The ImageNavigationData class is a data record that is used for navigating between pages.
00014     class ImageNavigationData
00015     {
00016     public:
00017         ImageNavigationData(IPhoto^ photo);
00018         ImageNavigationData(Platform::String^ serializationString);
00019
00020         Platform::String^ GetFilePath() const;
00021         Windows::Foundation::DateTime GetFileDate() const;
00022         Platform::String^ GetDateQuery();
00023         Platform::String^ SerializeToString();
00024
00025     private:
00026         Windows::Foundation::DateTime m_fileDate;
00027         Platform::String^ m_dateQuery;
00028         Platform::String^ m_filePath;
00029     };
00030 }
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: App package information/C++/common/LayoutAwarePage.cpp Source File

  • App package information
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:30 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKTemplate::MainPage Member List

This is the complete list of members for SDKTemplate::MainPage, including all inherited members.
__pad0__ | Element |
AcceptChildNode(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^childXmlNode) override | Page | [virtual]
AddChild(_In_ Element^element) | Element |
AddSibling(_In_ Element^element) | Element |
AutoSizeInputSectionWhenSnapped | SDKTemplate::MainPage |
BindResource(_In_ Element^rootElement) | Element | [virtual]
CameraFound | SDKTemplate::MainPage |
Create(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^xmlNode) | Element | [static]
Current | SDKTemplate::MainPage | [static]
DefaultViewModel | SDKTemplate::Common::LayoutAwarePage | [protected]
DefaultViewModelProperty | SDKTemplate::Common::LayoutAwarePage | [static]
DetermineVisualState(ApplicationViewState viewState) | SDKTemplate::Common::LayoutAwarePage | [inline, protected, virtual]
DetermineVisualState(ApplicationViewState viewState) | SDKTemplate::Common::LayoutAwarePage | [inline, protected, virtual]
DeviceChecked | SDKTemplate::MainPage |
Draw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
EnsureMediaExtensionManager() | SDKTemplate::MainPage | [inline]
FEATURE_NAME | SDKTemplate::MainPage |
Footer_Click(object sender, RoutedEventArgs e) | SDKTemplate::MainPage | [inline, private]
Footer_Click(object sender, RoutedEventArgs e) | SDKTemplate::MainPage | [inline, private]
Footer_Click(object sender, RoutedEventArgs e) | SDKTemplate::MainPage | [inline, private]
Footer_Click(object sender, RoutedEventArgs e) | SDKTemplate::MainPage | [inline, private]
Footer_Click(object sender, RoutedEventArgs e) | SDKTemplate::MainPage | [inline, private]
GetFirstChild() | Element | [inline]
GetName() | Element | [inline]
GetNextSibling() | Element | [inline]
GetOpacity() | Element | [inline, virtual]
GetParent() | Element | [inline]
GetSize() | Element | [inline]
GoBack(object sender, RoutedEventArgs e) | SDKTemplate::Common::LayoutAwarePage | [inline, protected, virtual]
GoBack(object sender, RoutedEventArgs e) | SDKTemplate::Common::LayoutAwarePage | [inline, protected, virtual]
GoHome(object sender, RoutedEventArgs e) | SDKTemplate::Common::LayoutAwarePage | [inline, protected, virtual]
GoHome(object sender, RoutedEventArgs e) | SDKTemplate::Common::LayoutAwarePage | [inline, protected, virtual]
HiddenFrame | SDKTemplate::MainPage | [private]
Initialize(_In_ Document^document, _In_ Windows::Data::Xml::Dom::XmlElement^xmlElement) | Element | [virtual]
InvalidateSize() | SDKTemplate::MainPage | [inline, private]
InvalidateSize() | SDKTemplate::MainPage | [inline, private]
InvalidateSize() | SDKTemplate::MainPage | [inline, private]
InvalidateSize() | SDKTemplate::MainPage | [inline, private]
InvalidateSize() | SDKTemplate::MainPage | [inline, private]
InvalidateViewState() | SDKTemplate::MainPage | [inline, private]
InvalidateViewState() | SDKTemplate::MainPage | [inline, private]
InvalidateViewState() | SDKTemplate::MainPage | [inline, private]
InvalidateViewState() | SDKTemplate::MainPage | [inline, private]
InvalidateViewState() | SDKTemplate::MainPage | [inline, private]
InvalidateVisualState() | SDKTemplate::Common::LayoutAwarePage | [inline]
InvalidateVisualState() | SDKTemplate::Common::LayoutAwarePage | [inline]
LaunchArgs | SDKTemplate::MainPage |
LayoutAwarePage() | SDKTemplate::Common::LayoutAwarePage | [inline]
LayoutAwarePage() | SDKTemplate::Common::LayoutAwarePage | [inline]
LoadScenario(Type scenarioClass) | SDKTemplate::MainPage | [inline]
LoadScenario(Type scenarioClass) | SDKTemplate::MainPage | [inline]
LoadScenario(Type scenarioClass) | SDKTemplate::MainPage | [inline]
LoadScenario(Type scenarioClass) | SDKTemplate::MainPage | [inline]
MainPage() | SDKTemplate::MainPage | [inline]
MainPage() | SDKTemplate::MainPage | [inline]
MainPage() | SDKTemplate::MainPage | [inline]
MainPage() | SDKTemplate::MainPage | [inline]
MainPage() | SDKTemplate::MainPage | [inline]
MainPage_SizeChanged(object sender, SizeChangedEventArgs e) | SDKTemplate::MainPage | [inline, private]
MainPage_SizeChanged(object sender, SizeChangedEventArgs e) | SDKTemplate::MainPage | [inline, private]
MainPage_SizeChanged(object sender, SizeChangedEventArgs e) | SDKTemplate::MainPage | [inline, private]
MainPage_SizeChanged(object sender, SizeChangedEventArgs e) | SDKTemplate::MainPage | [inline, private]
MainPage_SizeChanged(object sender, SizeChangedEventArgs e) | SDKTemplate::MainPage | [inline, private]
MainPageResized | SDKTemplate::MainPage |
Measure(_In_ Document^document, D2D1_SIZE_F const &parentSize, _Out_ D2D1_RECT_F *bounds) | Element | [virtual]
mediaExtensionMgr | SDKTemplate::MainPage | [private]
NotifyUser(string strMessage, NotifyType type) | SDKTemplate::MainPage | [inline]
NotifyUser(string strMessage, NotifyType type) | SDKTemplate::MainPage | [inline]
NotifyUser(string strMessage, NotifyType type) | SDKTemplate::MainPage | [inline]
NotifyUser(string strMessage, NotifyType type) | SDKTemplate::MainPage | [inline]
OnNavigatedTo(NavigationEventArgs e) | SDKTemplate::MainPage | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | SDKTemplate::MainPage | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | SDKTemplate::MainPage | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | SDKTemplate::MainPage | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | SDKTemplate::MainPage | [inline, protected]
PopulateScenarios() | SDKTemplate::MainPage | [inline, private]
PopulateScenarios() | SDKTemplate::MainPage | [inline, private]
PopulateScenarios() | SDKTemplate::MainPage | [inline, private]
PopulateScenarios() | SDKTemplate::MainPage | [inline, private]
PrepareToDraw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
ReleaseParent() | Element | [virtual]
ScenarioLoaded | SDKTemplate::MainPage |
scenarios | SDKTemplate::MainPage | [private]
Scenarios_SelectionChanged(object sender, SelectionChangedEventArgs e) | SDKTemplate::MainPage | [inline, private]
Scenarios_SelectionChanged(object sender, SelectionChangedEventArgs e) | SDKTemplate::MainPage | [inline, private]
Scenarios_SelectionChanged(object sender, SelectionChangedEventArgs e) | SDKTemplate::MainPage | [inline, private]
Scenarios_SelectionChanged(object sender, SelectionChangedEventArgs e) | SDKTemplate::MainPage | [inline, private]
SetFeatureName(string str) | SDKTemplate::MainPage | [inline, private]
SetFeatureName(string str) | SDKTemplate::MainPage | [inline, private]
SetFeatureName(string str) | SDKTemplate::MainPage | [inline, private]
SetFeatureName(string str) | SDKTemplate::MainPage | [inline, private]
SetFeatureName(string str) | SDKTemplate::MainPage | [inline, private]
StartLayoutUpdates(object sender, RoutedEventArgs e) | SDKTemplate::Common::LayoutAwarePage | [inline]
StartLayoutUpdates(object sender, RoutedEventArgs e) | SDKTemplate::Common::LayoutAwarePage | [inline]
StopLayoutUpdates(object sender, RoutedEventArgs e) | SDKTemplate::Common::LayoutAwarePage | [inline]
StopLayoutUpdates(object sender, RoutedEventArgs e) | SDKTemplate::Common::LayoutAwarePage | [inline]
Generated on Sat Nov 23 2024 16:09:53 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Bing Maps Trip Optimizer/C++,JavaScript/cpp/TripOptimizer.cpp Source File

  • Bing Maps Trip Optimizer
  • C++,JavaScript
  • cpp

TripOptimizer.cpp

Go to the documentation of this file.
00001 ﻿//-----------------------------------------------------------------------
00002 //
00003 //  Copyright (C) Microsoft Corporation.  All rights reserved.
00004 //
00005 //
00006 // THIS CODE AND INFORMATION ARE PROVIDED AS-IS WITHOUT WARRANTY OF ANY
00007 // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
00008 // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00009 // PARTICULAR PURPOSE.
00010 //-----------------------------------------------------------------------
00011 #include "pch.h"
00012 #include "TripOptimizer.h"
00013 #include "TripOptimizerImpl.h"
00014
00015 using namespace Windows::Foundation;
00016 using namespace Windows::Foundation::Collections;
00017 using namespace Platform;
00018 using namespace std;
00019 using namespace TripOptimizerComponent;
00020 using namespace TripOptimizerComponent::Details;
00021
00022 TripOptimizer::TripOptimizer()
00023     : m_impl(new TripOptimizerImpl())
00024 {
00025 }
00026
00027 TripOptimizer::~TripOptimizer()
00028 {
00029 }
00030
00031 // Optimizes a trip as an asynchronous process.
00032 IAsyncOperationWithProgress<IMap<String^, IVector<String^>^>^, String^>^
00033 TripOptimizer::OptimizeTripAsync(
00034     IVector<String^>^ waypoints,
00035     String^ travelMode,
00036     String^ optimize,
00037     String^ bingMapsKey,
00038     double alpha, double beta, double rho,
00039     unsigned int iterations, bool parallel)
00040 {
00041     // Forward to implementation.
00042     return m_impl->OptimizeTripAsync(waypoints,travelMode, optimize, bingMapsKey,
00043         alpha, beta, rho, iterations, parallel);
00044 }
Generated on Sat Nov 23 2024 16:07:58 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application data/C++/SetVersion.xaml.h Source File

  • Application data

SetVersion.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 // SetVersion.xaml.h
00013 // Declaration of the SetVersion class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "SetVersion.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace ApplicationDataSample
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 SetVersion sealed
00031         {
00032         public:
00033             SetVersion();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             Windows::Storage::ApplicationData^ appData;
00040
00041             void SetVersionHandler0(Windows::Storage::SetVersionRequest^ request);
00042             void SetVersionHandler1(Windows::Storage::SetVersionRequest^ request);
00043
00044             void SetVersion0_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00045             void SetVersion1_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00046
00047             void DisplayOutput();
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Triangle Member List

This is the complete list of members for Triangle, including all inherited members.
A | Triangle |
B | Triangle |
C | Triangle |
CheckSharesVertsOrCoplanar(FXMVECTOR V0, FXMVECTOR V1, FXMVECTOR V2, CXMVECTOR planeIn, BOOL &sharesEdgeOut, BOOL &coplanar) const | Triangle | [inline]
IsDegenerate() const | Triangle | [inline]
Normal() const | Triangle | [inline]
plane | Triangle |
Triangle(const Triangle &rhs) | Triangle | [inline]
Triangle(const XMFLOAT3 &V0, const XMFLOAT3 &V1, const XMFLOAT3 &V2) | Triangle | [inline]
Generated on Sat Nov 23 2024 16:09:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Audio Session (WASAPI)/C++/WASAPIRenderer.cpp Source File

  • Windows Audio Session (WASAPI)
  • C++

WASAPIRenderer.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 // wasapirenderer.h
00013 //
00014
00015 #include "pch.h"
00016 #include "WASAPIRenderer.h"
00017
00018 using namespace Windows::System::Threading;
00019 using namespace SDKSample::WASAPIAudio;
00020
00021 //
00022 //  WASAPIRenderer()
00023 //
00024 WASAPIRenderer::WASAPIRenderer() :
00025     m_BufferFrames( 0 ),
00026     m_DeviceStateChanged( nullptr ),
00027     m_AudioClient( nullptr ),
00028     m_AudioRenderClient( nullptr ),
00029     m_SampleReadyAsyncResult( nullptr ),
00030     m_ToneSource( nullptr ),
00031     m_MFSource( nullptr )
00032 {
00033     // Create events for sample ready or user stop
00034     m_SampleReadyEvent = CreateEventEx( nullptr, nullptr, 0, EVENT_ALL_ACCESS );
00035     if (nullptr == m_SampleReadyEvent)
00036     {
00037         ThrowIfFailed( HRESULT_FROM_WIN32( GetLastError() ) );
00038     }
00039
00040     if (!InitializeCriticalSectionEx( &m_CritSec, 0, 0 ))
00041     {
00042         ThrowIfFailed( HRESULT_FROM_WIN32( GetLastError() ) );
00043     }
00044
00045     m_DeviceStateChanged = ref new DeviceStateChangedEvent();
00046     if (nullptr == m_DeviceStateChanged)
00047     {
00048         ThrowIfFailed( E_OUTOFMEMORY );
00049     }
00050 }
00051
00052 //
00053 //  ~WASAPIRenderer()
00054 //
00055 WASAPIRenderer::~WASAPIRenderer()
00056 {
00057     SAFE_RELEASE( m_AudioClient );
00058     SAFE_RELEASE( m_AudioRenderClient );
00059     SAFE_RELEASE( m_SampleReadyAsyncResult );
00060     SAFE_RELEASE( m_MFSource );
00061     SAFE_DELETE( m_ToneSource );
00062     SAFE_DELETE( m_DeviceStateChanged );
00063
00064     if (INVALID_HANDLE_VALUE != m_SampleReadyEvent)
00065     {
00066         CloseHandle( m_SampleReadyEvent );
00067         m_SampleReadyEvent = INVALID_HANDLE_VALUE;
00068     }
00069
00070     DeleteCriticalSection( &m_CritSec );
00071 }
00072
00073 //
00074 //  InitializeAudioDeviceAsync()
00075 //
00076 //  Activates the default audio renderer on a asynchronous callback thread.  This needs
00077 //  to be called from the main UI thread.
00078 //
00079 HRESULT WASAPIRenderer::InitializeAudioDeviceAsync()
00080 {
00081     IActivateAudioInterfaceAsyncOperation *asyncOp;
00082     HRESULT hr = S_OK;
00083
00084     // Get a string representing the Default Audio Device Renderer
00085     m_DeviceIdString = MediaDevice::GetDefaultAudioRenderId( Windows::Media::Devices::AudioDeviceRole::Default );
00086
00087     // This call must be made on the main UI thread.  Async operation will call back to
00088     // IActivateAudioInterfaceCompletionHandler::ActivateCompleted, which must be an agile interface implementation
00089     hr = ActivateAudioInterfaceAsync( m_DeviceIdString->Data(), __uuidof(IAudioClient2), nullptr, this, &asyncOp );
00090     if (FAILED( hr ))
00091     {
00092         m_DeviceStateChanged->SetState( DeviceState::DeviceStateInError, hr, true );
00093     }
00094
00095     SAFE_RELEASE( asyncOp );
00096
00097     return hr;
00098 }
00099
00100 //
00101 //  ActivateCompleted()
00102 //
00103 //  Callback implementation of ActivateAudioInterfaceAsync function.  This will be called on MTA thread
00104 //  when results of the activation are available.
00105 //
00106 HRESULT WASAPIRenderer::ActivateCompleted( IActivateAudioInterfaceAsyncOperation *operation )
00107 {
00108     HRESULT hr = S_OK;
00109     HRESULT hrActivateResult = S_OK;
00110     IUnknown *punkAudioInterface = nullptr;
00111
00112     if (m_DeviceStateChanged->GetState() != DeviceState::DeviceStateUnInitialized)
00113     {
00114         hr = E_NOT_VALID_STATE;
00115         goto exit;
00116     }
00117
00118     // Check for a successful activation result
00119     hr = operation->GetActivateResult( &hrActivateResult, &punkAudioInterface );
00120     if (SUCCEEDED( hr ) && SUCCEEDED( hrActivateResult ))
00121     {
00122         m_DeviceStateChanged->SetState( DeviceState::DeviceStateActivated, S_OK, false );
00123
00124         // Get the pointer for the Audio Client
00125         punkAudioInterface->QueryInterface( IID_PPV_ARGS(&m_AudioClient) );
00126         if( nullptr == m_AudioClient )
00127         {
00128             hr = E_FAIL;
00129             goto exit;
00130         }
00131
00132         // Configure user defined properties
00133         hr = ConfigureDeviceInternal();
00134         if (FAILED( hr ))
00135         {
00136             goto exit;
00137         }
00138
00139         // Initialize the AudioClient in Shared Mode with the user specified buffer
00140         hr = m_AudioClient->Initialize( AUDCLNT_SHAREMODE_SHARED,
00141                                         AUDCLNT_STREAMFLAGS_EVENTCALLBACK | AUDCLNT_STREAMFLAGS_NOPERSIST,
00142                                         m_DeviceProps.hnsBufferDuration,
00143                                         m_DeviceProps.hnsBufferDuration,
00144                                         m_MixFormat,
00145                                         nullptr );
00146         if (FAILED( hr ))
00147         {
00148             goto exit;
00149         }
00150
00151         // Get the maximum size of the AudioClient Buffer
00152         hr = m_AudioClient->GetBufferSize( &m_BufferFrames );
00153         if (FAILED( hr ))
00154         {
00155             goto exit;
00156         }
00157
00158         // Get the render client
00159         hr = m_AudioClient->GetService( __uuidof(IAudioRenderClient), (void**) &m_AudioRenderClient );
00160         if (FAILED( hr ))
00161         {
00162             goto exit;
00163         }
00164
00165         // Create Async callback for sample events
00166         hr = MFCreateAsyncResult( nullptr, &m_xSampleReady, nullptr, &m_SampleReadyAsyncResult );
00167         if (FAILED( hr ))
00168         {
00169             goto exit;
00170         }
00171
00172         // Sets the event handle that the system signals when an audio buffer is ready to be processed by the client
00173         hr = m_AudioClient->SetEventHandle( m_SampleReadyEvent );
00174         if (FAILED( hr ))
00175         {
00176             goto exit;
00177         }
00178
00179         // Everything succeeded
00180         m_DeviceStateChanged->SetState( DeviceState::DeviceStateInitialized, S_OK, true );
00181
00182     }
00183
00184 exit:
00185     SAFE_RELEASE( punkAudioInterface );
00186
00187     if (FAILED( hr ))
00188     {
00189         m_DeviceStateChanged->SetState( DeviceState::DeviceStateInError, hr, true );
00190         SAFE_RELEASE( m_AudioClient );
00191         SAFE_RELEASE( m_AudioRenderClient );
00192         SAFE_RELEASE( m_SampleReadyAsyncResult );
00193     }
00194
00195     // Need to return S_OK
00196     return S_OK;
00197 }
00198
00199 //
00200 //  SetProperties()
00201 //
00202 //  Sets various properties that the user defines in the scenario
00203 //
00204 HRESULT WASAPIRenderer::SetProperties( DEVICEPROPS props )
00205 {
00206     m_DeviceProps = props;
00207     return S_OK;
00208 }
00209
00210 //
00211 //  GetBufferFramesPerPeriod()
00212 //
00213 //  Get the time in seconds between passes of the audio device
00214 //
00215 UINT32 WASAPIRenderer::GetBufferFramesPerPeriod()
00216 {
00217     REFERENCE_TIME defaultDevicePeriod = 0;
00218     REFERENCE_TIME minimumDevicePeriod = 0;
00219
00220     if (m_DeviceProps.IsHWOffload)
00221     {
00222         return m_BufferFrames;
00223     }
00224
00225     // Get the audio device period
00226     HRESULT hr = m_AudioClient->GetDevicePeriod( &defaultDevicePeriod, &minimumDevicePeriod);
00227     if (FAILED( hr ))
00228     {
00229         return 0;
00230     }
00231
00232     double devicePeriodInSeconds = defaultDevicePeriod / (10000.0*1000.0);
00233
00234     return static_cast<UINT32>( m_MixFormat->nSamplesPerSec * devicePeriodInSeconds + 0.5 );
00235 }
00236
00237 //
00238 //  ConfigureDeviceInternal()
00239 //
00240 //  Sets additional playback parameters and opts into hardware offload
00241 //
00242 HRESULT WASAPIRenderer::ConfigureDeviceInternal()
00243 {
00244     if (m_DeviceStateChanged->GetState() != DeviceState::DeviceStateActivated)
00245     {
00246         return E_NOT_VALID_STATE;
00247     }
00248
00249     HRESULT hr = S_OK;
00250
00251     // Opt into HW Offloading.  If the endpoint does not support offload it will return AUDCLNT_E_ENDPOINT_OFFLOAD_NOT_CAPABLE
00252     AudioClientProperties audioProps;
00253     audioProps.cbSize = sizeof( AudioClientProperties );
00254     audioProps.bIsOffload = m_DeviceProps.IsHWOffload;
00255     audioProps.eCategory = ( m_DeviceProps.IsBackground ? AudioCategory_BackgroundCapableMedia : AudioCategory_ForegroundOnlyMedia );
00256
00257     hr = m_AudioClient->SetClientProperties( &audioProps );
00258     if (FAILED( hr ))
00259     {
00260         return hr;
00261     }
00262
00263     // This sample opens the device is shared mode so we need to find the supported WAVEFORMATEX mix format
00264     hr = m_AudioClient->GetMixFormat( &m_MixFormat );
00265     if (FAILED( hr ))
00266     {
00267         return hr;
00268     }
00269
00270     // Verify the user defined value for hardware buffer
00271     hr = ValidateBufferValue();
00272
00273     return hr;
00274 }
00275
00276 //
00277 //  ValidateBufferValue()
00278 //
00279 //  Verifies the user specified buffer value for hardware offload
00280 //
00281 HRESULT WASAPIRenderer::ValidateBufferValue()
00282 {
00283     HRESULT hr = S_OK;
00284
00285     if (!m_DeviceProps.IsHWOffload)
00286     {
00287         // If we aren't using HW Offload, set this to 0 to use the default value
00288         m_DeviceProps.hnsBufferDuration = 0;
00289         return hr;
00290     }
00291
00292     REFERENCE_TIME hnsMinBufferDuration;
00293     REFERENCE_TIME hnsMaxBufferDuration;
00294
00295     hr = m_AudioClient->GetBufferSizeLimits( m_MixFormat, true, &hnsMinBufferDuration, &hnsMaxBufferDuration );
00296     if (SUCCEEDED( hr ))
00297     {
00298         if (m_DeviceProps.hnsBufferDuration < hnsMinBufferDuration)
00299         {
00300             // using MINIMUM size instead
00301             m_DeviceProps.hnsBufferDuration = hnsMinBufferDuration;
00302         }
00303         else if (hnsMinBufferDuration > hnsMaxBufferDuration)
00304         {
00305             // using MAXIMUM size instead
00306             m_DeviceProps.hnsBufferDuration = hnsMaxBufferDuration;
00307         }
00308     }
00309
00310     return hr;
00311 }
00312
00313 //
00314 //  SetVolumeOnSession()
00315 //
00316 HRESULT WASAPIRenderer::SetVolumeOnSession( UINT32 volume )
00317 {
00318     if (volume > 100)
00319     {
00320         return E_INVALIDARG;
00321     }
00322
00323     HRESULT hr = S_OK;
00324     ISimpleAudioVolume *SessionAudioVolume = nullptr;
00325     float ChannelVolume = 0.0;
00326
00327     hr = m_AudioClient->GetService( __uuidof(ISimpleAudioVolume), reinterpret_cast<void**>(&SessionAudioVolume) );
00328     if (FAILED( hr ))
00329     {
00330         goto exit;
00331     }
00332
00333     ChannelVolume = volume / (float)100.0;
00334
00335     // Set the session volume on the endpoint
00336     hr = SessionAudioVolume->SetMasterVolume( ChannelVolume, nullptr );
00337
00338 exit:
00339     SAFE_RELEASE( SessionAudioVolume );
00340     return hr;
00341 }
00342
00343 //
00344 //  ConfigureSource()
00345 //
00346 //  Configures tone or file playback
00347 //
00348 HRESULT WASAPIRenderer::ConfigureSource()
00349 {
00350     HRESULT hr = S_OK;
00351     UINT32 FramesPerPeriod = GetBufferFramesPerPeriod();
00352
00353     if (m_DeviceProps.IsTonePlayback)
00354     {
00355         // Generate the sine wave sample buffer
00356         m_ToneSource = new ToneSampleGenerator();
00357         if (m_ToneSource)
00358         {
00359             hr = m_ToneSource->GenerateSampleBuffer( m_DeviceProps.Frequency, FramesPerPeriod, m_MixFormat );
00360         }
00361         else
00362         {
00363             hr = E_OUTOFMEMORY;
00364         }
00365     }
00366     else
00367     {
00368         m_MFSource = new MFSampleGenerator();
00369         if (m_MFSource)
00370         {
00371             hr = m_MFSource->Initialize( m_DeviceProps.ContentStream, FramesPerPeriod, m_MixFormat );
00372         }
00373         else
00374         {
00375             hr = E_OUTOFMEMORY;
00376         }
00377     }
00378
00379     return hr;
00380 }
00381
00382 //
00383 //  StartPlaybackAsync()
00384 //
00385 //  Starts asynchronous playback on a separate thread via MF Work Item
00386 //
00387 HRESULT WASAPIRenderer::StartPlaybackAsync()
00388 {
00389     HRESULT hr = S_OK;
00390
00391     // We should be stopped if the user stopped playback, or we should be
00392     // initialzied if this is the first time through getting ready to playback.
00393     if ( (m_DeviceStateChanged->GetState() == DeviceState::DeviceStateStopped) ||
00394          (m_DeviceStateChanged->GetState() == DeviceState::DeviceStateInitialized) )
00395     {
00396         // Setup either ToneGeneration or File Playback
00397         hr = ConfigureSource();
00398         if (FAILED( hr ))
00399         {
00400             m_DeviceStateChanged->SetState( DeviceState::DeviceStateInError, hr, true );
00401             return hr;
00402         }
00403
00404         m_DeviceStateChanged->SetState( DeviceState::DeviceStateStarting, S_OK, true );
00405         return MFPutWorkItem2( MFASYNC_CALLBACK_QUEUE_MULTITHREADED, 0, &m_xStartPlayback, nullptr );
00406     }
00407     else if (m_DeviceStateChanged->GetState() == DeviceState::DeviceStatePaused)
00408     {
00409         return MFPutWorkItem2( MFASYNC_CALLBACK_QUEUE_MULTITHREADED, 0, &m_xStartPlayback, nullptr );
00410     }
00411
00412     // Otherwise something else happened
00413     return E_FAIL;
00414 }
00415
00416 //
00417 //  OnStartPlayback()
00418 //
00419 //  Callback method to start playback
00420 //
00421 HRESULT WASAPIRenderer::OnStartPlayback( IMFAsyncResult* pResult )
00422 {
00423     HRESULT hr = S_OK;
00424
00425     // Pre-Roll the buffer with silence
00426     hr = OnAudioSampleRequested( true );
00427     if (FAILED( hr ))
00428     {
00429         goto exit;
00430     }
00431
00432     // For MF Source playback, need to start the source reader
00433     if (!m_DeviceProps.IsTonePlayback)
00434     {
00435         hr = m_MFSource->StartSource();
00436         if (FAILED( hr ))
00437         {
00438             goto exit;
00439         }
00440     }
00441
00442     // Actually start the playback
00443     hr = m_AudioClient->Start();
00444     if (SUCCEEDED( hr ))
00445     {
00446         m_DeviceStateChanged->SetState( DeviceState::DeviceStatePlaying, S_OK, true );
00447         hr = MFPutWaitingWorkItem( m_SampleReadyEvent, 0, m_SampleReadyAsyncResult, &m_SampleReadyKey );
00448     }
00449
00450 exit:
00451     if (FAILED( hr ))
00452     {
00453         m_DeviceStateChanged->SetState( DeviceState::DeviceStateInError, hr, true );
00454     }
00455
00456     return S_OK;
00457 }
00458
00459 //
00460 //  StopPlaybackAsync()
00461 //
00462 //  Stop playback asynchronously via MF Work Item
00463 //
00464 HRESULT WASAPIRenderer::StopPlaybackAsync()
00465 {
00466     if ( (m_DeviceStateChanged->GetState() != DeviceState::DeviceStatePlaying) &&
00467          (m_DeviceStateChanged->GetState() != DeviceState::DeviceStatePaused) &&
00468          (m_DeviceStateChanged->GetState() != DeviceState::DeviceStateInError) )
00469     {
00470         return E_NOT_VALID_STATE;
00471     }
00472
00473     m_DeviceStateChanged->SetState( DeviceState::DeviceStateStopping, S_OK, true );
00474
00475     return MFPutWorkItem2( MFASYNC_CALLBACK_QUEUE_MULTITHREADED, 0, &m_xStopPlayback, nullptr );
00476 }
00477
00478 //
00479 //  OnStopPlayback()
00480 //
00481 //  Callback method to stop playback
00482 //
00483 HRESULT WASAPIRenderer::OnStopPlayback( IMFAsyncResult* pResult )
00484 {
00485     // Stop playback by cancelling Work Item
00486     // Cancel the queued work item (if any)
00487     if (0 != m_SampleReadyKey)
00488     {
00489         MFCancelWorkItem( m_SampleReadyKey );
00490         m_SampleReadyKey = 0;
00491     }
00492
00493     // Flush anything left in buffer with silence
00494     OnAudioSampleRequested( true );
00495
00496     m_AudioClient->Stop();
00497     SAFE_RELEASE( m_SampleReadyAsyncResult );
00498
00499     if (m_DeviceProps.IsTonePlayback)
00500     {
00501         // Flush remaining buffers
00502         m_ToneSource->Flush();
00503     }
00504     else
00505     {
00506         // Stop Source and Flush remaining buffers
00507         m_MFSource->StopSource();
00508         m_MFSource->Shutdown();
00509     }
00510
00511     m_DeviceStateChanged->SetState( DeviceState::DeviceStateStopped, S_OK, true );
00512     return S_OK;
00513 }
00514
00515 //
00516 //  PausePlaybackAsync()
00517 //
00518 //  Pause playback asynchronously via MF Work Item
00519 //
00520 HRESULT WASAPIRenderer::PausePlaybackAsync()
00521 {
00522     if ( (m_DeviceStateChanged->GetState() !=  DeviceState::DeviceStatePlaying) &&
00523          (m_DeviceStateChanged->GetState() != DeviceState::DeviceStateInError) )
00524     {
00525         return E_NOT_VALID_STATE;
00526     }
00527
00528     // Change state to stop automatic queueing of samples
00529     m_DeviceStateChanged->SetState( DeviceState::DeviceStatePausing, S_OK, false );
00530     return MFPutWorkItem2( MFASYNC_CALLBACK_QUEUE_MULTITHREADED, 0, &m_xPausePlayback, nullptr );
00531
00532 }
00533
00534 //
00535 //  OnPausePlayback()
00536 //
00537 //  Callback method to pause playback
00538 //
00539 HRESULT WASAPIRenderer::OnPausePlayback( IMFAsyncResult* pResult )
00540 {
00541     m_AudioClient->Stop();
00542     m_DeviceStateChanged->SetState( DeviceState::DeviceStatePaused, S_OK, true );
00543     return S_OK;
00544 }
00545
00546 //
00547 //  OnSampleReady()
00548 //
00549 //  Callback method when ready to fill sample buffer
00550 //
00551 HRESULT WASAPIRenderer::OnSampleReady( IMFAsyncResult* pResult )
00552 {
00553     HRESULT hr = S_OK;
00554
00555     hr = OnAudioSampleRequested( false );
00556
00557     if (SUCCEEDED( hr ))
00558     {
00559         // Re-queue work item for next sample
00560         if (m_DeviceStateChanged->GetState() ==  DeviceState::DeviceStatePlaying)
00561         {
00562             hr = MFPutWaitingWorkItem( m_SampleReadyEvent, 0, m_SampleReadyAsyncResult, &m_SampleReadyKey );
00563         }
00564     }
00565     else
00566     {
00567         m_DeviceStateChanged->SetState( DeviceState::DeviceStateInError, hr, true );
00568     }
00569
00570     return hr;
00571 }
00572
00573 //
00574 //  OnAudioSampleRequested()
00575 //
00576 //  Called when audio device fires m_SampleReadyEvent
00577 //
00578 HRESULT WASAPIRenderer::OnAudioSampleRequested( Platform::Boolean IsSilence )
00579 {
00580     HRESULT hr = S_OK;
00581     UINT32 PaddingFrames = 0;
00582     UINT32 FramesAvailable = 0;
00583
00584     EnterCriticalSection( &m_CritSec );
00585
00586     // Get padding in existing buffer
00587     hr = m_AudioClient->GetCurrentPadding( &PaddingFrames );
00588     if (FAILED( hr ))
00589     {
00590         goto exit;
00591     }
00592
00593     // Audio frames available in buffer
00594     if (m_DeviceProps.IsHWOffload)
00595     {
00596         // In HW mode, GetCurrentPadding returns the number of available frames in the
00597         // buffer, so we can just use that directly
00598         FramesAvailable = PaddingFrames;
00599     }
00600     else
00601     {
00602         // In non-HW shared mode, GetCurrentPadding represents the number of queued frames
00603         // so we can subtract that from the overall number of frames we have
00604         FramesAvailable = m_BufferFrames - PaddingFrames;
00605     }
00606
00607     // Only continue if we have buffer to write data
00608     if (FramesAvailable > 0)
00609     {
00610         if (IsSilence)
00611         {
00612             BYTE *Data;
00613
00614             // Fill the buffer with silence
00615             hr = m_AudioRenderClient->GetBuffer( FramesAvailable, &Data );
00616             if (FAILED( hr ))
00617             {
00618                 goto exit;
00619             }
00620
00621             hr = m_AudioRenderClient->ReleaseBuffer( FramesAvailable, AUDCLNT_BUFFERFLAGS_SILENT );
00622             goto exit;
00623         }
00624
00625         // Even if we cancel a work item, this may still fire due to the async
00626         // nature of things.  There should be a queued work item already to handle
00627         // the process of stopping or stopped
00628         if (m_DeviceStateChanged->GetState() == DeviceState::DeviceStatePlaying)
00629         {
00630             // Fill the buffer with a playback sample
00631             if (m_DeviceProps.IsTonePlayback)
00632             {
00633                 hr = GetToneSample( FramesAvailable );
00634             }
00635             else
00636             {
00637                 hr = GetMFSample( FramesAvailable );
00638             }
00639         }
00640     }
00641
00642 exit:
00643     LeaveCriticalSection( &m_CritSec );
00644
00645     if (AUDCLNT_E_RESOURCES_INVALIDATED == hr)
00646     {
00647         m_DeviceStateChanged->SetState( DeviceState::DeviceStateUnInitialized, hr, false );
00648         SAFE_RELEASE( m_AudioClient );
00649         SAFE_RELEASE( m_AudioRenderClient );
00650         SAFE_RELEASE( m_SampleReadyAsyncResult );
00651
00652         hr = InitializeAudioDeviceAsync();
00653     }
00654
00655     return hr;
00656 }
00657
00658 //
00659 //  GetToneSample()
00660 //
00661 //  Fills buffer with a tone sample
00662 //
00663 HRESULT WASAPIRenderer::GetToneSample( UINT32 FramesAvailable )
00664 {
00665     HRESULT hr = S_OK;
00666     BYTE *Data;
00667
00668     // Post-Roll Silence
00669     if (m_ToneSource->IsEOF())
00670     {
00671         hr = m_AudioRenderClient->GetBuffer( FramesAvailable, &Data );
00672         if (SUCCEEDED( hr ))
00673         {
00674             // Ignore the return
00675             hr = m_AudioRenderClient->ReleaseBuffer( FramesAvailable, AUDCLNT_BUFFERFLAGS_SILENT );
00676         }
00677
00678         StopPlaybackAsync();
00679     }
00680     else if (m_ToneSource->GetBufferLength() <= ( FramesAvailable * m_MixFormat->nBlockAlign ))
00681     {
00682         UINT32 ActualFramesToRead = m_ToneSource->GetBufferLength() / m_MixFormat->nBlockAlign;
00683         UINT32 ActualBytesToRead = ActualFramesToRead * m_MixFormat->nBlockAlign;
00684
00685         hr = m_AudioRenderClient->GetBuffer( ActualFramesToRead, &Data );
00686         if (SUCCEEDED( hr ))
00687         {
00688             hr = m_ToneSource->FillSampleBuffer( ActualBytesToRead, Data );
00689             if (SUCCEEDED( hr ))
00690             {
00691                 hr = m_AudioRenderClient->ReleaseBuffer( ActualFramesToRead, 0 );
00692             }
00693         }
00694     }
00695
00696     return hr;
00697 }
00698
00699 //
00700 //  GetMFSample()
00701 //
00702 //  Fills buffer with a MF sample
00703 //
00704 HRESULT WASAPIRenderer::GetMFSample( UINT32 FramesAvailable )
00705 {
00706     HRESULT hr = S_OK;
00707     BYTE *Data = nullptr;
00708
00709     // Post-Roll Silence
00710     if (m_MFSource->IsEOF())
00711     {
00712         hr = m_AudioRenderClient->GetBuffer( FramesAvailable, &Data );
00713         if (SUCCEEDED( hr ))
00714         {
00715             // Ignore the return
00716             hr = m_AudioRenderClient->ReleaseBuffer( FramesAvailable, AUDCLNT_BUFFERFLAGS_SILENT );
00717         }
00718
00719         StopPlaybackAsync();
00720     }
00721     else
00722     {
00723         UINT32 ActualBytesRead = 0;
00724         UINT32 ActualBytesToRead = FramesAvailable * m_MixFormat->nBlockAlign;
00725
00726         hr = m_AudioRenderClient->GetBuffer( FramesAvailable, &Data );
00727         if (SUCCEEDED( hr ))
00728         {
00729             hr = m_MFSource->FillSampleBuffer( ActualBytesToRead, Data, &ActualBytesRead );
00730             if (hr == S_FALSE)
00731             {
00732                 // Hit EOS
00733                 hr = m_AudioRenderClient->ReleaseBuffer( FramesAvailable, AUDCLNT_BUFFERFLAGS_SILENT );
00734                 StopPlaybackAsync();
00735             }
00736             else if (SUCCEEDED( hr ))
00737             {
00738                 // This can happen if we are pre-rolling so just insert silence
00739                 if (0 == ActualBytesRead)
00740                 {
00741                     hr = m_AudioRenderClient->ReleaseBuffer( FramesAvailable, AUDCLNT_BUFFERFLAGS_SILENT );
00742                 }
00743                 else
00744                 {
00745                     hr = m_AudioRenderClient->ReleaseBuffer( ( ActualBytesRead / m_MixFormat->nBlockAlign ), 0 );
00746                 }
00747             }
00748         }
00749     }
00750
00751     return hr;
00752 }
00753
Generated on Sat Nov 23 2024 16:08:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::TileContent::TileWidePeekImageCollection05 Member List

This is the complete list of members for NotificationsExtensions::TileContent::TileWidePeekImageCollection05, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
Branding | NotificationsExtensions::TileContent::TileNotificationBase |
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
ImageMain | NotificationsExtensions::TileContent::TileWidePeekImageCollection05 |
Images | NotificationsExtensions::NotificationBase |
ImageSecondary | NotificationsExtensions::TileContent::TileWidePeekImageCollection05 |
ImageSmallColumn1Row1 | NotificationsExtensions::TileContent::TileWidePeekImageCollection05 |
ImageSmallColumn1Row2 | NotificationsExtensions::TileContent::TileWidePeekImageCollection05 |
ImageSmallColumn2Row1 | NotificationsExtensions::TileContent::TileWidePeekImageCollection05 |
ImageSmallColumn2Row2 | NotificationsExtensions::TileContent::TileWidePeekImageCollection05 |
Lang | NotificationsExtensions::NotificationBase |
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
RequireSquareContent | NotificationsExtensions::TileContent::TileWideBase |
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SquareContent | NotificationsExtensions::TileContent::TileWideBase |
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextBodyWrap | NotificationsExtensions::TileContent::TileWidePeekImageCollection05 |
TextFields | NotificationsExtensions::NotificationBase |
TextHeading | NotificationsExtensions::TileContent::TileWidePeekImageCollection05 |
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWidePeekImageCollection05() | NotificationsExtensions::TileContent::TileWidePeekImageCollection05 | [inline]
TileWidePeekImageCollection05() | NotificationsExtensions::TileContent::TileWidePeekImageCollection05 | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:44 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Samples::Devices::Fx2::sealed Member List

This is the complete list of members for Samples::Devices::Fx2::sealed, including all inherited members.
BarGraphDisplayResult() | Samples::Devices::Fx2::sealed | [inline]
BarGraphDisplayResult() | Samples::Devices::Fx2::sealed | [inline]
BarGraphDisplayResult() | Samples::Devices::Fx2::sealed | [inline]
Buffer | Samples::Devices::Fx2::sealed |
CancelContext | Samples::Devices::Fx2::sealed |
CheckResult(void) | Samples::Devices::Fx2::sealed | [inline, private]
CheckResult(void) | Samples::Devices::Fx2::sealed | [inline, private]
CheckResult(void) | Samples::Devices::Fx2::sealed | [inline, private]
FailureCount | Samples::Devices::Fx2::sealed |
FromId(__in String^InterfacePath) | Samples::Devices::Fx2::sealed | [static]
FromId(__in String^InterfacePath) | Samples::Devices::Fx2::sealed | [static]
FromId(__in String^InterfacePath) | Samples::Devices::Fx2::sealed | [static]
Fx2Device(__in IDeviceIoControl *DeviceControl, __in String^Id) | Samples::Devices::Fx2::sealed | [private]
Fx2Device(__in IDeviceIoControl *DeviceControl, __in String^Id) | Samples::Devices::Fx2::sealed | [private]
Fx2Device(__in IDeviceIoControl *DeviceControl, __in String^Id) | Samples::Devices::Fx2::sealed | [private]
GetBarGraphDisplayAsync(void) | Samples::Devices::Fx2::sealed |
GetBarGraphDisplayAsync(void) | Samples::Devices::Fx2::sealed |
GetBarGraphDisplayAsync(void) | Samples::Devices::Fx2::sealed |
GetDeviceSelector() | Samples::Devices::Fx2::sealed | [static]
GetDeviceSelector() | Samples::Devices::Fx2::sealed | [static]
GetDeviceSelector() | Samples::Devices::Fx2::sealed | [static]
ListenerCount | Samples::Devices::Fx2::sealed |
m_Bars | Samples::Devices::Fx2::sealed | [private]
m_CancelToken | Samples::Devices::Fx2::sealed | [private]
m_DeviceIoControl | Samples::Devices::Fx2::sealed | [private]
m_Hr | Samples::Devices::Fx2::sealed | [private]
m_Id | Samples::Devices::Fx2::sealed | [private]
m_State | Samples::Devices::Fx2::sealed | [private]
m_State | Samples::Devices::Fx2::sealed | [private]
m_Switches | Samples::Devices::Fx2::sealed | [private]
m_SwitchState | Samples::Devices::Fx2::sealed | [private]
m_SwitchState | Samples::Devices::Fx2::sealed | [private]
m_SwitchState | Samples::Devices::Fx2::sealed | [private]
m_SwitchStateChangedEvent | Samples::Devices::Fx2::sealed | [private]
Repeater | Samples::Devices::Fx2::sealed |
StartEventLoop() | Samples::Devices::Fx2::sealed | [private]
StartEventLoop() | Samples::Devices::Fx2::sealed | [private]
StartEventLoop() | Samples::Devices::Fx2::sealed | [private]
StopEventLoop() | Samples::Devices::Fx2::sealed | [private]
StopEventLoop() | Samples::Devices::Fx2::sealed | [private]
StopEventLoop() | Samples::Devices::Fx2::sealed | [private]
SwitchStateChangedEventArgs(__in HRESULT Hr) | Samples::Devices::Fx2::sealed | [inline, private]
SwitchStateChangedEventArgs(__in SWITCH_STATE State) | Samples::Devices::Fx2::sealed | [inline, private]
SwitchStateChangedEventArgs(__in HRESULT Hr) | Samples::Devices::Fx2::sealed | [inline, private]
SwitchStateChangedEventArgs(__in SWITCH_STATE State) | Samples::Devices::Fx2::sealed | [inline, private]
SwitchStateChangedEventArgs(__in HRESULT Hr) | Samples::Devices::Fx2::sealed | [inline, private]
SwitchStateChangedEventArgs(__in SWITCH_STATE State) | Samples::Devices::Fx2::sealed | [inline, private]
UpdateBars() | Samples::Devices::Fx2::sealed | [inline, private]
UpdateBars() | Samples::Devices::Fx2::sealed | [inline, private]
UpdateBars() | Samples::Devices::Fx2::sealed | [inline, private]
~Fx2Device() | Samples::Devices::Fx2::sealed | [private]
~Fx2Device() | Samples::Devices::Fx2::sealed | [private]
~Fx2Device() | Samples::Devices::Fx2::sealed | [private]
Generated on Sat Nov 23 2024 16:09:46 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::TouchKeyboardTextInput::sealed Member List

This is the complete list of members for SDKSample::TouchKeyboardTextInput::sealed, including all inherited members.
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::TouchKeyboardTextInput::sealed | [protected, virtual]
rootPage | SDKSample::TouchKeyboardTextInput::sealed | [private]
ScopedViews() | SDKSample::TouchKeyboardTextInput::sealed |
Generated on Sat Nov 23 2024 16:09:53 for Win8-Examples by doxygen 1.7.1


Win8-Examples: User domain name/C++/App.xaml.h Source File

  • User domain name

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Bing Maps Trip Optimizer/C++,JavaScript/cpp/pch.cpp Source File

  • Bing Maps Trip Optimizer
  • C++,JavaScript
  • cpp

pch.cpp

Go to the documentation of this file.
00001 ﻿// pch.cpp : source file that includes just the standard includes
00002 //   pch.pch will be the pre-compiled header
00003 //   pch.obj will contain the pre-compiled type information
00004
00005 #include "pch.h"
00006
00007 // TODO: reference any additional headers you need in PCH.H and not in this file
Generated on Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML ListView and GridView essentials/C++/Scenario1.xaml.h Source File

  • XAML ListView and GridView essentials

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 #include "SampleDataSource.h"
00022
00023 namespace SDKSample
00024 {
00025   namespace ListViewSimple
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::WebHostHiddenAttribute]
00031     public ref class Scenario1 sealed
00032     {
00033     public:
00034       Scenario1();
00035
00036     protected:
00037       virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00038
00039     private:
00040       MainPage^ rootPage;
00041       ListViewSampleDataSource::StoreData^ storeData;
00042
00043       void Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00044       void Other_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00045     };
00046   }
00047 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D stereoscopic 3D/C++/DDSTextureLoader.h Source File

  • Direct3D stereoscopic 3D

DDSTextureLoader.h

Go to the documentation of this file.
00001 //--------------------------------------------------------------------------------------
00002 // File: DDSTextureLoader.h
00003 //
00004 // Function for loading a DDS texture and creating a Direct3D 11 runtime resource for it
00005 //
00006 // Note this function is 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
00018 #pragma once
00019
00020 void CreateDDSTextureFromMemory(
00021     _In_ ID3D11Device* d3dDevice,
00022     _In_reads_bytes_(ddsDataSize) const byte* ddsData,
00023     _In_ size_t ddsDataSize,
00024     _Out_opt_ ID3D11Resource** texture,
00025     _Out_opt_ ID3D11ShaderResourceView** textureView,
00026     _In_ size_t maxsize = 0
00027     );
Generated on Sat Nov 23 2024 16:08:11 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/Level4.cpp Source File

  • XAML DirectX 3D shooting game

Level4.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 "Level4.h"
00010 #include "Face.h"
00011
00012 //----------------------------------------------------------------------
00013
00014 Level4::Level4()
00015 {
00016     m_timeLimit = 30.0f;
00017     m_objective = "Hit each of the moving targets in ORDER before time runs out.";
00018 }
00019
00020 //----------------------------------------------------------------------
00021
00022 void Level4::Initialize(std::vector<GameObject^> objects)
00023 {
00024     Level3::Initialize(objects);
00025
00026     int targetCount = 0;
00027     for (auto object = objects.begin(); object != objects.end(); object++)
00028     {
00029         if (Face^ target = dynamic_cast<Face^>(*object))
00030         {
00031             if (targetCount < 9)
00032             {
00033                 target->Target(targetCount == 0 ? true : false);
00034                 targetCount++;
00035             }
00036         }
00037     }
00038     m_nextId = 1;
00039 }
00040
00041 //----------------------------------------------------------------------
00042
00043 bool Level4::Update(
00044     float /* time */,
00045     float /* elapsedTime */,
00046     float /* timeRemaining */,
00047     std::vector<GameObject^> objects
00048     )
00049 {
00050     int left = 0;
00051     for (auto object = objects.begin(); object != objects.end(); object++)
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 //----------------------------------------------------------------------
00074
00075 void Level4::SaveState(PersistentState^ state)
00076 {
00077     state->SaveInt32(":NextTarget", m_nextId);
00078 }
00079
00080 //----------------------------------------------------------------------
00081
00082 void Level4::LoadState(PersistentState^ state)
00083 {
00084     m_nextId = state->LoadInt32(":NextTarget", 1);
00085 }
00086
00087 //----------------------------------------------------------------------
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Transcoding media/C++/Constants.h Source File

  • Transcoding media

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"Transcode");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044
00045
00046 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite paragraph text/C++/DirectXSample.h Source File

  • DirectWrite paragraph text

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
00010 // This header defines helper utilities to make DirectX APIs work with exceptions.
00011 namespace DX
00012 {
00013     inline void ThrowIfFailed(HRESULT hr)
00014     {
00015         if (FAILED(hr))
00016         {
00017             // Set a breakpoint on this line to catch DX API errors.
00018             throw Platform::Exception::CreateException(hr);
00019         }
00020     }
00021 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Portable device API/C++/S4_GetFromDevice.xaml.h Source File

  • Portable device API

S4_GetFromDevice.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 // S4_GetFromDevice.xaml.h
00013 // Declaration of the S4_GetFromDevice class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "S4_GetFromDevice.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace PortableDeviceCPP
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 S4_GetFromDevice sealed
00031         {
00032         public:
00033             S4_GetFromDevice();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037
00038         private:
00039             void Run_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040             void ShowDeviceSelectorAsync();
00041             void DeviceList_Tapped(Platform::Object^ sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^ e);
00042             void GetContentFromDeviceAsync(Windows::Devices::Enumeration::DeviceInformation^ deviceInfoElement);
00043             void FindAndTransferFirstImageFileFromDevice(_In_ IPortableDevice* device);
00044             void TransferFileFromDeviceToAppLocalFolderAsync(_In_ IPortableDevice* device, Platform::String^ sourceObjectId, Platform::String^ desiredFilename);
00045
00046             MainPage^ rootPage;
00047             // Contains the device information used for populating the device selection list
00048             Windows::Devices::Enumeration::DeviceInformationCollection^ _deviceInfoCollection;
00049         };
00050     }
00051 }
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Removable storage/C++/App.xaml.h Source File

  • Removable storage

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Lock screen apps/C#,C++/ScenarioOutput2.xaml.cpp Source File

  • Lock screen apps
  • C#,C++

ScenarioOutput2.xaml.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 //
00009 // Scenario2Output.xaml.cpp
00010 // Implementation of the Scenario2Output class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioOutput2.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace LockScreenAppsCPP;
00018
00019 using namespace Platform;
00020
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Foundation::Collections;
00023 using namespace Windows::Graphics::Display;
00024 using namespace Windows::UI::ViewManagement;
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 ScenarioOutput2::ScenarioOutput2()
00034 {
00035     InitializeComponent();
00036 }
00037
00038 ScenarioOutput2::~ScenarioOutput2()
00039 {
00040 }
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: StreamSocket/C++/Scenario3.xaml.h Source File

  • StreamSocket

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 StreamSocketSample
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         void SendHello_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038     };
00039 }
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Print/C++/pch.cpp Source File

  • Print

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 //
00009 // pch.cpp
00010 // Include the standard header and generate the precompiled header.
00011 //
00012
00013 #include "pch.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Lock screen personalization/C++/common/suspensionmanager.h Source File

  • Lock screen personalization
  • common

suspensionmanager.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 // SuspensionManager.h
00013 // Declaration of the SuspensionManager class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019
00020 namespace SDKSample
00021 {
00022     namespace Common
00023     {
00024         /// <summary>
00025         /// SuspensionManager captures global session state to simplify process lifetime management
00026         /// for an application.  Note that session state will be automatically cleared under a variety
00027         /// of conditions and should only be used to store information that would be convenient to
00028         /// carry across sessions, but that should be disacarded when an application crashes or is
00029         /// upgraded.
00030         /// </summary>
00031         ref class SuspensionManager sealed
00032         {
00033         internal:
00034             static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
00035             static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
00036             static Concurrency::task<void> SaveAsync(void);
00037             static Concurrency::task<void> RestoreAsync(void);
00038             static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
00039             {
00040                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
00041             };
00042             static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
00043                 Windows::UI::Xaml::Controls::Frame^ frame);
00044
00045         private:
00046             static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00047             static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
00048         };
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: App settings/C++/DefaultScenario.xaml.h Source File

  • App settings

DefaultScenario.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 // DefaultScenario.xaml.h
00013 // Declaration of the DefaultScenario class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "DefaultScenario.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace ApplicationSettings
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 DefaultScenario sealed
00031         {
00032         public:
00033             DefaultScenario();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037
00038         private:
00039             MainPage^ rootPage;
00040         };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:07:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D tutorial/C++/Lesson2.Triangles/BasicReaderWriter.cpp Source File

  • Direct3D tutorial
  • Lesson2.Triangles

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     m_locationPath = Platform::String::Concat(m_location->Path, "\\");
00023 }
00024
00025 BasicReaderWriter::BasicReaderWriter(
00026     _In_ Windows::Storage::StorageFolder^ folder
00027     )
00028 {
00029     m_location = folder;
00030     Platform::String^ path = m_location->Path;
00031     if (path->Length() == 0)
00032     {
00033         // Applications are not permitted to access certain
00034         // folders, such as the Documents folder, using this
00035         // code path.  In such cases, the Path property for
00036         // the folder will be an empty string.
00037         throw ref new Platform::FailureException();
00038     }
00039     m_locationPath = Platform::String::Concat(path, "\\");
00040 }
00041
00042 Platform::Array<byte>^ BasicReaderWriter::ReadData(
00043     _In_ Platform::String^ filename
00044     )
00045 {
00046     CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {0};
00047     extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
00048     extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
00049     extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN;
00050     extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
00051     extendedParams.lpSecurityAttributes = nullptr;
00052     extendedParams.hTemplateFile = nullptr;
00053
00054     Wrappers::FileHandle file(
00055         CreateFile2(
00056             Platform::String::Concat(m_locationPath, filename)->Data(),
00057             GENERIC_READ,
00058             FILE_SHARE_READ,
00059             OPEN_EXISTING,
00060             &extendedParams
00061             )
00062         );
00063     if (file.Get() == INVALID_HANDLE_VALUE)
00064     {
00065         throw ref new Platform::FailureException();
00066     }
00067
00068     FILE_STANDARD_INFO fileInfo = {0};
00069     if (!GetFileInformationByHandleEx(
00070         file.Get(),
00071         FileStandardInfo,
00072         &fileInfo,
00073         sizeof(fileInfo)
00074         ))
00075     {
00076         throw ref new Platform::FailureException();
00077     }
00078
00079     if (fileInfo.EndOfFile.HighPart != 0)
00080     {
00081         throw ref new Platform::OutOfMemoryException();
00082     }
00083
00084     Platform::Array<byte>^ fileData = ref new Platform::Array<byte>(fileInfo.EndOfFile.LowPart);
00085
00086     if (!ReadFile(
00087         file.Get(),
00088         fileData->Data,
00089         fileData->Length,
00090         nullptr,
00091         nullptr
00092         ))
00093     {
00094         throw ref new Platform::FailureException();
00095     }
00096
00097     return fileData;
00098 }
00099
00100 task<Platform::Array<byte>^> BasicReaderWriter::ReadDataAsync(
00101     _In_ Platform::String^ filename
00102     )
00103 {
00104     return task<StorageFile^>(m_location->GetFileAsync(filename)).then([=](StorageFile^ file)
00105     {
00106         return FileIO::ReadBufferAsync(file);
00107     }).then([=](IBuffer^ buffer)
00108     {
00109         auto fileData = ref new Platform::Array<byte>(buffer->Length);
00110         DataReader::FromBuffer(buffer)->ReadBytes(fileData);
00111         return fileData;
00112     });
00113 }
00114
00115 uint32 BasicReaderWriter::WriteData(
00116     _In_ Platform::String^ filename,
00117     _In_ const Platform::Array<byte>^ fileData
00118     )
00119 {
00120     CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {0};
00121     extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
00122     extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
00123     extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN;
00124     extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
00125     extendedParams.lpSecurityAttributes = nullptr;
00126     extendedParams.hTemplateFile = nullptr;
00127
00128     Wrappers::FileHandle file(
00129         CreateFile2(
00130             Platform::String::Concat(m_locationPath, filename)->Data(),
00131             GENERIC_WRITE,
00132             0,
00133             CREATE_ALWAYS,
00134             &extendedParams
00135             )
00136         );
00137     if (file.Get() == INVALID_HANDLE_VALUE)
00138     {
00139         throw ref new Platform::FailureException();
00140     }
00141
00142     DWORD numBytesWritten;
00143     if (
00144         !WriteFile(
00145             file.Get(),
00146             fileData->Data,
00147             fileData->Length,
00148             &numBytesWritten,
00149             nullptr
00150             ) ||
00151         numBytesWritten != fileData->Length
00152         )
00153     {
00154         throw ref new Platform::FailureException();
00155     }
00156
00157     return numBytesWritten;
00158 }
00159
00160 task<void> BasicReaderWriter::WriteDataAsync(
00161     _In_ Platform::String^ filename,
00162     _In_ const Platform::Array<byte>^ fileData
00163     )
00164 {
00165     return task<StorageFile^>(m_location->CreateFileAsync(filename, CreationCollisionOption::ReplaceExisting)).then([=](StorageFile^ file)
00166     {
00167         FileIO::WriteBytesAsync(file, fileData);
00168     });
00169 }
Generated on Sat Nov 23 2024 16:08:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media capture using capture device/C++/AdvancedCapture.xaml.cpp Source File

  • Media capture using capture device

AdvancedCapture.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 // AdvancedCapture.xaml.cpp
00013 // Implementation of the AdvancedCapture class
00014 //
00015
00016 #include "pch.h"
00017 #include "AdvancedCapture.xaml.h"
00018
00019 using namespace SDKSample::MediaCapture;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Navigation;
00023 using namespace Windows::UI::Xaml::Data;
00024 using namespace Windows::System;
00025 using namespace Windows::Foundation;
00026 using namespace Platform;
00027 using namespace Windows::UI;
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::Data;
00032 using namespace Windows::UI::Xaml::Media;
00033 using namespace Windows::Storage;
00034 using namespace Windows::Media::MediaProperties;
00035 using namespace Windows::Storage::Streams;
00036 using namespace Windows::System;
00037 using namespace Windows::UI::Xaml::Media::Imaging;
00038 using namespace Windows::Devices::Enumeration;
00039
00040 ref class ReencodeState sealed
00041 {
00042 public:
00043     ReencodeState()
00044     {
00045     }
00046
00047     virtual ~ReencodeState()
00048     {
00049         if (InputStream != nullptr)
00050         {
00051             delete InputStream;
00052         }
00053         if (OutputStream != nullptr)
00054         {
00055             delete OutputStream;
00056         }
00057     }
00058
00059 internal:
00060     Windows::Storage::Streams::IRandomAccessStream ^InputStream;
00061     Windows::Storage::Streams::IRandomAccessStream ^OutputStream;
00062     Windows::Storage::StorageFile ^PhotoStorage;
00063     Windows::Graphics::Imaging::BitmapDecoder ^Decoder;
00064     Windows::Graphics::Imaging::BitmapEncoder ^Encoder;
00065 };
00066
00067 AdvancedCapture::AdvancedCapture()
00068 {
00069     InitializeComponent();
00070     ScenarioInit();
00071 }
00072
00073 /// <summary>
00074 /// Invoked when this page is about to be displayed in a Frame.
00075 /// </summary>
00076 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00077 /// property is typically used to configure the page.</param>
00078 void AdvancedCapture::OnNavigatedTo(NavigationEventArgs^ e)
00079 {
00080     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00081     // as NotifyUser()
00082     rootPage = MainPage::Current;
00083     m_eventRegistrationToken = Windows::Media::MediaControl::SoundLevelChanged += ref new EventHandler<Object^>(this, &AdvancedCapture::SoundLevelChanged);
00084
00085     m_orientationChangedEventToken = Windows::Graphics::Display::DisplayProperties::OrientationChanged += ref new Windows::Graphics::Display::DisplayPropertiesEventHandler(this, &AdvancedCapture::DisplayProperties_OrientationChanged);
00086 }
00087
00088 void AdvancedCapture::OnNavigatedFrom(NavigationEventArgs^ e)
00089 {
00090     Windows::Media::MediaControl::SoundLevelChanged -= m_eventRegistrationToken;
00091     Windows::Graphics::Display::DisplayProperties::OrientationChanged  -= m_orientationChangedEventToken;
00092 }
00093
00094 void  AdvancedCapture::ScenarioInit()
00095 {
00096     rootPage = MainPage::Current;
00097     btnStartDevice2->IsEnabled = true;
00098     btnStartPreview2->IsEnabled = false;
00099     btnStartStopRecord2->IsEnabled = false;
00100     m_bRecording = false;
00101     m_bPreviewing = false;
00102     m_bEffectAdded = false;
00103     btnStartStopRecord2->Content = "StartRecord";
00104     btnTakePhoto2->IsEnabled = false;
00105     previewElement2->Source = nullptr;
00106     playbackElement2->Source = nullptr;
00107     imageElement2->Source= nullptr;
00108     ShowStatusMessage("");
00109     chkAddRemoveEffect->IsChecked = false;
00110     chkAddRemoveEffect->IsEnabled = false;
00111     previewCanvas2->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00112     EnumerateWebcamsAsync();
00113     m_bSuspended = false;
00114 }
00115
00116 void AdvancedCapture::ScenarioReset()
00117 {
00118     previewCanvas2->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00119     ScenarioInit();
00120 }
00121
00122 void AdvancedCapture::SoundLevelChanged(Object^ sender, Object^ e)
00123 {
00124     create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([this]()
00125     {
00126         if(Windows::Media::MediaControl::SoundLevel != Windows::Media::SoundLevel::Muted)
00127         {
00128             ScenarioReset();
00129         }
00130         else
00131         {
00132             if (m_bRecording)
00133             {
00134                 ShowStatusMessage("Stopping Record on invisibility");
00135
00136                 create_task(m_mediaCaptureMgr->StopRecordAsync()).then([this](task<void> recordTask)
00137                 {
00138                     try
00139                     {
00140                         recordTask.get();
00141                         m_bRecording = false;
00142                     }
00143                     catch (Exception ^e)
00144                     {
00145                         ShowExceptionMessage(e);
00146                     }
00147                 });
00148             }
00149             if (m_bPreviewing)
00150             {
00151                 ShowStatusMessage("Stopping Preview on invisibility");
00152
00153                 create_task(m_mediaCaptureMgr->StopPreviewAsync()).then([this](task<void> previewTask)
00154                 {
00155                     try
00156                     {
00157                         previewTask.get();
00158                         m_bPreviewing = false;
00159
00160                     }catch (Exception ^e)
00161                     {
00162                         ShowExceptionMessage(e);
00163                     }
00164                 });
00165             }
00166         }
00167     })));
00168 }
00169
00170 void AdvancedCapture::RecordLimitationExceeded(Windows::Media::Capture::MediaCapture ^currentCaptureObject)
00171 {
00172     try
00173     {
00174         if (m_bRecording)
00175         {
00176             create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([this]()
00177             {
00178                 try
00179                 {
00180                     ShowStatusMessage("Stopping Record on exceeding max record duration");
00181                     EnableButton(false, "StartStopRecord");
00182                     create_task(m_mediaCaptureMgr->StopRecordAsync()).then([this](task<void> recordTask)
00183                     {
00184                         try
00185                         {
00186                             recordTask.get();
00187                             m_bRecording = false;
00188                             SwitchRecordButtonContent();
00189                             EnableButton(true, "StartStopRecord");
00190                             ShowStatusMessage("Stopped record on exceeding max record duration:" + m_recordStorageFile->Path);
00191                         }
00192                         catch (Exception ^e)
00193                         {
00194                             ShowExceptionMessage(e);
00195                             m_bRecording = false;
00196                             SwitchRecordButtonContent();
00197                             EnableButton(true, "StartStopRecord");
00198                         }
00199                     });
00200                 }
00201                 catch (Exception ^e)
00202                 {
00203                     m_bRecording = false;
00204                     SwitchRecordButtonContent();
00205                     EnableButton(true, "StartStopRecord");
00206                     ShowExceptionMessage(e);
00207                 }
00208             })));
00209         }
00210     }
00211     catch (Exception ^e)
00212     {
00213         m_bRecording = false;
00214         SwitchRecordButtonContent();
00215         EnableButton(true, "StartStopRecord");
00216         ShowExceptionMessage(e);
00217     }
00218 }
00219
00220 void AdvancedCapture::Failed(Windows::Media::Capture::MediaCapture ^currentCaptureObject, Windows::Media::Capture::MediaCaptureFailedEventArgs^ currentFailure)
00221 {
00222     String ^message = "Fatal error" + currentFailure->Message;
00223     create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High,
00224         ref new Windows::UI::Core::DispatchedHandler([this, message]()
00225     {
00226         ShowStatusMessage(message);
00227     })));
00228 }
00229
00230 void AdvancedCapture::btnStartDevice_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00231 {
00232     try
00233     {
00234         EnableButton(false, "StartDevice");
00235         ShowStatusMessage("Starting device");
00236         auto mediaCapture = ref new Windows::Media::Capture::MediaCapture();
00237         m_mediaCaptureMgr = mediaCapture;
00238         auto settings = ref new Windows::Media::Capture::MediaCaptureInitializationSettings();
00239         auto chosenDevInfo = m_devInfoCollection->GetAt(EnumedDeviceList2->SelectedIndex);
00240         settings->VideoDeviceId = chosenDevInfo->Id;
00241         if (chosenDevInfo->EnclosureLocation != nullptr && chosenDevInfo->EnclosureLocation->Panel == Windows::Devices::Enumeration::Panel::Back)
00242         {
00243             m_bRotateVideoOnOrientationChange = true;
00244             m_bReversePreviewRotation = false;
00245         }
00246         else if (chosenDevInfo->EnclosureLocation != nullptr && chosenDevInfo->EnclosureLocation->Panel == Windows::Devices::Enumeration::Panel::Front)
00247         {
00248             m_bRotateVideoOnOrientationChange = true;
00249             m_bReversePreviewRotation = true;
00250         }
00251         else
00252         {
00253             m_bRotateVideoOnOrientationChange = false;
00254         }
00255
00256         create_task(mediaCapture->InitializeAsync(settings)).then([this](task<void> initTask)
00257         {
00258             try
00259             {
00260                 initTask.get();
00261
00262                 auto mediaCapture =  m_mediaCaptureMgr.Get();
00263
00264                 DisplayProperties_OrientationChanged(nullptr);
00265
00266                 EnableButton(true, "StartPreview");
00267                 EnableButton(true, "StartStopRecord");
00268                 EnableButton(true, "TakePhoto");
00269                 ShowStatusMessage("Device initialized successful");
00270                 chkAddRemoveEffect->IsEnabled = true;
00271                 mediaCapture->RecordLimitationExceeded += ref new Windows::Media::Capture::RecordLimitationExceededEventHandler(this, &AdvancedCapture::RecordLimitationExceeded);
00272                 mediaCapture->Failed += ref new Windows::Media::Capture::MediaCaptureFailedEventHandler(this, &AdvancedCapture::Failed);
00273             }
00274             catch (Exception ^ e)
00275             {
00276                 ShowExceptionMessage(e);
00277             }
00278         });
00279     }
00280     catch (Platform::Exception^ e)
00281     {
00282         ShowExceptionMessage(e);
00283     }
00284 }
00285
00286 void AdvancedCapture::btnStartPreview_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00287 {
00288     m_bPreviewing = false;
00289     try
00290     {
00291         ShowStatusMessage("Starting preview");
00292         EnableButton(false, "StartPreview");
00293
00294         auto mediaCapture = m_mediaCaptureMgr.Get();
00295         previewCanvas2->Visibility = Windows::UI::Xaml::Visibility::Visible;
00296         previewElement2->Source = mediaCapture;
00297         create_task(mediaCapture->StartPreviewAsync()).then([this](task<void> previewTask)
00298         {
00299             try
00300             {
00301                 previewTask.get();
00302                 m_bPreviewing = true;
00303                 ShowStatusMessage("Start preview successful");
00304             }
00305             catch (Exception ^e)
00306             {
00307                 ShowExceptionMessage(e);
00308             }
00309         });
00310     }
00311     catch (Platform::Exception^ e)
00312     {
00313         m_bPreviewing = false;
00314         previewElement2->Source = nullptr;
00315         EnableButton(true, "StartPreview");
00316         ShowExceptionMessage(e);
00317     }
00318 }
00319
00320 void AdvancedCapture::btnTakePhoto_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00321 {
00322     try
00323     {
00324         ShowStatusMessage("Taking photo");
00325         EnableButton(false, "TakePhoto");
00326         auto currentRotation = GetCurrentPhotoRotation();
00327
00328         task<StorageFile^>(KnownFolders::PicturesLibrary->CreateFileAsync(TEMP_PHOTO_FILE_NAME, Windows::Storage::CreationCollisionOption::GenerateUniqueName)).then([this, currentRotation](task<StorageFile^> getFileTask)
00329         {
00330             try
00331             {
00332                 auto tempPhotoStorageFile = getFileTask.get();
00333                 ShowStatusMessage("Create photo file successful");
00334                 ImageEncodingProperties^ imageProperties = ImageEncodingProperties::CreateJpeg();
00335
00336                 create_task(m_mediaCaptureMgr->CapturePhotoToStorageFileAsync(imageProperties, tempPhotoStorageFile)).then([this,tempPhotoStorageFile,currentRotation](task<void> photoTask)
00337                 {
00338                     try
00339                     {
00340                         photoTask.get();
00341
00342                         ReencodePhotoAsync(tempPhotoStorageFile, currentRotation).then([this] (task<StorageFile^> reencodeImageTask)
00343                         {
00344                             try
00345                             {
00346                                 auto photoStorageFile = reencodeImageTask.get();
00347
00348                                 EnableButton(true, "TakePhoto");
00349                                 ShowStatusMessage("Photo taken");
00350
00351                                 task<IRandomAccessStream^>(photoStorageFile->OpenAsync(FileAccessMode::Read)).then([this](task<IRandomAccessStream^> getStreamTask)
00352                                 {
00353                                     try
00354                                     {
00355                                         auto photoStream = getStreamTask.get();
00356                                         ShowStatusMessage("File open successful");
00357                                         auto bmpimg = ref new BitmapImage();
00358
00359                                         bmpimg->SetSource(photoStream);
00360                                         imageElement2->Source = bmpimg;
00361                                     }
00362                                     catch (Exception^ e)
00363                                     {
00364                                         ShowExceptionMessage(e);
00365                                         EnableButton(true, "TakePhoto");
00366                                     }
00367                                 });
00368                             }
00369                             catch (Platform::Exception ^ e)
00370                             {
00371                                 ShowExceptionMessage(e);
00372                                 EnableButton(true, "TakePhoto");
00373                             }
00374                         });
00375                     }
00376                     catch (Platform::Exception ^ e)
00377                     {
00378                         ShowExceptionMessage(e);
00379                         EnableButton(true, "TakePhoto");
00380                     }
00381                 });
00382             }
00383             catch (Exception^ e)
00384             {
00385                 ShowExceptionMessage(e);
00386                 EnableButton(true, "TakePhoto");
00387
00388             }
00389         });
00390     }
00391     catch (Platform::Exception^ e)
00392     {
00393         ShowExceptionMessage(e);
00394         EnableButton(true, "TakePhoto");
00395     }
00396 }
00397
00398 void AdvancedCapture::btnStartStopRecord_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00399 {
00400     try
00401     {
00402         String ^fileName;
00403         EnableButton(false, "StartStopRecord");
00404
00405         if (!m_bRecording)
00406         {
00407             ShowStatusMessage("Starting Record");
00408
00409             fileName = VIDEO_FILE_NAME;
00410
00411             PrepareForVideoRecording();
00412
00413             task<StorageFile^>(KnownFolders::VideosLibrary->CreateFileAsync(fileName, Windows::Storage::CreationCollisionOption::GenerateUniqueName)).then([this](task<StorageFile^> fileTask)
00414             {
00415                 try
00416                 {
00417                     this->m_recordStorageFile = fileTask.get();
00418                     ShowStatusMessage("Create record file successful");
00419
00420                     MediaEncodingProfile^ recordProfile= nullptr;
00421                     recordProfile = MediaEncodingProfile::CreateMp4(Windows::Media::MediaProperties::VideoEncodingQuality::Auto);
00422
00423                     create_task(m_mediaCaptureMgr->StartRecordToStorageFileAsync(recordProfile, this->m_recordStorageFile)).then([this](task<void> recordTask)
00424                     {
00425                         try
00426                         {
00427                             recordTask.get();
00428                             m_bRecording = true;
00429                             SwitchRecordButtonContent();
00430                             EnableButton(true, "StartStopRecord");
00431
00432                             ShowStatusMessage("Start Record successful");
00433                         }
00434                         catch (Exception ^e)
00435                         {
00436                             m_bRecording = true;
00437                             SwitchRecordButtonContent();
00438                             EnableButton(true, "StartStopRecord");
00439                             ShowExceptionMessage(e);
00440                         }
00441                     });
00442                 }
00443                 catch (Exception ^e)
00444                 {
00445                     m_bRecording = false;
00446                     EnableButton(true, "StartStopRecord");
00447                     ShowExceptionMessage(e);
00448                 }
00449             });
00450         }
00451         else
00452         {
00453             ShowStatusMessage("Stopping Record");
00454
00455             create_task(m_mediaCaptureMgr->StopRecordAsync()).then([this](task<void> recordTask)
00456             {
00457                 try
00458                 {
00459                     recordTask.get();
00460                     m_bRecording = false;
00461                     EnableButton(true, "StartStopRecord");
00462                     SwitchRecordButtonContent();
00463
00464                     ShowStatusMessage("Stop record successful");
00465                     if (!m_bSuspended)
00466                     {
00467                         task<IRandomAccessStream^>(this->m_recordStorageFile->OpenAsync(FileAccessMode::Read)).then([this](task<IRandomAccessStream^> streamTask)
00468                         {
00469                             try
00470                             {
00471                                 auto stream = streamTask.get();
00472                                 ShowStatusMessage("Record file opened");
00473                                 ShowStatusMessage(this->m_recordStorageFile->Path);
00474                                 playbackElement2->AutoPlay = true;
00475                                 playbackElement2->SetSource(stream, this->m_recordStorageFile->FileType);
00476                                 playbackElement2->Play();
00477                             }
00478                             catch (Exception ^e)
00479                             {
00480                                 ShowExceptionMessage(e);
00481                                 m_bRecording = false;
00482                                 EnableButton(true, "StartStopRecord");
00483                                 SwitchRecordButtonContent();
00484                             }
00485                         });
00486                     }
00487                 }
00488                 catch (Exception ^e)
00489                 {
00490                     m_bRecording = false;
00491                     EnableButton(true, "StartStopRecord");
00492                     SwitchRecordButtonContent();
00493                     ShowExceptionMessage(e);
00494                 }
00495             });
00496         }
00497     }
00498     catch (Platform::Exception^ e)
00499     {
00500         EnableButton(true, "StartStopRecord");
00501         ShowExceptionMessage(e);
00502         m_bRecording = false;
00503         SwitchRecordButtonContent();
00504     }
00505 }
00506 void AdvancedCapture::lstEnumedDevices_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e)
00507 {
00508      if ( m_bPreviewing )
00509      {
00510          create_task(m_mediaCaptureMgr->StopPreviewAsync()).then([this](task<void> previewTask)
00511          {
00512              try
00513              {
00514                  previewTask.get();
00515                  m_bPreviewing = false;
00516              }
00517              catch (Exception ^e)
00518              {
00519                 ShowExceptionMessage(e);
00520              }
00521          });
00522     }
00523
00524     btnStartDevice2->IsEnabled = true;
00525     btnStartPreview2->IsEnabled = false;
00526     btnStartStopRecord2->IsEnabled = false;
00527     m_bRecording = false;
00528     btnStartStopRecord2->Content = "StartRecord";
00529     btnTakePhoto2->IsEnabled = false;
00530     previewElement2->Source = nullptr;
00531     playbackElement2->Source = nullptr;
00532     imageElement2->Source= nullptr;
00533     chkAddRemoveEffect->IsEnabled = false;
00534     chkAddRemoveEffect->IsChecked = false;
00535     m_bEffectAdded = false;
00536     m_bEffectAddedToRecord = false;
00537     m_bEffectAddedToPhoto = false;
00538     ShowStatusMessage("");
00539 }
00540
00541 void AdvancedCapture::EnumerateWebcamsAsync()
00542 {
00543     try
00544     {
00545         ShowStatusMessage("Enumerating Webcams...");
00546         m_devInfoCollection = nullptr;
00547
00548         EnumedDeviceList2->Items->Clear();
00549
00550         task<DeviceInformationCollection^>(DeviceInformation::FindAllAsync(DeviceClass::VideoCapture)).then([this](task<DeviceInformationCollection^> findTask)
00551         {
00552             try
00553             {
00554                 m_devInfoCollection = findTask.get();
00555                 if (m_devInfoCollection == nullptr || m_devInfoCollection->Size == 0)
00556                 {
00557                     ShowStatusMessage("No WebCams found.");
00558                 }
00559                 else
00560                 {
00561                     for(unsigned int i = 0; i < m_devInfoCollection->Size; i++)
00562                     {
00563                         auto devInfo = m_devInfoCollection->GetAt(i);
00564                         EnumedDeviceList2->Items->Append(devInfo->Name);
00565                     }
00566                     EnumedDeviceList2->SelectedIndex = 0;
00567                     ShowStatusMessage("Enumerating Webcams completed successfully.");
00568                     btnStartDevice2->IsEnabled = true;
00569                 }
00570             }
00571             catch (Exception ^e)
00572             {
00573                 ShowExceptionMessage(e);
00574             }
00575         });
00576     }
00577     catch (Platform::Exception^ e)
00578     {
00579         ShowExceptionMessage(e);
00580     }
00581 }
00582
00583 void AdvancedCapture::AddEffectToImageStream()
00584 {
00585     auto mediaCapture = m_mediaCaptureMgr.Get();
00586     Windows::Media::Capture::VideoDeviceCharacteristic charecteristic = mediaCapture->MediaCaptureSettings->VideoDeviceCharacteristic;
00587
00588     if((charecteristic != Windows::Media::Capture::VideoDeviceCharacteristic::AllStreamsIdentical) &&
00589         (charecteristic != Windows::Media::Capture::VideoDeviceCharacteristic::PreviewPhotoStreamsIdentical) &&
00590         (charecteristic != Windows::Media::Capture::VideoDeviceCharacteristic::RecordPhotoStreamsIdentical))
00591     {
00592         Windows::Media::MediaProperties::IMediaEncodingProperties ^props = mediaCapture->VideoDeviceController->GetMediaStreamProperties(Windows::Media::Capture::MediaStreamType::Photo);
00593         if(props->Type->Equals("Image"))
00594         {
00595             //Switch to a video media type instead since we cant add an effect to a image media type
00596             Windows::Foundation::Collections::IVectorView<Windows::Media::MediaProperties::IMediaEncodingProperties^>^ supportedPropsList = mediaCapture->VideoDeviceController->GetAvailableMediaStreamProperties(Windows::Media::Capture::MediaStreamType::Photo);
00597             {
00598                 unsigned int i = 0;
00599                 while (i<  supportedPropsList->Size)
00600                 {
00601                     Windows::Media::MediaProperties::IMediaEncodingProperties^ props = supportedPropsList->GetAt(i);
00602
00603                     String^ s = props->Type;
00604                     if(props->Type->Equals("Video"))
00605                     {
00606                         task<void>(mediaCapture->VideoDeviceController->SetMediaStreamPropertiesAsync(Windows::Media::Capture::MediaStreamType::Photo,props)).then([this](task<void> changeTypeTask)
00607                         {
00608                             try
00609                             {
00610                                 changeTypeTask.get();
00611                                 ShowStatusMessage("Change type on photo stream successful");
00612                                 //Now add the effect on the image pin
00613                                 task<void>(m_mediaCaptureMgr->AddEffectAsync(Windows::Media::Capture::MediaStreamType::Photo,"GrayscaleTransform.GrayscaleEffect", nullptr)).then([this](task<void> effectTask3)
00614                                 {
00615                                     try
00616                                     {
00617                                         effectTask3.get();
00618                                         m_bEffectAddedToPhoto = true;
00619                                         ShowStatusMessage("Adding effect to photo stream successful");
00620                                         chkAddRemoveEffect->IsEnabled = true;
00621
00622                                     }
00623                                     catch(Exception ^e)
00624                                     {
00625                                         ShowExceptionMessage(e);
00626                                         chkAddRemoveEffect->IsEnabled = true;
00627                                         chkAddRemoveEffect->IsChecked = false;
00628                                     }
00629                                 });
00630
00631                             }
00632                             catch(Exception ^e)
00633                             {
00634                                 ShowExceptionMessage(e);
00635                                 chkAddRemoveEffect->IsEnabled = true;
00636                                 chkAddRemoveEffect->IsChecked = false;
00637
00638                             }
00639
00640                         });
00641                         break;
00642
00643                     }
00644                     i++;
00645                 }
00646             }
00647         }
00648         else
00649         {
00650             //Add the effect to the image pin if the type is already "Video"
00651             task<void>(mediaCapture->AddEffectAsync(Windows::Media::Capture::MediaStreamType::Photo,"GrayscaleTransform.GrayscaleEffect", nullptr)).then([this](task<void> effectTask3)
00652             {
00653                 try
00654                 {
00655                     effectTask3.get();
00656                     m_bEffectAddedToPhoto = true;
00657                     ShowStatusMessage("Adding effect to photo stream successful");
00658                     chkAddRemoveEffect->IsEnabled = true;
00659
00660                 }
00661                 catch(Exception ^e)
00662                 {
00663                     ShowExceptionMessage(e);
00664                     chkAddRemoveEffect->IsEnabled = true;
00665                     chkAddRemoveEffect->IsChecked = false;
00666                 }
00667             });
00668         }
00669     }
00670 }
00671
00672
00673
00674 void AdvancedCapture::chkAddRemoveEffect_Checked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00675 {
00676     try
00677     {
00678         chkAddRemoveEffect->IsEnabled = false;
00679         m_bEffectAdded = true;
00680         create_task(m_mediaCaptureMgr->AddEffectAsync(Windows::Media::Capture::MediaStreamType::VideoPreview,"GrayscaleTransform.GrayscaleEffect", nullptr)).then([this](task<void> effectTask)
00681         {
00682             try
00683             {
00684                 effectTask.get();
00685
00686                 auto mediaCapture = m_mediaCaptureMgr.Get();
00687                 Windows::Media::Capture::VideoDeviceCharacteristic charecteristic = mediaCapture->MediaCaptureSettings->VideoDeviceCharacteristic;
00688
00689                 ShowStatusMessage("Add effect successful to preview stream successful");
00690                 if((charecteristic != Windows::Media::Capture::VideoDeviceCharacteristic::AllStreamsIdentical) &&
00691                     (charecteristic != Windows::Media::Capture::VideoDeviceCharacteristic::PreviewRecordStreamsIdentical))
00692                 {
00693                     Windows::Media::MediaProperties::IMediaEncodingProperties ^props = mediaCapture->VideoDeviceController->GetMediaStreamProperties(Windows::Media::Capture::MediaStreamType::VideoRecord);
00694                     Windows::Media::MediaProperties::VideoEncodingProperties ^videoEncodingProperties  = static_cast<Windows::Media::MediaProperties::VideoEncodingProperties ^>(props);
00695                     if(!videoEncodingProperties->Subtype->Equals("H264")) //Cant add an effect to an H264 stream
00696                     {
00697                         task<void>(mediaCapture->AddEffectAsync(Windows::Media::Capture::MediaStreamType::VideoRecord,"GrayscaleTransform.GrayscaleEffect", nullptr)).then([this](task<void> effectTask2)
00698                         {
00699                             try
00700                             {
00701                                 effectTask2.get();
00702                                 ShowStatusMessage("Add effect successful to record stream successful");
00703                                 m_bEffectAddedToRecord = true;
00704                                 AddEffectToImageStream();
00705                                 chkAddRemoveEffect->IsEnabled = true;
00706                             }
00707                             catch(Exception ^e)
00708                             {
00709                                 ShowExceptionMessage(e);
00710                                 chkAddRemoveEffect->IsEnabled = true;
00711                                 chkAddRemoveEffect->IsChecked = false;
00712                             }
00713                         });
00714                     }
00715                     else
00716                     {
00717                         AddEffectToImageStream();
00718                         chkAddRemoveEffect->IsEnabled = true;
00719                     }
00720
00721                 }
00722                 else
00723                 {
00724                     AddEffectToImageStream();
00725                     chkAddRemoveEffect->IsEnabled = true;
00726                 }
00727             }
00728             catch (Exception ^e)
00729             {
00730                 ShowExceptionMessage(e);
00731                 chkAddRemoveEffect->IsEnabled = true;
00732                 chkAddRemoveEffect->IsChecked = false;
00733             }
00734         });
00735     }
00736     catch (Platform::Exception ^e)
00737     {
00738         ShowExceptionMessage(e);
00739         chkAddRemoveEffect->IsEnabled = true;
00740         chkAddRemoveEffect->IsChecked = false;
00741     }
00742 }
00743
00744 void AdvancedCapture::chkAddRemoveEffect_Unchecked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00745 {
00746     try
00747     {
00748         chkAddRemoveEffect->IsEnabled = false;
00749         m_bEffectAdded = false;
00750         create_task(m_mediaCaptureMgr->ClearEffectsAsync(Windows::Media::Capture::MediaStreamType::VideoPreview)).then([this](task<void> effectTask)
00751         {
00752             try
00753             {
00754                 effectTask.get();
00755                 ShowStatusMessage("Remove effect from video preview stream successful");
00756                 if(m_bEffectAddedToRecord)
00757                 {
00758                     task<void>(m_mediaCaptureMgr->ClearEffectsAsync(Windows::Media::Capture::MediaStreamType::VideoRecord)).then([this](task<void> effectTask)
00759                     {
00760                         try
00761                         {
00762                             effectTask.get();
00763                             ShowStatusMessage("Remove effect from video record stream successful");
00764                             m_bEffectAddedToRecord = false;
00765                             if(m_bEffectAddedToPhoto)
00766                             {
00767                                 task<void>(m_mediaCaptureMgr->ClearEffectsAsync(Windows::Media::Capture::MediaStreamType::Photo)).then([this](task<void> effectTask)
00768                                 {
00769                                     try
00770                                     {
00771                                         effectTask.get();
00772                                         ShowStatusMessage("Remove effect from Photo stream successful");
00773                                         m_bEffectAddedToPhoto = false;
00774
00775                                     }
00776                                     catch(Exception ^e)
00777                                     {
00778                                         ShowExceptionMessage(e);
00779                                         chkAddRemoveEffect->IsEnabled = true;
00780                                         chkAddRemoveEffect->IsChecked = true;
00781                                     }
00782
00783                                 });
00784                             }
00785                             else
00786                             {
00787                             }
00788                             chkAddRemoveEffect->IsEnabled = true;
00789                         }
00790                         catch(Exception ^e)
00791                         {
00792                             ShowExceptionMessage(e);
00793                             chkAddRemoveEffect->IsEnabled = true;
00794                             chkAddRemoveEffect->IsChecked = true;
00795
00796                         }
00797
00798                     });
00799
00800                 }
00801                 else if(m_bEffectAddedToPhoto)
00802                 {
00803                     task<void>(m_mediaCaptureMgr->ClearEffectsAsync(Windows::Media::Capture::MediaStreamType::Photo)).then([this](task<void> effectTask)
00804                     {
00805                         try
00806                         {
00807                             effectTask.get();
00808                             ShowStatusMessage("Remove effect from Photo stream successful");
00809                             m_bEffectAddedToPhoto = false;
00810
00811                         }
00812                         catch(Exception ^e)
00813                         {
00814                             ShowExceptionMessage(e);
00815                             chkAddRemoveEffect->IsEnabled = true;
00816                             chkAddRemoveEffect->IsChecked = true;
00817                         }
00818
00819                     });
00820                 }
00821                 else
00822                 {
00823                     chkAddRemoveEffect->IsEnabled = true;
00824                     chkAddRemoveEffect->IsChecked = true;
00825                 }
00826             }
00827             catch (Exception ^e)
00828             {
00829                 ShowExceptionMessage(e);
00830                 chkAddRemoveEffect->IsEnabled = true;
00831                 chkAddRemoveEffect->IsChecked = true;
00832             }
00833         });
00834     }
00835     catch (Platform::Exception ^e)
00836     {
00837         ShowExceptionMessage(e);
00838         chkAddRemoveEffect->IsEnabled = true;
00839         chkAddRemoveEffect->IsChecked = true;
00840     }
00841 }
00842
00843 void AdvancedCapture::ShowStatusMessage(Platform::String^ text)
00844 {
00845     rootPage->NotifyUser(text, NotifyType::StatusMessage);
00846 }
00847
00848 void AdvancedCapture::ShowExceptionMessage(Platform::Exception^ ex)
00849 {
00850     rootPage->NotifyUser(ex->Message, NotifyType::ErrorMessage);
00851 }
00852
00853 void AdvancedCapture::SwitchRecordButtonContent()
00854 {
00855     if (m_bRecording)
00856     {
00857         btnStartStopRecord2->Content="StopRecord";
00858     }
00859     else
00860     {
00861         btnStartStopRecord2->Content="StartRecord";
00862     }
00863 }
00864
00865 void AdvancedCapture::EnableButton(bool enabled, String^ name)
00866 {
00867     if (name->Equals("StartDevice"))
00868     {
00869         btnStartDevice2->IsEnabled = enabled;
00870     }
00871     else if (name->Equals("StartPreview"))
00872     {
00873         btnStartPreview2->IsEnabled = enabled;
00874     }
00875     else if (name->Equals("StartStopRecord"))
00876     {
00877         btnStartStopRecord2->IsEnabled = enabled;
00878     }
00879     else if (name->Equals("TakePhoto"))
00880     {
00881         btnTakePhoto2->IsEnabled = enabled;
00882     }
00883 }
00884
00885 task<Windows::Storage::StorageFile^> AdvancedCapture::ReencodePhotoAsync(
00886     Windows::Storage::StorageFile ^tempStorageFile,
00887     Windows::Storage::FileProperties::PhotoOrientation photoRotation)
00888 {
00889     ReencodeState ^state = ref new ReencodeState();
00890
00891     return create_task(tempStorageFile->OpenAsync(Windows::Storage::FileAccessMode::Read)).then([state](Windows::Storage::Streams::IRandomAccessStream ^stream)
00892     {
00893         state->InputStream = stream;
00894         return Windows::Graphics::Imaging::BitmapDecoder::CreateAsync(state->InputStream);
00895     }).then([state](Windows::Graphics::Imaging::BitmapDecoder ^decoder)
00896     {
00897         state->Decoder = decoder;
00898         return Windows::Storage::KnownFolders::PicturesLibrary->CreateFileAsync(PHOTO_FILE_NAME, Windows::Storage::CreationCollisionOption::GenerateUniqueName);
00899     }).then([state](Windows::Storage::StorageFile ^storageFile)
00900     {
00901         state->PhotoStorage = storageFile;
00902         return state->PhotoStorage->OpenAsync(Windows::Storage::FileAccessMode::ReadWrite);
00903     }).then([state](Windows::Storage::Streams::IRandomAccessStream ^stream)
00904     {
00905         state->OutputStream = stream;
00906         state->OutputStream->Size = 0;
00907         return Windows::Graphics::Imaging::BitmapEncoder::CreateForTranscodingAsync(state->OutputStream, state->Decoder);
00908     }).then([state, photoRotation](Windows::Graphics::Imaging::BitmapEncoder ^encoder)
00909     {
00910         state->Encoder = encoder;
00911         auto properties = ref new Windows::Graphics::Imaging::BitmapPropertySet();
00912         properties->Insert("System.Photo.Orientation",
00913             ref new Windows::Graphics::Imaging::BitmapTypedValue((unsigned short)photoRotation, Windows::Foundation::PropertyType::UInt16));
00914         return create_task(state->Encoder->BitmapProperties->SetPropertiesAsync(properties));
00915     }).then([state]()
00916     {
00917         return state->Encoder->FlushAsync();
00918     }).then([tempStorageFile, state](task<void> previousTask)
00919     {
00920         auto result = state->PhotoStorage;
00921         delete state;
00922
00923         tempStorageFile->DeleteAsync(Windows::Storage::StorageDeleteOption::PermanentDelete);
00924
00925         previousTask.get();
00926
00927         return result;
00928     });
00929 }
00930
00931 Windows::Storage::FileProperties::PhotoOrientation AdvancedCapture::GetCurrentPhotoRotation()
00932 {
00933     bool counterclockwiseRotation = m_bReversePreviewRotation;
00934
00935     if (m_bRotateVideoOnOrientationChange)
00936     {
00937         return PhotoRotationLookup(Windows::Graphics::Display::DisplayProperties::CurrentOrientation, counterclockwiseRotation);
00938     }
00939     else
00940     {
00941         return Windows::Storage::FileProperties::PhotoOrientation::Normal;
00942     }
00943 }
00944
00945 void AdvancedCapture::PrepareForVideoRecording()
00946 {
00947     Windows::Media::Capture::MediaCapture ^mediaCapture = m_mediaCaptureMgr.Get();
00948     if (mediaCapture == nullptr)
00949     {
00950         return;
00951     }
00952
00953     bool counterclockwiseRotation = m_bReversePreviewRotation;
00954
00955     if (m_bRotateVideoOnOrientationChange)
00956     {
00957         mediaCapture->SetRecordRotation(VideoRotationLookup(Windows::Graphics::Display::DisplayProperties::CurrentOrientation, counterclockwiseRotation));
00958     }
00959     else
00960     {
00961         mediaCapture->SetRecordRotation(Windows::Media::Capture::VideoRotation::None);
00962     }
00963 }
00964
00965 void AdvancedCapture::DisplayProperties_OrientationChanged(Platform::Object^ sender)
00966 {
00967     Windows::Media::Capture::MediaCapture ^mediaCapture = m_mediaCaptureMgr.Get();
00968     if (mediaCapture == nullptr)
00969     {
00970         return;
00971     }
00972
00973     bool previewMirroring = mediaCapture->GetPreviewMirroring();
00974     bool counterclockwiseRotation = (previewMirroring && !m_bReversePreviewRotation) ||
00975         (!previewMirroring && m_bReversePreviewRotation);
00976
00977     if (m_bRotateVideoOnOrientationChange)
00978     {
00979         mediaCapture->SetPreviewRotation(VideoRotationLookup(Windows::Graphics::Display::DisplayProperties::CurrentOrientation, counterclockwiseRotation));
00980     }
00981     else
00982     {
00983         mediaCapture->SetPreviewRotation(Windows::Media::Capture::VideoRotation::None);
00984     }
00985 }
00986
00987 Windows::Storage::FileProperties::PhotoOrientation AdvancedCapture::PhotoRotationLookup(
00988     Windows::Graphics::Display::DisplayOrientations displayOrientation, bool counterclockwise)
00989 {
00990     switch (displayOrientation)
00991     {
00992     case Windows::Graphics::Display::DisplayOrientations::Landscape:
00993         return Windows::Storage::FileProperties::PhotoOrientation::Normal;
00994
00995     case Windows::Graphics::Display::DisplayOrientations::Portrait:
00996         return (counterclockwise) ? Windows::Storage::FileProperties::PhotoOrientation::Rotate270:
00997             Windows::Storage::FileProperties::PhotoOrientation::Rotate90;
00998
00999     case Windows::Graphics::Display::DisplayOrientations::LandscapeFlipped:
01000         return Windows::Storage::FileProperties::PhotoOrientation::Rotate180;
01001
01002     case Windows::Graphics::Display::DisplayOrientations::PortraitFlipped:
01003         return (counterclockwise) ? Windows::Storage::FileProperties::PhotoOrientation::Rotate90 :
01004             Windows::Storage::FileProperties::PhotoOrientation::Rotate270;
01005
01006     default:
01007         return Windows::Storage::FileProperties::PhotoOrientation::Unspecified;
01008     }
01009 }
01010
01011 Windows::Media::Capture::VideoRotation AdvancedCapture::VideoRotationLookup(
01012     Windows::Graphics::Display::DisplayOrientations displayOrientation, bool counterclockwise)
01013 {
01014     switch (displayOrientation)
01015     {
01016     case Windows::Graphics::Display::DisplayOrientations::Landscape:
01017         return Windows::Media::Capture::VideoRotation::None;
01018
01019     case Windows::Graphics::Display::DisplayOrientations::Portrait:
01020         return (counterclockwise) ? Windows::Media::Capture::VideoRotation::Clockwise270Degrees :
01021             Windows::Media::Capture::VideoRotation::Clockwise90Degrees;
01022
01023     case Windows::Graphics::Display::DisplayOrientations::LandscapeFlipped:
01024         return Windows::Media::Capture::VideoRotation::Clockwise180Degrees;
01025
01026     case Windows::Graphics::Display::DisplayOrientations::PortraitFlipped:
01027         return (counterclockwise) ? Windows::Media::Capture::VideoRotation::Clockwise90Degrees:
01028             Windows::Media::Capture::VideoRotation::Clockwise270Degrees ;
01029
01030     default:
01031         return Windows::Media::Capture::VideoRotation::None;
01032     }
01033 }
01034
Generated on Sat Nov 23 2024 16:08:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::SimpleOrientationSensorCPP::sealed Member List

This is the complete list of members for SDKSample::SimpleOrientationSensorCPP::sealed, including all inherited members.
DisplayOrientation(Windows::Devices::Sensors::SimpleOrientation orientation) | SDKSample::SimpleOrientationSensorCPP::sealed | [private]
DisplayOrientation(Windows::Devices::Sensors::SimpleOrientation orientation) | SDKSample::SimpleOrientationSensorCPP::sealed | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::SimpleOrientationSensorCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::SimpleOrientationSensorCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::SimpleOrientationSensorCPP::sealed | [protected, virtual]
OrientationChanged(Windows::Devices::Sensors::SimpleOrientationSensor^sender, Windows::Devices::Sensors::SimpleOrientationSensorOrientationChangedEventArgs^e) | SDKSample::SimpleOrientationSensorCPP::sealed | [private]
orientationToken | SDKSample::SimpleOrientationSensorCPP::sealed | [private]
rootPage | SDKSample::SimpleOrientationSensorCPP::sealed | [private]
Scenario1() | SDKSample::SimpleOrientationSensorCPP::sealed |
Scenario2() | SDKSample::SimpleOrientationSensorCPP::sealed |
ScenarioDisable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::SimpleOrientationSensorCPP::sealed | [private]
ScenarioEnable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::SimpleOrientationSensorCPP::sealed | [private]
ScenarioGet(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::SimpleOrientationSensorCPP::sealed | [private]
sensor | SDKSample::SimpleOrientationSensorCPP::sealed | [private]
VisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | SDKSample::SimpleOrientationSensorCPP::sealed | [private]
visibilityToken | SDKSample::SimpleOrientationSensorCPP::sealed | [private]
Generated on Sat Nov 23 2024 16:09:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Print/C++/pch.h Source File

  • Print

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 //
00009 // pch.h
00010 // Header for standard system include files.
00011 //
00012
00013 #pragma once
00014 #include "CppSamplesUtils.h"
00015 #include "BasePrintPage.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite hello world/C++/SampleOverlay.h Source File

  • DirectWrite hello world

SampleOverlay.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 "DirectXSample.h"
00011
00012 // This class is responsible for initializing and rendering the title overlay visible
00013 // at the top of the DirectX SDK samples.
00014 ref class SampleOverlay
00015 {
00016 internal:
00017     SampleOverlay();
00018
00019     void Initialize(
00020         _In_ ID2D1Device*         d2dDevice,
00021         _In_ ID2D1DeviceContext*  d2dContext,
00022         _In_ IWICImagingFactory*  wicFactory,
00023         _In_ IDWriteFactory*      dwriteFactory,
00024         _In_ Platform::String^    caption
00025         );
00026
00027     void ResetDirectXResources();
00028
00029     void UpdateForWindowSizeChange();
00030
00031     void Render();
00032
00033     float GetTitleHeightInDips();
00034
00035 private:
00036
00037     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00038     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00039     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00040     Microsoft::WRL::ComPtr<IDWriteFactory>          m_dwriteFactory;
00041     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_whiteBrush;
00042     Microsoft::WRL::ComPtr<ID2D1DrawingStateBlock>  m_stateBlock;
00043
00044     Microsoft::WRL::ComPtr<IWICImagingFactory>      m_wicFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Bitmap>             m_logoBitmap;
00046     Microsoft::WRL::ComPtr<IDWriteTextLayout>       m_textLayout;
00047
00048     UINT                                            m_idIncrement;
00049     bool                                            m_drawOverlay;
00050     Platform::String^                               m_sampleName;
00051     float                                           m_padding;
00052     float                                           m_textVerticalOffset;
00053     D2D1_SIZE_F                                     m_logoSize;
00054     float                                           m_overlayWidth;
00055 };
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Secondary tiles/C#,C++/SecondaryTileNotification.xaml.cpp Source File

  • Secondary tiles
  • C#,C++

SecondaryTileNotification.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 // SecondaryTileNotification.xaml.cpp
00013 // Implementation of the SecondaryTileNotification class
00014 //
00015
00016 #include "pch.h"
00017 #include "SecondaryTileNotification.xaml.h"
00018
00019 using namespace SecondaryTiles;
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::UI::StartScreen;
00025 using namespace Windows::Foundation;
00026 using namespace Platform;
00027 using namespace concurrency;
00028 using namespace Windows::UI::Notifications;
00029 using namespace NotificationsExtensions::TileContent;
00030 using namespace NotificationsExtensions::BadgeContent;
00031 using namespace Windows::Data::Xml::Dom;
00032 using namespace Windows::Globalization;
00033 using namespace Windows::Globalization::DateTimeFormatting;
00034
00035 SecondaryTileNotification::SecondaryTileNotification()
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 void SecondaryTileNotification::OnNavigatedTo(NavigationEventArgs^ e)
00046 {
00047     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00048     // as NotifyUser()
00049     rootPage = MainPage::current;
00050     ToggleButtons(SecondaryTile::Exists(rootPage->dynamicTileId));
00051     // Preserve the app bar
00052     appBar = rootPage->BottomAppBar;
00053     // Now null it so we don't show the appbar in this scenario
00054     rootPage->BottomAppBar = nullptr;
00055 }
00056
00057 /// <summary>
00058 /// Invoked when this page is about to be navigated out 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 void SecondaryTileNotification::OnNavigatingFrom(NavigatingCancelEventArgs^ e)
00063 {
00064     // Restore the app bar
00065     rootPage->BottomAppBar = appBar;
00066 }
00067
00068 void SecondaryTileNotification::ToggleButtons(bool isEnabled)
00069 {
00070     SendTileNotification->IsEnabled = isEnabled;
00071     SendBadgeNotification->IsEnabled = isEnabled;
00072     SendTileNotificationString->IsEnabled = isEnabled;
00073     SendBadgeNotificationString->IsEnabled = isEnabled;
00074 }
00075
00076 void SecondaryTiles::SecondaryTileNotification::PinLiveTile_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00077 {
00078     Button^ button = safe_cast<Button^>(sender);
00079     if (button != nullptr)
00080     {
00081         // Prepare package images for use as the Tile Logo and small logo in the tile to be pinned.
00082         // The path provided is a relative path to the package
00083         auto logo = ref new Uri("ms-appx:///Assets/squareTile-sdk.png");
00084         auto wideLogo = ref new Uri("ms-appx:///Assets/tile-sdk.png");
00085
00086         Calendar^ cal = ref new Calendar();
00087         auto longtime = ref new DateTimeFormatter("longtime");
00088         DateTime time = cal->GetDateTime();
00089
00090         // During creation of secondary tile, an application may set additional arguments on the tile that will be passed in during activation.
00091         // These arguments should be meaningful to the application. In this sample, we will just pass a text as an argument.
00092         String^ tileActivationArguments = rootPage->dynamicTileId + " WasPinnedAt=" + longtime->Format(time);
00093
00094         auto secondaryTile = ref new SecondaryTile(rootPage->dynamicTileId,
00095             "Live Secondary Tile", //short tile name (will be displayed on the tile)
00096             "SDK Sample Live Secondary Tile", // Long tile name (for search, tooltip)
00097             tileActivationArguments,
00098             Windows::UI::StartScreen::TileOptions::None,
00099             logo,
00100             wideLogo);
00101
00102         // The tile background color is inherited from the parent unless a separate value is specified.
00103         // This operation will over-ride the default.
00104         secondaryTile->ForegroundText = ForegroundText::Light;
00105
00106             // OK, the tile is created and we can now attempt to pin the tile.
00107             // Note that the status message is updated when the async operation to pin the tile completes.
00108             auto const rect = rootPage->GetElementRect(safe_cast<FrameworkElement^>(sender));
00109             create_task(secondaryTile->RequestCreateForSelectionAsync(rect, Windows::UI::Popups::Placement::Below)).then([this](bool isCreated)
00110             {
00111                 if (isCreated)
00112                 {
00113                     rootPage->NotifyUser("Secondary tile successfully pinned.", NotifyType::StatusMessage);
00114                     ToggleButtons(true);
00115                 }
00116                 else
00117                 {
00118                     rootPage->NotifyUser("Secondary tile not pinned.", NotifyType::ErrorMessage);
00119                 }
00120             });
00121         }
00122 }
00123
00124 void SecondaryTiles::SecondaryTileNotification::SendTileNotification_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00125 {
00126     Button^ button = safe_cast<Button^>(sender);
00127     if (button != nullptr)
00128     {
00129         if (SecondaryTile::Exists(rootPage->dynamicTileId))
00130         {
00131             // Note: This sample contains an additional reference, NotificationsExtensions, which you can use in your apps
00132             auto tileContent = TileContentFactory::CreateTileWideText04();
00133             tileContent->TextBodyWrap->Text = "Sent to a secondary tile from NotificationsExtensions!";
00134
00135             auto squareContent = TileContentFactory::CreateTileSquareText04();
00136         squareContent->TextBodyWrap->Text = "Sent to a secondary tile from NotificationsExtensions!";
00137         tileContent->SquareContent = squareContent;
00138
00139             // Send the notification to the secondary tile by creating a secondary tile updater
00140             TileUpdateManager::CreateTileUpdaterForSecondaryTile(rootPage->dynamicTileId)->Update(tileContent->CreateNotification());
00141
00142             rootPage->NotifyUser("Tile Notification sent to " + rootPage->dynamicTileId + ".", NotifyType::StatusMessage);
00143         }
00144         else
00145         {
00146             ToggleButtons(false);
00147             rootPage->NotifyUser(rootPage->dynamicTileId + " not pinned.", NotifyType::ErrorMessage);
00148         }
00149     }
00150 }
00151
00152 void SecondaryTiles::SecondaryTileNotification::SendBadgeNotification_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00153 {
00154     Button^ button = safe_cast<Button^>(sender);
00155     if (button != nullptr)
00156     {
00157         if (SecondaryTile::Exists(rootPage->dynamicTileId))
00158         {
00159             auto badgeContent = ref new BadgeNumericNotificationContent(6);
00160
00161             // Send the notification to the secondary tile
00162             BadgeUpdateManager::CreateBadgeUpdaterForSecondaryTile(rootPage->dynamicTileId)->Update(badgeContent->CreateNotification());
00163             rootPage->NotifyUser("BadgeNotification sent to " + rootPage->dynamicTileId + ".", NotifyType::StatusMessage);
00164         }
00165         else
00166         {
00167             ToggleButtons(false);
00168             rootPage->NotifyUser(rootPage->dynamicTileId + " not pinned.", NotifyType::ErrorMessage);
00169         }
00170     }
00171 }
00172
00173 void SecondaryTiles::SecondaryTileNotification::SendBadgeNotificationWithStringManipulation_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00174 {
00175     Button^ button = safe_cast<Button^>(sender);
00176     if (button != nullptr)
00177     {
00178         Platform::String^ badgeXmlString = "<badge value='9'/>";
00179         auto badgeDOM = ref new Windows::Data::Xml::Dom::XmlDocument();
00180         badgeDOM->LoadXml(badgeXmlString);
00181         auto badge = ref new BadgeNotification(badgeDOM);
00182
00183         // Send the notification to the secondary tile
00184         BadgeUpdateManager::CreateBadgeUpdaterForSecondaryTile(rootPage->dynamicTileId)->Update(badge);
00185
00186         rootPage->NotifyUser("BadgeNotification sent to " + rootPage->dynamicTileId + ".", NotifyType::StatusMessage);
00187     }
00188 }
00189
00190
00191 void SecondaryTiles::SecondaryTileNotification::SendTileNotificationWithStringManipulation_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00192 {
00193     Button^ button = safe_cast<Button^>(sender);
00194     if (button != nullptr)
00195     {
00196         auto tileXmlString = "<tile>"
00197             +  "<visual>"
00198             +   "<binding template='TileWideText04'>"
00199             +    "<text id='1'>Send to a secondary tile from strings</text>"
00200             +   "</binding>"
00201             +   "<binding template='TileSquareText04'>"
00202             +    "<text id='1'>Send to a secondary tile from strings</text>"
00203             +   "</binding>"
00204             +  "</visual>"
00205             + "</tile>";
00206
00207         auto tileDOM = ref new Windows::Data::Xml::Dom::XmlDocument();
00208         tileDOM->LoadXml(tileXmlString);
00209         auto tile = ref new TileNotification(tileDOM);
00210
00211         // Send the notification to the secondary tile by creating a secondary tile updater
00212         TileUpdateManager::CreateTileUpdaterForSecondaryTile(rootPage->dynamicTileId)->Update(tile);
00213
00214         rootPage->NotifyUser("Tile Notification sent to " + rootPage->dynamicTileId + ".", NotifyType::StatusMessage);
00215     }
00216 }
Generated on Sat Nov 23 2024 16:08:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/CartoonEffect/pch.cpp Source File

  • Hilo C++
  • CartoonEffect

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 #include "pch.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Push and periodic notifications client-side/C++/Scenario2.xaml.h Source File

  • Push and periodic notifications client-side

Scenario2.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 #pragma once
00012
00013 #include "pch.h"
00014 #include "Scenario2.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKSample
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       [Windows::Foundation::Metadata::WebHostHidden]
00025         public ref class Scenario2 sealed
00026         {
00027         public:
00028             Scenario2();
00029
00030         protected:
00031             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00032         private:
00033             MainPage^ rootPage;
00034             void RenewChannelsButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00035             void RegisterTaskButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00036         void UnregisterTaskButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00037
00038         Windows::ApplicationModel::Background::IBackgroundTaskRegistration^ GetRegisteredTask();
00039         };
00040     }
00041 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File picker/C++/Scenario4.xaml.h Source File

  • File picker

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
00022 namespace SDKSample
00023 {
00024     namespace FilePicker
00025     {
00026         /// <summary>
00027         /// An empty page that can be used on its own or navigated to within a Frame.
00028         /// </summary>
00029         public ref class Scenario4 sealed
00030         {
00031         public:
00032             Scenario4();
00033
00034         private:
00035             MainPage^ rootPage;
00036
00037             void SaveFileButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038         };
00039     }
00040 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Display orientation/C++/MainPage.xaml.cpp Source File

  • Display orientation

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:42 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

BasicSprites::SpriteRunInfo Member List

This is the complete list of members for BasicSprites::SpriteRunInfo, including all inherited members.
blendState | BasicSprites::SpriteRunInfo
numSprites | BasicSprites::SpriteRunInfo
textureView | BasicSprites::SpriteRunInfo
Generated on Sat Nov 23 2024 16:09:36 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D convolve matrix effect/C++/DirectXBase.cpp Source File

  • Direct2D convolve matrix effect

DirectXBase.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 "DirectXBase.h"
00010
00011 using namespace Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::Graphics::Display;
00015 using namespace D2D1;
00016
00017 // Constructor.
00018 DirectXBase::DirectXBase() :
00019     m_windowSizeChangeInProgress(false),
00020     m_dpi(-1.0f)
00021 {
00022 }
00023
00024 // Initialize the DirectX resources required to run.
00025 void DirectXBase::Initialize(CoreWindow^ window, float dpi)
00026 {
00027     m_window = window;
00028
00029     CreateDeviceIndependentResources();
00030     CreateDeviceResources();
00031     SetDpi(dpi);
00032 }
00033
00034 // Recreate all device resources and set them back to the current state.
00035 void DirectXBase::HandleDeviceLost()
00036 {
00037     // Reset these member variables to ensure that SetDpi recreates all resources.
00038     float dpi = m_dpi;
00039     m_dpi = -1.0f;
00040     m_windowBounds.Width = 0;
00041     m_windowBounds.Height = 0;
00042     m_swapChain = nullptr;
00043
00044     CreateDeviceResources();
00045     SetDpi(dpi);
00046 }
00047
00048 // These are the resources required independent of the device.
00049 void DirectXBase::CreateDeviceIndependentResources()
00050 {
00051     D2D1_FACTORY_OPTIONS options;
00052     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00053
00054 #if defined(_DEBUG)
00055     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00056     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00057 #endif
00058
00059     DX::ThrowIfFailed(
00060         D2D1CreateFactory(
00061             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00062             __uuidof(ID2D1Factory1),
00063             &options,
00064             &m_d2dFactory
00065             )
00066         );
00067
00068     DX::ThrowIfFailed(
00069         DWriteCreateFactory(
00070             DWRITE_FACTORY_TYPE_SHARED,
00071             __uuidof(IDWriteFactory),
00072             &m_dwriteFactory
00073             )
00074         );
00075
00076     DX::ThrowIfFailed(
00077         CoCreateInstance(
00078             CLSID_WICImagingFactory,
00079             nullptr,
00080             CLSCTX_INPROC_SERVER,
00081             IID_PPV_ARGS(&m_wicFactory)
00082             )
00083         );
00084 }
00085
00086 // These are the resources that depend on the device.
00087 void DirectXBase::CreateDeviceResources()
00088 {
00089     // This flag adds support for surfaces with a different color channel ordering
00090     // than the API default. It is required for compatibility with Direct2D.
00091     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00092     ComPtr<IDXGIDevice> dxgiDevice;
00093
00094 #if defined(_DEBUG)
00095     // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00096     creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00097 #endif
00098
00099     // This array defines the set of DirectX hardware feature levels this app will support.
00100     // Note the ordering should be preserved.
00101     // Don't forget to declare your application's minimum required feature level in its
00102     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00103     D3D_FEATURE_LEVEL featureLevels[] =
00104     {
00105         D3D_FEATURE_LEVEL_11_1,
00106         D3D_FEATURE_LEVEL_11_0,
00107         D3D_FEATURE_LEVEL_10_1,
00108         D3D_FEATURE_LEVEL_10_0,
00109         D3D_FEATURE_LEVEL_9_3,
00110         D3D_FEATURE_LEVEL_9_2,
00111         D3D_FEATURE_LEVEL_9_1
00112     };
00113
00114     // Create the Direct3D 11 API device object and a corresponding context.
00115     ComPtr<ID3D11Device> device;
00116     ComPtr<ID3D11DeviceContext> context;
00117     DX::ThrowIfFailed(
00118         D3D11CreateDevice(
00119             nullptr,                    // Specify nullptr to use the default adapter.
00120             D3D_DRIVER_TYPE_HARDWARE,
00121             0,
00122             creationFlags,              // Set debug and Direct2D compatibility flags.
00123             featureLevels,              // List of feature levels this app can support.
00124             ARRAYSIZE(featureLevels),
00125             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Metro style apps.
00126             &device,                    // Returns the Direct3D device created.
00127             &m_featureLevel,            // Returns feature level of device created.
00128             &context                    // Returns the device immediate context.
00129             )
00130         );
00131
00132     // Get the Direct3D 11.1 API device and context interfaces.
00133     DX::ThrowIfFailed(
00134         device.As(&m_d3dDevice)
00135         );
00136
00137     DX::ThrowIfFailed(
00138         context.As(&m_d3dContext)
00139         );
00140
00141     // Get the underlying DXGI device of the Direct3D device.
00142     DX::ThrowIfFailed(
00143         m_d3dDevice.As(&dxgiDevice)
00144         );
00145
00146     // Create the Direct2D device object and a corresponding context.
00147     DX::ThrowIfFailed(
00148         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00149         );
00150
00151     DX::ThrowIfFailed(
00152         m_d2dDevice->CreateDeviceContext(
00153             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00154             &m_d2dContext
00155             )
00156         );
00157 }
00158
00159 // Helps track the DPI in the helper class.
00160 // This is called in the dpiChanged event handler in the view class.
00161 void DirectXBase::SetDpi(float dpi)
00162 {
00163     if (dpi != m_dpi)
00164     {
00165         // Save the DPI of this display in our class.
00166         m_dpi = dpi;
00167
00168         // Update Direct2D's stored DPI.
00169         m_d2dContext->SetDpi(m_dpi, m_dpi);
00170
00171         // Often a DPI change implies a window size change. In some cases Windows will issue
00172         // both a size changed event and a DPI changed event. In this case, the resulting bounds
00173         // will not change, and the window resize code will only be executed once.
00174         UpdateForWindowSizeChange();
00175     }
00176 }
00177
00178 // This routine is called in the event handler for the view SizeChanged event.
00179 void DirectXBase::UpdateForWindowSizeChange()
00180 {
00181     // Only handle window size changed if there is no pending DPI change.
00182     if (m_dpi != DisplayProperties::LogicalDpi)
00183     {
00184         return;
00185     }
00186
00187     if (m_window->Bounds.Width  != m_windowBounds.Width ||
00188         m_window->Bounds.Height != m_windowBounds.Height)
00189     {
00190         m_d2dContext->SetTarget(nullptr);
00191         m_d2dTargetBitmap = nullptr;
00192         m_d3dRenderTargetView = nullptr;
00193         m_d3dDepthStencilView = nullptr;
00194         m_windowSizeChangeInProgress = true;
00195         CreateWindowSizeDependentResources();
00196     }
00197 }
00198
00199 // Allocate all memory resources that change on a window SizeChanged event.
00200 void DirectXBase::CreateWindowSizeDependentResources()
00201 {
00202     // Store the window bounds so the next time we get a SizeChanged event we can
00203     // avoid rebuilding everything if the size is identical.
00204     m_windowBounds = m_window->Bounds;
00205
00206     if (m_swapChain != nullptr)
00207     {
00208         // If the swap chain already exists, resize it.
00209         HRESULT hr = m_swapChain->ResizeBuffers(2, 0, 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0);
00210
00211         if (hr == DXGI_ERROR_DEVICE_REMOVED)
00212         {
00213             // If the device was removed for any reason, a new device and swapchain will need to be created.
00214             HandleDeviceLost();
00215
00216             // Everything is set up now. Do not continue execution of this method.
00217             return;
00218         }
00219         else
00220         {
00221             DX::ThrowIfFailed(hr);
00222         }
00223     }
00224     else
00225     {
00226         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00227         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00228         swapChainDesc.Width = 0;                                     // Use automatic sizing.
00229         swapChainDesc.Height = 0;
00230         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;           // This is the most common swap chain format.
00231         swapChainDesc.Stereo = false;
00232         swapChainDesc.SampleDesc.Count = 1;                          // Don't use multi-sampling.
00233         swapChainDesc.SampleDesc.Quality = 0;
00234         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00235         swapChainDesc.BufferCount = 2;                               // Use double-buffering to minimize latency.
00236         swapChainDesc.Scaling = DXGI_SCALING_NONE;
00237         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Metro style apps must use this SwapEffect.
00238         swapChainDesc.Flags = 0;
00239
00240         ComPtr<IDXGIDevice1> dxgiDevice;
00241         DX::ThrowIfFailed(
00242             m_d3dDevice.As(&dxgiDevice)
00243             );
00244
00245         ComPtr<IDXGIAdapter> dxgiAdapter;
00246         DX::ThrowIfFailed(
00247             dxgiDevice->GetAdapter(&dxgiAdapter)
00248             );
00249
00250         ComPtr<IDXGIFactory2> dxgiFactory;
00251         DX::ThrowIfFailed(
00252             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00253             );
00254
00255         CoreWindow^ window = m_window.Get();
00256         DX::ThrowIfFailed(
00257             dxgiFactory->CreateSwapChainForCoreWindow(
00258                 m_d3dDevice.Get(),
00259                 reinterpret_cast<IUnknown*>(window),
00260                 &swapChainDesc,
00261                 nullptr,
00262                 &m_swapChain
00263                 )
00264             );
00265
00266         // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
00267         // ensures that the application will only render after each VSync, minimizing power consumption.
00268         DX::ThrowIfFailed(
00269             dxgiDevice->SetMaximumFrameLatency(1)
00270             );
00271     }
00272
00273     // Create a Direct3D render target view of the swap chain back buffer.
00274     ComPtr<ID3D11Texture2D> backBuffer;
00275     DX::ThrowIfFailed(
00276         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00277         );
00278
00279     DX::ThrowIfFailed(
00280         m_d3dDevice->CreateRenderTargetView(
00281             backBuffer.Get(),
00282             nullptr,
00283             &m_d3dRenderTargetView
00284             )
00285         );
00286
00287     // Cache the rendertarget dimensions in our helper class for convenient use.
00288     D3D11_TEXTURE2D_DESC backBufferDesc = {0};
00289     backBuffer->GetDesc(&backBufferDesc);
00290     m_renderTargetSize.Width  = static_cast<float>(backBufferDesc.Width);
00291     m_renderTargetSize.Height = static_cast<float>(backBufferDesc.Height);
00292
00293     // Create a depth stencil view for use with 3D rendering if needed.
00294     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00295         DXGI_FORMAT_D24_UNORM_S8_UINT,
00296         backBufferDesc.Width,
00297         backBufferDesc.Height,
00298         1,
00299         1,
00300         D3D11_BIND_DEPTH_STENCIL
00301         );
00302
00303     ComPtr<ID3D11Texture2D> depthStencil;
00304     DX::ThrowIfFailed(
00305         m_d3dDevice->CreateTexture2D(
00306             &depthStencilDesc,
00307             nullptr,
00308             &depthStencil
00309             )
00310         );
00311
00312     auto viewDesc = CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D);
00313     DX::ThrowIfFailed(
00314         m_d3dDevice->CreateDepthStencilView(
00315             depthStencil.Get(),
00316             &viewDesc,
00317             &m_d3dDepthStencilView
00318             )
00319         );
00320
00321     // Set the 3D rendering viewport to target the entire window.
00322     CD3D11_VIEWPORT viewport(
00323         0.0f,
00324         0.0f,
00325         static_cast<float>(backBufferDesc.Width),
00326         static_cast<float>(backBufferDesc.Height)
00327         );
00328
00329     m_d3dContext->RSSetViewports(1, &viewport);
00330
00331     // Create a Direct2D target bitmap associated with the
00332     // swap chain back buffer and set it as the current target.
00333     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00334         BitmapProperties1(
00335             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00336             PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00337             m_dpi,
00338             m_dpi
00339             );
00340
00341     ComPtr<IDXGISurface> dxgiBackBuffer;
00342     DX::ThrowIfFailed(
00343         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00344         );
00345
00346     DX::ThrowIfFailed(
00347         m_d2dContext->CreateBitmapFromDxgiSurface(
00348             dxgiBackBuffer.Get(),
00349             &bitmapProperties,
00350             &m_d2dTargetBitmap
00351             )
00352         );
00353
00354     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00355
00356     // Grayscale text anti-aliasing is recommended for all Metro style apps.
00357     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00358 }
00359
00360 // Method to deliver the final image to the display.
00361 void DirectXBase::Present()
00362 {
00363     // The application may optionally specify "dirty" or "scroll" rects to improve efficiency
00364     // in certain scenarios.  In this sample, however, we do not utilize those features.
00365     DXGI_PRESENT_PARAMETERS parameters = {0};
00366     parameters.DirtyRectsCount = 0;
00367     parameters.pDirtyRects = nullptr;
00368     parameters.pScrollRect = nullptr;
00369     parameters.pScrollOffset = nullptr;
00370
00371     // The first argument instructs DXGI to block until VSync, putting the application
00372     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00373     // frames that will never be displayed to the screen.
00374     HRESULT hr = m_swapChain->Present1(1, 0, &parameters);
00375
00376     // Discard the contents of the render target.
00377     // This is a valid operation only when the existing contents will be entirely
00378     // overwritten. If dirty or scroll rects are used, this call should be removed.
00379     m_d3dContext->DiscardView(m_d3dRenderTargetView.Get());
00380
00381     // Discard the contents of the depth stencil.
00382     m_d3dContext->DiscardView(m_d3dDepthStencilView.Get());
00383
00384     // If the device was removed either by a disconnect or a driver upgrade, we
00385     // must recreate all device resources.
00386     if (hr == DXGI_ERROR_DEVICE_REMOVED)
00387     {
00388         HandleDeviceLost();
00389     }
00390     else
00391     {
00392         DX::ThrowIfFailed(hr);
00393     }
00394
00395     if (m_windowSizeChangeInProgress)
00396     {
00397         // A window size change has been initiated and the app has just completed presenting
00398         // the first frame with the new size. Notify the resize manager so we can short
00399         // circuit any resize animation and prevent unnecessary delays.
00400         CoreWindowResizeManager::GetForCurrentView()->NotifyLayoutCompleted();
00401         m_windowSizeChangeInProgress = false;
00402     }
00403 }
00404
00405 void DirectXBase::ValidateDevice()
00406 {
00407     // The D3D Device is no longer valid if the default adapter changes or if
00408     // the device has been removed.
00409
00410     // First, get the information for the adapter related to the current device.
00411
00412     ComPtr<IDXGIDevice1> dxgiDevice;
00413     ComPtr<IDXGIAdapter> deviceAdapter;
00414     DXGI_ADAPTER_DESC deviceDesc;
00415     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00416     DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter));
00417     DX::ThrowIfFailed(deviceAdapter->GetDesc(&deviceDesc));
00418
00419     // Next, get the information for the default adapter.
00420
00421     ComPtr<IDXGIFactory2> dxgiFactory;
00422     ComPtr<IDXGIAdapter1> currentAdapter;
00423     DXGI_ADAPTER_DESC currentDesc;
00424     DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)));
00425     DX::ThrowIfFailed(dxgiFactory->EnumAdapters1(0, &currentAdapter));
00426     DX::ThrowIfFailed(currentAdapter->GetDesc(&currentDesc));
00427
00428     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00429     // a new D3D device must be created.
00430
00431     if ((deviceDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart) ||
00432         (deviceDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart) ||
00433         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00434     {
00435         // Release references to resources related to the old device.
00436         dxgiDevice = nullptr;
00437         deviceAdapter = nullptr;
00438
00439         // Create a new device and swap chain.
00440         HandleDeviceLost();
00441     }
00442 }
Generated on Sat Nov 23 2024 16:08:02 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D interpolation modes/C++/SampleOverlay.cpp Source File

  • Direct2D interpolation modes

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 Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::UI::ViewManagement;
00015 using namespace Windows::Graphics::Display;
00016 using namespace D2D1;
00017
00018 SampleOverlay::SampleOverlay() :
00019     m_drawOverlay(true)
00020 {
00021 }
00022
00023 void SampleOverlay::Initialize(
00024     _In_ ID2D1Device*         d2dDevice,
00025     _In_ ID2D1DeviceContext*  d2dContext,
00026     _In_ IWICImagingFactory*  wicFactory,
00027     _In_ IDWriteFactory*      dwriteFactory,
00028     _In_ Platform::String^    caption
00029     )
00030 {
00031     m_wicFactory = wicFactory;
00032     m_dwriteFactory = dwriteFactory;
00033     m_sampleName = caption;
00034     m_d2dDevice = d2dDevice;
00035     m_d2dContext = d2dContext;
00036     m_padding = 3.0f;
00037     m_textVerticalOffset = 5.0f;
00038     m_logoSize = D2D1::SizeF(0.0f, 0.0f);
00039     m_overlayWidth = 0.0f;
00040
00041     ComPtr<ID2D1Factory> factory;
00042     d2dDevice->GetFactory(&factory);
00043
00044     DX::ThrowIfFailed(
00045         factory.As(&m_d2dFactory)
00046         );
00047
00048     ResetDirectXResources();
00049 }
00050
00051 void SampleOverlay::ResetDirectXResources()
00052 {
00053     DX::ThrowIfFailed(
00054         m_d2dContext->CreateSolidColorBrush(ColorF(ColorF::White), &m_whiteBrush)
00055         );
00056
00057     ComPtr<IWICBitmapDecoder> wicBitmapDecoder;
00058     DX::ThrowIfFailed(
00059         m_wicFactory->CreateDecoderFromFilename(
00060             L"windowsbig-sdk.png",
00061             nullptr,
00062             GENERIC_READ,
00063             WICDecodeMetadataCacheOnDemand,
00064             &wicBitmapDecoder
00065             )
00066         );
00067
00068     ComPtr<IWICBitmapFrameDecode> wicBitmapFrame;
00069     DX::ThrowIfFailed(
00070         wicBitmapDecoder->GetFrame(0, &wicBitmapFrame)
00071         );
00072
00073     ComPtr<IWICFormatConverter> wicFormatConverter;
00074     DX::ThrowIfFailed(
00075         m_wicFactory->CreateFormatConverter(&wicFormatConverter)
00076         );
00077
00078     DX::ThrowIfFailed(
00079         wicFormatConverter->Initialize(
00080             wicBitmapFrame.Get(),
00081             GUID_WICPixelFormat32bppPBGRA,
00082             WICBitmapDitherTypeNone,
00083             nullptr,
00084             0.0,
00085             WICBitmapPaletteTypeCustom  // the BGRA format has no palette so this value is ignored
00086             )
00087         );
00088
00089     double dpiX = 96.0f;
00090     double dpiY = 96.0f;
00091     DX::ThrowIfFailed(
00092         wicFormatConverter->GetResolution(&dpiX, &dpiY)
00093         );
00094
00095     DX::ThrowIfFailed(
00096         m_d2dContext->CreateBitmapFromWicBitmap(
00097             wicFormatConverter.Get(),
00098             BitmapProperties(
00099                 PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00100                 static_cast<float>(dpiX),
00101                 static_cast<float>(dpiY)
00102                 ),
00103             &m_logoBitmap
00104             )
00105         );
00106
00107     m_logoSize = m_logoBitmap->GetSize();
00108
00109     ComPtr<IDWriteTextFormat> nameTextFormat;
00110     DX::ThrowIfFailed(
00111         m_dwriteFactory->CreateTextFormat(
00112             L"Segoe UI",
00113             nullptr,
00114             DWRITE_FONT_WEIGHT_LIGHT,
00115             DWRITE_FONT_STYLE_NORMAL,
00116             DWRITE_FONT_STRETCH_NORMAL,
00117             36.0f,
00118             L"en-US",
00119             &nameTextFormat
00120             )
00121         );
00122
00123     DX::ThrowIfFailed(
00124         nameTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)
00125         );
00126
00127     DX::ThrowIfFailed(
00128         nameTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)
00129         );
00130
00131     DX::ThrowIfFailed(
00132         m_dwriteFactory->CreateTextLayout(
00133             m_sampleName->Data(),
00134             m_sampleName->Length(),
00135             nameTextFormat.Get(),
00136             4096.0f,
00137             4096.0f,
00138             &m_textLayout
00139             )
00140         );
00141
00142     DWRITE_TEXT_METRICS metrics = {0};
00143     DX::ThrowIfFailed(
00144         m_textLayout->GetMetrics(&metrics)
00145         );
00146
00147     m_overlayWidth = m_padding * 3.0f + m_logoSize.width + metrics.width;
00148
00149     DX::ThrowIfFailed(
00150         m_d2dFactory->CreateDrawingStateBlock(&m_stateBlock)
00151         );
00152
00153     UpdateForWindowSizeChange();
00154 }
00155
00156 void SampleOverlay::UpdateForWindowSizeChange()
00157 {
00158     if (CoreWindow::GetForCurrentThread()->Bounds.Width < m_overlayWidth)
00159     {
00160         m_drawOverlay = false;
00161     }
00162     else
00163     {
00164         m_drawOverlay = true;
00165     }
00166 }
00167
00168 void SampleOverlay::Render()
00169 {
00170     if (m_drawOverlay)
00171     {
00172         m_d2dContext->SaveDrawingState(m_stateBlock.Get());
00173
00174         m_d2dContext->BeginDraw();
00175         m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00176         m_d2dContext->DrawBitmap(
00177             m_logoBitmap.Get(),
00178             D2D1::RectF(m_padding, 0.0f, m_logoSize.width + m_padding, m_logoSize.height)
00179             );
00180
00181         m_d2dContext->DrawTextLayout(
00182             Point2F(m_logoSize.width + 2.0f * m_padding, m_textVerticalOffset),
00183             m_textLayout.Get(),
00184             m_whiteBrush.Get()
00185             );
00186
00187         // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00188         // is lost. It will be handled during the next call to Present.
00189         HRESULT hr = m_d2dContext->EndDraw();
00190         if (hr != D2DERR_RECREATE_TARGET)
00191         {
00192             DX::ThrowIfFailed(hr);
00193         }
00194
00195         m_d2dContext->RestoreDrawingState(m_stateBlock.Get());
00196     }
00197 }
00198
00199 float SampleOverlay::GetTitleHeightInDips()
00200 {
00201     return m_logoSize.height;
00202 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text display/C++/MainPage.xaml.h Source File

  • XAML text display

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Certificate enrollment/C++/Scenario_Enroll.xaml.cpp Source File

  • Certificate enrollment

Scenario_Enroll.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 // Scenario_Enroll.xaml.cpp
00013 // Implementation of the Scenario_Enroll class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario_Enroll.xaml.h"
00018
00019 using namespace std;
00020 using namespace SDKSample::CertificateEnrollment;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024 using namespace Windows::Security::Cryptography::Certificates;
00025 using namespace Windows::Foundation;
00026 using namespace Concurrency;
00027 using namespace Platform;
00028 using namespace Microsoft::WRL::Details;
00029 using namespace Microsoft::WRL;
00030 using namespace Windows::Storage::Streams;
00031 using namespace Windows::Data::Xml::Dom;
00032
00033
00034 Scenario_Enroll::Scenario_Enroll()
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 Scenario_Enroll::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 void SDKSample::CertificateEnrollment::Scenario_Enroll::CreateRequest_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00052 {
00053     rootPage = MainPage::Current;
00054     TextBlock^ outputTextBlock =  safe_cast<TextBlock^>(rootPage->FindName(L"OutputTextBlock"));
00055
00056     outputTextBlock->Text = L"Creating certificate request...";
00057
00058     //call the default constructor of CertificateRequestProperties
00059     CertificateRequestProperties^ reqProp = ref new CertificateRequestProperties();
00060     reqProp->Subject = L"Toby";
00061     reqProp->FriendlyName = L"Toby's Cert";
00062
00063     try{
00064         //call Certificate Enrollment function createRequest to create a certificate request
00065         create_task(CertificateEnrollmentManager::CreateRequestAsync(reqProp))
00066             .then([this, outputTextBlock](String^ req) {
00067             this->certificateRequest = req;
00068             outputTextBlock->Text += L"\nRequest created, content:\n" + certificateRequest;
00069         })
00070         .then([this, outputTextBlock] (task<void> t)
00071         {
00072             try
00073             {
00074                 t.get();
00075             }
00076             catch(Platform::Exception^ e)
00077             {
00078                 outputTextBlock->Text += L"\n\nCertificate request creation failed with error: " + e->Message;
00079             }
00080         });
00081     }
00082     catch(Platform::Exception^ e)
00083     {
00084         outputTextBlock->Text += L"\n\nCertificate request creation failed with error: " + e->Message;
00085     }
00086 }
00087
00088 void SDKSample::CertificateEnrollment::Scenario_Enroll::InstallCertifiate_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00089 {
00090     String^ response = "";
00091
00092     rootPage = MainPage::Current;
00093     TextBlock^ outputTextBlock =  safe_cast<TextBlock^>(rootPage->FindName(L"OutputTextBlock"));
00094
00095
00096     if (certificateRequest->IsEmpty())
00097     {
00098         outputTextBlock -> Text = L"\nYou need to create a certificate request first";
00099         return;
00100     }
00101
00102     // To submit request, a valid url need to be provided. the url needs to point to a server which can take certificate request and issue certs
00103     String^ url = "";
00104     // Add code here to initialize url
00105
00106     if (url->IsEmpty())
00107     {
00108         outputTextBlock->Text = L"\nTo submit a request, please update the code provide a valid URL.";
00109         return;
00110     }
00111     outputTextBlock->Text = L"Submitting request to server...";
00112
00113     try
00114     {
00115         SubmitCertificateRequestAndGetResponse(this->certificateRequest, url);
00116     }
00117     catch(...)
00118     {
00119         outputTextBlock->Text += "\n\nCertificate Installation failed with error:";
00120     }
00121 }
00122
00123 void Scenario_Enroll::SubmitCertificateRequestAndGetResponse(String^ certificateRequest, String^ url)
00124 {
00125     rootPage = MainPage::Current;
00126     TextBlock^ outputTextBlock =  safe_cast<TextBlock^>(rootPage->FindName(L"OutputTextBlock"));
00127
00128     ////Depends on the server implementaion, the XML format could be different
00129     String^ body = L"<SubmitRequest xmlns=\"http://tempuri.org/\"><strRequest>" + certificateRequest + L"</strRequest></SubmitRequest>";
00130
00131     Uri^ uri = ref new Uri(url);
00132     httpRequest.PostAsync(uri, L"text/xml;charset=utf-8", body->Data()).then([this](task<std::wstring> response)
00133     {
00134         TextBlock^ outputTextBlock =  safe_cast<TextBlock^>(rootPage->FindName(L"OutputTextBlock"));
00135         String^ xml = ref new String(response.get().c_str());
00136
00137         if (200 != httpRequest.GetStatusCode())
00138         {
00139             outputTextBlock -> Text += L"\nSubmit request finished, but the returned status code indicated an error.\n\n";
00140             outputTextBlock -> Text += xml;
00141             return;
00142         }
00143
00144         XmlDocument^ xDoc = ref new XmlDocument();
00145
00146         xDoc->LoadXml(xml);
00147         auto nodeList = xDoc->GetElementsByTagName("SubmitRequestResult");
00148         if (nodeList->Length != 1)
00149         {
00150             outputTextBlock -> Text = L"The certificate response is not in expected XML format";
00151             return;
00152         }
00153
00154         String^ certResponse = nodeList->GetAt(0)->InnerText;
00155         if (certResponse->IsEmpty())
00156         {
00157             outputTextBlock->Text += L"\nSubmit request succeeded but the returned response is empty.";
00158         }
00159
00160         outputTextBlock->Text += L"\nResponse received, content: \n" + certResponse;
00161
00162         // install
00163         outputTextBlock->Text += L"\nInstalling certificate ...";
00164         create_task(CertificateEnrollmentManager::InstallCertificateAsync(certResponse, InstallOptions::None))
00165         .then([outputTextBlock]()
00166         {
00167             outputTextBlock->Text += L"\nThe certificate response is installed sucessfully.\n";
00168         })
00169         .then([this, outputTextBlock] (task<void> t)
00170         {
00171             try
00172             {
00173                 t.get();
00174             }
00175             catch(Platform::Exception^ ex)
00176             {
00177                 outputTextBlock->Text += "\n\nCertificate Installation failed with error: " + ex->Message + "\n";
00178             }
00179         });
00180
00181     }, task_continuation_context::use_current());
00182 }
Generated on Sat Nov 23 2024 16:07:58 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::GeolocationCPP::sealed Member List

This is the complete list of members for SDKSample::GeolocationCPP::sealed, including all inherited members.
CancelGetGeolocation(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::GeolocationCPP::sealed | [private]
geolocator | SDKSample::GeolocationCPP::sealed | [private]
geolocTask | SDKSample::GeolocationCPP::sealed | [private]
geopositionTaskTokenSource | SDKSample::GeolocationCPP::sealed | [private]
GetGeolocation(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::GeolocationCPP::sealed | [private]
GetGeopositionAsync() | SDKSample::GeolocationCPP::sealed | [private]
OnCompleted(Windows::ApplicationModel::Background::BackgroundTaskRegistration^sender, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^e) | SDKSample::GeolocationCPP::sealed | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::GeolocationCPP::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::GeolocationCPP::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::GeolocationCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::GeolocationCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::GeolocationCPP::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::GeolocationCPP::sealed | [protected, virtual]
OnPositionChanged(Windows::Devices::Geolocation::Geolocator^sender, Windows::Devices::Geolocation::PositionChangedEventArgs^e) | SDKSample::GeolocationCPP::sealed | [private]
OnStatusChanged(Windows::Devices::Geolocation::Geolocator^sender, Windows::Devices::Geolocation::StatusChangedEventArgs^e) | SDKSample::GeolocationCPP::sealed | [private]
positionToken | SDKSample::GeolocationCPP::sealed | [private]
RegisterBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::GeolocationCPP::sealed | [private]
rootPage | SDKSample::GeolocationCPP::sealed | [private]
sampleBackgroundTaskEntryPoint | SDKSample::GeolocationCPP::sealed | [private]
sampleBackgroundTaskName | SDKSample::GeolocationCPP::sealed | [private]
Scenario1() | SDKSample::GeolocationCPP::sealed |
Scenario2() | SDKSample::GeolocationCPP::sealed |
Scenario3() | SDKSample::GeolocationCPP::sealed |
StartTracking(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::GeolocationCPP::sealed | [private]
statusToken | SDKSample::GeolocationCPP::sealed | [private]
StopTracking(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::GeolocationCPP::sealed | [private]
taskCompletedToken | SDKSample::GeolocationCPP::sealed | [private]
UnregisterBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::GeolocationCPP::sealed | [private]
Generated on Sat Nov 23 2024 16:09:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/HiloPage.cpp Source File

  • Hilo C++
  • Hilo

HiloPage.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 #include "HiloPage.h"
00009 #include "Common\SuspensionManager.h"
00010
00011 using namespace Hilo;
00012 using namespace Platform;
00013 using namespace Platform::Collections;
00014 using namespace std;
00015 using namespace Windows::Foundation::Collections;
00016 using namespace Windows::System;
00017 using namespace Windows::UI::Core;
00018 using namespace Windows::UI::Xaml;
00019 using namespace Windows::UI::Xaml::Data;
00020 using namespace Windows::UI::Xaml::Interop;
00021 using namespace Windows::UI::Xaml::Navigation;
00022
00023 // See http://go.microsoft.com/fwlink/?LinkId=267274 for info about the Hilo app.
00024
00025 static TypeName hiloPageTypeName = { Hilo::HiloPage::typeid->FullName, TypeKind::Metadata };
00026 static TypeName objectTypeName = { "Object", TypeKind::Primitive };
00027 static Platform::String^ viewModelStateKey = "ViewModelState";
00028
00029 static TypeName rotateImageViewType = { "Hilo.RotateImageView", TypeKind::Metadata };
00030 static TypeName cropImageViewType = { "Hilo.CropImageView", TypeKind::Metadata };
00031 static TypeName cartoonizeImageViewType = { "Hilo.CartoonizeImageView", TypeKind::Metadata };
00032 static TypeName imageViewType = { "Hilo.ImageView", TypeKind::Metadata };
00033 static TypeName imageBrowserType =  { "Hilo.ImageBrowserView", TypeKind::Metadata };
00034 static TypeName mainHubType = { "Hilo.MainHubView", TypeKind::Metadata };
00035
00036 map<PageType, TypeName> create_map()
00037 {
00038     std::map<PageType, TypeName> pages;
00039     pages.insert(std::make_pair(PageType::Crop, cropImageViewType));
00040     pages.insert(std::make_pair(PageType::Rotate, rotateImageViewType));
00041     pages.insert(std::make_pair(PageType::Cartoonize, cartoonizeImageViewType));
00042     pages.insert(std::make_pair(PageType::Image, imageViewType));
00043     pages.insert(std::make_pair(PageType::Browse, imageBrowserType));
00044     pages.insert(std::make_pair(PageType::Hub, mainHubType));
00045     return pages;
00046 }
00047 static map<PageType, TypeName> m_pages(create_map());
00048
00049 static DependencyProperty^ _hiloDataContextProperty =
00050     DependencyProperty::Register(
00051     "HiloDataContext",
00052     objectTypeName,
00053     hiloPageTypeName,
00054     ref new PropertyMetadata(
00055     nullptr,
00056     ref new PropertyChangedCallback(
00057     &HiloPage::OnHiloDataContextPropertyChanged)
00058     ));
00059
00060 void HiloPage::OnHiloDataContextPropertyChanged(Windows::UI::Xaml::DependencyObject^ element, Windows::UI::Xaml::DependencyPropertyChangedEventArgs^ e)
00061 {
00062     HiloPage^ page = static_cast<HiloPage^>(element);
00063     ViewModelBase^ oldViewModel = dynamic_cast<ViewModelBase^>(e->OldValue);
00064     page->DetachNavigationHandlers(oldViewModel);
00065
00066     ViewModelBase^ newViewModel = dynamic_cast<ViewModelBase^>(e->NewValue);
00067     page->AttachNavigationHandlers(newViewModel);
00068 }
00069
00070 DependencyProperty^ HiloPage::HiloDataContextProperty::get()
00071 {
00072     return _hiloDataContextProperty;
00073 }
00074
00075 HiloPage::HiloPage() : m_hasHandlers(false)
00076 {
00077     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00078     {
00079         return;
00080     }
00081
00082     // binding for data context changed
00083     SetBinding(HiloPage::HiloDataContextProperty, ref new Binding());
00084 }
00085
00086
00087 // See http://go.microsoft.com/fwlink/?LinkId=267278 for info on how Hilo creates pages and navigates to pages.
00088
00089 void HiloPage::NavigateBack()
00090 {
00091     GoBack(nullptr, nullptr);
00092 }
00093
00094 void HiloPage::NavigateHome()
00095 {
00096     GoHome(nullptr, nullptr);
00097 }
00098
00099 void HiloPage::NavigateToPage(PageType page, Platform::Object^ parameter)
00100 {
00101     if (Frame != nullptr)
00102     {
00103         TypeName source = m_pages[page];
00104         Frame->Navigate(source, parameter);
00105     }
00106 }
00107
00108 void HiloPage::OnNavigatedTo(NavigationEventArgs^ e)
00109 {
00110
00111     ViewModelBase^ viewModel = dynamic_cast<ViewModelBase^>(DataContext);
00112     this->AttachNavigationHandlers(viewModel);
00113     if (viewModel != nullptr)
00114     {
00115         viewModel->OnNavigatedTo(e);
00116     }
00117
00118     LayoutAwarePage::OnNavigatedTo(e);
00119 }
00120
00121 // See http://go.microsoft.com/fwlink/?LinkId=267280 for more info on Hilo's implementation of suspend/resume.
00122 void Hilo::HiloPage::OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
00123 {
00124     ViewModelBase^ viewModel = dynamic_cast<ViewModelBase^>(DataContext);
00125     if (!HiloPage::IsSuspending)
00126     {
00127         // Since we never receive destructs, this is the only place to unsubscribe.
00128         DetachNavigationHandlers(viewModel);
00129         viewModel->OnNavigatedFrom(e);
00130     }
00131
00132    LayoutAwarePage::OnNavigatedFrom(e);
00133 }
00134
00135 // See http://go.microsoft.com/fwlink/?LinkId=267280 for more info on Hilo's implementation of suspend/resume.
00136 void HiloPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00137 {
00138     auto vm = dynamic_cast<ViewModelBase^>(DataContext);
00139     if (vm != nullptr && pageState != nullptr)
00140     {
00141         IMap<String^, Object^>^ state = nullptr;
00142         state = dynamic_cast<IMap<String^, Object^>^>(pageState->Lookup(viewModelStateKey));
00143
00144         vm->LoadState(state);
00145     }
00146 }
00147
00148 // See http://go.microsoft.com/fwlink/?LinkId=267280 for more info on Hilo's implementation of suspend/resume.
00149 void HiloPage::SaveState(IMap<String^, Object^>^ pageState)
00150 {
00151     auto vm = dynamic_cast<ViewModelBase^>(DataContext);
00152     if (vm != nullptr)
00153     {
00154         auto vmStateMap = ref new Map<String^, Object^>();
00155         vm->SaveState(vmStateMap);
00156
00157         pageState->Insert(viewModelStateKey, vmStateMap);
00158     }
00159 }
00160
00161 void HiloPage::AttachNavigationHandlers(ViewModelBase^ viewModel)
00162 {
00163     if (nullptr == viewModel) return;
00164
00165     // Only resusbcribe if our tokens are empty.
00166
00167     if (!m_hasHandlers)
00168     {
00169         m_navigateBackEventToken = viewModel->NavigateBack::add(ref new NavigateEventHandler(this, &HiloPage::NavigateBack));
00170         m_navigateHomeEventToken = viewModel->NavigateHome::add(ref new NavigateEventHandler(this, &HiloPage::NavigateHome));
00171         m_navigateToPageEventToken = viewModel->NavigateToPage::add(ref new PageNavigateEventHandler(this, &HiloPage::NavigateToPage));
00172         m_hasHandlers = true;
00173     }
00174 }
00175
00176 void HiloPage::DetachNavigationHandlers(ViewModelBase^ viewModel)
00177 {
00178     if (nullptr == viewModel) return;
00179     assert(!HiloPage::IsSuspending);
00180
00181     if (m_hasHandlers)
00182     {
00183         viewModel->NavigateBack::remove(m_navigateBackEventToken);
00184         viewModel->NavigateHome::remove(m_navigateHomeEventToken);
00185         viewModel->NavigateToPage::remove(m_navigateToPageEventToken);
00186         m_hasHandlers = false;
00187     };
00188 }
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Search contract/C++/common/LayoutAwarePage.cpp Source File

  • Search contract
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:32 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D geometry realization/C++/GeometryRealizationSample.h Source File

  • Direct2D geometry realization

GeometryRealizationSample.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
00009 #pragma once
00010
00011 #include "DirectXBase.h"
00012 #include "SampleOverlay.h"
00013 #include "FPSCounter.h"
00014
00015 #include "GeometryRealizationPackage.h"
00016
00017 ref class GeometryRealizationSample : public DirectXBase, public Windows::ApplicationModel::Core::IFrameworkView
00018 {
00019 internal:
00020     GeometryRealizationSample();
00021
00022     // DirectXBase Methods
00023     virtual void CreateDeviceIndependentResources() override;
00024     virtual void CreateDeviceResources() override;
00025     virtual void UpdateForWindowSizeChange() override;
00026     virtual void Render() override;
00027
00028 public:
00029     // IFrameworkView Methods
00030     virtual void Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00031     virtual void SetWindow(_In_ Windows::UI::Core::CoreWindow^ window);
00032     virtual void Load(_In_ Platform::String^ entryPoint);
00033     virtual void Run();
00034     virtual void Uninitialize();
00035
00036 private:
00037     // Event Handlers
00038     void OnWindowSizeChanged(
00039         _In_ Windows::UI::Core::CoreWindow^ sender,
00040         _In_ Windows::UI::Core::WindowSizeChangedEventArgs^ args
00041         );
00042
00043     void OnVisibilityChanged(
00044         _In_ Windows::UI::Core::CoreWindow^ sender,
00045         _In_ Windows::UI::Core::VisibilityChangedEventArgs^ args
00046         );
00047
00048     void OnLogicalDpiChanged(
00049         _In_ Platform::Object^ sender
00050         );
00051
00052     void OnActivated(
00053         _In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView,
00054         _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^ args
00055         );
00056
00057     void OnSuspending(
00058         _In_ Platform::Object^ sender,
00059         _In_ Windows::ApplicationModel::SuspendingEventArgs^ args
00060         );
00061
00062     void OnResuming(
00063         _In_ Platform::Object^ sender,
00064         _In_ Platform::Object^ args
00065         );
00066
00067     void CreateGeometries();
00068     void DiscardGeometries();
00069     void RenderMainContent(float time);
00070     void ShowMenu(Windows::Foundation::Point position);
00071     void UpdateGeometryRendering(Windows::UI::Popups::IUICommand^ command);
00072
00073     void OnPointerMoved(
00074         _In_ Windows::UI::Core::CoreWindow^ window,
00075         _In_ Windows::UI::Core::PointerEventArgs^ args
00076         );
00077
00078     void OnHolding(
00079         _In_ Windows::UI::Input::GestureRecognizer^ recognizer,
00080         _In_ Windows::UI::Input::HoldingEventArgs^ args
00081         );
00082
00083     void OnPointerPressed(
00084         _In_ Windows::UI::Core::CoreWindow^ window,
00085         _In_ Windows::UI::Core::PointerEventArgs^ args
00086         );
00087
00088     void OnPointerReleased(
00089         _In_ Windows::UI::Core::CoreWindow^ window,
00090         _In_ Windows::UI::Core::PointerEventArgs^ args
00091         );
00092
00093     void OnWindowClosed(
00094         _In_ Windows::UI::Core::CoreWindow^ sender,
00095         _In_ Windows::UI::Core::CoreWindowEventArgs^ args
00096         );
00097
00098     SampleOverlay^ m_sampleOverlay;
00099     void UpdateDisplayText();
00100
00101     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>                    m_blackBrush;
00102     Microsoft::WRL::ComPtr<IDWriteTextFormat>                       m_textFormat;
00103     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>                    m_solidColorBrush;
00104     Microsoft::WRL::ComPtr<ID2D1Geometry>                           m_geometry;
00105     Microsoft::WRL::ComPtr<IGeometryRealization>                    m_realization;
00106     uint32                                                          m_numberOfSquares;
00107     int64                                                           m_pausedTime;
00108     int64                                                           m_timeDelta;
00109     FPSCounter^                                                     m_displayText;
00110     D2D1_ANTIALIAS_MODE                                             m_antialiasMode;
00111     bool                                                            m_useRealizations;
00112     bool                                                            m_drawStroke;
00113     bool                                                            m_paused;
00114     bool                                                            m_updateRealization;
00115     bool                                                            m_updateDisplayText;
00116     Platform::Agile<Windows::UI::Input::GestureRecognizer>          m_gestureRecognizer;
00117     bool                                                            m_windowClosed;
00118     bool                                                            m_windowVisible;
00119 };
00120
00121 ref class DirectXAppSource : Windows::ApplicationModel::Core::IFrameworkViewSource
00122 {
00123 public:
00124     virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00125 };
00126
Generated on Sat Nov 23 2024 16:08:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Animation metrics/C++/common/suspensionmanager.cpp Source File

  • Animation metrics
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/WorldMesh.cpp Source File

  • DirectX 3D shooting game

WorldMesh.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 "WorldMesh.h"
00010 #include "DirectXSample.h"
00011 #include "ConstantBuffers.h"
00012
00013 using namespace Microsoft::WRL;
00014 using namespace DirectX;
00015
00016 WorldCeilingMesh::WorldCeilingMesh(_In_ ID3D11Device *device)
00017 {
00018     PNTVertex cellVertices[] =
00019     {
00020         // CEILING
00021         {XMFLOAT3(-4.0f,  3.0f, -6.0f), XMFLOAT3(0.0f, -1.0f, 0.0f), XMFLOAT2(-0.15f, 0.0f)},
00022         {XMFLOAT3( 4.0f,  3.0f, -6.0f), XMFLOAT3(0.0f, -1.0f, 0.0f), XMFLOAT2( 1.25f, 0.0f)},
00023         {XMFLOAT3(-4.0f,  3.0f,  6.0f), XMFLOAT3(0.0f, -1.0f, 0.0f), XMFLOAT2(-0.15f, 2.1f)},
00024         {XMFLOAT3( 4.0f,  3.0f,  6.0f), XMFLOAT3(0.0f, -1.0f, 0.0f), XMFLOAT2( 1.25f, 2.1f)},
00025     };
00026
00027     WORD cellIndices[] = {
00028         0, 1, 2,
00029         1, 3, 2,
00030     };
00031
00032     m_vertexCount = 4;
00033     m_indexCount = 6;
00034
00035     D3D11_BUFFER_DESC bd = {0};
00036     D3D11_SUBRESOURCE_DATA initData = {0};
00037
00038     bd.Usage = D3D11_USAGE_DEFAULT;
00039     bd.ByteWidth = sizeof(PNTVertex) * m_vertexCount;
00040     bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
00041     bd.CPUAccessFlags = 0;
00042     initData.pSysMem = cellVertices;
00043     DX::ThrowIfFailed(
00044         device->CreateBuffer(&bd, &initData, &m_vertexBuffer)
00045         );
00046
00047     bd.Usage = D3D11_USAGE_DEFAULT;
00048     bd.ByteWidth = sizeof(WORD) * m_indexCount;
00049     bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
00050     bd.CPUAccessFlags = 0;
00051     initData.pSysMem = cellIndices;
00052     DX::ThrowIfFailed(
00053         device->CreateBuffer(&bd, &initData, &m_indexBuffer)
00054         );
00055 }
00056
00057 WorldFloorMesh::WorldFloorMesh(_In_ ID3D11Device *device)
00058 {
00059     PNTVertex cellVertices[] =
00060     {
00061         // FLOOR
00062         {XMFLOAT3(-4.0f, -3.0f,  6.0f), XMFLOAT3(0.0f, 1.0f, 0.0f), XMFLOAT2(0.0f, 0.0f)},
00063         {XMFLOAT3( 4.0f, -3.0f,  6.0f), XMFLOAT3(0.0f, 1.0f, 0.0f), XMFLOAT2(1.0f, 0.0f)},
00064         {XMFLOAT3(-4.0f, -3.0f, -6.0f), XMFLOAT3(0.0f, 1.0f, 0.0f), XMFLOAT2(0.0f, 1.5f)},
00065         {XMFLOAT3( 4.0f, -3.0f, -6.0f), XMFLOAT3(0.0f, 1.0f, 0.0f), XMFLOAT2(1.0f, 1.5f)},
00066     };
00067
00068     WORD cellIndices[] = {
00069         0, 1, 2,
00070         1, 3, 2,
00071     };
00072
00073     m_vertexCount = 4;
00074     m_indexCount = 6;
00075
00076     D3D11_BUFFER_DESC bd = {0};
00077     D3D11_SUBRESOURCE_DATA initData = {0};
00078
00079     bd.Usage = D3D11_USAGE_DEFAULT;
00080     bd.ByteWidth = sizeof(PNTVertex) * m_vertexCount;
00081     bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
00082     bd.CPUAccessFlags = 0;
00083     initData.pSysMem = cellVertices;
00084     DX::ThrowIfFailed(
00085         device->CreateBuffer(&bd, &initData, &m_vertexBuffer)
00086         );
00087
00088     bd.Usage = D3D11_USAGE_DEFAULT;
00089     bd.ByteWidth = sizeof(WORD) * m_indexCount;
00090     bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
00091     bd.CPUAccessFlags = 0;
00092     initData.pSysMem = cellIndices;
00093     DX::ThrowIfFailed(
00094         device->CreateBuffer(&bd, &initData, &m_indexBuffer)
00095         );
00096 }
00097
00098 WorldWallsMesh::WorldWallsMesh(_In_ ID3D11Device *device)
00099 {
00100     PNTVertex cellVertices[] =
00101     {
00102         // WALL
00103         {XMFLOAT3(-4.0f,  3.0f,  6.0f), XMFLOAT3(0.0f, 0.0f, -1.0f), XMFLOAT2(0.0f, 0.0f)},
00104         {XMFLOAT3( 4.0f,  3.0f,  6.0f), XMFLOAT3(0.0f, 0.0f, -1.0f), XMFLOAT2(2.0f, 0.0f)},
00105         {XMFLOAT3(-4.0f, -3.0f,  6.0f), XMFLOAT3(0.0f, 0.0f, -1.0f), XMFLOAT2(0.0f, 1.5f)},
00106         {XMFLOAT3( 4.0f, -3.0f,  6.0f), XMFLOAT3(0.0f, 0.0f, -1.0f), XMFLOAT2(2.0f, 1.5f)},
00107         // WALL
00108         {XMFLOAT3(4.0f,  3.0f,  6.0f), XMFLOAT3(-1.0f, 0.0f, 0.0f), XMFLOAT2(0.0f, 0.0f)},
00109         {XMFLOAT3(4.0f,  3.0f, -6.0f), XMFLOAT3(-1.0f, 0.0f, 0.0f), XMFLOAT2(3.0f, 0.0f)},
00110         {XMFLOAT3(4.0f, -3.0f,  6.0f), XMFLOAT3(-1.0f, 0.0f, 0.0f), XMFLOAT2(0.0f, 1.5f)},
00111         {XMFLOAT3(4.0f, -3.0f, -6.0f), XMFLOAT3(-1.0f, 0.0f, 0.0f), XMFLOAT2(3.0f, 1.5f)},
00112         // WALL
00113         {XMFLOAT3( 4.0f,  3.0f, -6.0f), XMFLOAT3(0.0f, 0.0f, 1.0f), XMFLOAT2(0.0f, 0.0f)},
00114         {XMFLOAT3(-4.0f,  3.0f, -6.0f), XMFLOAT3(0.0f, 0.0f, 1.0f), XMFLOAT2(2.0f, 0.0f)},
00115         {XMFLOAT3( 4.0f, -3.0f, -6.0f), XMFLOAT3(0.0f, 0.0f, 1.0f), XMFLOAT2(0.0f, 1.5f)},
00116         {XMFLOAT3(-4.0f, -3.0f, -6.0f), XMFLOAT3(0.0f, 0.0f, 1.0f), XMFLOAT2(2.0f, 1.5f)},
00117         // WALL
00118         {XMFLOAT3(-4.0f,  3.0f, -6.0f), XMFLOAT3(1.0f, 0.0f, 0.0f), XMFLOAT2(0.0f, 0.0f)},
00119         {XMFLOAT3(-4.0f,  3.0f,  6.0f), XMFLOAT3(1.0f, 0.0f, 0.0f), XMFLOAT2(3.0f, 0.0f)},
00120         {XMFLOAT3(-4.0f, -3.0f, -6.0f), XMFLOAT3(1.0f, 0.0f, 0.0f), XMFLOAT2(0.0f, 1.5f)},
00121         {XMFLOAT3(-4.0f, -3.0f,  6.0f), XMFLOAT3(1.0f, 0.0f, 0.0f), XMFLOAT2(3.0f, 1.5f)},
00122     };
00123
00124     WORD cellIndices[] = {
00125          0,  1,  2,
00126          1,  3,  2,
00127          4,  5,  6,
00128          5,  7,  6,
00129          8,  9, 10,
00130          9, 11, 10,
00131         12, 13, 14,
00132         13, 15, 14,
00133     };
00134
00135     m_vertexCount = 16;
00136     m_indexCount = 24;
00137
00138     D3D11_BUFFER_DESC bd = {0};
00139     D3D11_SUBRESOURCE_DATA initData = {0};
00140
00141     bd.Usage = D3D11_USAGE_DEFAULT;
00142     bd.ByteWidth = sizeof(PNTVertex) * m_vertexCount;
00143     bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
00144     bd.CPUAccessFlags = 0;
00145     initData.pSysMem = cellVertices;
00146     DX::ThrowIfFailed(
00147         device->CreateBuffer(&bd, &initData, &m_vertexBuffer)
00148         );
00149
00150     bd.Usage = D3D11_USAGE_DEFAULT;
00151     bd.ByteWidth = sizeof(WORD) * m_indexCount;
00152     bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
00153     bd.CPUAccessFlags = 0;
00154     initData.pSysMem = cellIndices;
00155     DX::ThrowIfFailed(
00156         device->CreateBuffer(&bd, &initData, &m_indexBuffer)
00157         );
00158 }
00159
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-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 Sat Nov 23 2024 16:09:19 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML FlipView control/C++/common/LayoutAwarePage.h Source File

  • XAML FlipView control
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Getting started with C++ simple blog reader/C++/App.xaml.cpp Source File

  • Getting started with C++ simple blog reader

App.xaml.cpp

Go to the documentation of this file.
00001 ﻿
00002 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00003 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00004 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00005 // PARTICULAR PURPOSE.
00006 //
00007 // Copyright (c) Microsoft Corporation. All rights reserved
00008
00009 //
00010 // App.xaml.cpp
00011 // Implementation of the App class.
00012 //
00013
00014
00015 #include "pch.h"
00016 #include "app.xaml.h"
00017 #include "MainPage.xaml.h"
00018 #include "ItemsPage.xaml.h"
00019 #include "common/SuspensionManager.h"
00020
00021 using namespace SimpleBlogReader;
00022 using namespace SimpleBlogReader::Common;
00023 using namespace concurrency;
00024 using namespace Platform;
00025 using namespace Platform::Collections;
00026
00027
00028
00029 using namespace Windows::ApplicationModel;
00030 using namespace Windows::ApplicationModel::Activation;
00031 using namespace Windows::Foundation;
00032 using namespace Windows::Foundation::Collections;
00033 using namespace Windows::UI::Xaml;
00034 using namespace Windows::UI::Xaml::Controls;
00035 using namespace Windows::UI::Xaml::Controls::Primitives;
00036 using namespace Windows::UI::Xaml::Data;
00037 using namespace Windows::UI::Xaml::Input;
00038 using namespace Windows::UI::Xaml::Interop;
00039 using namespace Windows::UI::Xaml::Media;
00040 using namespace Windows::UI::Xaml::Navigation;
00041
00042 // The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227
00043
00044 /// <summary>
00045 /// Initializes the singleton application object.  This is the first line of authored code
00046 /// executed, and as such is the logical equivalent of main() or WinMain().
00047 /// </summary>
00048 App::App()
00049 {
00050     InitializeComponent();
00051     Suspending += ref new SuspendingEventHandler(this, &App::OnSuspending);
00052 }
00053
00054 /// <summary>
00055 /// Invoked when the application is launched normally by the end user.  Other entry points
00056 /// will be used when the application is launched to open a specific file, to display
00057 /// search results, and so forth.
00058 /// </summary>
00059 /// <param name="pArgs">Details about the launch request and process.</param>
00060
00061 void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs)
00062 {
00063
00064     // Do not repeat app initialization when already running, just ensure that
00065     // the window is active
00066     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00067     {
00068         Window::Current->Activate();
00069         return;
00070     }
00071
00072     FeedDataSource^ feedDataSource = safe_cast<FeedDataSource^>(App::Current->Resources->Lookup("feedDataSource"));
00073     if (feedDataSource->Feeds->Size == 0)
00074     {
00075         feedDataSource->InitDataSource();
00076     }
00077
00078     auto prerequisite = task<void>([](){});
00079     auto rootFrame = ref new Frame();
00080     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00081     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Terminated)
00082     {
00083         // Restore the saved session state only when appropriate, scheduling the
00084         // final launch steps after the restore is complete
00085         prerequisite = SuspensionManager::RestoreAsync();
00086     }
00087     prerequisite.then([=]()
00088     {
00089         // When the navigation stack isn't restored navigate to the first page,
00090         // configuring the new page by passing required information as a navigation
00091         // parameter
00092         if (rootFrame->Content == nullptr)
00093         {
00094             if (!rootFrame->Navigate(TypeName(ItemsPage::typeid)))
00095             {
00096                 throw ref new FailureException("Failed to create initial page");
00097             }
00098         }
00099
00100         // Place the frame in the current Window and ensure that it is active
00101         Window::Current->Content = rootFrame;
00102         Window::Current->Activate();
00103     }, task_continuation_context::use_current());
00104
00105 }
00106
00107 /// <summary>
00108 /// Invoked when application execution is being suspended.  Application state is saved
00109 /// without knowing whether the application will be terminated or resumed with the contents
00110 /// of memory still intact.
00111 /// </summary>
00112 /// <param name="sender">The source of the suspend request.</param>
00113 /// <param name="e">Details about the suspend request.</param>
00114 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00115 {
00116     (void) sender;  // Unused parameter
00117
00118     //Save application state and stop any background activity
00119     auto deferral = e->SuspendingOperation->GetDeferral();
00120
00121     auto saveOp = SuspensionManager::SaveAsync();
00122
00123     saveOp.then ([deferral]()
00124     {
00125         deferral->Complete();
00126     });
00127 }
Generated on Sat Nov 23 2024 16:07:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: EAS policies for mail clients/C++/common/LayoutAwarePage.h Source File

  • EAS policies for mail clients
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/MonthGroup.h Source File

  • Hilo C++
  • Hilo

MonthGroup.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
00009 #include "IPhotoGroup.h"
00010
00011 namespace Hilo
00012 {
00013     interface class IPhotoGroup;
00014     class ExceptionPolicy;
00015     class PhotoCache;
00016     class Repository;
00017
00018     // The MonthGroup class provides data to the image browser's grid control.
00019     [Windows::UI::Xaml::Data::Bindable]
00020     [Windows::Foundation::Metadata::WebHostHidden]
00021     public ref class MonthGroup sealed : public IPhotoGroup, public Windows::UI::Xaml::Data::INotifyPropertyChanged
00022     {
00023     internal:
00024         MonthGroup(std::shared_ptr<PhotoCache> photoCache, Windows::Storage::Search::IStorageFolderQueryOperations^ folderQuery, std::shared_ptr<Repository> repository, std::shared_ptr<ExceptionPolicy> exceptionPolicy);
00025         concurrency::task<Windows::Foundation::DateTime> QueryPhotosAsync();
00026
00027     public:
00028         virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler^ PropertyChanged;
00029
00030         property Platform::String^ Title
00031         {
00032             virtual Platform::String^ get();
00033         }
00034
00035         property Windows::Foundation::Collections::IObservableVector<IPhoto^>^ Items
00036         {
00037             virtual Windows::Foundation::Collections::IObservableVector<IPhoto^>^ get();
00038         }
00039
00040         property bool HasPhotos
00041         {
00042             bool get();
00043         }
00044
00045         property bool IsRunning
00046         {
00047             bool get();
00048         }
00049
00050     private:
00051         Platform::String^ m_title;
00052         Windows::Foundation::DateTime m_dateTimeForTitle;
00053         std::weak_ptr<PhotoCache> m_weakPhotoCache;
00054         Windows::Storage::Search::IStorageFolderQueryOperations^ m_folderQuery;
00055         std::shared_ptr<Repository> m_repository;
00056         std::shared_ptr<ExceptionPolicy> m_exceptionPolicy;
00057         Platform::Collections::Vector<IPhoto^>^ m_photos;
00058         size_t m_count;
00059         bool m_hasCount;
00060         bool m_runningQuery;
00061
00062         void OnPropertyChanged(Platform::String^ propertyName);
00063     };
00064 }
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: StreamSocket/C++/Scenario4.xaml.cpp Source File

  • StreamSocket

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 StreamSocketSample;
00020
00021 using namespace Concurrency;
00022 using namespace Windows::ApplicationModel::Core;
00023 using namespace Windows::Foundation;
00024 using namespace Windows::Networking::Sockets;
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::Navigation;
00029
00030 Scenario4::Scenario4()
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 void Scenario4::OnNavigatedTo(NavigationEventArgs^ e)
00041 {
00042     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00043     // as NotifyUser()
00044     rootPage = MainPage::Current;
00045 }
00046
00047 void StreamSocketSample::Scenario4::CloseSockets_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00048 {
00049     if (CoreApplication::Properties->HasKey("clientDataWriter"))
00050     {
00051         // Remove the listener from the list of application properties as we are about to close it.
00052         DataWriter^ dataWriter = dynamic_cast<DataWriter^>(CoreApplication::Properties->Lookup("clientDataWriter"));
00053         CoreApplication::Properties->Remove("clientDataWriter");
00054
00055         // Close the data writer.
00056         delete dataWriter;
00057         dataWriter = nullptr;
00058     }
00059
00060     if (CoreApplication::Properties->HasKey("clientSocket"))
00061     {
00062         // Remove the socket from the list of application properties as we are about to close it.
00063         StreamSocket^ socket = dynamic_cast<StreamSocket^>(CoreApplication::Properties->Lookup("clientSocket"));
00064         CoreApplication::Properties->Remove("clientSocket");
00065
00066         // Close the socket.
00067         delete socket;
00068         socket = nullptr;
00069     }
00070
00071     if (CoreApplication::Properties->HasKey("listener"))
00072     {
00073         // This is the last reference to the context, so once removed the object will be deleted.
00074         CoreApplication::Properties->Remove("listener");
00075     }
00076
00077     if (CoreApplication::Properties->HasKey("connected"))
00078     {
00079         CoreApplication::Properties->Remove("connected");
00080     }
00081
00082     rootPage->NotifyUser("Socket and listener closed", NotifyType::StatusMessage);
00083 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite vertical text/C++/DirectXSample.h Source File

  • DirectWrite vertical text

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
00010 // This header defines helper utilities to make DirectX APIs work with exceptions.
00011 namespace DX
00012 {
00013     inline void ThrowIfFailed(HRESULT hr)
00014     {
00015         if (FAILED(hr))
00016         {
00017             // Set a breakpoint on this line to catch DX API errors.
00018             throw Platform::Exception::CreateException(hr);
00019         }
00020     }
00021 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Audio Session (WASAPI)/C++/common/LayoutAwarePage.cpp Source File

  • Windows Audio Session (WASAPI)
  • C++
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:33 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Getting started with C++ simple blog reader/C++/pch.h Source File

  • Getting started with C++ simple blog reader

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 //
00009 // pch.h
00010 // Header for standard system include files.
00011 //
00012
00013 #pragma once
00014
00015 #include <collection.h>
00016 #include <ppltasks.h>
00017 #include <string>
00018 #include <map>
00019 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Connecting with WebSockets/C++/common/suspensionmanager.cpp Source File

  • Connecting with WebSockets
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Direct3DTutorialFrameworkView Member List

This is the complete list of members for Direct3DTutorialFrameworkView, including all inherited members.
CreateWindowSizeDependentResources() | Direct3DTutorialFrameworkView | [inline, private]
CreateWindowSizeDependentResources() | Direct3DTutorialFrameworkView | [inline, private]
CreateWindowSizeDependentResources() | Direct3DTutorialFrameworkView | [inline, private]
CreateWindowSizeDependentResources() | Direct3DTutorialFrameworkView | [inline, private]
Initialize(_In_ CoreApplicationView^applicationView) | Direct3DTutorialFrameworkView | [inline, virtual]
Initialize(_In_ CoreApplicationView^applicationView) | Direct3DTutorialFrameworkView | [inline, virtual]
Initialize(_In_ CoreApplicationView^applicationView) | Direct3DTutorialFrameworkView | [inline, virtual]
Initialize(_In_ CoreApplicationView^applicationView) | Direct3DTutorialFrameworkView | [inline, virtual]
Load(_In_ Platform::String^entryPoint) | Direct3DTutorialFrameworkView | [inline, virtual]
Load(_In_ Platform::String^entryPoint) | Direct3DTutorialFrameworkView | [inline, virtual]
Load(_In_ Platform::String^entryPoint) | Direct3DTutorialFrameworkView | [inline, virtual]
Load(_In_ Platform::String^entryPoint) | Direct3DTutorialFrameworkView | [inline, virtual]
m_constantBuffer | Direct3DTutorialFrameworkView | [private]
m_constantBufferData | Direct3DTutorialFrameworkView | [private]
m_d3dDevice | Direct3DTutorialFrameworkView | [private]
m_d3dDeviceContext | Direct3DTutorialFrameworkView | [private]
m_depthStencilView | Direct3DTutorialFrameworkView | [private]
m_renderTargetView | Direct3DTutorialFrameworkView | [private]
m_swapChain | Direct3DTutorialFrameworkView | [private]
m_window | Direct3DTutorialFrameworkView | [private]
OnActivated(_In_ CoreApplicationView^applicationView, _In_ IActivatedEventArgs^args) | Direct3DTutorialFrameworkView | [inline]
OnActivated(_In_ CoreApplicationView^applicationView, _In_ IActivatedEventArgs^args) | Direct3DTutorialFrameworkView | [inline]
OnActivated(_In_ CoreApplicationView^applicationView, _In_ IActivatedEventArgs^args) | Direct3DTutorialFrameworkView | [inline]
OnActivated(_In_ CoreApplicationView^applicationView, _In_ IActivatedEventArgs^args) | Direct3DTutorialFrameworkView | [inline]
OnWindowSizeChanged(_In_ CoreWindow^sender, _In_ WindowSizeChangedEventArgs^args) | Direct3DTutorialFrameworkView | [inline, private]
OnWindowSizeChanged(_In_ CoreWindow^sender, _In_ WindowSizeChangedEventArgs^args) | Direct3DTutorialFrameworkView | [inline, private]
OnWindowSizeChanged(_In_ CoreWindow^sender, _In_ WindowSizeChangedEventArgs^args) | Direct3DTutorialFrameworkView | [inline, private]
OnWindowSizeChanged(_In_ CoreWindow^sender, _In_ WindowSizeChangedEventArgs^args) | Direct3DTutorialFrameworkView | [inline, private]
Run() | Direct3DTutorialFrameworkView | [inline, virtual]
Run() | Direct3DTutorialFrameworkView | [inline, virtual]
Run() | Direct3DTutorialFrameworkView | [inline, virtual]
Run() | Direct3DTutorialFrameworkView | [inline, virtual]
SetWindow(_In_ CoreWindow^window) | Direct3DTutorialFrameworkView | [inline, virtual]
SetWindow(_In_ CoreWindow^window) | Direct3DTutorialFrameworkView | [inline, virtual]
SetWindow(_In_ CoreWindow^window) | Direct3DTutorialFrameworkView | [inline, virtual]
SetWindow(_In_ CoreWindow^window) | Direct3DTutorialFrameworkView | [inline, virtual]
Uninitialize() | Direct3DTutorialFrameworkView | [inline, virtual]
Uninitialize() | Direct3DTutorialFrameworkView | [inline, virtual]
Uninitialize() | Direct3DTutorialFrameworkView | [inline, virtual]
Uninitialize() | Direct3DTutorialFrameworkView | [inline, virtual]
Generated on Sat Nov 23 2024 16:09:11 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite inline object/C++/DirectXSample.h Source File

  • DirectWrite inline object

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
00010 // This header defines helper utilities to make DirectX APIs work with exceptions.
00011 namespace DX
00012 {
00013     inline void ThrowIfFailed(HRESULT hr)
00014     {
00015         if (FAILED(hr))
00016         {
00017             // Set a breakpoint on this line to catch DX API errors.
00018             throw Platform::Exception::CreateException(hr);
00019         }
00020     }
00021 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playlist/C++/Clear.xaml.h Source File

  • Playlist

Clear.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 // Clear.xaml.h
00013 // Declaration of the Clear class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Clear.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace Playlists
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 Clear sealed
00031         {
00032         public:
00033             Clear();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void PickPlaylistButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Sharing content source app/C++/ShareCustomData.xaml.cpp Source File

  • Sharing content source app

ShareCustomData.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 // ShareCustomData.xaml.cpp
00013 // Implementation of the ShareCustomData class
00014 //
00015
00016 #include "pch.h"
00017 #include "ShareCustomData.xaml.h"
00018
00019 using namespace SDKSample::ShareSource;
00020 using namespace SDKSample::Common;
00021
00022 using namespace Platform;
00023 using namespace Windows::ApplicationModel::DataTransfer;
00024
00025 ShareCustomData::ShareCustomData()
00026 {
00027     InitializeComponent();
00028     CustomDataTextBox->Text = CUSTOM_DATA_CONTENT;
00029 }
00030
00031 bool ShareCustomData::GetShareContent(DataRequest^ request)
00032 {
00033     bool succeeded = false;
00034
00035     auto dataPackageFormat = DataFormatInputBox->Text;
00036     if (dataPackageFormat != nullptr)
00037     {
00038         auto dataPackageText = CustomDataTextBox->Text;
00039         if (dataPackageText != nullptr)
00040         {
00041             auto requestData = request->Data;
00042             requestData->Properties->Title = TitleInputBox->Text;
00043
00044             // The description is optional.
00045             auto dataPackageDescription = DescriptionInputBox->Text;
00046             if (dataPackageDescription != nullptr)
00047             {
00048                 requestData->Properties->Description = dataPackageDescription;
00049             }
00050             requestData->SetData(dataPackageFormat, dataPackageText);
00051             succeeded = true;
00052         }
00053         else
00054         {
00055             request->FailWithDisplayText("Enter the custom data you would like to share and try again.");
00056         }
00057     }
00058     else
00059     {
00060         request->FailWithDisplayText("Enter a custom data format and try again.");
00061     }
00062     return succeeded;
00063 }
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Background task/C++/BackgroundTask/common/suspensionmanager.cpp Source File

  • Background task
  • BackgroundTask
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Configure keys for media/C++/MainPage.xaml.h Source File

  • Configure keys for media

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML animation library/C++/Scenario1.xaml.cpp Source File

  • XAML animation library

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::Animation;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 Scenario1::Scenario1()
00026 {
00027     InitializeComponent();
00028 }
00029
00030
00031 // Invoked when this page is about to be displayed in a Frame.
00032 void Scenario1::OnNavigatedTo(NavigationEventArgs^ e)
00033 {
00034     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00035     // as NotifyUser()
00036     rootPage = MainPage::Current;
00037
00038   // Start the animation
00039   Scenario1Storyboard->Begin();
00040 }
Generated on Sat Nov 23 2024 16:07:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/texconv/DirectXTexResize.cpp Source File

  • Direct3D resource loading
  • texconv

DirectXTexResize.cpp

Go to the documentation of this file.
00001 //-------------------------------------------------------------------------------------
00002 // DirectXTexResize.cpp
00003 //
00004 // DirectX Texture Library - Image resizing operations
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 #include "directxtexp.h"
00015
00016 namespace DirectX
00017 {
00018
00019 extern HRESULT _ResizeSeparateColorAndAlpha( _In_ IWICImagingFactory* pWIC, _In_ IWICBitmap* original,
00020                                              _In_ size_t newWidth, _In_ size_t newHeight, _In_ DWORD filter, _Inout_ const Image* img );
00021
00022 //-------------------------------------------------------------------------------------
00023 // Do image resize using WIC
00024 //-------------------------------------------------------------------------------------
00025 static HRESULT _PerformResizeUsingWIC( _In_ const Image& srcImage, _In_ DWORD filter,
00026                                        _In_ const WICPixelFormatGUID& pfGUID, _In_ const Image& destImage )
00027 {
00028     if ( !srcImage.pixels || !destImage.pixels )
00029         return E_POINTER;
00030
00031     assert( srcImage.format == destImage.format );
00032
00033     IWICImagingFactory* pWIC = _GetWIC();
00034     if ( !pWIC )
00035         return E_NOINTERFACE;
00036
00037     ScopedObject<IWICComponentInfo> componentInfo;
00038     HRESULT hr = pWIC->CreateComponentInfo( pfGUID, &componentInfo );
00039     if ( FAILED(hr) )
00040         return hr;
00041
00042     ScopedObject<IWICPixelFormatInfo2> pixelFormatInfo;
00043     hr = componentInfo->QueryInterface( __uuidof(IWICPixelFormatInfo2), (void**)&pixelFormatInfo );
00044     if ( FAILED(hr) )
00045         return hr;
00046
00047     BOOL supportsTransparency = FALSE;
00048     hr = pixelFormatInfo->SupportsTransparency( &supportsTransparency );
00049     if ( FAILED(hr) )
00050         return hr;
00051
00052     ScopedObject<IWICBitmap> source;
00053     hr = pWIC->CreateBitmapFromMemory( static_cast<UINT>( srcImage.width ), static_cast<UINT>( srcImage.height ), pfGUID,
00054                                        static_cast<UINT>( srcImage.rowPitch ), static_cast<UINT>( srcImage.slicePitch ),
00055                                        srcImage.pixels, &source );
00056     if ( FAILED(hr) )
00057         return hr;
00058
00059     if ( (filter & TEX_FILTER_SEPARATE_ALPHA) && supportsTransparency )
00060     {
00061         hr = _ResizeSeparateColorAndAlpha( pWIC, source.Get(), destImage.width, destImage.height, filter, &destImage );
00062         if ( FAILED(hr) )
00063             return hr;
00064     }
00065     else
00066     {
00067         ScopedObject<IWICBitmapScaler> scaler;
00068         hr = pWIC->CreateBitmapScaler( &scaler );
00069         if ( FAILED(hr) )
00070             return hr;
00071
00072         hr = scaler->Initialize( source.Get(), static_cast<UINT>( destImage.width ), static_cast<UINT>( destImage.height ), _GetWICInterp( filter ) );
00073         if ( FAILED(hr) )
00074             return hr;
00075
00076         WICPixelFormatGUID pfScaler;
00077         hr = scaler->GetPixelFormat( &pfScaler );
00078         if ( FAILED(hr) )
00079             return hr;
00080
00081         if ( memcmp( &pfScaler, &pfGUID, sizeof(WICPixelFormatGUID) ) == 0 )
00082         {
00083             hr = scaler->CopyPixels( 0, static_cast<UINT>( destImage.rowPitch ), static_cast<UINT>( destImage.slicePitch ), destImage.pixels );
00084             if ( FAILED(hr) )
00085                 return hr;
00086         }
00087         else
00088         {
00089             // The WIC bitmap scaler is free to return a different pixel format than the source image, so here we
00090             // convert it back
00091             ScopedObject<IWICFormatConverter> FC;
00092             hr = pWIC->CreateFormatConverter( &FC );
00093             if ( FAILED(hr) )
00094                 return hr;
00095
00096             hr = FC->Initialize( scaler.Get(), pfGUID, _GetWICDither( filter ), 0, 0, WICBitmapPaletteTypeCustom );
00097             if ( FAILED(hr) )
00098                 return hr;
00099
00100             hr = FC->CopyPixels( 0, static_cast<UINT>( destImage.rowPitch ), static_cast<UINT>( destImage.slicePitch ), destImage.pixels );
00101             if ( FAILED(hr) )
00102                 return hr;
00103         }
00104     }
00105
00106     return S_OK;
00107 }
00108
00109
00110 //-------------------------------------------------------------------------------------
00111 // Do conversion, resize using WIC, conversion cycle
00112 //-------------------------------------------------------------------------------------
00113 static HRESULT _PerformResizeViaF32( _In_ const Image& srcImage, _In_ DWORD filter, _In_ const Image& destImage )
00114 {
00115     if ( !srcImage.pixels || !destImage.pixels )
00116         return E_POINTER;
00117
00118     assert( srcImage.format != DXGI_FORMAT_R32G32B32A32_FLOAT );
00119     assert( srcImage.format == destImage.format );
00120
00121     ScratchImage temp;
00122     HRESULT hr = _ConvertToR32G32B32A32( srcImage, temp );
00123     if ( FAILED(hr) )
00124         return hr;
00125
00126     const Image *tsrc = temp.GetImage( 0, 0, 0 );
00127     if ( !tsrc )
00128         return E_POINTER;
00129
00130     ScratchImage rtemp;
00131     hr = rtemp.Initialize2D( DXGI_FORMAT_R32G32B32A32_FLOAT, destImage.width, destImage.height, 1, 1 );
00132     if ( FAILED(hr) )
00133         return hr;
00134
00135     const Image *tdest = rtemp.GetImage( 0, 0, 0 );
00136     if ( !tdest )
00137         return E_POINTER;
00138
00139     hr = _PerformResizeUsingWIC( *tsrc, filter, GUID_WICPixelFormat128bppRGBAFloat, *tdest );
00140     if ( FAILED(hr) )
00141         return hr;
00142
00143     temp.Release();
00144
00145     hr = _ConvertFromR32G32B32A32( *tdest, destImage );
00146     if ( FAILED(hr) )
00147         return hr;
00148
00149     return S_OK;
00150 }
00151
00152
00153 //=====================================================================================
00154 // Entry-points
00155 //=====================================================================================
00156
00157 //-------------------------------------------------------------------------------------
00158 // Resize image
00159 //-------------------------------------------------------------------------------------
00160 _Use_decl_annotations_
00161 HRESULT Resize( const Image& srcImage, size_t width, size_t height, DWORD filter, ScratchImage& image )
00162 {
00163     if ( width == 0 || height == 0 )
00164         return E_INVALIDARG;
00165
00166 #ifdef _AMD64_
00167     if ( (srcImage.width > 0xFFFFFFFF) || (srcImage.height > 0xFFFFFFFF) )
00168         return E_INVALIDARG;
00169
00170     if ( (width > 0xFFFFFFFF) || (height > 0xFFFFFFFF) )
00171         return E_INVALIDARG;
00172 #endif
00173
00174     if ( !srcImage.pixels )
00175         return E_POINTER;
00176
00177     if ( IsCompressed( srcImage.format ) )
00178     {
00179         // We don't support resizing compressed images
00180         return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
00181     }
00182
00183     HRESULT hr = image.Initialize2D( srcImage.format, width, height, 1, 1 );
00184     if ( FAILED(hr) )
00185         return hr;
00186
00187     const Image *rimage = image.GetImage( 0, 0, 0 );
00188     if ( !rimage )
00189         return E_POINTER;
00190
00191     // WIC only supports CLAMP
00192
00193     WICPixelFormatGUID pfGUID;
00194     if ( _DXGIToWIC( srcImage.format, pfGUID ) )
00195     {
00196         // Case 1: Source format is supported by Windows Imaging Component
00197         hr = _PerformResizeUsingWIC( srcImage, filter, pfGUID, *rimage );
00198     }
00199     else
00200     {
00201         // Case 2: Source format is not supported by WIC, so we have to convert, resize, and convert back
00202         hr = _PerformResizeViaF32( srcImage, filter, *rimage );
00203     }
00204
00205     if ( FAILED(hr) )
00206     {
00207         image.Release();
00208         return hr;
00209     }
00210
00211     return S_OK;
00212 }
00213
00214
00215 //-------------------------------------------------------------------------------------
00216 // Resize image (complex)
00217 //-------------------------------------------------------------------------------------
00218 _Use_decl_annotations_
00219 HRESULT Resize( const Image* srcImages, size_t nimages, const TexMetadata& metadata,
00220                 size_t width, size_t height, DWORD filter, ScratchImage& result )
00221 {
00222     if ( !srcImages || !nimages || width == 0 || height == 0 )
00223         return E_INVALIDARG;
00224
00225 #ifdef _AMD64_
00226     if ( (width > 0xFFFFFFFF) || (height > 0xFFFFFFFF) )
00227         return E_INVALIDARG;
00228 #endif
00229
00230     TexMetadata mdata2 = metadata;
00231     mdata2.width = width;
00232     mdata2.height = height;
00233     mdata2.mipLevels = 1;
00234     HRESULT hr = result.Initialize( mdata2 );
00235     if ( FAILED(hr) )
00236         return hr;
00237
00238     WICPixelFormatGUID pfGUID;
00239     bool wicpf = _DXGIToWIC( metadata.format, pfGUID );
00240
00241     switch ( metadata.dimension )
00242     {
00243     case TEX_DIMENSION_TEXTURE1D:
00244     case TEX_DIMENSION_TEXTURE2D:
00245         assert( metadata.depth == 1 );
00246
00247         for( size_t item = 0; item < metadata.arraySize; ++item )
00248         {
00249             size_t srcIndex = metadata.ComputeIndex( 0, item, 0 );
00250             if ( srcIndex >= nimages )
00251             {
00252                 result.Release();
00253                 return E_FAIL;
00254             }
00255
00256             const Image* srcimg = &srcImages[ srcIndex ];
00257             const Image* destimg = result.GetImage( 0, item, 0 );
00258             if ( !srcimg || !destimg )
00259             {
00260                 result.Release();
00261                 return E_POINTER;
00262             }
00263
00264             if ( srcimg->format != metadata.format )
00265             {
00266                 result.Release();
00267                 return E_FAIL;
00268             }
00269
00270 #ifdef _AMD64_
00271             if ( (srcimg->width > 0xFFFFFFFF) || (srcimg->height > 0xFFFFFFFF) )
00272             {
00273                 result.Release();
00274                 return E_FAIL;
00275             }
00276 #endif
00277
00278             if ( wicpf )
00279             {
00280                 // Case 1: Source format is supported by Windows Imaging Component
00281                 hr = _PerformResizeUsingWIC( *srcimg, filter, pfGUID, *destimg );
00282             }
00283             else
00284             {
00285                 // Case 2: Source format is not supported by WIC, so we have to convert, resize, and convert back
00286                 hr = _PerformResizeViaF32( *srcimg, filter, *destimg );
00287             }
00288
00289             if ( FAILED(hr) )
00290             {
00291                 result.Release();
00292                 return hr;
00293             }
00294         }
00295         break;
00296
00297     case TEX_DIMENSION_TEXTURE3D:
00298         assert( metadata.arraySize == 1 );
00299
00300         for( size_t slice = 0; slice < metadata.depth; ++slice )
00301         {
00302             size_t srcIndex = metadata.ComputeIndex( 0, 0, slice );
00303             if ( srcIndex >= nimages )
00304             {
00305                 result.Release();
00306                 return E_FAIL;
00307             }
00308
00309             const Image* srcimg = &srcImages[ srcIndex ];
00310             const Image* destimg = result.GetImage( 0, 0, slice );
00311             if ( !srcimg || !destimg )
00312             {
00313                 result.Release();
00314                 return E_POINTER;
00315             }
00316
00317             if ( srcimg->format != metadata.format )
00318             {
00319                 result.Release();
00320                 return E_FAIL;
00321             }
00322
00323 #ifdef _AMD64_
00324             if ( (srcimg->width > 0xFFFFFFFF) || (srcimg->height > 0xFFFFFFFF) )
00325             {
00326                 result.Release();
00327                 return E_FAIL;
00328             }
00329 #endif
00330
00331             if ( wicpf )
00332             {
00333                 // Case 1: Source format is supported by Windows Imaging Component
00334                 hr = _PerformResizeUsingWIC( *srcimg, filter, pfGUID, *destimg );
00335             }
00336             else
00337             {
00338                 // Case 2: Source format is not supported by WIC, so we have to convert, resize, and convert back
00339                 hr = _PerformResizeViaF32( *srcimg, filter, *destimg );
00340             }
00341
00342             if ( FAILED(hr) )
00343             {
00344                 result.Release();
00345                 return hr;
00346             }
00347         }
00348         break;
00349
00350     default:
00351         result.Release();
00352         return E_FAIL;
00353     }
00354
00355     return S_OK;
00356 }
00357
00358 }; // namespace
Generated on Sat Nov 23 2024 16:08:12 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::TileContent::TileWidePeekImage04 Member List

This is the complete list of members for NotificationsExtensions::TileContent::TileWidePeekImage04, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
Branding | NotificationsExtensions::TileContent::TileNotificationBase |
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Image | NotificationsExtensions::TileContent::TileWidePeekImage04 |
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
RequireSquareContent | NotificationsExtensions::TileContent::TileWideBase |
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SquareContent | NotificationsExtensions::TileContent::TileWideBase |
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextBodyWrap | NotificationsExtensions::TileContent::TileWidePeekImage04 |
TextFields | NotificationsExtensions::NotificationBase |
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWidePeekImage04() | NotificationsExtensions::TileContent::TileWidePeekImage04 | [inline]
TileWidePeekImage04() | NotificationsExtensions::TileContent::TileWidePeekImage04 | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:44 for Win8-Examples by doxygen 1.7.1


Win8-Examples: User domain name/C++/common/suspensionmanager.cpp Source File

  • User domain name
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:37 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/texconv/DirectXTexFlipRotate.cpp Source File

  • Direct3D resource loading
  • texconv

DirectXTexFlipRotate.cpp

Go to the documentation of this file.
00001 //-------------------------------------------------------------------------------------
00002 // DirectXTexFlipRotate.cpp
00003 //
00004 // DirectX Texture Library - Image flip/rotate operations
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 #include "directxtexp.h"
00015
00016 namespace DirectX
00017 {
00018
00019 //-------------------------------------------------------------------------------------
00020 // Do flip/rotate operation using WIC
00021 //-------------------------------------------------------------------------------------
00022 static HRESULT _PerformFlipRotateUsingWIC( _In_ const Image& srcImage, _In_ DWORD flags,
00023                                            _In_ const WICPixelFormatGUID& pfGUID, _In_ const Image& destImage )
00024 {
00025     if ( !srcImage.pixels || !destImage.pixels )
00026         return E_POINTER;
00027
00028     assert( srcImage.format == destImage.format );
00029
00030     IWICImagingFactory* pWIC = _GetWIC();
00031     if ( !pWIC )
00032         return E_NOINTERFACE;
00033
00034     ScopedObject<IWICBitmap> source;
00035     HRESULT hr = pWIC->CreateBitmapFromMemory( static_cast<UINT>( srcImage.width ), static_cast<UINT>( srcImage.height ), pfGUID,
00036                                                static_cast<UINT>( srcImage.rowPitch ), static_cast<UINT>( srcImage.slicePitch ),
00037                                                srcImage.pixels, &source );
00038     if ( FAILED(hr) )
00039         return hr;
00040
00041     ScopedObject<IWICBitmapFlipRotator> FR;
00042     hr = pWIC->CreateBitmapFlipRotator( &FR );
00043     if ( FAILED(hr) )
00044         return hr;
00045
00046     hr = FR->Initialize( source.Get(), static_cast<WICBitmapTransformOptions>( flags ) );
00047     if ( FAILED(hr) )
00048         return hr;
00049
00050     WICPixelFormatGUID pfFR;
00051     hr = FR->GetPixelFormat( &pfFR );
00052     if ( FAILED(hr) )
00053         return hr;
00054
00055     if ( memcmp( &pfFR, &pfGUID, sizeof(GUID) ) != 0 )
00056     {
00057         // Flip/rotate should return the same format as the source...
00058         return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
00059     }
00060
00061     UINT nwidth, nheight;
00062     hr = FR->GetSize( &nwidth, &nheight );
00063     if ( FAILED(hr) )
00064         return hr;
00065
00066     if ( destImage.width != nwidth || destImage.height != nheight )
00067         return E_FAIL;
00068
00069     hr = FR->CopyPixels( 0, static_cast<UINT>( destImage.rowPitch ), static_cast<UINT>( destImage.slicePitch ), destImage.pixels );
00070     if ( FAILED(hr) )
00071         return hr;
00072
00073     return S_OK;
00074 }
00075
00076
00077 //-------------------------------------------------------------------------------------
00078 // Do conversion, flip/rotate using WIC, conversion cycle
00079 //-------------------------------------------------------------------------------------
00080 static HRESULT _PerformFlipRotateViaF32( _In_ const Image& srcImage, _In_ DWORD flags, _In_ const Image& destImage )
00081 {
00082     if ( !srcImage.pixels || !destImage.pixels )
00083         return E_POINTER;
00084
00085     assert( srcImage.format != DXGI_FORMAT_R32G32B32A32_FLOAT );
00086     assert( srcImage.format == destImage.format );
00087
00088     ScratchImage temp;
00089     HRESULT hr = _ConvertToR32G32B32A32( srcImage, temp );
00090     if ( FAILED(hr) )
00091         return hr;
00092
00093     const Image *tsrc = temp.GetImage( 0, 0, 0 );
00094     if ( !tsrc )
00095         return E_POINTER;
00096
00097     ScratchImage rtemp;
00098     hr = rtemp.Initialize2D( DXGI_FORMAT_R32G32B32A32_FLOAT, destImage.width, destImage.height, 1, 1 );
00099     if ( FAILED(hr) )
00100         return hr;
00101
00102     const Image *tdest = rtemp.GetImage( 0, 0, 0 );
00103     if ( !tdest )
00104         return E_POINTER;
00105
00106     hr = _PerformFlipRotateUsingWIC( *tsrc, flags, GUID_WICPixelFormat128bppRGBAFloat, *tdest );
00107     if ( FAILED(hr) )
00108         return hr;
00109
00110     temp.Release();
00111
00112     hr = _ConvertFromR32G32B32A32( *tdest, destImage );
00113     if ( FAILED(hr) )
00114         return hr;
00115
00116     return S_OK;
00117 }
00118
00119
00120 //=====================================================================================
00121 // Entry-points
00122 //=====================================================================================
00123
00124 //-------------------------------------------------------------------------------------
00125 // Flip/rotate image
00126 //-------------------------------------------------------------------------------------
00127 _Use_decl_annotations_
00128 HRESULT FlipRotate( const Image& srcImage, DWORD flags, ScratchImage& image )
00129 {
00130     if ( !srcImage.pixels )
00131         return E_POINTER;
00132
00133     if ( !flags )
00134         return E_INVALIDARG;
00135
00136 #ifdef _AMD64_
00137     if ( (srcImage.width > 0xFFFFFFFF) || (srcImage.height > 0xFFFFFFFF) )
00138         return E_INVALIDARG;
00139 #endif
00140
00141     if ( IsCompressed( srcImage.format ) )
00142     {
00143         // We don't support flip/rotate operations on compressed images
00144         return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
00145     }
00146
00147     static_assert( TEX_FR_ROTATE0 == WICBitmapTransformRotate0, "TEX_FR_ROTATE0 no longer matches WIC" );
00148     static_assert( TEX_FR_ROTATE90 == WICBitmapTransformRotate90, "TEX_FR_ROTATE90 no longer matches WIC" );
00149     static_assert( TEX_FR_ROTATE180 == WICBitmapTransformRotate180, "TEX_FR_ROTATE180 no longer matches WIC" );
00150     static_assert( TEX_FR_ROTATE270 == WICBitmapTransformRotate270, "TEX_FR_ROTATE270 no longer matches WIC" );
00151     static_assert( TEX_FR_FLIP_HORIZONTAL == WICBitmapTransformFlipHorizontal, "TEX_FR_FLIP_HORIZONTAL no longer matches WIC" );
00152     static_assert( TEX_FR_FLIP_VERTICAL == WICBitmapTransformFlipVertical, "TEX_FR_FLIP_VERTICAL no longer matches WIC" );
00153
00154     // Only supports 90, 180, 270, or no rotation flags... not a combination of rotation flags
00155     switch ( flags & (TEX_FR_ROTATE90|TEX_FR_ROTATE180|TEX_FR_ROTATE270) )
00156     {
00157     case 0:
00158     case TEX_FR_ROTATE90:
00159     case TEX_FR_ROTATE180:
00160     case TEX_FR_ROTATE270:
00161         break;
00162
00163     default:
00164         return E_INVALIDARG;
00165     }
00166
00167     size_t nwidth = srcImage.width;
00168     size_t nheight = srcImage.height;
00169
00170     if (flags & (TEX_FR_ROTATE90|TEX_FR_ROTATE270))
00171     {
00172         nwidth = srcImage.height;
00173         nheight = srcImage.width;
00174     }
00175
00176     HRESULT hr = image.Initialize2D( srcImage.format, nwidth, nheight, 1, 1 );
00177     if ( FAILED(hr) )
00178         return hr;
00179
00180     const Image *rimage = image.GetImage( 0, 0, 0 );
00181     if ( !rimage )
00182         return E_POINTER;
00183
00184     WICPixelFormatGUID pfGUID;
00185     if ( _DXGIToWIC( srcImage.format, pfGUID ) )
00186     {
00187         // Case 1: Source format is supported by Windows Imaging Component
00188         hr = _PerformFlipRotateUsingWIC( srcImage, flags, pfGUID, *rimage );
00189     }
00190     else
00191     {
00192         // Case 2: Source format is not supported by WIC, so we have to convert, flip/rotate, and convert back
00193         hr = _PerformFlipRotateViaF32( srcImage, flags, *rimage );
00194     }
00195
00196     if ( FAILED(hr) )
00197     {
00198         image.Release();
00199         return hr;
00200     }
00201
00202     return S_OK;
00203 }
00204
00205
00206 //-------------------------------------------------------------------------------------
00207 // Flip/rotate image (complex)
00208 //-------------------------------------------------------------------------------------
00209 _Use_decl_annotations_
00210 HRESULT FlipRotate( const Image* srcImages, size_t nimages, const TexMetadata& metadata,
00211                     DWORD flags, ScratchImage& result )
00212 {
00213     if ( !srcImages || !nimages )
00214         return E_INVALIDARG;
00215
00216     if ( IsCompressed( metadata.format ) )
00217     {
00218         // We don't support flip/rotate operations on compressed images
00219         return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
00220     }
00221
00222     static_assert( TEX_FR_ROTATE0 == WICBitmapTransformRotate0, "TEX_FR_ROTATE0 no longer matches WIC" );
00223     static_assert( TEX_FR_ROTATE90 == WICBitmapTransformRotate90, "TEX_FR_ROTATE90 no longer matches WIC" );
00224     static_assert( TEX_FR_ROTATE180 == WICBitmapTransformRotate180, "TEX_FR_ROTATE180 no longer matches WIC" );
00225     static_assert( TEX_FR_ROTATE270 == WICBitmapTransformRotate270, "TEX_FR_ROTATE270 no longer matches WIC" );
00226     static_assert( TEX_FR_FLIP_HORIZONTAL == WICBitmapTransformFlipHorizontal, "TEX_FR_FLIP_HORIZONTAL no longer matches WIC" );
00227     static_assert( TEX_FR_FLIP_VERTICAL == WICBitmapTransformFlipVertical, "TEX_FR_FLIP_VERTICAL no longer matches WIC" );
00228
00229     // Only supports 90, 180, 270, or no rotation flags... not a combination of rotation flags
00230     switch ( flags & (TEX_FR_ROTATE90|TEX_FR_ROTATE180|TEX_FR_ROTATE270) )
00231     {
00232     case 0:
00233     case TEX_FR_ROTATE90:
00234     case TEX_FR_ROTATE180:
00235     case TEX_FR_ROTATE270:
00236         break;
00237
00238     default:
00239         return E_INVALIDARG;
00240     }
00241
00242     TexMetadata mdata2 = metadata;
00243
00244     bool flipwh = false;
00245     if (flags & (TEX_FR_ROTATE90|TEX_FR_ROTATE270))
00246     {
00247         flipwh = true;
00248         mdata2.width = metadata.height;
00249         mdata2.height = metadata.width;
00250     }
00251
00252     HRESULT hr = result.Initialize( mdata2 );
00253     if ( FAILED(hr) )
00254         return hr;
00255
00256     if ( nimages != result.GetImageCount() )
00257     {
00258         result.Release();
00259         return E_FAIL;
00260     }
00261
00262     const Image* dest = result.GetImages();
00263     if ( !dest )
00264     {
00265         result.Release();
00266         return E_POINTER;
00267     }
00268
00269     WICPixelFormatGUID pfGUID;
00270     bool wicpf = _DXGIToWIC( metadata.format, pfGUID );
00271
00272     for( size_t index=0; index < nimages; ++index )
00273     {
00274         const Image& src = srcImages[ index ];
00275         if ( src.format != metadata.format )
00276         {
00277             result.Release();
00278             return E_FAIL;
00279         }
00280
00281 #ifdef _AMD64_
00282         if ( (src.width > 0xFFFFFFFF) || (src.height > 0xFFFFFFFF) )
00283             return E_FAIL;
00284 #endif
00285
00286         const Image& dst = dest[ index ];
00287         assert( dst.format == metadata.format );
00288
00289         if ( flipwh )
00290         {
00291             if ( src.width != dst.height || src.height != dst.width )
00292             {
00293                 result.Release();
00294                 return E_FAIL;
00295             }
00296         }
00297         else
00298         {
00299             if ( src.width != dst.width || src.height != dst.height )
00300             {
00301                 result.Release();
00302                 return E_FAIL;
00303             }
00304         }
00305
00306         if (wicpf)
00307         {
00308             // Case 1: Source format is supported by Windows Imaging Component
00309             hr = _PerformFlipRotateUsingWIC( src, flags, pfGUID, dst );
00310         }
00311         else
00312         {
00313             // Case 2: Source format is not supported by WIC, so we have to convert, flip/rotate, and convert back
00314             hr = _PerformFlipRotateViaF32( src, flags, dst );
00315         }
00316
00317         if ( FAILED(hr) )
00318         {
00319             result.Release();
00320             return hr;
00321         }
00322     }
00323
00324     return S_OK;
00325 }
00326
00327 }; // namespace
Generated on Sat Nov 23 2024 16:08:12 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SimpleCommunication::SdkSample Member List

This is the complete list of members for SimpleCommunication::SdkSample, including all inherited members.
__pad0__ | SimpleCommunication::SdkSample |
_dispatcher | SimpleCommunication::SdkSample | [private]
_statusMessage | SimpleCommunication::SdkSample | [private]
ClearLastStatus() | SimpleCommunication::SdkSample |
Deinitialize() | SimpleCommunication::SdkSample |
dispatcher | SimpleCommunication::SdkSample |
DisplayError(Platform::String^msg) | SimpleCommunication::SdkSample |
DisplayStatus(Platform::String^msg) | SimpleCommunication::SdkSample |
FormatError(HResult err, Platform::String^msg, Platform::String^prefix) | SimpleCommunication::SdkSample |
FormatError(CaptureFailedEventArgs^e, Platform::String^prefix) | SimpleCommunication::SdkSample |
Log(Platform::String^message) | SimpleCommunication::SdkSample | [private]
Log(Platform::String^message, Platform::String^tag, Platform::String^type) | SimpleCommunication::SdkSample | [private]
Generated on Sat Nov 23 2024 16:09:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Manipulations and gestures (C++)/C++/pch.h Source File

  • Input Manipulations and gestures (C++)
  • C++

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 // C RunTime Header Files
00011 #include <strsafe.h>
00012 #define _USE_MATH_DEFINES
00013 #include <math.h>
00014
00015 // WinRT Header Files
00016 #include <wrl.h>
00017
00018 // DirectX Header Files
00019 #include <d3d11_1.h>
00020 #include <d2d1_1.h>
00021 #include <d2d1effects.h>
00022 #include <dwrite_1.h>
00023 #include <wincodec.h>
00024 #include <agile.h>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX touch input/C++/DDSTextureLoader.cpp Source File

  • DirectX touch input

DDSTextureLoader.cpp

Go to the documentation of this file.
00001 //--------------------------------------------------------------------------------------
00002 // File: DDSTextureLoader.cpp
00003 //
00004 // Function for loading a DDS texture and creating a Direct3D 11 runtime resource for it
00005 //
00006 // Note this function is 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
00018 #include "pch.h"
00019 #include <dxgiformat.h>
00020 #include <assert.h>
00021 #include <memory>
00022 #include <algorithm>
00023 #include "DDSTextureLoader.h"
00024 #include "DirectXSample.h"
00025
00026 using namespace Microsoft::WRL;
00027
00028 //--------------------------------------------------------------------------------------
00029 // Macros
00030 //--------------------------------------------------------------------------------------
00031 #ifndef MAKEFOURCC
00032     #define MAKEFOURCC(ch0, ch1, ch2, ch3)                              \
00033                 ((uint32)(byte)(ch0) | ((uint32)(byte)(ch1) << 8) |       \
00034                 ((uint32)(byte)(ch2) << 16) | ((uint32)(byte)(ch3) << 24))
00035 #endif /* defined(MAKEFOURCC) */
00036
00037 //--------------------------------------------------------------------------------------
00038 // DDS file structure definitions
00039 //
00040 // See DDS.h in the 'Texconv' sample and the 'DirectXTex' library
00041 //--------------------------------------------------------------------------------------
00042 #pragma pack(push, 1)
00043
00044 #define DDS_MAGIC 0x20534444 // "DDS "
00045
00046 struct DDS_PIXELFORMAT
00047 {
00048     uint32  size;
00049     uint32  flags;
00050     uint32  fourCC;
00051     uint32  RGBBitCount;
00052     uint32  RBitMask;
00053     uint32  GBitMask;
00054     uint32  BBitMask;
00055     uint32  ABitMask;
00056 };
00057
00058 #define DDS_FOURCC      0x00000004  // DDPF_FOURCC
00059 #define DDS_RGB         0x00000040  // DDPF_RGB
00060 #define DDS_RGBA        0x00000041  // DDPF_RGB | DDPF_ALPHAPIXELS
00061 #define DDS_LUMINANCE   0x00020000  // DDPF_LUMINANCE
00062 #define DDS_LUMINANCEA  0x00020001  // DDPF_LUMINANCE | DDPF_ALPHAPIXELS
00063 #define DDS_ALPHA       0x00000002  // DDPF_ALPHA
00064 #define DDS_PAL8        0x00000020  // DDPF_PALETTEINDEXED8
00065
00066 #define DDS_HEADER_FLAGS_TEXTURE        0x00001007  // DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT
00067 #define DDS_HEADER_FLAGS_MIPMAP         0x00020000  // DDSD_MIPMAPCOUNT
00068 #define DDS_HEADER_FLAGS_VOLUME         0x00800000  // DDSD_DEPTH
00069 #define DDS_HEADER_FLAGS_PITCH          0x00000008  // DDSD_PITCH
00070 #define DDS_HEADER_FLAGS_LINEARSIZE     0x00080000  // DDSD_LINEARSIZE
00071
00072 #define DDS_HEIGHT 0x00000002 // DDSD_HEIGHT
00073 #define DDS_WIDTH  0x00000004 // DDSD_WIDTH
00074
00075 #define DDS_SURFACE_FLAGS_TEXTURE 0x00001000 // DDSCAPS_TEXTURE
00076 #define DDS_SURFACE_FLAGS_MIPMAP  0x00400008 // DDSCAPS_COMPLEX | DDSCAPS_MIPMAP
00077 #define DDS_SURFACE_FLAGS_CUBEMAP 0x00000008 // DDSCAPS_COMPLEX
00078
00079 #define DDS_CUBEMAP_POSITIVEX 0x00000600 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEX
00080 #define DDS_CUBEMAP_NEGATIVEX 0x00000a00 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEX
00081 #define DDS_CUBEMAP_POSITIVEY 0x00001200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEY
00082 #define DDS_CUBEMAP_NEGATIVEY 0x00002200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEY
00083 #define DDS_CUBEMAP_POSITIVEZ 0x00004200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEZ
00084 #define DDS_CUBEMAP_NEGATIVEZ 0x00008200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEZ
00085
00086 #define DDS_CUBEMAP_ALLFACES (DDS_CUBEMAP_POSITIVEX | DDS_CUBEMAP_NEGATIVEX |\
00087                               DDS_CUBEMAP_POSITIVEY | DDS_CUBEMAP_NEGATIVEY |\
00088                               DDS_CUBEMAP_POSITIVEZ | DDS_CUBEMAP_NEGATIVEZ)
00089
00090 #define DDS_CUBEMAP 0x00000200 // DDSCAPS2_CUBEMAP
00091
00092 #define DDS_FLAGS_VOLUME 0x00200000 // DDSCAPS2_VOLUME
00093
00094 typedef struct
00095 {
00096     uint32          size;
00097     uint32          flags;
00098     uint32          height;
00099     uint32          width;
00100     uint32          pitchOrLinearSize;
00101     uint32          depth; // only if DDS_HEADER_FLAGS_VOLUME is set in flags
00102     uint32          mipMapCount;
00103     uint32          reserved1[11];
00104     DDS_PIXELFORMAT ddspf;
00105     uint32          caps;
00106     uint32          caps2;
00107     uint32          caps3;
00108     uint32          caps4;
00109     uint32          reserved2;
00110 } DDS_HEADER;
00111
00112 typedef struct
00113 {
00114     DXGI_FORMAT dxgiFormat;
00115     uint32      resourceDimension;
00116     uint32      miscFlag; // see D3D11_RESOURCE_MISC_FLAG
00117     uint32      arraySize;
00118     uint32      reserved;
00119 } DDS_HEADER_DXT10;
00120
00121 #pragma pack(pop)
00122
00123 //--------------------------------------------------------------------------------------
00124 // Return the BPP for a particular format
00125 //--------------------------------------------------------------------------------------
00126 static size_t BitsPerPixel(_In_ DXGI_FORMAT fmt)
00127 {
00128     switch (fmt)
00129     {
00130     case DXGI_FORMAT_R32G32B32A32_TYPELESS:
00131     case DXGI_FORMAT_R32G32B32A32_FLOAT:
00132     case DXGI_FORMAT_R32G32B32A32_UINT:
00133     case DXGI_FORMAT_R32G32B32A32_SINT:
00134         return 128;
00135
00136     case DXGI_FORMAT_R32G32B32_TYPELESS:
00137     case DXGI_FORMAT_R32G32B32_FLOAT:
00138     case DXGI_FORMAT_R32G32B32_UINT:
00139     case DXGI_FORMAT_R32G32B32_SINT:
00140         return 96;
00141
00142     case DXGI_FORMAT_R16G16B16A16_TYPELESS:
00143     case DXGI_FORMAT_R16G16B16A16_FLOAT:
00144     case DXGI_FORMAT_R16G16B16A16_UNORM:
00145     case DXGI_FORMAT_R16G16B16A16_UINT:
00146     case DXGI_FORMAT_R16G16B16A16_SNORM:
00147     case DXGI_FORMAT_R16G16B16A16_SINT:
00148     case DXGI_FORMAT_R32G32_TYPELESS:
00149     case DXGI_FORMAT_R32G32_FLOAT:
00150     case DXGI_FORMAT_R32G32_UINT:
00151     case DXGI_FORMAT_R32G32_SINT:
00152     case DXGI_FORMAT_R32G8X24_TYPELESS:
00153     case DXGI_FORMAT_D32_FLOAT_S8X24_UINT:
00154     case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS:
00155     case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT:
00156         return 64;
00157
00158     case DXGI_FORMAT_R10G10B10A2_TYPELESS:
00159     case DXGI_FORMAT_R10G10B10A2_UNORM:
00160     case DXGI_FORMAT_R10G10B10A2_UINT:
00161     case DXGI_FORMAT_R11G11B10_FLOAT:
00162     case DXGI_FORMAT_R8G8B8A8_TYPELESS:
00163     case DXGI_FORMAT_R8G8B8A8_UNORM:
00164     case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
00165     case DXGI_FORMAT_R8G8B8A8_UINT:
00166     case DXGI_FORMAT_R8G8B8A8_SNORM:
00167     case DXGI_FORMAT_R8G8B8A8_SINT:
00168     case DXGI_FORMAT_R16G16_TYPELESS:
00169     case DXGI_FORMAT_R16G16_FLOAT:
00170     case DXGI_FORMAT_R16G16_UNORM:
00171     case DXGI_FORMAT_R16G16_UINT:
00172     case DXGI_FORMAT_R16G16_SNORM:
00173     case DXGI_FORMAT_R16G16_SINT:
00174     case DXGI_FORMAT_R32_TYPELESS:
00175     case DXGI_FORMAT_D32_FLOAT:
00176     case DXGI_FORMAT_R32_FLOAT:
00177     case DXGI_FORMAT_R32_UINT:
00178     case DXGI_FORMAT_R32_SINT:
00179     case DXGI_FORMAT_R24G8_TYPELESS:
00180     case DXGI_FORMAT_D24_UNORM_S8_UINT:
00181     case DXGI_FORMAT_R24_UNORM_X8_TYPELESS:
00182     case DXGI_FORMAT_X24_TYPELESS_G8_UINT:
00183     case DXGI_FORMAT_R9G9B9E5_SHAREDEXP:
00184     case DXGI_FORMAT_R8G8_B8G8_UNORM:
00185     case DXGI_FORMAT_G8R8_G8B8_UNORM:
00186     case DXGI_FORMAT_B8G8R8A8_UNORM:
00187     case DXGI_FORMAT_B8G8R8X8_UNORM:
00188     case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM:
00189     case DXGI_FORMAT_B8G8R8A8_TYPELESS:
00190     case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
00191     case DXGI_FORMAT_B8G8R8X8_TYPELESS:
00192     case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB:
00193         return 32;
00194
00195     case DXGI_FORMAT_R8G8_TYPELESS:
00196     case DXGI_FORMAT_R8G8_UNORM:
00197     case DXGI_FORMAT_R8G8_UINT:
00198     case DXGI_FORMAT_R8G8_SNORM:
00199     case DXGI_FORMAT_R8G8_SINT:
00200     case DXGI_FORMAT_R16_TYPELESS:
00201     case DXGI_FORMAT_R16_FLOAT:
00202     case DXGI_FORMAT_D16_UNORM:
00203     case DXGI_FORMAT_R16_UNORM:
00204     case DXGI_FORMAT_R16_UINT:
00205     case DXGI_FORMAT_R16_SNORM:
00206     case DXGI_FORMAT_R16_SINT:
00207     case DXGI_FORMAT_B5G6R5_UNORM:
00208     case DXGI_FORMAT_B5G5R5A1_UNORM:
00209     case DXGI_FORMAT_B4G4R4A4_UNORM:
00210         return 16;
00211
00212     case DXGI_FORMAT_R8_TYPELESS:
00213     case DXGI_FORMAT_R8_UNORM:
00214     case DXGI_FORMAT_R8_UINT:
00215     case DXGI_FORMAT_R8_SNORM:
00216     case DXGI_FORMAT_R8_SINT:
00217     case DXGI_FORMAT_A8_UNORM:
00218         return 8;
00219
00220     case DXGI_FORMAT_R1_UNORM:
00221         return 1;
00222
00223     case DXGI_FORMAT_BC1_TYPELESS:
00224     case DXGI_FORMAT_BC1_UNORM:
00225     case DXGI_FORMAT_BC1_UNORM_SRGB:
00226     case DXGI_FORMAT_BC4_TYPELESS:
00227     case DXGI_FORMAT_BC4_UNORM:
00228     case DXGI_FORMAT_BC4_SNORM:
00229         return 4;
00230
00231     case DXGI_FORMAT_BC2_TYPELESS:
00232     case DXGI_FORMAT_BC2_UNORM:
00233     case DXGI_FORMAT_BC2_UNORM_SRGB:
00234     case DXGI_FORMAT_BC3_TYPELESS:
00235     case DXGI_FORMAT_BC3_UNORM:
00236     case DXGI_FORMAT_BC3_UNORM_SRGB:
00237     case DXGI_FORMAT_BC5_TYPELESS:
00238     case DXGI_FORMAT_BC5_UNORM:
00239     case DXGI_FORMAT_BC5_SNORM:
00240     case DXGI_FORMAT_BC6H_TYPELESS:
00241     case DXGI_FORMAT_BC6H_UF16:
00242     case DXGI_FORMAT_BC6H_SF16:
00243     case DXGI_FORMAT_BC7_TYPELESS:
00244     case DXGI_FORMAT_BC7_UNORM:
00245     case DXGI_FORMAT_BC7_UNORM_SRGB:
00246         return 8;
00247
00248     default:
00249         return 0;
00250     }
00251 }
00252
00253
00254 //--------------------------------------------------------------------------------------
00255 // Get surface information for a particular format
00256 //--------------------------------------------------------------------------------------
00257 static void GetSurfaceInfo(
00258     _In_ size_t width,
00259     _In_ size_t height,
00260     _In_ DXGI_FORMAT fmt,
00261     _Out_opt_ size_t* outNumBytes,
00262     _Out_opt_ size_t* outRowBytes,
00263     _Out_opt_ size_t* outNumRows
00264     )
00265 {
00266     size_t numBytes = 0;
00267     size_t rowBytes = 0;
00268     size_t numRows = 0;
00269
00270     bool bc = false;
00271     bool packed  = false;
00272     size_t bcnumBytesPerBlock = 0;
00273     switch (fmt)
00274     {
00275     case DXGI_FORMAT_BC1_TYPELESS:
00276     case DXGI_FORMAT_BC1_UNORM:
00277     case DXGI_FORMAT_BC1_UNORM_SRGB:
00278     case DXGI_FORMAT_BC4_TYPELESS:
00279     case DXGI_FORMAT_BC4_UNORM:
00280     case DXGI_FORMAT_BC4_SNORM:
00281         bc = true;
00282         bcnumBytesPerBlock = 8;
00283         break;
00284
00285     case DXGI_FORMAT_BC2_TYPELESS:
00286     case DXGI_FORMAT_BC2_UNORM:
00287     case DXGI_FORMAT_BC2_UNORM_SRGB:
00288     case DXGI_FORMAT_BC3_TYPELESS:
00289     case DXGI_FORMAT_BC3_UNORM:
00290     case DXGI_FORMAT_BC3_UNORM_SRGB:
00291     case DXGI_FORMAT_BC5_TYPELESS:
00292     case DXGI_FORMAT_BC5_UNORM:
00293     case DXGI_FORMAT_BC5_SNORM:
00294     case DXGI_FORMAT_BC6H_TYPELESS:
00295     case DXGI_FORMAT_BC6H_UF16:
00296     case DXGI_FORMAT_BC6H_SF16:
00297     case DXGI_FORMAT_BC7_TYPELESS:
00298     case DXGI_FORMAT_BC7_UNORM:
00299     case DXGI_FORMAT_BC7_UNORM_SRGB:
00300         bc = true;
00301         bcnumBytesPerBlock = 16;
00302         break;
00303
00304     case DXGI_FORMAT_R8G8_B8G8_UNORM:
00305     case DXGI_FORMAT_G8R8_G8B8_UNORM:
00306         packed = true;
00307         break;
00308     }
00309
00310     if (bc)
00311     {
00312         size_t numBlocksWide = 0;
00313         if (width > 0)
00314         {
00315             numBlocksWide = std::max<size_t>(1, (width + 3) / 4);
00316         }
00317         size_t numBlocksHigh = 0;
00318         if (height > 0)
00319         {
00320             numBlocksHigh = std::max<size_t>(1, (height + 3) / 4);
00321         }
00322         rowBytes = numBlocksWide * bcnumBytesPerBlock;
00323         numRows = numBlocksHigh;
00324     }
00325     else if (packed)
00326     {
00327         rowBytes = ((width + 1) >> 1) * 4;
00328         numRows = height;
00329     }
00330     else
00331     {
00332         size_t bpp = BitsPerPixel(fmt);
00333         rowBytes = (width * bpp + 7) / 8; // round up to nearest byte
00334         numRows = height;
00335     }
00336
00337     numBytes = rowBytes * numRows;
00338     if (outNumBytes)
00339     {
00340         *outNumBytes = numBytes;
00341     }
00342     if (outRowBytes)
00343     {
00344         *outRowBytes = rowBytes;
00345     }
00346     if (outNumRows)
00347     {
00348         *outNumRows = numRows;
00349     }
00350 }
00351
00352
00353 //--------------------------------------------------------------------------------------
00354 #define ISBITMASK(r, g, b, a) (ddpf.RBitMask == r && ddpf.GBitMask == g && ddpf.BBitMask == b && ddpf.ABitMask == a)
00355
00356 static DXGI_FORMAT GetDXGIFormat(const DDS_PIXELFORMAT& ddpf)
00357 {
00358     if (ddpf.flags & DDS_RGB)
00359     {
00360         // Note that sRGB formats are written using the "DX10" extended header
00361
00362         switch (ddpf.RGBBitCount)
00363         {
00364         case 32:
00365             if (ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000))
00366             {
00367                 return DXGI_FORMAT_R8G8B8A8_UNORM;
00368             }
00369
00370             if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000))
00371             {
00372                 return DXGI_FORMAT_B8G8R8A8_UNORM;
00373             }
00374
00375             if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0x00000000))
00376             {
00377                 return DXGI_FORMAT_B8G8R8X8_UNORM;
00378             }
00379
00380             // No DXGI format maps to ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0x00000000) aka D3DFMT_X8B8G8R8
00381
00382             // Note that many common DDS reader/writers (including D3DX) swap the
00383             // the RED/BLUE masks for 10:10:10:2 formats. We assumme
00384             // below that the 'backwards' header mask is being used since it is most
00385             // likely written by D3DX. The more robust solution is to use the 'DX10'
00386             // header extension and specify the DXGI_FORMAT_R10G10B10A2_UNORM format directly
00387
00388             // For 'correct' writers, this should be 0x000003ff, 0x000ffc00, 0x3ff00000 for RGB data
00389             if (ISBITMASK(0x3ff00000, 0x000ffc00, 0x000003ff, 0xc0000000))
00390             {
00391                 return DXGI_FORMAT_R10G10B10A2_UNORM;
00392             }
00393
00394             // No DXGI format maps to ISBITMASK(0x000003ff, 0x000ffc00, 0x3ff00000, 0xc0000000) aka D3DFMT_A2R10G10B10
00395
00396             if (ISBITMASK(0x0000ffff, 0xffff0000, 0x00000000, 0x00000000))
00397             {
00398                 return DXGI_FORMAT_R16G16_UNORM;
00399             }
00400
00401             if (ISBITMASK(0xffffffff, 0x00000000, 0x00000000, 0x00000000))
00402             {
00403                 // Only 32-bit color channel format in D3D9 was R32F
00404                 return DXGI_FORMAT_R32_FLOAT; // D3DX writes this out as a FourCC of 114
00405             }
00406             break;
00407
00408         case 24:
00409             // No 24bpp DXGI formats aka D3DFMT_R8G8B8
00410             break;
00411
00412         case 16:
00413             if (ISBITMASK(0x7c00, 0x03e0, 0x001f, 0x8000))
00414             {
00415                 return DXGI_FORMAT_B5G5R5A1_UNORM;
00416             }
00417             if (ISBITMASK(0xf800, 0x07e0, 0x001f, 0x0000))
00418             {
00419                 return DXGI_FORMAT_B5G6R5_UNORM;
00420             }
00421
00422             // No DXGI format maps to ISBITMASK(0x7c00, 0x03e0, 0x001f, 0x0000) aka D3DFMT_X1R5G5B5
00423             if (ISBITMASK(0x0f00, 0x00f0, 0x000f, 0xf000))
00424             {
00425                 return DXGI_FORMAT_B4G4R4A4_UNORM;
00426             }
00427
00428             // No DXGI format maps to ISBITMASK(0x0f00, 0x00f0, 0x000f, 0x0000) aka D3DFMT_X4R4G4B4
00429
00430             // No 3:3:2, 3:3:2:8, or paletted DXGI formats aka D3DFMT_A8R3G3B2, D3DFMT_R3G3B2, D3DFMT_P8, D3DFMT_A8P8, etc.
00431             break;
00432         }
00433     }
00434     else if (ddpf.flags & DDS_LUMINANCE)
00435     {
00436         if (8 == ddpf.RGBBitCount)
00437         {
00438             if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x00000000))
00439             {
00440                 return DXGI_FORMAT_R8_UNORM; // D3DX10/11 writes this out as DX10 extension
00441             }
00442
00443             // No DXGI format maps to ISBITMASK(0x0f, 0x00, 0x00, 0xf0) aka D3DFMT_A4L4
00444         }
00445
00446         if (16 == ddpf.RGBBitCount)
00447         {
00448             if (ISBITMASK(0x0000ffff, 0x00000000, 0x00000000, 0x00000000))
00449             {
00450                 return DXGI_FORMAT_R16_UNORM; // D3DX10/11 writes this out as DX10 extension
00451             }
00452             if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x0000ff00))
00453             {
00454                 return DXGI_FORMAT_R8G8_UNORM; // D3DX10/11 writes this out as DX10 extension
00455             }
00456         }
00457     }
00458     else if (ddpf.flags & DDS_ALPHA)
00459     {
00460         if (8 == ddpf.RGBBitCount)
00461         {
00462             return DXGI_FORMAT_A8_UNORM;
00463         }
00464     }
00465     else if (ddpf.flags & DDS_FOURCC)
00466     {
00467         if (MAKEFOURCC('D', 'X', 'T', '1') == ddpf.fourCC)
00468         {
00469             return DXGI_FORMAT_BC1_UNORM;
00470         }
00471         if (MAKEFOURCC('D', 'X', 'T', '3') == ddpf.fourCC)
00472         {
00473             return DXGI_FORMAT_BC2_UNORM;
00474         }
00475         if (MAKEFOURCC('D', 'X', 'T', '5') == ddpf.fourCC)
00476         {
00477             return DXGI_FORMAT_BC3_UNORM;
00478         }
00479
00480         // While pre-mulitplied alpha isn't directly supported by the DXGI formats,
00481         // they are basically the same as these BC formats so they can be mapped
00482         if (MAKEFOURCC('D', 'X', 'T', '2') == ddpf.fourCC)
00483         {
00484             return DXGI_FORMAT_BC2_UNORM;
00485         }
00486         if (MAKEFOURCC('D', 'X', 'T', '4') == ddpf.fourCC)
00487         {
00488             return DXGI_FORMAT_BC3_UNORM;
00489         }
00490
00491         if (MAKEFOURCC('A', 'T', 'I', '1') == ddpf.fourCC)
00492         {
00493             return DXGI_FORMAT_BC4_UNORM;
00494         }
00495         if (MAKEFOURCC('B', 'C', '4', 'U') == ddpf.fourCC)
00496         {
00497             return DXGI_FORMAT_BC4_UNORM;
00498         }
00499         if (MAKEFOURCC('B', 'C', '4', 'S') == ddpf.fourCC)
00500         {
00501             return DXGI_FORMAT_BC4_SNORM;
00502         }
00503
00504         if (MAKEFOURCC('A', 'T', 'I', '2') == ddpf.fourCC)
00505         {
00506             return DXGI_FORMAT_BC5_UNORM;
00507         }
00508         if (MAKEFOURCC('B', 'C', '5', 'U') == ddpf.fourCC)
00509         {
00510             return DXGI_FORMAT_BC5_UNORM;
00511         }
00512         if (MAKEFOURCC('B', 'C', '5', 'S') == ddpf.fourCC)
00513         {
00514             return DXGI_FORMAT_BC5_SNORM;
00515         }
00516
00517         // BC6H and BC7 are written using the "DX10" extended header
00518
00519         if (MAKEFOURCC('R', 'G', 'B', 'G') == ddpf.fourCC)
00520         {
00521             return DXGI_FORMAT_R8G8_B8G8_UNORM;
00522         }
00523         if (MAKEFOURCC('G', 'R', 'G', 'B') == ddpf.fourCC)
00524         {
00525             return DXGI_FORMAT_G8R8_G8B8_UNORM;
00526         }
00527
00528         // Check for D3DFORMAT enums being set here
00529         switch (ddpf.fourCC)
00530         {
00531         case 36: // D3DFMT_A16B16G16R16
00532             return DXGI_FORMAT_R16G16B16A16_UNORM;
00533
00534         case 110: // D3DFMT_Q16W16V16U16
00535             return DXGI_FORMAT_R16G16B16A16_SNORM;
00536
00537         case 111: // D3DFMT_R16F
00538             return DXGI_FORMAT_R16_FLOAT;
00539
00540         case 112: // D3DFMT_G16R16F
00541             return DXGI_FORMAT_R16G16_FLOAT;
00542
00543         case 113: // D3DFMT_A16B16G16R16F
00544             return DXGI_FORMAT_R16G16B16A16_FLOAT;
00545
00546         case 114: // D3DFMT_R32F
00547             return DXGI_FORMAT_R32_FLOAT;
00548
00549         case 115: // D3DFMT_G32R32F
00550             return DXGI_FORMAT_R32G32_FLOAT;
00551
00552         case 116: // D3DFMT_A32B32G32R32F
00553             return DXGI_FORMAT_R32G32B32A32_FLOAT;
00554         }
00555     }
00556
00557     return DXGI_FORMAT_UNKNOWN;
00558 }
00559
00560
00561 //--------------------------------------------------------------------------------------
00562 static void FillInitData(
00563     _In_ size_t width,
00564     _In_ size_t height,
00565     _In_ size_t depth,
00566     _In_ size_t mipCount,
00567     _In_ size_t arraySize,
00568     _In_ DXGI_FORMAT format,
00569     _In_ size_t maxsize,
00570     _In_ size_t bitSize,
00571     _In_reads_bytes_(bitSize) const byte* bitData,
00572     _Out_ size_t& twidth,
00573     _Out_ size_t& theight,
00574     _Out_ size_t& tdepth,
00575     _Out_ size_t& skipMip,
00576     _Out_writes_(mipCount*arraySize) D3D11_SUBRESOURCE_DATA* initData
00577     )
00578 {
00579     if (!bitData || !initData)
00580     {
00581         throw ref new Platform::InvalidArgumentException();
00582     }
00583
00584     skipMip = 0;
00585     twidth = 0;
00586     theight = 0;
00587     tdepth = 0;
00588
00589     size_t NumBytes = 0;
00590     size_t RowBytes = 0;
00591     size_t NumRows = 0;
00592     const byte* pSrcBits = bitData;
00593     const byte* pEndBits = bitData + bitSize;
00594
00595     size_t index = 0;
00596     for (size_t j = 0; j < arraySize; j++)
00597     {
00598         size_t w = width;
00599         size_t h = height;
00600         size_t d = depth;
00601         for (size_t i = 0; i < mipCount; i++)
00602         {
00603             GetSurfaceInfo(w, h, format, &NumBytes, &RowBytes, &NumRows);
00604
00605             if ((mipCount <= 1) || !maxsize || (w <= maxsize && h <= maxsize && d <= maxsize))
00606             {
00607                 if (!twidth)
00608                 {
00609                     twidth = w;
00610                     theight = h;
00611                     tdepth = d;
00612                 }
00613
00614                 initData[index].pSysMem = (const void*)pSrcBits;
00615                 initData[index].SysMemPitch = static_cast<UINT>(RowBytes);
00616                 initData[index].SysMemSlicePitch = static_cast<UINT>(NumBytes);
00617                 ++index;
00618             }
00619             else
00620             {
00621                 ++skipMip;
00622             }
00623
00624             if (pSrcBits + (NumBytes*d) > pEndBits)
00625             {
00626                 throw ref new Platform::OutOfBoundsException();
00627             }
00628
00629             pSrcBits += NumBytes * d;
00630
00631             w = w >> 1;
00632             h = h >> 1;
00633             d = d >> 1;
00634             if (w == 0)
00635             {
00636                 w = 1;
00637             }
00638             if (h == 0)
00639             {
00640                 h = 1;
00641             }
00642             if (d == 0)
00643             {
00644                 d = 1;
00645             }
00646         }
00647     }
00648
00649     if (!index)
00650     {
00651         throw ref new Platform::FailureException();
00652     }
00653 }
00654
00655
00656 //--------------------------------------------------------------------------------------
00657 static HRESULT CreateD3DResources(
00658     _In_ ID3D11Device* d3dDevice,
00659     _In_ uint32 resDim,
00660     _In_ size_t width,
00661     _In_ size_t height,
00662     _In_ size_t depth,
00663     _In_ size_t mipCount,
00664     _In_ size_t arraySize,
00665     _In_ DXGI_FORMAT format,
00666     _In_ bool isCubeMap,
00667     _In_reads_(mipCount*arraySize) D3D11_SUBRESOURCE_DATA* initData,
00668     _Out_opt_ ID3D11Resource** texture,
00669     _Out_opt_ ID3D11ShaderResourceView** textureView
00670     )
00671 {
00672     if (!d3dDevice || !initData)
00673     {
00674         return E_INVALIDARG;
00675     }
00676
00677     HRESULT hr = E_FAIL;
00678
00679     switch (resDim)
00680     {
00681         case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
00682             {
00683                 D3D11_TEXTURE1D_DESC desc;
00684                 desc.Width = static_cast<UINT>(width);
00685                 desc.MipLevels = static_cast<UINT>(mipCount);
00686                 desc.ArraySize = static_cast<UINT>(arraySize);
00687                 desc.Format = format;
00688                 desc.Usage = D3D11_USAGE_DEFAULT;
00689                 desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
00690                 desc.CPUAccessFlags = 0;
00691                 desc.MiscFlags = 0;
00692
00693                 ID3D11Texture1D* tex = nullptr;
00694                 hr = d3dDevice->CreateTexture1D(&desc, initData, &tex);
00695
00696                 if (SUCCEEDED(hr) && tex != 0)
00697                 {
00698                     if (textureView != 0)
00699                     {
00700                         D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
00701                         memset(&SRVDesc, 0, sizeof(SRVDesc));
00702                         SRVDesc.Format = format;
00703
00704                         if (arraySize > 1)
00705                         {
00706                             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE1DARRAY;
00707                             SRVDesc.Texture1DArray.MipLevels = desc.MipLevels;
00708                             SRVDesc.Texture1DArray.ArraySize = static_cast<UINT>(arraySize);
00709                         }
00710                         else
00711                         {
00712                             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE1D;
00713                             SRVDesc.Texture1D.MipLevels = desc.MipLevels;
00714                         }
00715
00716                         hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView);
00717
00718                         if (FAILED(hr))
00719                         {
00720                             tex->Release();
00721                             return hr;
00722                         }
00723                     }
00724
00725                     if (texture != 0)
00726                     {
00727                         *texture = tex;
00728                     }
00729                     else
00730                     {
00731                         tex->Release();
00732                     }
00733                 }
00734             }
00735             break;
00736
00737         case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
00738             {
00739                 D3D11_TEXTURE2D_DESC desc;
00740                 desc.Width = static_cast<UINT>(width);
00741                 desc.Height = static_cast<UINT>(height);
00742                 desc.MipLevels = static_cast<UINT>(mipCount);
00743                 desc.ArraySize = static_cast<UINT>(arraySize);
00744                 desc.Format = format;
00745                 desc.SampleDesc.Count = 1;
00746                 desc.SampleDesc.Quality = 0;
00747                 desc.Usage = D3D11_USAGE_DEFAULT;
00748                 desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
00749                 desc.CPUAccessFlags = 0;
00750                 desc.MiscFlags = (isCubeMap) ? D3D11_RESOURCE_MISC_TEXTURECUBE : 0;
00751
00752                 ID3D11Texture2D* tex = nullptr;
00753                 hr = d3dDevice->CreateTexture2D(&desc, initData, &tex);
00754
00755                 if (SUCCEEDED(hr) && tex != 0)
00756                 {
00757                     if (textureView != 0)
00758                     {
00759                         D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
00760                         memset(&SRVDesc, 0, sizeof(SRVDesc));
00761                         SRVDesc.Format = format;
00762
00763                         if (isCubeMap)
00764                         {
00765                             if (arraySize > 6)
00766                             {
00767                                 SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURECUBEARRAY;
00768                                 SRVDesc.TextureCubeArray.MipLevels = desc.MipLevels;
00769
00770                                 // Earlier we set arraySize to (NumCubes * 6)
00771                                 SRVDesc.TextureCubeArray.NumCubes = static_cast<UINT>(arraySize / 6);
00772                             }
00773                             else
00774                             {
00775                                 SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURECUBE;
00776                                 SRVDesc.TextureCube.MipLevels = desc.MipLevels;
00777                             }
00778                         }
00779                         else if (arraySize > 1)
00780                         {
00781                             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE2DARRAY;
00782                             SRVDesc.Texture2DArray.MipLevels = desc.MipLevels;
00783                             SRVDesc.Texture2DArray.ArraySize = static_cast<UINT>(arraySize);
00784                         }
00785                         else
00786                         {
00787                             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE2D;
00788                             SRVDesc.Texture2D.MipLevels = desc.MipLevels;
00789                         }
00790
00791                         hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView);
00792
00793                         if (FAILED(hr))
00794                         {
00795                             tex->Release();
00796                             return hr;
00797                         }
00798                     }
00799
00800                     if (texture != 0)
00801                     {
00802                         *texture = tex;
00803                     }
00804                     else
00805                     {
00806                         tex->Release();
00807                     }
00808                 }
00809             }
00810             break;
00811
00812         case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
00813             {
00814                 D3D11_TEXTURE3D_DESC desc;
00815                 desc.Width = static_cast<UINT>(width);
00816                 desc.Height = static_cast<UINT>(height);
00817                 desc.Depth = static_cast<UINT>(depth);
00818                 desc.MipLevels = static_cast<UINT>(mipCount);
00819                 desc.Format = format;
00820                 desc.Usage = D3D11_USAGE_DEFAULT;
00821                 desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
00822                 desc.CPUAccessFlags = 0;
00823                 desc.MiscFlags = 0;
00824
00825                 ID3D11Texture3D* tex = nullptr;
00826                 hr = d3dDevice->CreateTexture3D(&desc, initData, &tex);
00827
00828                 if (SUCCEEDED(hr) && tex != 0)
00829                 {
00830                     if (textureView != 0)
00831                     {
00832                         D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
00833                         memset(&SRVDesc, 0, sizeof(SRVDesc));
00834                         SRVDesc.Format = format;
00835                         SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE3D;
00836                         SRVDesc.Texture3D.MipLevels = desc.MipLevels;
00837
00838                         hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView);
00839
00840                         if (FAILED(hr))
00841                         {
00842                             tex->Release();
00843                             return hr;
00844                         }
00845                     }
00846
00847                     if (texture != 0)
00848                     {
00849                         *texture = tex;
00850                     }
00851                     else
00852                     {
00853                         tex->Release();
00854                     }
00855                 }
00856             }
00857             break;
00858     }
00859
00860     return hr;
00861 }
00862
00863
00864 //--------------------------------------------------------------------------------------
00865 static void CreateTextureFromDDS(
00866     _In_ ID3D11Device* d3dDevice,
00867     _In_ const DDS_HEADER* header,
00868     _In_reads_bytes_(bitSize) const byte* bitData,
00869     _In_ size_t bitSize,
00870     _Out_opt_ ID3D11Resource** texture,
00871     _Out_opt_ ID3D11ShaderResourceView** textureView,
00872     _In_ size_t maxsize
00873     )
00874 {
00875     HRESULT hr = S_OK;
00876
00877     size_t width = header->width;
00878     size_t height = header->height;
00879     size_t depth = header->depth;
00880
00881     uint32 resDim = D3D11_RESOURCE_DIMENSION_UNKNOWN;
00882     size_t arraySize = 1;
00883     DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;
00884     bool isCubeMap = false;
00885
00886     size_t mipCount = header->mipMapCount;
00887     if (0 == mipCount)
00888     {
00889         mipCount = 1;
00890     }
00891
00892     if ((header->ddspf.flags & DDS_FOURCC) &&
00893         (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC))
00894     {
00895         const DDS_HEADER_DXT10* d3d10ext = reinterpret_cast<const DDS_HEADER_DXT10*>((const char*)header + sizeof(DDS_HEADER));
00896
00897         arraySize = d3d10ext->arraySize;
00898         if (arraySize == 0)
00899         {
00900             throw ref new Platform::FailureException();
00901         }
00902
00903         if (BitsPerPixel(d3d10ext->dxgiFormat) == 0)
00904         {
00905             throw ref new Platform::FailureException();
00906         }
00907
00908         format = d3d10ext->dxgiFormat;
00909
00910         switch (d3d10ext->resourceDimension)
00911         {
00912         case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
00913             // D3DX writes 1D textures with a fixed Height of 1
00914             if ((header->flags & DDS_HEIGHT) && height != 1)
00915             {
00916                 throw ref new Platform::FailureException();
00917             }
00918             height = depth = 1;
00919             break;
00920
00921         case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
00922             if (d3d10ext->miscFlag & D3D11_RESOURCE_MISC_TEXTURECUBE)
00923             {
00924                 arraySize *= 6;
00925                 isCubeMap = true;
00926             }
00927             depth = 1;
00928             break;
00929
00930         case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
00931             if (!(header->flags & DDS_HEADER_FLAGS_VOLUME))
00932             {
00933                 throw ref new Platform::FailureException();
00934             }
00935
00936             if (arraySize > 1)
00937             {
00938                 throw ref new Platform::FailureException();
00939             }
00940             break;
00941
00942         default:
00943             return throw ref new Platform::FailureException();
00944         }
00945
00946         resDim = d3d10ext->resourceDimension;
00947     }
00948     else
00949     {
00950         format = GetDXGIFormat(header->ddspf);
00951
00952         if (format == DXGI_FORMAT_UNKNOWN)
00953         {
00954             return throw ref new Platform::FailureException();
00955         }
00956
00957         if (header->flags & DDS_HEADER_FLAGS_VOLUME)
00958         {
00959             resDim = D3D11_RESOURCE_DIMENSION_TEXTURE3D;
00960         }
00961         else
00962         {
00963             if (header->caps2 & DDS_CUBEMAP)
00964             {
00965                 // We require all six faces to be defined
00966                 if ((header->caps2 & DDS_CUBEMAP_ALLFACES) != DDS_CUBEMAP_ALLFACES)
00967                 {
00968                     return throw ref new Platform::FailureException();
00969                 }
00970
00971                 arraySize = 6;
00972                 isCubeMap = true;
00973             }
00974
00975             depth = 1;
00976             resDim = D3D11_RESOURCE_DIMENSION_TEXTURE2D;
00977
00978             // Note there's no way for a legacy Direct3D 9 DDS to express a '1D' texture
00979         }
00980
00981         assert(BitsPerPixel(format) != 0);
00982     }
00983
00984     // Bound sizes (for security purposes we don't trust DDS file metadata larger than the D3D 11.x hardware requirements)
00985     if (mipCount > D3D11_REQ_MIP_LEVELS)
00986     {
00987         return throw ref new Platform::FailureException();
00988     }
00989
00990     switch (resDim)
00991     {
00992         case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
00993             if ((arraySize > D3D11_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION) ||
00994                 (width > D3D11_REQ_TEXTURE1D_U_DIMENSION))
00995             {
00996                 return throw ref new Platform::FailureException();
00997             }
00998             break;
00999
01000         case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
01001             if (isCubeMap)
01002             {
01003                 // This is the right bound because we set arraySize to (NumCubes*6) above
01004                 if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) ||
01005                     (width > D3D11_REQ_TEXTURECUBE_DIMENSION) ||
01006                     (height > D3D11_REQ_TEXTURECUBE_DIMENSION))
01007                 {
01008                     return throw ref new Platform::FailureException();
01009                 }
01010             }
01011             else if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) ||
01012                     (width > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION) ||
01013                     (height > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION))
01014             {
01015                 return throw ref new Platform::FailureException();
01016             }
01017             break;
01018
01019         case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
01020             if ((arraySize > 1) ||
01021                 (width > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) ||
01022                 (height > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) ||
01023                 (depth > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION))
01024             {
01025                 return throw ref new Platform::FailureException();
01026             }
01027             break;
01028     }
01029
01030     // Create the texture
01031     std::unique_ptr<D3D11_SUBRESOURCE_DATA> initData(new D3D11_SUBRESOURCE_DATA[mipCount * arraySize]);
01032
01033     size_t skipMip = 0;
01034     size_t twidth = 0;
01035     size_t theight = 0;
01036     size_t tdepth = 0;
01037     FillInitData(width, height, depth, mipCount, arraySize, format, maxsize, bitSize, bitData, twidth, theight, tdepth, skipMip, initData.get());
01038
01039     hr = CreateD3DResources(d3dDevice, resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize, format, isCubeMap, initData.get(), texture, textureView);
01040
01041     if (FAILED(hr) && !maxsize && (mipCount > 1))
01042     {
01043         // Retry with a maxsize determined by feature level
01044         switch (d3dDevice->GetFeatureLevel())
01045         {
01046         case D3D_FEATURE_LEVEL_9_1:
01047         case D3D_FEATURE_LEVEL_9_2:
01048             if (isCubeMap)
01049             {
01050                 maxsize = D3D_FL9_1_REQ_TEXTURECUBE_DIMENSION;
01051             }
01052             else
01053             {
01054                 maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D)
01055                     ? D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION
01056                     : D3D_FL9_1_REQ_TEXTURE2D_U_OR_V_DIMENSION;
01057             }
01058             break;
01059
01060         case D3D_FEATURE_LEVEL_9_3:
01061             maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D)
01062                 ? D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION
01063                 : D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION;
01064             break;
01065
01066         default: // D3D_FEATURE_LEVEL_10_0 & D3D_FEATURE_LEVEL_10_1
01067             maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D)
01068                 ? D3D10_REQ_TEXTURE3D_U_V_OR_W_DIMENSION
01069                 : D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION;
01070             break;
01071         }
01072
01073         FillInitData(width, height, depth, mipCount, arraySize, format, maxsize, bitSize, bitData, twidth, theight, tdepth, skipMip, initData.get());
01074
01075         hr = CreateD3DResources(d3dDevice, resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize, format, isCubeMap, initData.get(), texture, textureView);
01076     }
01077
01078     DX::ThrowIfFailed(hr);
01079 }
01080
01081 //--------------------------------------------------------------------------------------
01082 void CreateDDSTextureFromMemory(
01083     _In_ ID3D11Device* d3dDevice,
01084     _In_reads_bytes_(ddsDataSize) const byte* ddsData,
01085     _In_ size_t ddsDataSize,
01086     _Out_opt_ ID3D11Resource** texture,
01087     _Out_opt_ ID3D11ShaderResourceView** textureView,
01088     _In_ size_t maxsize
01089     )
01090 {
01091     if (!d3dDevice || !ddsData || (!texture && !textureView))
01092     {
01093         throw ref new Platform::InvalidArgumentException();
01094     }
01095
01096     // Validate DDS file in memory
01097     if (ddsDataSize < (sizeof(uint32) + sizeof(DDS_HEADER)))
01098     {
01099         throw ref new Platform::FailureException();
01100     }
01101
01102     uint32 dwMagicNumber = *(const uint32*)(ddsData);
01103     if (dwMagicNumber != DDS_MAGIC)
01104     {
01105         throw ref new Platform::FailureException();
01106     }
01107
01108     const DDS_HEADER* header = reinterpret_cast<const DDS_HEADER*>(ddsData + sizeof(uint32));
01109
01110     // Verify header to validate DDS file
01111     if (header->size != sizeof(DDS_HEADER) ||
01112         header->ddspf.size != sizeof(DDS_PIXELFORMAT))
01113     {
01114         throw ref new Platform::FailureException();
01115     }
01116
01117     // Check for DX10 extension
01118     bool bDXT10Header = false;
01119     if ((header->ddspf.flags & DDS_FOURCC) &&
01120         (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC))
01121     {
01122         // Must be long enough for both headers and magic value
01123         if (ddsDataSize < (sizeof(DDS_HEADER) + sizeof(uint32) + sizeof(DDS_HEADER_DXT10)))
01124         {
01125             throw ref new Platform::FailureException();
01126         }
01127
01128         bDXT10Header = true;
01129     }
01130
01131     ptrdiff_t offset = sizeof(uint32) + sizeof(DDS_HEADER) + (bDXT10Header ? sizeof(DDS_HEADER_DXT10) : 0);
01132
01133     CreateTextureFromDDS(d3dDevice, header, ddsData + offset, ddsDataSize - offset, texture, textureView, maxsize);
01134 }
Generated on Sat Nov 23 2024 16:08:11 for Win8-Examples by doxygen 1.7.1


Win8-Examples: User domain name/C++/MainPage.xaml.cpp Source File

  • User domain name

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:44 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/pch.cpp Source File

  • Hilo C++
  • Hilo

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 // pch.cpp
00009 // Include the standard header and generate the precompiled header.
00010 //
00011
00012 #include "pch.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Scheduled notifications/C#,C++/App.xaml.h Source File

  • Scheduled notifications
  • C#,C++

App.xaml.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 //
00009 // App.xaml.h
00010 // Declaration of the App.xaml class.
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "App.g.h"
00017
00018 namespace ScheduledNotificationsSampleCPP
00019 {
00020     ref class App sealed
00021     {
00022     public:
00023         App();
00024         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00025         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00026     };
00027 }
00028
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File access/C++/Scenario1.xaml.h Source File

  • File access

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 SDKSample
00023 {
00024     namespace FileAccess
00025     {
00026         /// <summary>
00027         /// An empty page that can be used on its own or navigated to within a Frame.
00028         /// </summary>
00029         public ref class Scenario1 sealed
00030         {
00031         public:
00032             Scenario1();
00033
00034         private:
00035             MainPage^ rootPage;
00036
00037             void CreateFileButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038         };
00039     }
00040 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: SimpleOrientationSensor/C++/Constants.cpp Source File

  • SimpleOrientationSensor

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     { "Simple orientation sensor data events", "SDKSample.SimpleOrientationSensorCPP.Scenario1" },
00020     { "Poll simple orientation sensor readings", "SDKSample.SimpleOrientationSensorCPP.Scenario2" }
00021 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/ScenarioInput2.xaml.h Source File

  • Media extensions

ScenarioInput2.xaml.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 //
00009 // Scenario2Input.xaml.h
00010 // Declaration of the Scenario2Input class.
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioInput2.g.h"
00017 #include "MainPage.g.h"
00018
00019 namespace MediaExtensionsCPP
00020 {
00021     [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class ScenarioInput2 sealed
00023     {
00024     public:
00025         ScenarioInput2();
00026
00027     protected:
00028         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030
00031     private:
00032         ~ScenarioInput2();
00033         MainPage^ rootPage;
00034         Windows::UI::Xaml::Controls::MediaElement^ outputVideo;
00035
00036         void rootPage_OutputFrameLoaded(Object^ sender, Object^ e);
00037         void Circle_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038         void Square_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039         void Triangle_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         Windows::Foundation::EventRegistrationToken _frameLoadedToken;
00041     };
00042 }
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File and folder thumbnail/C++/pch.h Source File

  • File and folder thumbnail

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: LightSensor/C++/Scenario2.xaml.cpp Source File

  • LightSensor

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 SDKSample::LightSensorCPP;
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::Devices::Sensors;
00025 using namespace Windows::Foundation;
00026 using namespace Windows::UI::Core;
00027 using namespace Platform;
00028
00029 Scenario2::Scenario2() : rootPage(MainPage::Current), desiredReportInterval(0)
00030 {
00031     InitializeComponent();
00032
00033     sensor = LightSensor::GetDefault();
00034     if (sensor != nullptr)
00035     {
00036         // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
00037         // This value will be used later to activate the sensor.
00038         uint32 minReportInterval = sensor->MinimumReportInterval;
00039         desiredReportInterval = minReportInterval > 100 ? minReportInterval : 100;
00040
00041         // Set up a DispatchTimer
00042         TimeSpan span;
00043         span.Duration = static_cast<int32>(desiredReportInterval) * 10000;   // convert to 100ns ticks
00044         dispatcherTimer = ref new DispatcherTimer();
00045         dispatcherTimer->Interval = span;
00046         dispatcherTimer->Tick += ref new Windows::Foundation::EventHandler<Object^>(this, &Scenario2::DisplayCurrentReading);
00047     }
00048     else
00049     {
00050         rootPage->NotifyUser("No light sensor found", NotifyType::ErrorMessage);
00051     }
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 void Scenario2::OnNavigatedTo(NavigationEventArgs^ e)
00060 {
00061     ScenarioEnableButton->IsEnabled = true;
00062     ScenarioDisableButton->IsEnabled = false;
00063 }
00064
00065 /// <summary>
00066 /// Invoked when this page is no longer displayed.
00067 /// </summary>
00068 /// <param name="e"></param>
00069 void Scenario2::OnNavigatedFrom(NavigationEventArgs^ e)
00070 {
00071     if (ScenarioDisableButton->IsEnabled)
00072     {
00073         Window::Current->VisibilityChanged::remove(visibilityToken);
00074         dispatcherTimer->Stop();
00075
00076         // Restore the default report interval to release resources while the sensor is not in use
00077         sensor->ReportInterval = 0;
00078     }
00079 }
00080
00081 /// <summary>
00082 /// This is the event handler for VisibilityChanged events. You would register for these notifications
00083 /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00084 /// </summary>
00085 /// <param name="sender"></param>
00086 /// <param name="e">
00087 /// Event data that can be examined for the current visibility state.
00088 /// </param>
00089 void Scenario2::VisibilityChanged(Object^ sender, VisibilityChangedEventArgs^ e)
00090 {
00091     // The app should watch for VisibilityChanged events to disable and re-enable sensor input as appropriate
00092     if (ScenarioDisableButton->IsEnabled)
00093     {
00094         if (e->Visible)
00095         {
00096             // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00097             dispatcherTimer->Start();
00098         }
00099         else
00100         {
00101             // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00102             dispatcherTimer->Stop();
00103         }
00104     }
00105 }
00106
00107 void Scenario2::DisplayCurrentReading(Object^ sender, Object^ e)
00108 {
00109     LightSensorReading^ reading = sensor->GetCurrentReading();
00110     if (reading != nullptr)
00111     {
00112         ScenarioOutput_LUX->Text = reading->IlluminanceInLux.ToString();
00113     }
00114 }
00115
00116 void Scenario2::ScenarioEnable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00117 {
00118     if (sensor != nullptr)
00119     {
00120         visibilityToken = Window::Current->VisibilityChanged::add(ref new WindowVisibilityChangedEventHandler(this, &Scenario2::VisibilityChanged));
00121
00122         // Set the report interval to enable the sensor for polling
00123         sensor->ReportInterval = desiredReportInterval;
00124
00125         dispatcherTimer->Start();
00126
00127         ScenarioEnableButton->IsEnabled = false;
00128         ScenarioDisableButton->IsEnabled = true;
00129     }
00130     else
00131     {
00132         rootPage->NotifyUser("No light sensor found", NotifyType::ErrorMessage);
00133     }
00134 }
00135
00136 void Scenario2::ScenarioDisable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00137 {
00138     Window::Current->VisibilityChanged::remove(visibilityToken);
00139
00140     dispatcherTimer->Stop();
00141
00142     // Restore the default report interval to release resources while the sensor is not in use
00143     sensor->ReportInterval = 0;
00144
00145     ScenarioEnableButton->IsEnabled = true;
00146     ScenarioDisableButton->IsEnabled = false;
00147 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SecondaryTiles::MainPage Member List

This is the complete list of members for SecondaryTiles::MainPage, including all inherited members.
scenariosInner SecondaryTiles::MainPage [private, static]
Generated on Sat Nov 23 2024 16:09:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CryptoWinRT/C++/Scenario3.xaml.h Source File

  • CryptoWinRT

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 SDKSample
00023 {
00024     namespace CryptoWinRT
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             void RunSample_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Hilo::IResourceLoader Member List

This is the complete list of members for Hilo::IResourceLoader, including all inherited members.
GetString(Platform::String^value) Hilo::IResourceLoader
Generated on Sat Nov 23 2024 16:09:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/MediaExtensions/Invert/TextureLock.h Source File

  • Media extensions
  • MediaExtensions
  • Invert

TextureLock.h

Go to the documentation of this file.
00001 #pragma once
00002 #include <assert.h>
00003 #include <D3D11.h>
00004 #include <wrl\client.h>
00005
00006 using namespace Microsoft::WRL;
00007
00008 class TextureLock
00009 {
00010 public:
00011   TextureLock( ID3D11DeviceContext *pContext, ID3D11Texture2D *pTex ) : _pTex(pTex), _pContext(pContext), _bLocked(false) {}
00012
00013   ~TextureLock()
00014   {
00015     assert(_pContext);
00016     assert(_pTex);
00017     if (_pTex && _bLocked)
00018     {
00019
00020       _pContext->Unmap(_pTex.Get(), _uiIndex);
00021       _bLocked = false;
00022     }
00023   }
00024
00025   HRESULT Map(UINT uiIndex, D3D11_MAP mapType, UINT mapFlags)
00026   {
00027     HRESULT hr = S_OK;
00028     assert(_pTex);
00029     assert(_pContext);
00030     assert(!_bLocked);
00031
00032     hr = _pContext->Map(_pTex.Get(), uiIndex, mapType, mapFlags, &map);
00033     _bLocked = SUCCEEDED(hr);
00034     _uiIndex = uiIndex;
00035     return hr;
00036   }
00037
00038   D3D11_MAPPED_SUBRESOURCE map;
00039
00040 private:
00041   ComPtr<ID3D11Texture2D> _pTex;
00042   ComPtr<ID3D11DeviceContext> _pContext;
00043   UINT _uiIndex;
00044   bool _bLocked;
00045 };
Generated on Sat Nov 23 2024 16:08:21 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SoundEffectData Member List

This is the complete list of members for SoundEffectData, including all inherited members.
m_audioBuffer | SoundEffectData
m_soundEffectBufferData | SoundEffectData
m_soundEffectBufferLength | SoundEffectData
m_soundEffectSampleRate | SoundEffectData
m_soundEffectSourceVoice | SoundEffectData
m_soundEffectStarted | SoundEffectData
m_soundEventType | SoundEffectData
Generated on Sat Nov 23 2024 16:09:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

Postcard::sealed Member List

This is the complete list of members for Postcard::sealed, including all inherited members.
AddButtonClicked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Postcard::sealed | [private]
AddConstructionPaperClicked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Postcard::sealed | [private]
AddEffectsClicked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Postcard::sealed | [private]
AddImage() | Postcard::sealed | [private]
AddPaperClicked | Postcard::sealed |
AddSignatureClicked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Postcard::sealed | [private]
AddTextClicked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Postcard::sealed | [private]
App() | Postcard::sealed |
EffectIntensityChanged | Postcard::sealed |
EffectIntensitySliderChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^e) | Postcard::sealed |
EffectIntensitySliderChanged(Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^e) | Postcard::sealed | [private]
EffectsFlyout() | Postcard::sealed |
EraseButtonClicked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Postcard::sealed | [private]
EraseClicked | Postcard::sealed |
EraseClicked() | Postcard::sealed | [private]
GotFocusHandler(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Postcard::sealed | [private]
Hide() | Postcard::sealed | [private]
Hide() | Postcard::sealed | [private]
LostFocusHandler(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Postcard::sealed | [private]
m_atStartScreen | Postcard::sealed | [private]
m_mainPage | Postcard::sealed | [private]
m_renderer | Postcard::sealed | [private]
MainPage() | Postcard::sealed |
MoveButtonClicked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Postcard::sealed | [private]
MovePaperClicked | Postcard::sealed |
OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^args) override | Postcard::sealed | [virtual]
OnLogicalDpiChanged(Platform::Object^sender) | Postcard::sealed | [private]
OnPointerMoved(Platform::Object^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^args) | Postcard::sealed | [private]
OnPointerPressed(Platform::Object^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^args) | Postcard::sealed | [private]
OnPointerReleased(Platform::Object^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^args) | Postcard::sealed | [private]
OnWindowSizeChanged(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::WindowSizeChangedEventArgs^args) | Postcard::sealed | [private]
PaperFlyout() | Postcard::sealed |
PaperFlyoutAddPaperClicked() | Postcard::sealed | [private]
PaperFlyoutDeletePaperClicked() | Postcard::sealed | [private]
PaperFlyoutMoveClicked() | Postcard::sealed | [private]
PaperFlyoutStampClicked() | Postcard::sealed | [private]
RemoveButtonClicked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Postcard::sealed | [private]
RemovePaperClicked | Postcard::sealed |
ResetClicked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Postcard::sealed | [private]
SaveClicked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Postcard::sealed | [private]
ShareClicked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Postcard::sealed | [private]
SignatureFlyout() | Postcard::sealed |
SignButtonCicked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Postcard::sealed | [private]
SignClicked | Postcard::sealed |
SignClicked() | Postcard::sealed | [private]
StampButtonClicked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | Postcard::sealed | [private]
StampPaperClicked | Postcard::sealed |
TextBoxKeyUp(Platform::Object^sender, Windows::UI::Xaml::Input::KeyRoutedEventArgs^e) | Postcard::sealed | [private]
TextFlyout() | Postcard::sealed |
TextSubmitted | Postcard::sealed |
TextSubmitted(Platform::String^text) | Postcard::sealed | [private]
Generated on Sat Nov 23 2024 16:09:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Portable device API/C++/Constants.cpp Source File

  • Portable device API

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016 using namespace Microsoft::WRL;
00017 using namespace Platform;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::UI::Core;
00020 using namespace Windows::UI::Xaml::Controls;
00021
00022 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00023 {
00024     { "Get device properties", "SDKSample.PortableDeviceCPP.S1_DeviceProperties" },
00025     { "List objects", "SDKSample.PortableDeviceCPP.S2_Enumeration" },
00026     { "Send file to device", "SDKSample.PortableDeviceCPP.S3_SendToDevice" },
00027     { "Get file from device", "SDKSample.PortableDeviceCPP.S4_GetFromDevice" },
00028     { "Event registration", "SDKSample.PortableDeviceCPP.S5_Events" },
00029     { "Get device status", "SDKSample.PortableDeviceCPP.S6_DeviceStatus" }
00030 };
00031
00032 /// <summary>
00033 /// Calls MainPage::NotifyUser from the UI thread.
00034 /// </summary>
00035 /// <param name="message"></param>
00036 /// <param name="type"></param>
00037 void MainPage::DispatcherNotifyUser(String^ message, NotifyType type)
00038 {
00039     Dispatcher->RunAsync(CoreDispatcherPriority::Normal,
00040         ref new DispatchedHandler(
00041             [this, message, type]()
00042             {
00043                 NotifyUser(message, type);
00044             },
00045             CallbackContext::Any
00046         )
00047     );
00048 }
00049
00050 /// <summary>
00051 /// Returns an IPortableDeviceValues containing information about this client app.
00052 /// </summary>
00053 /// <returns>The client information.</returns>
00054 ComPtr<IPortableDeviceValues> SDKSample::GetClientInfo()
00055 {
00056     ComPtr<IPortableDeviceValues> result;
00057
00058     ThrowIfFailed(CoCreateInstance(CLSID_PortableDeviceValues, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&result)));
00059
00060     result->SetStringValue(WPD_CLIENT_NAME, MainPage::FEATURE_NAME->Begin());
00061     result->SetUnsignedIntegerValue(WPD_CLIENT_MAJOR_VERSION, 1);
00062     result->SetUnsignedIntegerValue(WPD_CLIENT_MINOR_VERSION, 0);
00063     result->SetUnsignedIntegerValue(WPD_CLIENT_REVISION, 0);
00064     return result;
00065 }
00066
00067 /// <summary>
00068 /// Returns the first storage object identifier for a portable device.
00069 /// </summary>
00070 /// <param name="device">Pointer to the IPortableDevice for a portable device.</param>
00071 /// <returns>Object identifier string for the first storage on the device.</returns>
00072 String^ SDKSample::GetFirstStorageId(_In_ IPortableDevice* device)
00073 {
00074     PROPVARIANT value = {};
00075     PropVariantPtr valuePtr(&value);
00076     DWORD storageCount = 0;
00077     String^ storageId = nullptr;
00078     ComPtr<IPortableDeviceCapabilities> capabilities;
00079     ComPtr<IPortableDevicePropVariantCollection> storageIds;
00080
00081     ThrowIfFailed(device->Capabilities(&capabilities));
00082     if (SUCCEEDED(capabilities->GetFunctionalObjects(WPD_FUNCTIONAL_CATEGORY_STORAGE, &storageIds)))
00083     {
00084         ThrowIfFailed(storageIds->GetCount(&storageCount));
00085         if (storageCount > 0)
00086         {
00087             ThrowIfFailed(storageIds->GetAt(0, &value));
00088             storageId = ref new String(value.pwszVal);
00089         }
00090     }
00091     return storageId;
00092 }
00093
00094 /// <summary>
00095 /// Copies data from a source stream to a destination stream using the
00096 /// specified transferSizeBytes as the temporary buffer size.
00097 /// </summary>
00098 /// <param name="destStream">Pointer to the destination IStream.</param>
00099 /// <param name="sourceStream">Pointer to the source IStream.</param>
00100 /// <param name="transferSizeBytes">The temporary buffer size to use during the copy.</param>
00101 /// <returns>The total number of bytes copied to the destination stream.</returns>
00102 ULONGLONG SDKSample::StreamCopy(_In_ IStream* destStream, _In_ IStream* sourceStream, DWORD transferSizeBytes)
00103 {
00104     HRESULT hr = S_OK;
00105     DWORD bytesRead = 0;
00106     ULONGLONG totalBytesWritten = 0;
00107
00108     // Allocate a temporary buffer (of Optimal transfer size) for the read results to be written to.
00109     std::unique_ptr<BYTE[]> objectData(new BYTE[transferSizeBytes]);
00110
00111     // Read until the number of bytes returned from the source stream is 0, or
00112     // an error occured during transfer.
00113     do
00114     {
00115         // Read object data from the source stream
00116         hr = sourceStream->Read(objectData.get(), transferSizeBytes, &bytesRead);
00117         if (SUCCEEDED(hr))
00118         {
00119             // Write object data to the destination stream
00120             DWORD bytesWritten = 0;
00121             hr = destStream->Write(objectData.get(), bytesRead, &bytesWritten);
00122             if (SUCCEEDED(hr))
00123             {
00124                 totalBytesWritten += bytesWritten;
00125             }
00126         }
00127
00128     } while (SUCCEEDED(hr) && (bytesRead > 0));
00129
00130     return totalBytesWritten;
00131 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/Level6.cpp Source File

  • XAML DirectX 3D shooting game

Level6.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 "Level6.h"
00010
00011 //----------------------------------------------------------------------
00012
00013 Level6::Level6()
00014 {
00015     m_timeLimit = 20.0f;
00016     m_objective = "Hit as many moving targets as possible while avoiding the obstacles before time runs out.";
00017 }
00018
00019 //----------------------------------------------------------------------
00020
00021 bool Level6::Update(
00022     float time,
00023     float elapsedTime,
00024     float timeRemaining,
00025     std::vector<GameObject^> objects
00026     )
00027 {
00028     for (auto object = objects.begin(); object != objects.end(); object++)
00029     {
00030         if ((*object)->Active() && (*object)->Target())
00031         {
00032             if ((*object)->Hit() && ((*object)->HitTime() < (time - 2.0f)))
00033             {
00034                 (*object)->Hit(false);
00035             }
00036         }
00037     }
00038     return ((timeRemaining - elapsedTime) <= 0.0f);
00039 }
00040
00041 //----------------------------------------------------------------------
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML AppBar control/C++/App.xaml.cpp Source File

  • XAML AppBar control

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "App.xaml.h"
00018 #include "MainPage.xaml.h"
00019
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Controls;
00022 using namespace Windows::ApplicationModel;
00023 using namespace Windows::ApplicationModel::Activation;
00024 using namespace CppSamplesUtils;
00025 using namespace AppBarControl;
00026 using namespace Windows::UI::Xaml::Interop;
00027
00028 App::App()
00029 {
00030     InitializeComponent();
00031     this->Suspending += ref new SuspendingEventHandler(this, &AppBarControl::App::OnSuspending);
00032 }
00033
00034 void App::OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs)
00035 {
00036     auto deferral = pArgs->SuspendingOperation->GetDeferral();
00037     SuspensionManager::StartSaveTask().then([=]()
00038     {
00039         deferral->Complete();
00040     });
00041 }
00042
00043 void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs)
00044 {
00045     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Terminated)
00046     {
00047         SuspensionManager::StartRestoreTask().then([=](concurrency::task<void> restoreTask)
00048         {
00049             try
00050             {
00051                 restoreTask.get();
00052             }
00053             catch (Platform::Exception^)
00054             {
00055                 // If restore fails, the app should proceed as though there was no restored state.
00056             }
00057         });
00058     }
00059     if (Window::Current->Content == nullptr)
00060     {
00061         rootFrame = ref new Frame();
00062         TypeName pageType = { "AppBarControl.MainPage", TypeKind::Custom };
00063         rootFrame->Navigate(pageType);
00064         Window::Current->Content = rootFrame;
00065     }
00066     MainPage^ p = safe_cast<MainPage^>(rootFrame->Content);
00067     p->LaunchArgs = pArgs;
00068     Window::Current->Activate();
00069 }
00070
Generated on Sat Nov 23 2024 16:07:28 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Association launching/C++/ReceiveUriInput.xaml.cpp Source File

  • Association launching

ReceiveUriInput.xaml.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 //
00009 // ReceiveUriInput.xaml.cpp
00010 // Implementation of the ReceiveUriInput class
00011 //
00012
00013 #include "pch.h"
00014 #include "ReceiveUriInput.xaml.h"
00015
00016 using namespace AssociationLaunching;
00017
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::UI::ViewManagement;
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
00031 ReceiveUriInput::ReceiveUriInput()
00032 {
00033     InitializeComponent();
00034 }
00035
00036 ReceiveUriInput::~ReceiveUriInput()
00037 {
00038 }
00039
00040 void ReceiveUriInput::OnNavigatedTo(NavigationEventArgs^ e)
00041 {
00042     // Get a pointer to our main page.
00043     rootPage = dynamic_cast<MainPage^>(e->Parameter);
00044
00045     // Display the result of the protocol activation if we got here as a result of being activated for a protocol.
00046     if (rootPage->ProtocolEvent != nullptr)
00047     {
00048         rootPage->NotifyUser("Protocol activation received. The received URI is " + rootPage->ProtocolEvent->Uri->AbsoluteUri + ".", NotifyType::StatusMessage);
00049     }
00050 }
Generated on Sat Nov 23 2024 16:07:57 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D custom image effects/C++/VertexShader/SampleOverlay.cpp Source File

  • Direct2D custom image effects
  • VertexShader

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 Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::UI::ViewManagement;
00015 using namespace Windows::Graphics::Display;
00016 using namespace D2D1;
00017
00018 SampleOverlay::SampleOverlay() :
00019     m_drawOverlay(true)
00020 {
00021 }
00022
00023 void SampleOverlay::Initialize(
00024     _In_ ID2D1Device*         d2dDevice,
00025     _In_ ID2D1DeviceContext*  d2dContext,
00026     _In_ IWICImagingFactory*  wicFactory,
00027     _In_ IDWriteFactory*      dwriteFactory,
00028     _In_ Platform::String^    caption
00029     )
00030 {
00031     m_wicFactory = wicFactory;
00032     m_dwriteFactory = dwriteFactory;
00033     m_sampleName = caption;
00034     m_d2dDevice = d2dDevice;
00035     m_d2dContext = d2dContext;
00036     m_padding = 3.0f;
00037     m_textVerticalOffset = 5.0f;
00038     m_logoSize = D2D1::SizeF(0.0f, 0.0f);
00039     m_overlayWidth = 0.0f;
00040
00041     ComPtr<ID2D1Factory> factory;
00042     d2dDevice->GetFactory(&factory);
00043
00044     DX::ThrowIfFailed(
00045         factory.As(&m_d2dFactory)
00046         );
00047
00048     ResetDirectXResources();
00049 }
00050
00051 void SampleOverlay::ResetDirectXResources()
00052 {
00053     DX::ThrowIfFailed(
00054         m_d2dContext->CreateSolidColorBrush(ColorF(ColorF::White), &m_whiteBrush)
00055         );
00056
00057     ComPtr<IWICBitmapDecoder> wicBitmapDecoder;
00058     DX::ThrowIfFailed(
00059         m_wicFactory->CreateDecoderFromFilename(
00060             L"windowsbig-sdk.png",
00061             nullptr,
00062             GENERIC_READ,
00063             WICDecodeMetadataCacheOnDemand,
00064             &wicBitmapDecoder
00065             )
00066         );
00067
00068     ComPtr<IWICBitmapFrameDecode> wicBitmapFrame;
00069     DX::ThrowIfFailed(
00070         wicBitmapDecoder->GetFrame(0, &wicBitmapFrame)
00071         );
00072
00073     ComPtr<IWICFormatConverter> wicFormatConverter;
00074     DX::ThrowIfFailed(
00075         m_wicFactory->CreateFormatConverter(&wicFormatConverter)
00076         );
00077
00078     DX::ThrowIfFailed(
00079         wicFormatConverter->Initialize(
00080             wicBitmapFrame.Get(),
00081             GUID_WICPixelFormat32bppPBGRA,
00082             WICBitmapDitherTypeNone,
00083             nullptr,
00084             0.0,
00085             WICBitmapPaletteTypeCustom  // the BGRA format has no palette so this value is ignored
00086             )
00087         );
00088
00089     double dpiX = 96.0f;
00090     double dpiY = 96.0f;
00091     DX::ThrowIfFailed(
00092         wicFormatConverter->GetResolution(&dpiX, &dpiY)
00093         );
00094
00095     DX::ThrowIfFailed(
00096         m_d2dContext->CreateBitmapFromWicBitmap(
00097             wicFormatConverter.Get(),
00098             BitmapProperties(
00099                 PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00100                 static_cast<float>(dpiX),
00101                 static_cast<float>(dpiY)
00102                 ),
00103             &m_logoBitmap
00104             )
00105         );
00106
00107     m_logoSize = m_logoBitmap->GetSize();
00108
00109     ComPtr<IDWriteTextFormat> nameTextFormat;
00110     DX::ThrowIfFailed(
00111         m_dwriteFactory->CreateTextFormat(
00112             L"Segoe UI",
00113             nullptr,
00114             DWRITE_FONT_WEIGHT_LIGHT,
00115             DWRITE_FONT_STYLE_NORMAL,
00116             DWRITE_FONT_STRETCH_NORMAL,
00117             36.0f,
00118             L"en-US",
00119             &nameTextFormat
00120             )
00121         );
00122
00123     DX::ThrowIfFailed(
00124         nameTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)
00125         );
00126
00127     DX::ThrowIfFailed(
00128         nameTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)
00129         );
00130
00131     DX::ThrowIfFailed(
00132         m_dwriteFactory->CreateTextLayout(
00133             m_sampleName->Data(),
00134             m_sampleName->Length(),
00135             nameTextFormat.Get(),
00136             4096.0f,
00137             4096.0f,
00138             &m_textLayout
00139             )
00140         );
00141
00142     DWRITE_TEXT_METRICS metrics = {0};
00143     DX::ThrowIfFailed(
00144         m_textLayout->GetMetrics(&metrics)
00145         );
00146
00147     m_overlayWidth = m_padding * 3.0f + m_logoSize.width + metrics.width;
00148
00149     DX::ThrowIfFailed(
00150         m_d2dFactory->CreateDrawingStateBlock(&m_stateBlock)
00151         );
00152
00153     UpdateForWindowSizeChange();
00154 }
00155
00156 void SampleOverlay::UpdateForWindowSizeChange()
00157 {
00158     if (CoreWindow::GetForCurrentThread()->Bounds.Width < m_overlayWidth)
00159     {
00160         m_drawOverlay = false;
00161     }
00162     else
00163     {
00164         m_drawOverlay = true;
00165     }
00166 }
00167
00168 void SampleOverlay::Render()
00169 {
00170     if (m_drawOverlay)
00171     {
00172         m_d2dContext->SaveDrawingState(m_stateBlock.Get());
00173
00174         m_d2dContext->BeginDraw();
00175         m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00176         m_d2dContext->DrawBitmap(
00177             m_logoBitmap.Get(),
00178             D2D1::RectF(m_padding, 0.0f, m_logoSize.width + m_padding, m_logoSize.height)
00179             );
00180
00181         m_d2dContext->DrawTextLayout(
00182             Point2F(m_logoSize.width + 2.0f * m_padding, m_textVerticalOffset),
00183             m_textLayout.Get(),
00184             m_whiteBrush.Get()
00185             );
00186
00187         // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00188         // is lost. It will be handled during the next call to Present.
00189         HRESULT hr = m_d2dContext->EndDraw();
00190         if (hr != D2DERR_RECREATE_TARGET)
00191         {
00192             DX::ThrowIfFailed(hr);
00193         }
00194
00195         m_d2dContext->RestoreDrawingState(m_stateBlock.Get());
00196     }
00197 }
00198
00199 float SampleOverlay::GetTitleHeightInDips()
00200 {
00201     return m_logoSize.height;
00202 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/MediaExtensions/Invert/dllmain.cpp Source File

  • Media extensions
  • MediaExtensions
  • Invert

dllmain.cpp

Go to the documentation of this file.
00001 //////////////////////////////////////////////////////////////////////////
00002 //
00003 // dllmain.cpp
00004 //
00005 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00007 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00008 // PARTICULAR PURPOSE.
00009 //
00010 // Copyright (c) Microsoft Corporation. All rights reserved.
00011 //
00012 //////////////////////////////////////////////////////////////////////////
00013
00014 #include <initguid.h>
00015 #include "Invert.h"
00016
00017 using namespace Microsoft::WRL;
00018
00019 namespace Microsoft { namespace Samples {
00020     ActivatableClass(CInvert);
00021 }}
00022
00023 BOOL WINAPI DllMain( __in_opt HINSTANCE hInstance, __in DWORD dwReason, __in_opt LPVOID lpReserved )
00024 {
00025     if( DLL_PROCESS_ATTACH == dwReason )
00026     {
00027         //
00028         //  Don't need per-thread callbacks
00029         //
00030         if( hInstance != NULL )
00031         {
00032             DisableThreadLibraryCalls( hInstance );
00033         }
00034
00035         Module<InProc>::GetModule().Create();
00036     }
00037     else if( DLL_PROCESS_DETACH == dwReason )
00038     {
00039         Module<InProc>::GetModule().Terminate();
00040     }
00041
00042     return TRUE;
00043 }
00044
00045 HRESULT WINAPI DllGetActivationFactory( __in HSTRING activatibleClassId, __deref_out IActivationFactory** factory )
00046 {
00047     auto &module = Microsoft::WRL::Module< Microsoft::WRL::InProc >::GetModule();
00048     return module.GetActivationFactory( activatibleClassId, factory );
00049 }
00050
00051 HRESULT WINAPI DllCanUnloadNow()
00052 {
00053     auto &module = Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule();
00054     return (module.Terminate()) ? S_OK : S_FALSE;
00055 }
00056
00057 STDAPI DllGetClassObject( __in REFCLSID rclsid, __in REFIID riid, __deref_out LPVOID FAR* ppv )
00058 {
00059     auto &module = Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule();
00060     return module.GetClassObject( rclsid, riid, ppv );
00061 }
Generated on Sat Nov 23 2024 16:08:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D convolve matrix effect/C++/ConvolutionKernels.h Source File

  • Direct2D convolve matrix effect

ConvolutionKernels.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 typedef enum class KernelSelection
00011 {
00012     Passthrough,
00013     BoxBlur,
00014     SimpleEdgeDetect,
00015     SimpleSharpen,
00016     Emboss,
00017     HorizontalSmear
00018 } KernelSelection;
00019
00020 namespace ConvolutionKernels
00021 {
00022     static const unsigned int PassthroughWidth      = 1;
00023     static const unsigned int BoxBlurWidth          = 5;
00024     static const unsigned int SimpleEdgeDetectWidth = 3;
00025     static const unsigned int SimpleSharpenWidth    = 3;
00026     static const unsigned int EmbossWidth           = 3;
00027     static const unsigned int HorizontalSmearWidth  = 20;
00028     static const unsigned int HorizontalSmearHeight = 1;
00029
00030     static const float BoxBlurDivisor               = 25.0f;
00031     static const float SimpleSharpenDivisor         = 2.0f;
00032     static const float HorizontalSmearDivisor       = 20.0f;
00033     static const float DefaultDivisor               = 1.0f;
00034
00035     static Platform::String^ PassthroughTitle       = "Passthrough";
00036     static Platform::String^ BoxBlurTitle           = "Box Blur (width 5)";
00037     static Platform::String^ SimpleEdgeDetectTitle  = "Simple Edge Detect";
00038     static Platform::String^ SimpleSharpenTitle     = "Simple Sharpen";
00039     static Platform::String^ EmbossTitle            = "Emboss";
00040     static Platform::String^ HorizontalSmearTitle   = "Horizontal Smear (width 20)";
00041
00042     static const float Passthrough[] =
00043     {
00044         1.0f
00045     };
00046
00047     static const float BoxBlur[] =
00048     {
00049         1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
00050         1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
00051         1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
00052         1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
00053         1.0f, 1.0f, 1.0f, 1.0f, 1.0f
00054     };
00055
00056     static const float SimpleEdgeDetect[] =
00057     {
00058          0.0f, -1.0f,  0.0f,
00059         -1.0f,  4.0f, -1.0f,
00060          0.0f, -1.0f,  0.0f
00061     };
00062
00063     static const float SimpleSharpen[] =
00064     {
00065          0.0f, -1.0f,  0.0f,
00066         -1.0f,  6.0f, -1.0f,
00067          0.0f, -1.0f,  0.0f
00068     };
00069
00070     static const float Emboss[] =
00071     {
00072         2.0f,  1.0f,  0.0f,
00073         1.0f,  1.0f, -1.0f,
00074         0.0f, -1.0f, -2.0f
00075     };
00076
00077     static const float HorizontalSmear[] =
00078     {
00079         1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
00080         1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f
00081     };
00082 }
Generated on Sat Nov 23 2024 16:08:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/WideFiveImageTile.h Source File

  • Hilo C++
  • Hilo

WideFiveImageTile.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
00009 namespace Hilo
00010 {
00011     interface class IResourceLoader;
00012
00013     // See http://go.microsoft.com/fwlink/?LinkId=267275 for info about Hilo's implementation of tiles.
00014
00015     // The WideFieImageTile class is a helper class for managing the app's start tile.
00016     class WideFiveImageTile
00017     {
00018     public:
00019         WideFiveImageTile();
00020         WideFiveImageTile(IResourceLoader^ loader);
00021
00022         Windows::UI::Notifications::TileNotification^ GetTileNotification();
00023         void SetImageFilePaths(const std::vector<std::wstring>& fileNames);
00024
00025     private:
00026         IResourceLoader^ m_loader;
00027         std::vector<std::wstring> m_fileNames;
00028         void UpdateContentWithValues(Windows::Data::Xml::Dom::XmlDocument^ content);
00029     };
00030 }
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text editing/C++/App.xaml.cpp Source File

  • XAML text editing

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Audio Session (WASAPI)/C++/Scenario1.xaml.cpp Source File

  • Windows Audio Session (WASAPI)
  • C++

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 Sat Nov 23 2024 16:07:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/LonLatController.cpp Source File

  • Direct3D resource loading

LonLatController.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
00009 #include "pch.h"
00010 #include "LonLatController.h"
00011
00012 using namespace Windows::UI::Core;
00013 using namespace Windows::System;
00014 using namespace Windows::Foundation;
00015 using namespace Windows::Foundation::Collections;
00016 using namespace Windows::Devices::Input;
00017 using namespace Windows::ApplicationModel;
00018
00019 // method for handling touch press events or mouse clicks
00020 void LonLatController::OnPointerPressed(
00021     _In_ CoreWindow^ sender,
00022     _In_ PointerEventArgs^ args
00023     )
00024 {
00025     if (!m_lonLatInUse) // if no pointer is in this control yet
00026     {
00027         m_lonLatLastPoint = float2( // save point for later move
00028             args->CurrentPoint->Position.X,
00029             args->CurrentPoint->Position.Y
00030             );
00031         m_lonLatPointerID = args->CurrentPoint->PointerId; // store the pointer using this control
00032         m_lonLatLastDelta.x = m_lonLatLastDelta.y = 0; // these are for smoothing
00033         m_lonLatInUse = TRUE;
00034     }
00035 }
00036
00037 void LonLatController::OnPointerMoved(
00038     _In_ CoreWindow^ sender,
00039     _In_ PointerEventArgs^ args
00040     )
00041 {
00042     if (args->CurrentPoint->PointerId == m_lonLatPointerID) // this is the look pointer
00043     {
00044         float2 position = float2(
00045             args->CurrentPoint->Position.X,
00046             args->CurrentPoint->Position.Y
00047             );
00048
00049         float2 pointerDelta;
00050         pointerDelta = position - m_lonLatLastPoint; // how far did pointer move
00051
00052         float2 rotationDelta;
00053         rotationDelta = pointerDelta * LONLAT_GAIN; // scale for control sensitivity
00054         m_lonLatLastPoint = position; // save for next time through
00055
00056         // update our orientation based on the command
00057         m_latitude  += rotationDelta.y;
00058         m_longitude -= rotationDelta.x;
00059
00060         // Limit lattitude to poles
00061         float limit = PI_F / 2.0f - 0.01f;
00062         m_latitude = (float) __max(-limit, m_latitude);
00063         m_latitude = (float) __min(+limit, m_latitude);
00064
00065         // keep longitude in sane range by wrapping
00066         if (m_longitude >  PI_F)
00067         {
00068             m_longitude -= PI_F * 2.0f;
00069         }
00070         else if (m_longitude < -PI_F)
00071         {
00072             m_longitude += PI_F * 2.0f;
00073         }
00074
00075         // limit us to positive radius
00076         m_radius = (float) __max(0.0, m_radius);
00077     }
00078 }
00079
00080 void LonLatController::OnPointerReleased(
00081     _In_ CoreWindow^ sender,
00082     _In_ PointerEventArgs^ args
00083     )
00084 {
00085     if (args->CurrentPoint->PointerId == m_lonLatPointerID) // this is the look pointer
00086     {
00087         m_lonLatInUse = FALSE;
00088         m_lonLatPointerID = 0;
00089     }
00090 }
00091
00092 void LonLatController::OnKeyDown(
00093     _In_ CoreWindow^ sender,
00094     _In_ KeyEventArgs^ args
00095     )
00096 {
00097     Windows::System::VirtualKey Key;
00098     Key = args->VirtualKey;
00099
00100     // figure out the command from the keyboard
00101     if (Key == VirtualKey::W) // forward
00102     {
00103         m_forward = true;
00104     }
00105     if (Key == VirtualKey::S) // back
00106     {
00107         m_back = true;
00108     }
00109     if (Key == VirtualKey::A) // left
00110     {
00111         m_left = true;
00112     }
00113     if (Key == VirtualKey::D) // right
00114     {
00115         m_right = true;
00116     }
00117     if (Key == VirtualKey::Space) // up
00118     {
00119         m_up = true;
00120     }
00121     if (Key == VirtualKey::X) // down
00122     {
00123         m_down = true;
00124     }
00125 }
00126
00127 void LonLatController::OnKeyUp(
00128     _In_ CoreWindow^ sender,
00129     _In_ KeyEventArgs^ args
00130     )
00131 {
00132     Windows::System::VirtualKey Key;
00133     Key = args->VirtualKey;
00134
00135     // figure out the command from the keyboard
00136     if (Key == VirtualKey::W) // forward
00137     {
00138         m_forward = false;
00139     }
00140     if (Key == VirtualKey::S) // back
00141     {
00142         m_back = false;
00143     }
00144     if (Key == VirtualKey::A) // left
00145     {
00146         m_left = false;
00147     }
00148     if (Key == VirtualKey::D) // right
00149     {
00150         m_right = false;
00151     }
00152     if (Key == VirtualKey::Space) // up
00153     {
00154         m_up = false;
00155     }
00156     if (Key == VirtualKey::X) // down
00157     {
00158         m_down = false;
00159     }
00160 }
00161
00162 // set up the Controls supported by this controller
00163 void LonLatController::Initialize(_In_ CoreWindow^ window)
00164 {
00165     // opt in to recieve touch/mouse/key events
00166
00167     window->PointerPressed +=
00168         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &LonLatController::OnPointerPressed);
00169
00170     window->PointerMoved +=
00171         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &LonLatController::OnPointerMoved);
00172
00173     window->PointerReleased +=
00174         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &LonLatController::OnPointerReleased);
00175
00176     window->KeyDown +=
00177         ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &LonLatController::OnKeyDown);
00178
00179     window->KeyUp +=
00180         ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &LonLatController::OnKeyUp);
00181
00182     // initialize controller state
00183
00184     m_lonLatInUse = FALSE; // no pointer is in the Look control
00185     m_lonLatPointerID = 0;
00186
00187     SetOrientation(0, 0); // look straight ahead
00188     m_radius = 1.0f;
00189 }
00190
00191 // accessor to set position of controller
00192 void LonLatController::SetPosition(_In_ float3 pos)
00193 {
00194     m_longitude = atan2f(pos.x, pos.z);
00195     float r = sqrtf(pos.x*pos.x + pos.z*pos.z);
00196     m_latitude = atan2f(pos.y, r);
00197     m_radius = sqrtf(pos.x*pos.x + pos.y*pos.y + pos.z*pos.z);
00198 }
00199
00200 // accessor to set position of controller
00201 void LonLatController::SetOrientation(_In_ float latitude, _In_ float longitude)
00202 {
00203     m_latitude = latitude;
00204     m_longitude = longitude;
00205 }
00206
00207 // returns the position of the controller object
00208 float3 LonLatController::get_Position()
00209 {
00210     float y = m_radius * sinf(m_latitude);  // up-down
00211     float r = m_radius * cosf(m_latitude);  // in the plane
00212     float z = r * cosf(m_longitude);        // fwd-back
00213     float x = r * sinf(m_longitude);        // left-right
00214
00215     return float3(x, y, z);
00216 }
00217
00218 // returns the point at which the camera controller is facing
00219 float3 LonLatController::get_LookPoint()
00220 {
00221     return float3(0, 0, 0);
00222 }
00223
00224 void LonLatController::Update()
00225 {
00226     // poll our state bits set by the keyboard input events
00227     if (m_forward)
00228     {
00229         m_lonLatCommand.y += 1.0f;
00230     }
00231     if (m_back)
00232     {
00233         m_lonLatCommand.y -= 1.0f;
00234     }
00235
00236     if (m_left)
00237     {
00238         m_lonLatCommand.x -= 1.0f;
00239     }
00240     if (m_right)
00241     {
00242         m_lonLatCommand.x += 1.0f;
00243     }
00244
00245     if (m_up)
00246     {
00247         m_lonLatCommand.z += 1.0f;
00248     }
00249     if (m_down)
00250     {
00251         m_lonLatCommand.z -= 1.0f;
00252     }
00253
00254     // scale for sensitivity adjustment
00255     float3 command = m_lonLatCommand*LONLATKEY_GAIN;
00256     command.y *= m_radius * 0.5f; // logarithmic gain
00257
00258     // update state with command input
00259     m_latitude  += command.z;
00260     m_longitude += command.x;
00261     m_radius    -= command.y; // fwd stick is down towards object
00262
00263     // Limit lattitude to poles
00264     float limit = PI_F / 2.0f - 0.01f;
00265     m_latitude = (float) __max(-limit, m_latitude);
00266     m_latitude = (float) __min(+limit, m_latitude);
00267
00268     // keep longitude in sane range by wrapping
00269     if (m_longitude >  PI_F)
00270     {
00271         m_longitude -= PI_F * 2.0f;
00272     }
00273     else if (m_longitude < -PI_F)
00274     {
00275         m_longitude += PI_F * 2.0f;
00276     }
00277
00278     // limit us to positive radius
00279     m_radius = (float) __max(0.0, m_radius);
00280
00281     // clear movement input accumulator for use during next frame
00282     m_lonLatCommand = float3(0.0f, 0.0f, 0.0f);
00283 }
00284
00285 void LonLatController::SaveInternalState(_In_ IPropertySet^ state)
00286 {
00287     if (state->HasKey("m_longitude"))
00288     {
00289         state->Remove("m_longitude");
00290     }
00291     if (state->HasKey("m_latitude"))
00292     {
00293         state->Remove("m_latitude");
00294     }
00295     if (state->HasKey("m_radius"))
00296     {
00297         state->Remove("m_radius");
00298     }
00299     state->Insert("m_longitude", PropertyValue::CreateSingle(m_longitude));
00300     state->Insert("m_latitude", PropertyValue::CreateSingle(m_latitude));
00301     state->Insert("m_radius", PropertyValue::CreateSingle(m_radius));
00302 }
00303
00304 void LonLatController::LoadInternalState(_In_ IPropertySet^ state)
00305 {
00306     if (state->HasKey("m_longitude") && state->HasKey("m_latitude") && state->HasKey("m_radius"))
00307     {
00308         m_longitude = safe_cast<IPropertyValue^>(state->Lookup("m_longitude"))->GetSingle();
00309         m_latitude = safe_cast<IPropertyValue^>(state->Lookup("m_latitude"))->GetSingle();
00310         m_radius = safe_cast<IPropertyValue^>(state->Lookup("m_radius"))->GetSingle();
00311     }
00312 }
00313
Generated on Sat Nov 23 2024 16:08:11 for Win8-Examples by doxygen 1.7.1


Win8-Examples: LightSensor/C++/Constants.cpp Source File

  • LightSensor

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     { "Light sensor data events", "SDKSample.LightSensorCPP.Scenario1" },
00020     { "Poll light sensor readings", "SDKSample.LightSensorCPP.Scenario2" }
00021 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Removable storage/C++/pch.cpp Source File

  • Removable storage

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Print/C++/ScenarioOutput3.xaml.h Source File

  • Print

ScenarioOutput3.xaml.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 //
00009 // Scenario3Output.xaml.h
00010 // Declaration of the Scenario3Output class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioOutput3.g.h"
00017 #include "MainPage.g.h"
00018
00019 namespace PrintSample
00020 {
00021     public ref class ScenarioOutput3 sealed
00022     {
00023     public:
00024         ScenarioOutput3();
00025     private:
00026         ~ScenarioOutput3();
00027     };
00028 }
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media Server client/C++/LocateVideo.xaml.cpp Source File

  • Media Server client

LocateVideo.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 //
00013 // Scenario1.xaml.cpp
00014 // Implementation of the Scenario1 class
00015 //
00016
00017 #include "pch.h"
00018 #include "LocateVideo.xaml.h"
00019
00020 using namespace SDKSample::MediaServerClient;
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Navigation;
00025
00026 using namespace Windows::Foundation;
00027 using namespace Windows::Storage::Search;
00028 using namespace Windows::Storage::Streams;
00029 using namespace Windows::UI::Core;
00030 using namespace Platform;
00031 using namespace Windows::UI::Xaml::Media;
00032
00033 Scenario1::Scenario1()
00034 {
00035     InitializeComponent();
00036     InitializeMediaServers();
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 Scenario1::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 void Scenario1::dmsRefreshButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00052 {
00053     Button^ b = safe_cast<Button^>(sender);
00054     if (b != nullptr)
00055     {
00056         rootPage->NotifyUser("Media Servers being refreshed... ", NotifyType::StatusMessage);
00057         InitializeMediaServers();
00058     }
00059 }
00060
00061 void Scenario1::dmsSelect_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e)
00062 {
00063     localVideo->Stop();
00064     mediaSelect->Items->Clear();
00065
00066     if (dmsSelect->SelectedIndex != -1)
00067     {
00068         rootPage->NotifyUser("Retrieving media files...", NotifyType::StatusMessage);
00069         LoadMediaFiles();
00070     }
00071 }
00072
00073 void Scenario1::mediaSelect_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e)
00074 {
00075     if (mediaSelect->SelectedIndex != -1 && mediaFiles != nullptr)
00076     {
00077         mediaFile = mediaFiles->GetAt(mediaSelect->SelectedIndex);
00078         concurrency::create_task(mediaFile->OpenAsync(FileAccessMode::Read))
00079             .then([this](concurrency::task<IRandomAccessStream^> result)
00080         {
00081             localVideo->Stop();
00082             try
00083             {
00084                 mediaStream = result.get();
00085                 localVideo->SetSource(mediaStream, mediaFile->ContentType);
00086                 localVideo->Play();
00087             }
00088             catch (Exception ^ex)
00089             {
00090                 rootPage->NotifyUser("Error during file selection :" + ex->Message, NotifyType::ErrorMessage);
00091             }
00092         });
00093     }
00094 }
00095
00096 void Scenario1::LoadMediaFiles()
00097 {
00098     mediaSelect->Items->Clear();
00099     StorageFolder^ mediaServerFolder = mediaServers->GetAt(dmsSelect->SelectedIndex);
00100     auto queryOptions = ref new QueryOptions();
00101     queryOptions->FolderDepth = FolderDepth::Deep;
00102     queryOptions->UserSearchFilter = "System.Kind:=video";
00103     auto queryFolder = mediaServerFolder->CreateFileQueryWithOptions(queryOptions);
00104     concurrency::create_task(queryFolder->GetFilesAsync(0, 25))
00105         .then([this](concurrency::task<IVectorView<StorageFile^>^> result)
00106     {
00107         try
00108         {
00109             mediaFiles = result.get();
00110             if (mediaFiles->Size != 0)
00111             {
00112                 std::for_each(begin(mediaFiles), end(mediaFiles), [this](StorageFile^ file)
00113                 {
00114                     mediaSelect->Items->Append(file->DisplayName);
00115                 });
00116                 rootPage->NotifyUser("Media files retrieved", NotifyType::StatusMessage);
00117             }
00118             else
00119             {
00120                 rootPage->NotifyUser("No Media Files found", NotifyType::StatusMessage);
00121             }
00122         }
00123         catch (Platform::Exception^ e)
00124         {
00125             rootPage->NotifyUser("Error locating media files :" + e->Message, NotifyType::ErrorMessage);
00126         }
00127     });
00128 }
00129
00130 void Scenario1::localVideo_MediaFailed(Platform::Object^ sender, Windows::UI::Xaml::ExceptionRoutedEventArgs^ e)
00131 {
00132     rootPage->NotifyUser("File :"+ mediaFile->DisplayName+ " - Playback error  :"+ e->ErrorMessage, NotifyType::ErrorMessage);
00133 }
00134
00135 void Scenario1::InitializeMediaServers()
00136 {
00137     dmsSelect->Items->Clear();
00138     concurrency::create_task(KnownFolders::MediaServerDevices->GetFoldersAsync())
00139         .then([this](concurrency::task<IVectorView<StorageFolder^>^> result)
00140     {
00141         try
00142         {
00143             mediaServers = result.get();
00144             if (mediaServers->Size != 0)
00145             {
00146                 std::for_each(begin(mediaServers), end(mediaServers), [this](StorageFolder^ folder)
00147                 {
00148                     dmsSelect->Items->Append(folder->DisplayName);
00149                 });
00150                 rootPage->NotifyUser("Media Servers refreshed", NotifyType::StatusMessage);
00151             }
00152             else
00153             {
00154                 rootPage->NotifyUser("No MediaServers found", NotifyType::StatusMessage);
00155             }
00156         }
00157         catch (Exception ^ex)
00158         {
00159             rootPage->NotifyUser("Unable to retrieve the media servers.", NotifyType::StatusMessage);
00160         }
00161     });
00162 }
00163
00164 void Scenario1::localVideo_CurrentStateChanged(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00165 {
00166     if (mediaFile != nullptr)
00167     {
00168         String^ filename = mediaFile->DisplayName;
00169         switch (localVideo->CurrentState)
00170         {
00171         case MediaElementState::Playing:
00172             rootPage->NotifyUser("File :"+ filename + " - Playing", NotifyType::StatusMessage);
00173             break;
00174         case MediaElementState::Paused:
00175             rootPage->NotifyUser("File :"+ filename + " - Paused", NotifyType::StatusMessage);
00176             break;
00177         case MediaElementState::Stopped:
00178             rootPage->NotifyUser("File :"+ filename + " - Stopped", NotifyType::StatusMessage);
00179             break;
00180         case MediaElementState::Opening:
00181             rootPage->NotifyUser("File :"+ filename + " - Opening", NotifyType::StatusMessage);
00182             break;
00183         case MediaElementState::Closed:
00184             break;
00185         case MediaElementState::Buffering:
00186             rootPage->NotifyUser("File :"+ filename + " - Buffering", NotifyType::StatusMessage);
00187             break;
00188         default:
00189             break;
00190         }
00191     }
00192 }
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Background task/C++/BackgroundTask/common/LayoutAwarePage.cpp Source File

  • Background task
  • BackgroundTask
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:30 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Touch keyboard text input/C++/MainPage.xaml.h Source File

  • Input Touch keyboard text input

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:46 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX touch input/C++/DirectXApp.h Source File

  • DirectX touch input

DirectXApp.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 "Simple3DTouch.h"
00011
00012 ref class DirectXApp : public Windows::ApplicationModel::Core::IFrameworkView
00013 {
00014 internal:
00015     DirectXApp();
00016
00017 public:
00018     // IFrameworkView Methods
00019     virtual void Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00020     virtual void SetWindow(_In_ Windows::UI::Core::CoreWindow^ window);
00021     virtual void Load(_In_ Platform::String^ entryPoint);
00022     virtual void Run();
00023     virtual void Uninitialize();
00024
00025 private:
00026     // Event Handlers
00027     void OnWindowSizeChanged(
00028         _In_ Windows::UI::Core::CoreWindow^ sender,
00029         _In_ Windows::UI::Core::WindowSizeChangedEventArgs^ args
00030         );
00031
00032     void OnVisibilityChanged(
00033         _In_ Windows::UI::Core::CoreWindow^ sender,
00034         _In_ Windows::UI::Core::VisibilityChangedEventArgs^ args
00035         );
00036
00037     void OnLogicalDpiChanged(
00038         _In_ Platform::Object^ sender
00039         );
00040
00041     void OnActivated(
00042         _In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView,
00043         _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^ args
00044         );
00045
00046     void OnSuspending(
00047         _In_ Platform::Object^ sender,
00048         _In_ Windows::ApplicationModel::SuspendingEventArgs^ args
00049         );
00050
00051     void OnResuming(
00052         _In_ Platform::Object^ sender,
00053         _In_ Platform::Object^ args
00054         );
00055
00056     void OnWindowClosed(
00057         _In_ Windows::UI::Core::CoreWindow^ sender,
00058         _In_ Windows::UI::Core::CoreWindowEventArgs^ args
00059         );
00060
00061     Simple3DTouch^ m_renderer;
00062     bool m_windowClosed;
00063     bool m_windowVisible;
00064 };
00065
00066 ref class DirectXAppSource : Windows::ApplicationModel::Core::IFrameworkViewSource
00067 {
00068 public:
00069     virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00070 };
Generated on Sat Nov 23 2024 16:08:07 for Win8-Examples by doxygen 1.7.1


Win8-Examples: LightSensor/C++/Scenario1.xaml.cpp Source File

  • LightSensor

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::LightSensorCPP;
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::Devices::Sensors;
00025 using namespace Windows::Foundation;
00026 using namespace Windows::UI::Core;
00027 using namespace Platform;
00028
00029 Scenario1::Scenario1() : rootPage(MainPage::Current), desiredReportInterval(0)
00030 {
00031     InitializeComponent();
00032
00033     sensor = LightSensor::GetDefault();
00034     if (sensor != nullptr)
00035     {
00036         // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
00037         // This value will be used later to activate the sensor.
00038         uint32 minReportInterval = sensor->MinimumReportInterval;
00039         desiredReportInterval = minReportInterval > 100 ? minReportInterval : 100;
00040     }
00041     else
00042     {
00043         rootPage->NotifyUser("No light sensor found", NotifyType::ErrorMessage);
00044     }
00045 }
00046
00047 /// <summary>
00048 /// Invoked when this page is about to be displayed in a Frame.
00049 /// </summary>
00050 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00051 /// property is typically used to configure the page.</param>
00052 void Scenario1::OnNavigatedTo(NavigationEventArgs^ e)
00053 {
00054     ScenarioEnableButton->IsEnabled = true;
00055     ScenarioDisableButton->IsEnabled = false;
00056 }
00057
00058 /// <summary>
00059 /// Invoked when this page is no longer displayed.
00060 /// </summary>
00061 /// <param name="e"></param>
00062 void Scenario1::OnNavigatedFrom(NavigationEventArgs^ e)
00063 {
00064     if (ScenarioDisableButton->IsEnabled)
00065     {
00066         Window::Current->VisibilityChanged::remove(visibilityToken);
00067         sensor->ReadingChanged::remove(readingToken);
00068
00069         // Restore the default report interval to release resources while the sensor is not in use
00070         sensor->ReportInterval = 0;
00071     }
00072 }
00073
00074 /// <summary>
00075 /// This is the event handler for VisibilityChanged events. You would register for these notifications
00076 /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00077 /// </summary>
00078 /// <param name="sender"></param>
00079 /// <param name="e">
00080 /// Event data that can be examined for the current visibility state.
00081 /// </param>
00082 void Scenario1::VisibilityChanged(Object^ sender, VisibilityChangedEventArgs^ e)
00083 {
00084     // The app should watch for VisibilityChanged events to disable and re-enable sensor input as appropriate
00085     if (ScenarioDisableButton->IsEnabled)
00086     {
00087         if (e->Visible)
00088         {
00089             // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00090             readingToken = sensor->ReadingChanged::add(ref new TypedEventHandler<LightSensor^, LightSensorReadingChangedEventArgs^>(this, &Scenario1::ReadingChanged));
00091         }
00092         else
00093         {
00094             // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00095             sensor->ReadingChanged::remove(readingToken);
00096         }
00097     }
00098 }
00099
00100 void Scenario1::ReadingChanged(LightSensor^ sender, LightSensorReadingChangedEventArgs^ e)
00101 {
00102     // We need to dispatch to the UI thread to display the output
00103     Dispatcher->RunAsync(
00104         CoreDispatcherPriority::Normal,
00105         ref new DispatchedHandler(
00106             [this, e]()
00107             {
00108                 LightSensorReading^ reading = e->Reading;
00109
00110                 ScenarioOutput_LUX->Text = reading->IlluminanceInLux.ToString();
00111             },
00112             CallbackContext::Any
00113             )
00114         );
00115 }
00116
00117 void Scenario1::ScenarioEnable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00118 {
00119     if (sensor != nullptr)
00120     {
00121         // Establish the report interval
00122         sensor->ReportInterval = desiredReportInterval;
00123
00124         visibilityToken = Window::Current->VisibilityChanged::add(ref new WindowVisibilityChangedEventHandler(this, &Scenario1::VisibilityChanged));
00125         readingToken = sensor->ReadingChanged::add(ref new TypedEventHandler<LightSensor^, LightSensorReadingChangedEventArgs^>(this, &Scenario1::ReadingChanged));
00126
00127         ScenarioEnableButton->IsEnabled = false;
00128         ScenarioDisableButton->IsEnabled = true;
00129     }
00130     else
00131     {
00132         rootPage->NotifyUser("No light sensor found", NotifyType::ErrorMessage);
00133     }
00134 }
00135
00136 void Scenario1::ScenarioDisable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00137 {
00138     Window::Current->VisibilityChanged::remove(visibilityToken);
00139     sensor->ReadingChanged::remove(readingToken);
00140
00141     // Restore the default report interval to release resources while the sensor is not in use
00142     sensor->ReportInterval = 0;
00143
00144     ScenarioEnableButton->IsEnabled = true;
00145     ScenarioDisableButton->IsEnabled = false;
00146 }
Generated on Sat Nov 23 2024 16:07:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Background task/C++/BackgroundTask/SampleBackgroundTask.xaml.cpp Source File

  • Background task
  • BackgroundTask

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 // SampleBackgroundTask.xaml.cpp
00013 // Implementation of the SampleBackgroundTask class
00014 //
00015
00016 #include "pch.h"
00017 #include "SampleBackgroundTask.xaml.h"
00018 #include "Constants.h"
00019
00020 using namespace SDKSample::BackgroundTask;
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     auto iter = BackgroundTaskRegistration::AllTasks->First();
00048     auto hascur = iter->HasCurrent;
00049     while (hascur)
00050     {
00051         auto cur = iter->Current->Value;
00052
00053         if (cur->Name == SampleBackgroundTaskName)
00054         {
00055             AttachProgressAndCompletedHandlers(cur);
00056             break;
00057         }
00058
00059         hascur = iter->MoveNext();
00060     }
00061
00062     UpdateUI();
00063 }
00064
00065 /// <summary>
00066 /// Attach progress and completed handers to a background task.
00067 /// </summary>
00068 /// <param name="task">The task to attach progress and completed handlers to.</param>
00069 void SampleBackgroundTask::AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration^ task)
00070 {
00071     auto progress = [this](BackgroundTaskRegistration^ task, BackgroundTaskProgressEventArgs^ args)
00072     {
00073         auto progress = "Progress: " + args->Progress + "%";
00074         BackgroundTaskSample::SampleBackgroundTaskProgress = progress;
00075         UpdateUI();
00076     };
00077     task->Progress += ref new BackgroundTaskProgressEventHandler(progress);
00078
00079     auto completed = [this](BackgroundTaskRegistration^ task, BackgroundTaskCompletedEventArgs^ args)
00080     {
00081         UpdateUI();
00082     };
00083     task->Completed += ref new BackgroundTaskCompletedEventHandler(completed);
00084 }
00085
00086 void SampleBackgroundTask::RegisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088     auto task = BackgroundTaskSample::RegisterBackgroundTask(SampleBackgroundTaskEntryPoint,
00089                                                              SampleBackgroundTaskName,
00090                                                              ref new SystemTrigger(SystemTriggerType::TimeZoneChange, false),
00091                                                              nullptr);
00092     AttachProgressAndCompletedHandlers(task);
00093     UpdateUI();
00094 }
00095
00096 void SampleBackgroundTask::UnregisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00097 {
00098     BackgroundTaskSample::UnregisterBackgroundTasks(SampleBackgroundTaskName);
00099     UpdateUI();
00100 }
00101
00102 /// <summary>
00103 /// Update the scenario UI.
00104 /// </summary>
00105 void SampleBackgroundTask::UpdateUI()
00106 {
00107     auto uiDelegate = [this]()
00108     {
00109         RegisterButton->IsEnabled = !BackgroundTaskSample::SampleBackgroundTaskRegistered;
00110         UnregisterButton->IsEnabled = BackgroundTaskSample::SampleBackgroundTaskRegistered;
00111         Progress->Text = BackgroundTaskSample::SampleBackgroundTaskProgress;
00112         Status->Text = BackgroundTaskSample::GetBackgroundTaskStatus(SampleBackgroundTaskName);
00113     };
00114     auto handler = ref new Windows::UI::Core::DispatchedHandler(uiDelegate, Platform::CallbackContext::Any);
00115
00116     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, handler);
00117 }
Generated on Sat Nov 23 2024 16:07:58 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D post-processing effects/C++/BasicLoader.h Source File

  • Direct3D post-processing effects

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 Sat Nov 23 2024 16:08:08 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D interpolation modes/C++/DirectXBase.h Source File

  • Direct2D interpolation modes

DirectXBase.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 "DirectXSample.h"
00011
00012 // Helper class that initializes DirectX APIs for both 2D and 3D rendering.
00013 // Some of the code in this class may be omitted if only 2D or only 3D rendering is being used.
00014 ref class DirectXBase abstract
00015 {
00016 internal:
00017     DirectXBase();
00018
00019     virtual void Initialize(Windows::UI::Core::CoreWindow^ window, float dpi);
00020     virtual void HandleDeviceLost();
00021     virtual void CreateDeviceIndependentResources();
00022     virtual void CreateDeviceResources();
00023     virtual void SetDpi(float dpi);
00024     virtual void UpdateForWindowSizeChange();
00025     virtual void CreateWindowSizeDependentResources();
00026     virtual void Render() = 0;
00027     virtual void Present();
00028     void ValidateDevice();
00029
00030 protected private:
00031     Platform::Agile<Windows::UI::Core::CoreWindow>  m_window;
00032
00033     // DirectWrite & Windows Imaging Component Objects.
00034     Microsoft::WRL::ComPtr<IDWriteFactory1>         m_dwriteFactory;
00035     Microsoft::WRL::ComPtr<IWICImagingFactory2>     m_wicFactory;
00036
00037     // DirectX Core Objects. Required for 2D and 3D.
00038     Microsoft::WRL::ComPtr<ID3D11Device1>           m_d3dDevice;
00039     Microsoft::WRL::ComPtr<ID3D11DeviceContext1>    m_d3dContext;
00040     Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00041     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00042
00043     // Direct2D Rendering Objects. Required for 2D.
00044     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00046     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00047     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmap;
00048
00049     // Direct3D Rendering Objects. Required for 3D.
00050     Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00051
00052     // Cached renderer properties.
00053     D3D_FEATURE_LEVEL                               m_featureLevel;
00054     Windows::Foundation::Size                       m_renderTargetSize;
00055     Windows::Foundation::Rect                       m_windowBounds;
00056     float                                           m_dpi;
00057     bool                                            m_windowSizeChangeInProgress;
00058 };
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::WASAPIAudio::WASAPIRenderer Member List

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


Win8-Examples: Member List

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

NotificationsExtensions::ToastContent::ToastNotificationBase Member List

This is the complete list of members for NotificationsExtensions::ToastContent::ToastNotificationBase, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
AppendAudioTag(StringBuilder builder) | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline, private]
AppendAudioTag(StringBuilder builder) | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline, private]
Audio | NotificationsExtensions::ToastContent::ToastNotificationBase |
AudioSrcIsLooping() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline, private]
AudioSrcIsLooping() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline, private]
BaseUri | NotificationsExtensions::NotificationBase |
CreateNotification() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline]
Duration | NotificationsExtensions::ToastContent::ToastNotificationBase |
GetContent() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline, virtual]
GetContent() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline, virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
Launch | NotificationsExtensions::ToastContent::ToastNotificationBase |
m_Audio | NotificationsExtensions::ToastContent::ToastNotificationBase | [private]
m_Duration | NotificationsExtensions::ToastContent::ToastNotificationBase | [private]
m_Launch | NotificationsExtensions::ToastContent::ToastNotificationBase | [private]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextFields | NotificationsExtensions::NotificationBase |
ToastNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline]
ToastNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ValidateAudio() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline, private]
ValidateAudio() | NotificationsExtensions::ToastContent::ToastNotificationBase | [inline, private]
Generated on Sat Nov 23 2024 16:09:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Globalization preferences/C++/common/LayoutAwarePage.h Source File

  • Globalization preferences
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/Camera.cpp Source File

  • XAML DirectX 3D shooting game

Camera.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 "Camera.h"
00010 #include "StereoProjection.h"
00011
00012 using namespace DirectX;
00013
00014 #undef min // Use __min instead.
00015 #undef max // Use __max instead.
00016
00017 //--------------------------------------------------------------------------------------
00018
00019 Camera::Camera()
00020 {
00021     // Setup the view matrix.
00022     SetViewParams(
00023         XMFLOAT3(0.0f, 0.0f, 0.0f),   // Default eye position.
00024         XMFLOAT3(0.0f, 0.0f, 1.0f),   // Default look at position.
00025         XMFLOAT3(0.0f, 1.0f, 0.0f)    // Default up vector.
00026         );
00027
00028     // Setup the projection matrix.
00029     SetProjParams(XM_PI / 4, 1.0f, 1.0f, 1000.0f);
00030 }
00031
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 //--------------------------------------------------------------------------------------
00045
00046 void Camera::Eye(_In_ XMFLOAT3 eye)
00047 {
00048     SetViewParams(eye, m_lookAt, m_up);
00049 }
00050
00051 //--------------------------------------------------------------------------------------
00052
00053 void Camera::SetViewParams(
00054     _In_ XMFLOAT3 eye,
00055     _In_ XMFLOAT3 lookAt,
00056     _In_ XMFLOAT3 up
00057     )
00058 {
00059     m_eye = eye;
00060     m_lookAt = lookAt;
00061     m_up = up;
00062
00063     // Calculate the view matrix.
00064     XMMATRIX view = XMMatrixLookAtLH(
00065         XMLoadFloat3(&m_eye),
00066         XMLoadFloat3(&m_lookAt),
00067         XMLoadFloat3(&m_up)
00068         );
00069
00070     XMVECTOR det;
00071     XMMATRIX inverseView = XMMatrixInverse(&det, view);
00072     XMStoreFloat4x4(&m_viewMatrix, view);
00073     XMStoreFloat4x4(&m_inverseView, inverseView);
00074
00075     // The axis basis vectors and camera position are stored inside the
00076     // position matrix in the 4 rows of the camera's world matrix.
00077     // To figure out the yaw/pitch of the camera, we just need the Z basis vector.
00078     XMFLOAT3 zBasis;
00079     XMStoreFloat3(&zBasis, inverseView.r[2]);
00080
00081     m_cameraYawAngle = atan2f(zBasis.x, zBasis.z);
00082
00083     float len = sqrtf(zBasis.z * zBasis.z + zBasis.x * zBasis.x);
00084     m_cameraPitchAngle = atan2f(zBasis.y, len);
00085 }
00086
00087 //--------------------------------------------------------------------------------------
00088
00089 void Camera::SetProjParams(
00090     _In_ float fieldOfView,
00091     _In_ float aspectRatio,
00092     _In_ float nearPlane,
00093     _In_ float farPlane
00094     )
00095 {
00096     // Set attributes for the projection matrix.
00097     m_fieldOfView = fieldOfView;
00098     m_aspectRatio = aspectRatio;
00099     m_nearPlane = nearPlane;
00100     m_farPlane = farPlane;
00101     XMStoreFloat4x4(
00102         &m_projectionMatrix,
00103         XMMatrixPerspectiveFovLH(
00104             m_fieldOfView,
00105             m_aspectRatio,
00106             m_nearPlane,
00107             m_farPlane
00108             )
00109         );
00110
00111     STEREO_PARAMETERS* stereoParams = nullptr;
00112     // Update the projection matrix.
00113     XMStoreFloat4x4(
00114         &m_projectionMatrixLeft,
00115         MatrixStereoProjectionFovLH(
00116             stereoParams,
00117             STEREO_CHANNEL::LEFT,
00118             m_fieldOfView,
00119             m_aspectRatio,
00120             m_nearPlane,
00121             m_farPlane,
00122             STEREO_MODE::NORMAL
00123             )
00124         );
00125
00126     XMStoreFloat4x4(
00127         &m_projectionMatrixRight,
00128         MatrixStereoProjectionFovLH(
00129             stereoParams,
00130             STEREO_CHANNEL::RIGHT,
00131             m_fieldOfView,
00132             m_aspectRatio,
00133             m_nearPlane,
00134             m_farPlane,
00135             STEREO_MODE::NORMAL
00136             )
00137         );
00138 }
00139
00140 //--------------------------------------------------------------------------------------
00141
00142 DirectX::XMMATRIX Camera::View()
00143 {
00144     return XMLoadFloat4x4(&m_viewMatrix);
00145 }
00146
00147 //--------------------------------------------------------------------------------------
00148
00149 DirectX::XMMATRIX Camera::Projection()
00150 {
00151     return XMLoadFloat4x4(&m_projectionMatrix);
00152 }
00153
00154 //--------------------------------------------------------------------------------------
00155
00156 DirectX::XMMATRIX Camera::LeftEyeProjection()
00157 {
00158     return XMLoadFloat4x4(&m_projectionMatrixLeft);
00159 }
00160
00161 //--------------------------------------------------------------------------------------
00162
00163 DirectX::XMMATRIX Camera::RightEyeProjection()
00164 {
00165     return XMLoadFloat4x4(&m_projectionMatrixRight);
00166 }
00167
00168 //--------------------------------------------------------------------------------------
00169
00170 DirectX::XMMATRIX Camera::World()
00171 {
00172     return XMLoadFloat4x4(&m_inverseView);
00173 }
00174
00175 //--------------------------------------------------------------------------------------
00176
00177 DirectX::XMFLOAT3 Camera::Eye()
00178 {
00179     return m_eye;
00180 }
00181
00182 //--------------------------------------------------------------------------------------
00183
00184 DirectX::XMFLOAT3 Camera::LookAt()
00185 {
00186     return m_lookAt;
00187 }
00188
00189 //--------------------------------------------------------------------------------------
00190
00191 float Camera::NearClipPlane()
00192 {
00193     return m_nearPlane;
00194 }
00195
00196 //--------------------------------------------------------------------------------------
00197
00198 float Camera::FarClipPlane()
00199 {
00200     return m_farPlane;
00201 }
00202
00203 //--------------------------------------------------------------------------------------
00204
00205 float Camera::Pitch()
00206 {
00207     return m_cameraPitchAngle;
00208 }
00209
00210 //--------------------------------------------------------------------------------------
00211
00212 float Camera::Yaw()
00213 {
00214     return m_cameraYawAngle;
00215 }
00216
00217 //--------------------------------------------------------------------------------------
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Globalization preferences/C++/GeographicRegion.xaml.h Source File

  • Globalization preferences

GeographicRegion.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 // GeographicRegionScenario.xaml.h
00013 // Declaration of the GeographicRegionScenario class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "GeographicRegion.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace GlobalizationPreferencesSample
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 GeographicRegionScenario sealed
00031         {
00032         public:
00033             GeographicRegionScenario();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void Display_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Background task/C++/BackgroundTask/App.xaml.cpp Source File

  • Background task
  • BackgroundTask

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047
00048     SDKSample::BackgroundTask::BackgroundTaskSample::RegisterServicingCompleteBackgroundTask();
00049     SDKSample::BackgroundTask::BackgroundTaskSample::InitializeBackgroundTaskStatus();
00050 }
00051
00052 /// <summary>
00053 /// Invoked when the application is launched normally by the end user.  Other entry points will
00054 /// be used when the application is launched to open a specific file, to display search results,
00055 /// and so forth.
00056 /// </summary>
00057 /// <param name="pArgs">Details about the launch request and process.</param>
00058 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00059 {
00060     this->LaunchArgs = pArgs;
00061
00062     // Do not repeat app initialization when already running, just ensure that
00063     // the window is active
00064     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00065     {
00066         Window::Current->Activate();
00067         return;
00068     }
00069
00070     // Create a Frame to act as the navigation context and associate it with
00071     // a SuspensionManager key
00072     auto rootFrame = ref new Frame();
00073     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00074
00075     auto prerequisite = task<void>([](){});
00076     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Terminated)
00077     {
00078         // Restore the saved session state only when appropriate, scheduling the
00079         // final launch steps after the restore is complete
00080         prerequisite = SuspensionManager::RestoreAsync();
00081     }
00082     prerequisite.then([=]()
00083     {
00084         // When the navigation stack isn't restored navigate to the first page,
00085         // configuring the new page by passing required information as a navigation
00086         // parameter
00087         if (rootFrame->Content == nullptr)
00088         {
00089             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00090             {
00091                 throw ref new FailureException("Failed to create initial page");
00092             }
00093         }
00094
00095         // Place the frame in the current Window and ensure that it is active
00096         Window::Current->Content = rootFrame;
00097         Window::Current->Activate();
00098     }, task_continuation_context::use_current());
00099 }
00100
00101 /// <summary>
00102 /// Invoked when application execution is being suspended.  Application state is saved
00103 /// without knowing whether the application will be terminated or resumed with the contents
00104 /// of memory still intact.
00105 /// </summary>
00106 /// <param name="sender">The source of the suspend request.</param>
00107 /// <param name="e">Details about the suspend request.</param>
00108 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00109 {
00110     (void) sender;  // Unused parameter
00111
00112     auto deferral = e->SuspendingOperation->GetDeferral();
00113     SuspensionManager::SaveAsync().then([=]()
00114     {
00115         deferral->Complete();
00116     });
00117 }
Generated on Sat Nov 23 2024 16:07:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML accessibility/C++/Scenario2.xaml.h Source File

  • XAML accessibility

Scenario2.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.xaml.h
00013 // Declaration of the Scenario2 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario2.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024   namespace Accessibility
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::WebHostHiddenAttribute]
00030     public ref class Scenario2 sealed
00031     {
00032     public:
00033       Scenario2();
00034
00035     protected:
00036       virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037     private:
00038       MainPage^ rootPage;
00039       void GiveControlFocus(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ args);
00040     };
00041   }
00042 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Simplified ink/C++/DirectXSample.h Source File

  • Input Simplified ink

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
00010 // This header defines helper utilities to make DirectX APIs work with exceptions.
00011 namespace DX
00012 {
00013     inline void ThrowIfFailed(HRESULT hr)
00014     {
00015         if (FAILED(hr))
00016         {
00017             // Set a breakpoint on this line to catch DX API errors.
00018             throw Platform::Exception::CreateException(hr);
00019         }
00020     }
00021 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKANIMATION_FRAME_DATA Member List

This is the complete list of members for SDKANIMATION_FRAME_DATA, including all inherited members.
AnimationData | SDKANIMATION_FRAME_DATA
DataOffset | SDKANIMATION_FRAME_DATA
FrameName | SDKANIMATION_FRAME_DATA
Generated on Sat Nov 23 2024 16:09:21 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D magazine app/C++/Layer.h Source File

  • Direct2D magazine app

Layer.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 "Element.h"
00011
00012 //  <layer> represents an intermediate bitmap surface to which the child content draws.
00013 //  It handles the user's scrolling gesture by initiating an animation transition sequence.
00014 //  Layer can fade to become fully transparent upon a user's tap gesture. This allows the
00015 //  content underneath it to become fully visible to the user.
00016 //
00017 //  Layer accepts no markup attribute in addition to the base attributes defined in Element.
00018 //
00019 ref class Layer : public Element
00020 {
00021 internal:
00022     Layer();
00023
00024     virtual bool AcceptChildNode(
00025         _In_ Document^ document,
00026         _In_ Windows::Data::Xml::Dom::IXmlNode^ childXmlNode
00027         ) override;
00028
00029     virtual float GetOpacity() override
00030     {
00031         return m_currentOpacity;
00032     }
00033
00034 private:
00035     // Initial layer opacity
00036     float m_initialOpacity;
00037
00038     // Current layer opacity. This would be 0 when a layer is faded out.
00039     float m_currentOpacity;
00040 };
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::StoreSample::sealed Member List

This is the complete list of members for SDKSample::StoreSample::sealed, including all inherited members.
AppListingUri() | SDKSample::StoreSample::sealed |
AppListingUriRefreshScenario() | SDKSample::StoreSample::sealed | [private]
BuyProduct1Button_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::StoreSample::sealed | [private]
BuyProduct2_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::StoreSample::sealed | [private]
ConvertTrial_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::StoreSample::sealed | [private]
DisplayLink_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::StoreSample::sealed | [private]
eventRegistrationToken | SDKSample::StoreSample::sealed | [private]
ExpiringProduct() | SDKSample::StoreSample::sealed |
ExpiringProductRefreshScenario() | SDKSample::StoreSample::sealed | [private]
FullProduct_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::StoreSample::sealed | [private]
InAppPurchase() | SDKSample::StoreSample::sealed |
InAppPurchaseRefreshScenario() | SDKSample::StoreSample::sealed | [private]
LoadAppListingUriProxyFile() | SDKSample::StoreSample::sealed | [private]
LoadExpiringProductProxyFile() | SDKSample::StoreSample::sealed | [private]
LoadInAppPurchaseProxyFile() | SDKSample::StoreSample::sealed | [private]
LoadReceiptProxyFile() | SDKSample::StoreSample::sealed | [private]
LoadTrialModeProxyFile() | SDKSample::StoreSample::sealed | [private]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::StoreSample::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::StoreSample::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::StoreSample::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::StoreSample::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::StoreSample::sealed | [protected, virtual]
OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^e) override | SDKSample::StoreSample::sealed | [protected, virtual]
OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^e) override | SDKSample::StoreSample::sealed | [protected, virtual]
OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^e) override | SDKSample::StoreSample::sealed | [protected, virtual]
OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^e) override | SDKSample::StoreSample::sealed | [protected, virtual]
OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^e) override | SDKSample::StoreSample::sealed | [protected, virtual]
Receipt() | SDKSample::StoreSample::sealed |
ReceiptRefreshScenario() | SDKSample::StoreSample::sealed | [private]
rootPage | SDKSample::StoreSample::sealed | [private]
ShowReceipt_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::StoreSample::sealed | [private]
TrialMode() | SDKSample::StoreSample::sealed |
TrialModeRefreshScenario() | SDKSample::StoreSample::sealed | [private]
TrialProduct_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::StoreSample::sealed | [private]
TrialTime_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::StoreSample::sealed | [private]
TryProduct1_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::StoreSample::sealed | [private]
TryProduct2_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::StoreSample::sealed | [private]
Generated on Sat Nov 23 2024 16:09:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: AtomPub/C++/common/LayoutAwarePage.h Source File

  • AtomPub
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: App settings/C++/pch.cpp Source File

  • App settings

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 Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File and folder thumbnail/C++/Scenario5.xaml.cpp Source File

  • File and folder thumbnail

Scenario5.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 // Scenario5.xaml.cpp
00013 // Implementation of the Scenario5 class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario5.xaml.h"
00018
00019 using namespace SDKSample::FileThumbnails;
00020
00021 using namespace concurrency;
00022 using namespace Platform;
00023 using namespace Windows::Foundation::Collections;
00024 using namespace Windows::Storage;
00025 using namespace Windows::Storage::FileProperties;
00026 using namespace Windows::Storage::Pickers;
00027 using namespace Windows::Storage::Search;
00028 using namespace Windows::UI::Xaml;
00029 using namespace Windows::UI::Xaml::Controls;
00030 using namespace Windows::UI::Xaml::Navigation;
00031
00032 Scenario5::Scenario5()
00033 {
00034     InitializeComponent();
00035     rootPage = MainPage::Current;
00036     GetThumbnailButton->Click += ref new RoutedEventHandler(this, &Scenario5::GetThumbnailButton_Click);
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     if (rootPage->EnsureUnsnapped())
00049     {
00050         // Pick a folder
00051         FolderPicker^ folderPicker = ref new FolderPicker();
00052         Array<String^>^ extensions = FileExtensions::Image;
00053         for (unsigned int i = 0; i < extensions->Length; i++)
00054         {
00055             folderPicker->FileTypeFilter->Append(extensions[i]);
00056         }
00057
00058         create_task(folderPicker->PickSingleFolderAsync()).then([this](StorageFolder^ folder)
00059         {
00060             if (folder != nullptr)
00061             {
00062                 const CommonFolderQuery monthShape = CommonFolderQuery::GroupByMonth;
00063                 // Verify queries are supported because they are not supported in all picked locations.
00064                 if (folder->IsCommonFolderQuerySupported(monthShape))
00065                 {
00066                     create_task(folder->CreateFolderQuery(monthShape)->GetFoldersAsync()).then([this, folder](IVectorView<StorageFolder^>^ months)
00067                     {
00068                         if (months != nullptr && months->Size > 0)
00069                         {
00070                             StorageFolder^ firstMonth = months->GetAt(0);
00071                             const ThumbnailMode thumbnailMode = ThumbnailMode::PicturesView;
00072                             const size_t size = 200;
00073                             create_task(firstMonth->GetThumbnailAsync(thumbnailMode, size)).then([this, folder, firstMonth, size](StorageItemThumbnail^ thumbnail)
00074                             {
00075                                 if (thumbnail != nullptr)
00076                                 {
00077                                     MainPage::DisplayResult(ThumbnailImage, OutputTextBlock, "PicturesView", size, folder, thumbnail, true);
00078
00079                                     // Also display the list of files in the file group
00080                                     create_task(firstMonth->GetFilesAsync()).then([this](IVectorView<StorageFile^>^ files)
00081                                     {
00082                                         String^ output = "\nList of files in the group:\n\n";
00083                                         for each (StorageFile^ file in files)
00084                                         {
00085                                             output += file->Name + "\n";
00086                                         }
00087                                         OutputDetails->Text = output;
00088                                     });
00089                                 }
00090                                 else
00091                                 {
00092                                     rootPage->NotifyUser(Errors::NoImages, NotifyType::StatusMessage);
00093                                 }
00094                             });
00095                         }
00096                         else
00097                         {
00098                             rootPage->NotifyUser(Errors::FileGroupEmpty, NotifyType::StatusMessage);
00099                         }
00100                     });
00101                 }
00102                 else
00103                 {
00104                     rootPage->NotifyUser(Errors::FileGroupLocation, NotifyType::StatusMessage);
00105                 }
00106             }
00107             else
00108             {
00109                 rootPage->NotifyUser(Errors::Cancel, NotifyType::StatusMessage);
00110             }
00111         });
00112     }
00113 }
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Credential picker/C++/ScenarioInput2.xaml.h Source File

  • Credential picker

ScenarioInput2.xaml.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 //
00009 // Scenario2Input.xaml.h
00010 // Declaration of the Scenario2Input class.
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioInput2.g.h"
00017 #include "MainPage.g.h"
00018
00019 namespace CredentialPickerCPP
00020 {
00021   [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class ScenarioInput2 sealed
00023     {
00024     public:
00025         ScenarioInput2();
00026
00027     protected:
00028         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030
00031     private:
00032         MainPage^ rootPage;
00033         void rootPage_OutputFrameLoaded(Object^ sender, Object^ e);
00034         void Launch_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00035         Windows::Foundation::EventRegistrationToken _frameLoadedToken;
00036         void SetError(Platform::String^ errorText);
00037         void SetResult(Windows::Security::Credentials::UI::CredentialPickerResults^ res);
00038         ~ScenarioInput2();
00039     };
00040 }
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Thread pool/C++/PeriodicTimerScenario.xaml.cpp Source File

  • Thread pool

PeriodicTimerScenario.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 // PeriodicTimerScenario.xaml.cpp
00013 // Implementation of the PeriodicTimerScenario class
00014 //
00015
00016 #include "pch.h"
00017 #include "PeriodicTimerScenario.xaml.h"
00018
00019 using namespace SDKSample::ThreadPool;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 PeriodicTimerScenario::PeriodicTimerScenario()
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 SDKSample::ThreadPool::PeriodicTimerScenario::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     SDKSample::ThreadPool::PeriodicScenario = this;
00041   PeriodMs->SelectedIndex = SDKSample::ThreadPool::PeriodicTimerSelectedIndex;
00042     UpdateUI(SDKSample::ThreadPool::PeriodicTimerStatus);
00043 }
00044
00045 void SDKSample::ThreadPool::PeriodicTimerScenario::OnNavigatedFrom(NavigationEventArgs^ e)
00046 {
00047   SDKSample::ThreadPool::PeriodicTimerSelectedIndex = PeriodMs->SelectedIndex;
00048 }
00049
00050 void SDKSample::ThreadPool::PeriodicTimerScenario::CreatePeriodicTimer(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00051 {
00052     auto timerDelegate = [this](Windows::System::Threading::ThreadPoolTimer^ timer)
00053     {
00054         auto uiDelegate = [this]()
00055         {
00056             SDKSample::ThreadPool::PeriodicTimerCount++;
00057             SDKSample::ThreadPool::PeriodicScenario->UpdateUI(Status::Completed);
00058         };
00059
00060         Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal,
00061                              ref new Windows::UI::Core::DispatchedHandler(uiDelegate));
00062     };
00063
00064     auto time = safe_cast<Platform::String^>(PeriodMs->SelectionBoxItem);
00065     PeriodicTimerMilliseconds = _wtol(time->Data());
00066
00067     Windows::Foundation::TimeSpan Period = ThreadPoolSample::MillisecondsToTimeSpan(PeriodicTimerMilliseconds);
00068     UpdateUI(Status::Started);
00069
00070     PeriodicTimer = Windows::System::Threading::ThreadPoolTimer::CreatePeriodicTimer(ref new Windows::System::Threading::TimerElapsedHandler(timerDelegate), Period);
00071 }
00072
00073 void SDKSample::ThreadPool::PeriodicTimerScenario::CancelPeriodicTimer(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00074 {
00075     if (PeriodicTimer != nullptr)
00076     {
00077         PeriodicTimer->Cancel();
00078         PeriodicTimerScenario::UpdateUI(Status::Canceled);
00079     }
00080 }
00081
00082 void SDKSample::ThreadPool::PeriodicTimerScenario::UpdateUI(Status status)
00083 {
00084     SDKSample::ThreadPool::PeriodicTimerStatus = status;
00085
00086     switch (status)
00087     {
00088         case Status::Completed:
00089             PeriodicTimerStatus->Text = "Completion count: " + SDKSample::ThreadPool::PeriodicTimerCount.ToString();
00090             break;
00091         default:
00092             PeriodicTimerStatus->Text = ThreadPoolSample::GetStatusString(status);
00093             break;
00094     }
00095
00096     PeriodicTimerInfo->Text = "Timer Period = " + PeriodicTimerMilliseconds.ToString() + " ms.";
00097
00098     auto createButtonEnabled = ((status != Status::Started) && (status != Status::Completed));
00099     CreatePeriodicTimerButton->IsEnabled = createButtonEnabled;
00100     CancelPeriodicTimerButton->IsEnabled = !createButtonEnabled;
00101 }
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D post-processing effects/C++/BasicReaderWriter.cpp Source File

  • Direct3D post-processing effects

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     m_locationPath = Platform::String::Concat(m_location->Path, "\\");
00023 }
00024
00025 BasicReaderWriter::BasicReaderWriter(
00026     _In_ Windows::Storage::StorageFolder^ folder
00027     )
00028 {
00029     m_location = folder;
00030     Platform::String^ path = m_location->Path;
00031     if (path->Length() == 0)
00032     {
00033         // Applications are not permitted to access certain
00034         // folders, such as the Documents folder, using this
00035         // code path.  In such cases, the Path property for
00036         // the folder will be an empty string.
00037         throw ref new Platform::FailureException();
00038     }
00039     m_locationPath = Platform::String::Concat(path, "\\");
00040 }
00041
00042 Platform::Array<byte>^ BasicReaderWriter::ReadData(
00043     _In_ Platform::String^ filename
00044     )
00045 {
00046     CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {0};
00047     extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
00048     extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
00049     extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN;
00050     extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
00051     extendedParams.lpSecurityAttributes = nullptr;
00052     extendedParams.hTemplateFile = nullptr;
00053
00054     Wrappers::FileHandle file(
00055         CreateFile2(
00056             Platform::String::Concat(m_locationPath, filename)->Data(),
00057             GENERIC_READ,
00058             FILE_SHARE_READ,
00059             OPEN_EXISTING,
00060             &extendedParams
00061             )
00062         );
00063     if (file.Get() == INVALID_HANDLE_VALUE)
00064     {
00065         throw ref new Platform::FailureException();
00066     }
00067
00068     FILE_STANDARD_INFO fileInfo = {0};
00069     if (!GetFileInformationByHandleEx(
00070         file.Get(),
00071         FileStandardInfo,
00072         &fileInfo,
00073         sizeof(fileInfo)
00074         ))
00075     {
00076         throw ref new Platform::FailureException();
00077     }
00078
00079     if (fileInfo.EndOfFile.HighPart != 0)
00080     {
00081         throw ref new Platform::OutOfMemoryException();
00082     }
00083
00084     Platform::Array<byte>^ fileData = ref new Platform::Array<byte>(fileInfo.EndOfFile.LowPart);
00085
00086     if (!ReadFile(
00087         file.Get(),
00088         fileData->Data,
00089         fileData->Length,
00090         nullptr,
00091         nullptr
00092         ))
00093     {
00094         throw ref new Platform::FailureException();
00095     }
00096
00097     return fileData;
00098 }
00099
00100 task<Platform::Array<byte>^> BasicReaderWriter::ReadDataAsync(
00101     _In_ Platform::String^ filename
00102     )
00103 {
00104     return task<StorageFile^>(m_location->GetFileAsync(filename)).then([=](StorageFile^ file)
00105     {
00106         return FileIO::ReadBufferAsync(file);
00107     }).then([=](IBuffer^ buffer)
00108     {
00109         auto fileData = ref new Platform::Array<byte>(buffer->Length);
00110         DataReader::FromBuffer(buffer)->ReadBytes(fileData);
00111         return fileData;
00112     });
00113 }
00114
00115 uint32 BasicReaderWriter::WriteData(
00116     _In_ Platform::String^ filename,
00117     _In_ const Platform::Array<byte>^ fileData
00118     )
00119 {
00120     CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {0};
00121     extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
00122     extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
00123     extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN;
00124     extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
00125     extendedParams.lpSecurityAttributes = nullptr;
00126     extendedParams.hTemplateFile = nullptr;
00127
00128     Wrappers::FileHandle file(
00129         CreateFile2(
00130             Platform::String::Concat(m_locationPath, filename)->Data(),
00131             GENERIC_WRITE,
00132             0,
00133             CREATE_ALWAYS,
00134             &extendedParams
00135             )
00136         );
00137     if (file.Get() == INVALID_HANDLE_VALUE)
00138     {
00139         throw ref new Platform::FailureException();
00140     }
00141
00142     DWORD numBytesWritten;
00143     if (
00144         !WriteFile(
00145             file.Get(),
00146             fileData->Data,
00147             fileData->Length,
00148             &numBytesWritten,
00149             nullptr
00150             ) ||
00151         numBytesWritten != fileData->Length
00152         )
00153     {
00154         throw ref new Platform::FailureException();
00155     }
00156
00157     return numBytesWritten;
00158 }
00159
00160 task<void> BasicReaderWriter::WriteDataAsync(
00161     _In_ Platform::String^ filename,
00162     _In_ const Platform::Array<byte>^ fileData
00163     )
00164 {
00165     return task<StorageFile^>(m_location->CreateFileAsync(filename, CreationCollisionOption::ReplaceExisting)).then([=](StorageFile^ file)
00166     {
00167         FileIO::WriteBytesAsync(file, fileData);
00168     });
00169 }
Generated on Sat Nov 23 2024 16:08:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Toast notifications/C#,C++/ScenarioInput3.xaml.cpp Source File

  • Toast notifications
  • C#,C++

ScenarioInput3.xaml.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 //
00009 // Scenario3Input.xaml.cpp
00010 // Implementation of the Scenario3Input class.
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioInput3.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace ToastsSampleCPP;
00018
00019 using namespace NotificationsExtensions::ToastContent;
00020 using namespace Platform;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Foundation::Collections;
00023 using namespace Windows::Graphics::Display;
00024 using namespace Windows::UI::Notifications;
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::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
00034 ScenarioInput3::ScenarioInput3()
00035 {
00036   InitializeComponent();
00037
00038   Scenario3DisplayToastImage01->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00039     Scenario3DisplayToast(ToastTemplateType::ToastImageAndText01);
00040   });
00041
00042   Scenario3DisplayToastImage02->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00043     Scenario3DisplayToast(ToastTemplateType::ToastImageAndText02);
00044   });
00045
00046   Scenario3DisplayToastImage03->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00047     Scenario3DisplayToast(ToastTemplateType::ToastImageAndText03);
00048   });
00049
00050   Scenario3DisplayToastImage04->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00051     Scenario3DisplayToast(ToastTemplateType::ToastImageAndText04);
00052   });
00053
00054
00055   Scenario3DisplayToastImage01String->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00056     Scenario3DisplayToastWithStringManipulation(ToastTemplateType::ToastImageAndText01);
00057   });
00058
00059   Scenario3DisplayToastImage02String->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00060     Scenario3DisplayToastWithStringManipulation(ToastTemplateType::ToastImageAndText02);
00061   });
00062
00063   Scenario3DisplayToastImage03String->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00064     Scenario3DisplayToastWithStringManipulation(ToastTemplateType::ToastImageAndText03);
00065   });
00066
00067   Scenario3DisplayToastImage04String->Click += ref new RoutedEventHandler([this](Object^ sender, RoutedEventArgs^ e) {
00068     Scenario3DisplayToastWithStringManipulation(ToastTemplateType::ToastImageAndText04);
00069   });
00070 }
00071
00072 ScenarioInput3::~ScenarioInput3()
00073 {
00074 }
00075
00076 #pragma region Template-Related Code - Do not remove
00077 void ScenarioInput3::OnNavigatedTo(NavigationEventArgs^ e)
00078 {
00079   // Get a pointer to our main page
00080   rootPage = dynamic_cast<MainPage^>(e->Parameter);
00081 }
00082
00083 void ScenarioInput3::OnNavigatedFrom(NavigationEventArgs^ e)
00084 {
00085
00086 }
00087
00088 #pragma endregion
00089
00090 void ScenarioInput3::OutputText(String^ text) {
00091   if (outputText == nullptr)
00092   {
00093     // Get a pointer to the content within the OutputFrame.
00094     Page^ outputFrame = dynamic_cast<Page^>(rootPage->OutputFrame->Content);
00095
00096     // Go find the elements that we need for this scenario
00097     outputText = dynamic_cast<TextBlock^>(outputFrame->FindName("Scenario3OutputText"));
00098   }
00099
00100   outputText->Text = text;
00101 }
00102
00103 void ScenarioInput3::Scenario3DisplayToast(ToastTemplateType templateType)
00104 {
00105   IToastNotificationContent^ toastContent = nullptr;
00106
00107   if (templateType == ToastTemplateType::ToastImageAndText01)
00108   {
00109     IToastImageAndText01^ specializedContent = ToastContentFactory::CreateToastImageAndText01();
00110     specializedContent->TextBodyWrap->Text = "Body text that wraps";
00111     specializedContent->Image->Src = Scenario3ImageUrl->Text;
00112     specializedContent->Image->Alt = "Web image";
00113     toastContent = specializedContent;
00114   }
00115   else if (templateType == ToastTemplateType::ToastImageAndText02)
00116   {
00117     IToastImageAndText02^ specializedContent = ToastContentFactory::CreateToastImageAndText02();
00118     specializedContent->TextHeading->Text = "Heading text";
00119     specializedContent->TextBodyWrap->Text = "Body text that wraps";
00120     specializedContent->Image->Src = Scenario3ImageUrl->Text;
00121     specializedContent->Image->Alt = "Web image";
00122     toastContent = specializedContent;
00123   }
00124   else if (templateType == ToastTemplateType::ToastImageAndText03)
00125   {
00126     IToastImageAndText03^ specializedContent = ToastContentFactory::CreateToastImageAndText03();
00127     specializedContent->TextHeadingWrap->Text = "Heading text that wraps";
00128     specializedContent->TextBody->Text = "Body text";
00129     specializedContent->Image->Src = Scenario3ImageUrl->Text;
00130     specializedContent->Image->Alt = "Web image";
00131     toastContent = specializedContent;
00132   }
00133   else if (templateType == ToastTemplateType::ToastImageAndText04)
00134   {
00135     IToastImageAndText04^ specializedContent = ToastContentFactory::CreateToastImageAndText04();
00136     specializedContent->TextHeading->Text = "Heading text that wraps";
00137     specializedContent->TextBody1->Text = "First body text";
00138     specializedContent->TextBody2->Text = "Second body text";
00139     specializedContent->Image->Src = Scenario3ImageUrl->Text;
00140     specializedContent->Image->Alt = "Web image";
00141     toastContent = specializedContent;
00142   }
00143
00144     if (toastContent != nullptr)
00145     {
00146         OutputText(toastContent->GetContent());
00147         // Create a toast, then create a ToastNotifier object to show
00148         // the toast
00149         auto toast = toastContent->CreateNotification();
00150         // If you have other applications in your package, you can specify the AppId of
00151         // the app to create a ToastNotifier for that application
00152         ToastNotificationManager::CreateToastNotifier()->Show(toast);
00153     }
00154 }
00155
00156 void ScenarioInput3::Scenario3DisplayToastWithStringManipulation(ToastTemplateType templateType)
00157 {
00158   String^ toastXmlString = nullptr;
00159
00160   if (templateType == ToastTemplateType::ToastImageAndText01)
00161   {
00162     toastXmlString = "<toast>"
00163       + "<visual version='1'>"
00164       + "<binding template='toastImageAndText01'>"
00165       + "<text id='1'>Body text that wraps over three lines</text>"
00166       + "<image id='1' src='" + Scenario3ImageUrl->Text + "' alt='Web image'/>"
00167       + "</binding>"
00168       + "</visual>"
00169       + "</toast>";
00170   }
00171   else if (templateType == ToastTemplateType::ToastImageAndText02)
00172   {
00173     toastXmlString = "<toast>"
00174       + "<visual version='1'>"
00175       + "<binding template='toastImageAndText02'>"
00176       + "<text id='1'>Heading text</text>"
00177       + "<text id='2'>Body text that wraps over two lines</text>"
00178       + "<image id='1' src='" + Scenario3ImageUrl->Text + "' alt='Web image'/>"
00179       + "</binding>"
00180       + "</visual>"
00181       + "</toast>";
00182   }
00183   else if (templateType == ToastTemplateType::ToastImageAndText03)
00184   {
00185     toastXmlString = "<toast>"
00186       + "<visual version='1'>"
00187       + "<binding template='toastImageAndText03'>"
00188       + "<text id='1'>Heading text that wraps over two lines</text>"
00189       + "<text id='2'>Body text</text>"
00190       + "<image id='1' src='" + Scenario3ImageUrl->Text + "' alt='Web image'/>"
00191       + "</binding>"
00192       + "</visual>"
00193       + "</toast>";
00194   }
00195   else if (templateType == ToastTemplateType::ToastImageAndText04)
00196   {
00197     toastXmlString = "<toast>"
00198       + "<visual version='1'>"
00199       + "<binding template='toastImageAndText04'>"
00200       + "<text id='1'>Heading text</text>"
00201       + "<text id='2'>First body text</text>"
00202       + "<text id='3'>Second body text</text>"
00203       + "<image id='1' src='" + Scenario3ImageUrl->Text + "' alt='Web image'/>"
00204       + "</binding>"
00205       + "</visual>"
00206       + "</toast>";
00207   }
00208
00209   auto toastDOM = ref new Windows::Data::Xml::Dom::XmlDocument();
00210   try
00211   {
00212     toastDOM->LoadXml(toastXmlString);
00213
00214     OutputText(toastDOM->GetXml());
00215
00216     // Create a toast, then create a ToastNotifier object to show
00217     // the toast
00218     auto toast = ref new ToastNotification(toastDOM);
00219
00220     // If you have other applications in your package, you can specify the AppId of
00221     // the app to create a ToastNotifier for that application
00222     ToastNotificationManager::CreateToastNotifier()->Show(toast);
00223   }
00224   catch (Exception^ e)
00225   {
00226     rootPage->NotifyUser("Error loading the xml, check for invalid characters in the input", NotifyType::ErrorMessage);
00227   }
00228 }
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

AssociationLaunching::sealed Member List

This is the complete list of members for AssociationLaunching::sealed, including all inherited members.
_displayHandlerToken | AssociationLaunching::sealed | [private]
_fileEventArgs | AssociationLaunching::sealed | [private]
_inputFrame | AssociationLaunching::sealed | [private]
_inputFrameLoadedToken | AssociationLaunching::sealed | [private]
_layoutHandlerToken | AssociationLaunching::sealed | [private]
_logicalDpiChangedToken | AssociationLaunching::sealed | [private]
_outputFrame | AssociationLaunching::sealed | [private]
_outputFrameLoadedToken | AssociationLaunching::sealed | [private]
_pageLoadedHandlerToken | AssociationLaunching::sealed | [private]
_protocolEventArgs | AssociationLaunching::sealed | [private]
_scenariosFrame | AssociationLaunching::sealed | [private]
App() | AssociationLaunching::sealed |
App::OnActivated(Windows::ApplicationModel::Activation::IActivatedEventArgs^args) override | AssociationLaunching::sealed | [virtual]
App::OnFileActivated(Windows::ApplicationModel::Activation::FileActivatedEventArgs^args) override | AssociationLaunching::sealed | [virtual]
CheckResolutionAndViewState() | AssociationLaunching::sealed | [private]
ConvertResolution(ResolutionScale scale) | AssociationLaunching::sealed |
ConvertViewState(ApplicationViewState state) | AssociationLaunching::sealed |
DisplayProperties_LogicalDpiChanged(Object^sender) | AssociationLaunching::sealed | [private]
DoNavigation(TypeName pageType, Windows::UI::Xaml::Controls::Frame^frame) | AssociationLaunching::sealed |
fileToLaunch | AssociationLaunching::sealed | [private, static]
Footer_Click(Object^sender, RoutedEventArgs^e) | AssociationLaunching::sealed | [private]
GetOpenWithPosition(Windows::UI::Xaml::FrameworkElement^element) | AssociationLaunching::sealed | [private, static]
GetOpenWithPosition(Windows::UI::Xaml::FrameworkElement^element) | AssociationLaunching::sealed | [private, static]
inputFrameNavigated(Object^sender, NavigationEventArgs^e) | AssociationLaunching::sealed | [private]
LaunchFileButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | AssociationLaunching::sealed | [private]
LaunchFileInput() | AssociationLaunching::sealed |
LaunchFileOpenWithButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | AssociationLaunching::sealed | [private]
LaunchFileOutput() | AssociationLaunching::sealed |
LaunchFileWithWarningButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | AssociationLaunching::sealed | [private]
LaunchUriButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | AssociationLaunching::sealed | [private]
LaunchUriInput() | AssociationLaunching::sealed |
LaunchUriOpenWithButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | AssociationLaunching::sealed | [private]
LaunchUriOutput() | AssociationLaunching::sealed |
LaunchUriWithWarningButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | AssociationLaunching::sealed | [private]
MainPage() | AssociationLaunching::sealed |
NotifyUser(String^strMessage, NotifyType type) | AssociationLaunching::sealed |
OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^args) override | AssociationLaunching::sealed | [virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | AssociationLaunching::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | AssociationLaunching::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | AssociationLaunching::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | AssociationLaunching::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | AssociationLaunching::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | AssociationLaunching::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | AssociationLaunching::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | AssociationLaunching::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | AssociationLaunching::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | AssociationLaunching::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | AssociationLaunching::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | AssociationLaunching::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | AssociationLaunching::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | AssociationLaunching::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | AssociationLaunching::sealed | [protected, virtual]
OnSuspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^pArgs) | AssociationLaunching::sealed | [virtual]
OutputFrameLoaded | AssociationLaunching::sealed |
outputFrameNavigated(Object^sender, NavigationEventArgs^e) | AssociationLaunching::sealed | [private]
Page_Loaded(Object^sender, RoutedEventArgs^e) | AssociationLaunching::sealed | [private]
Page_SizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | AssociationLaunching::sealed | [private]
PickAndLaunchFileButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | AssociationLaunching::sealed | [private]
ReceiveFileInput() | AssociationLaunching::sealed |
ReceiveFileOutput() | AssociationLaunching::sealed |
ReceiveUriInput() | AssociationLaunching::sealed |
ReceiveUriOutput() | AssociationLaunching::sealed |
rootPage | AssociationLaunching::sealed | [private]
ScenarioList() | AssociationLaunching::sealed |
Scenarios_SelectionChanged(Object^sender, SelectionChangedEventArgs^e) | AssociationLaunching::sealed | [protected]
SetFeatureName(Platform::String^strFeature) | AssociationLaunching::sealed | [private]
uriToLaunch | AssociationLaunching::sealed | [private, static]
~App() | AssociationLaunching::sealed | [private]
~LaunchFileInput() | AssociationLaunching::sealed | [private]
~LaunchFileOutput() | AssociationLaunching::sealed | [private]
~LaunchUriInput() | AssociationLaunching::sealed | [private]
~LaunchUriOutput() | AssociationLaunching::sealed | [private]
~MainPage() | AssociationLaunching::sealed | [private]
~ReceiveFileInput() | AssociationLaunching::sealed | [private]
~ReceiveFileOutput() | AssociationLaunching::sealed | [private]
~ReceiveUriInput() | AssociationLaunching::sealed | [private]
~ReceiveUriOutput() | AssociationLaunching::sealed | [private]
~ScenarioList() | AssociationLaunching::sealed | [private]
Generated on Sat Nov 23 2024 16:09:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/DirectXBase.cpp Source File

  • DirectX 3D shooting game

DirectXBase.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 "DirectXBase.h"
00010
00011 using namespace Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::Graphics::Display;
00015 using namespace D2D1;
00016 using namespace DirectX;
00017
00018 DirectXBase::DirectXBase() :
00019     m_windowSizeChangeInProgress(false),
00020     m_dpi(-1.0f)
00021 {
00022 }
00023
00024 // Initialize the DirectX resources required to run.
00025 void DirectXBase::Initialize(CoreWindow^ window, float dpi)
00026 {
00027     m_window = window;
00028
00029     CreateDeviceIndependentResources();
00030     CreateDeviceResources();
00031     SetDpi(dpi);
00032
00033     DisplayProperties::StereoEnabledChanged +=
00034         ref new DisplayPropertiesEventHandler(this, &DirectXBase::OnStereoEnabledChanged);
00035 }
00036
00037 // Recreate all device resources and set them back to the current state.
00038 void DirectXBase::HandleDeviceLost()
00039 {
00040     // Reset these member variables to ensure that SetDpi recreates all resources.
00041     float dpi = m_dpi;
00042     m_dpi = -1.0f;
00043     m_windowBounds.Width = 0;
00044     m_windowBounds.Height = 0;
00045     m_swapChain = nullptr;
00046
00047     // Send notifications via the DeviceLost event to any registered handlers.
00048     DeviceLost();
00049
00050     // Make sure the rendering state has been released.
00051     m_d3dContext->OMSetRenderTargets(0, nullptr, nullptr);
00052     m_d3dDepthStencilView = nullptr;
00053     m_d3dRenderTargetView = nullptr;
00054     m_d3dRenderTargetViewRight = nullptr;
00055
00056     m_d2dContext->SetTarget(nullptr);
00057     m_d2dTargetBitmap = nullptr;
00058     m_d2dTargetBitmapRight = nullptr;
00059     m_d2dContext = nullptr;
00060     m_d2dDevice = nullptr;
00061
00062     m_d3dContext->Flush();
00063
00064     CreateDeviceResources();
00065     SetDpi(dpi);
00066
00067     // Send notifications via the DeviceReset event to any registered handlers.
00068     DeviceReset();
00069 }
00070
00071 // These are the resources required independent of the device.
00072 void DirectXBase::CreateDeviceIndependentResources()
00073 {
00074     D2D1_FACTORY_OPTIONS options;
00075     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00076
00077 #if defined(_DEBUG)
00078     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00079     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00080 #endif
00081
00082     DX::ThrowIfFailed(
00083         D2D1CreateFactory(
00084             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00085             __uuidof(ID2D1Factory1),
00086             &options,
00087             &m_d2dFactory
00088             )
00089         );
00090
00091     DX::ThrowIfFailed(
00092         DWriteCreateFactory(
00093             DWRITE_FACTORY_TYPE_SHARED,
00094             __uuidof(IDWriteFactory),
00095             &m_dwriteFactory
00096             )
00097         );
00098
00099     DX::ThrowIfFailed(
00100         CoCreateInstance(
00101             CLSID_WICImagingFactory,
00102             nullptr,
00103             CLSCTX_INPROC_SERVER,
00104             IID_PPV_ARGS(&m_wicFactory)
00105             )
00106         );
00107 }
00108
00109 // These are the resources that depend on the device.
00110 void DirectXBase::CreateDeviceResources()
00111 {
00112     // This flag adds support for surfaces with a different color channel ordering
00113     // than the API default. It is required for compatibility with Direct2D.
00114     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00115     ComPtr<IDXGIDevice> dxgiDevice;
00116
00117 #if defined(_DEBUG)
00118     // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00119     creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00120 #endif
00121
00122     // This array defines the set of DirectX hardware feature levels this app will support.
00123     // Note the ordering should be preserved.
00124     // Don't forget to declare your application's minimum required feature level in its
00125     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00126     D3D_FEATURE_LEVEL featureLevels[] =
00127     {
00128         D3D_FEATURE_LEVEL_11_1,
00129         D3D_FEATURE_LEVEL_11_0,
00130         D3D_FEATURE_LEVEL_10_1,
00131         D3D_FEATURE_LEVEL_10_0,
00132         D3D_FEATURE_LEVEL_9_3,
00133         D3D_FEATURE_LEVEL_9_2,
00134         D3D_FEATURE_LEVEL_9_1
00135     };
00136
00137     // Create the Direct3D 11 API device object and a corresponding context.
00138     ComPtr<ID3D11Device> device;
00139     ComPtr<ID3D11DeviceContext> context;
00140     DX::ThrowIfFailed(
00141         D3D11CreateDevice(
00142             nullptr,                    // Specify nullptr to use the default adapter.
00143             D3D_DRIVER_TYPE_HARDWARE,
00144             0,
00145             creationFlags,              // Set debug and Direct2D compatibility flags.
00146             featureLevels,              // List of feature levels this app can support.
00147             ARRAYSIZE(featureLevels),
00148             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Metro style apps.
00149             &device,                    // Returns the Direct3D device created.
00150             &m_featureLevel,            // Returns feature level of device created.
00151             &context                    // Returns the device immediate context.
00152             )
00153         );
00154
00155     // Get the Direct3D 11.1 API device and context interfaces.
00156     DX::ThrowIfFailed(
00157         device.As(&m_d3dDevice)
00158         );
00159
00160     DX::ThrowIfFailed(
00161         context.As(&m_d3dContext)
00162         );
00163
00164     // Get the underlying DXGI device of the Direct3D device.
00165     DX::ThrowIfFailed(
00166         m_d3dDevice.As(&dxgiDevice)
00167         );
00168
00169     // Create the Direct2D device object and a corresponding context.
00170     DX::ThrowIfFailed(
00171         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00172         );
00173
00174     DX::ThrowIfFailed(
00175         m_d2dDevice->CreateDeviceContext(
00176             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00177             &m_d2dContext
00178             )
00179         );
00180 }
00181
00182 // Event handler for StereoEnabled changes.
00183 void DirectXBase::OnStereoEnabledChanged(
00184     _In_ Platform::Object^ /* sender */
00185     )
00186 {
00187     UpdateForWindowSizeChange();
00188 }
00189
00190 // Helps track the DPI in the helper class.
00191 void DirectXBase::SetDpi(float dpi)
00192 {
00193     if (dpi != m_dpi)
00194     {
00195         // Save the DPI of this display in our class.
00196         m_dpi = dpi;
00197
00198         // Update Direct2D's stored DPI.
00199         m_d2dContext->SetDpi(m_dpi, m_dpi);
00200
00201         // Often a DPI change implies a window size change. In some cases Windows will issue
00202         // both a size changed event and a DPI changed event. In this case, the resulting bounds
00203         // will not change, and the window resize code will only be executed once.
00204         UpdateForWindowSizeChange();
00205     }
00206 }
00207
00208 void DirectXBase::CheckStereoEnabledStatus()
00209 {
00210     ComPtr<IDXGIDevice1> dxgiDevice;
00211     DX::ThrowIfFailed(
00212         m_d3dDevice.As(&dxgiDevice)
00213         );
00214
00215     ComPtr<IDXGIAdapter> dxgiAdapter;
00216     DX::ThrowIfFailed(
00217         dxgiDevice->GetAdapter(&dxgiAdapter)
00218         );
00219
00220     ComPtr<IDXGIFactory2> dxgiFactory;
00221     DX::ThrowIfFailed(
00222         dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00223         );
00224
00225     m_stereoEnabled = dxgiFactory->IsWindowedStereoEnabled() ? true : false;
00226 }
00227
00228 // This routine is called in the event handler for the view SizeChanged event.
00229 void DirectXBase::UpdateForWindowSizeChange()
00230 {
00231     // Only handle window size changed if there is no pending DPI change.
00232     if (m_dpi != DisplayProperties::LogicalDpi)
00233     {
00234         return;
00235     }
00236
00237     bool previousStereoState = m_stereoEnabled;
00238     CheckStereoEnabledStatus();
00239     if (previousStereoState != m_stereoEnabled)
00240     {
00241         // Swap chain needs to be recreated so release the existing one.
00242         // The rest of the dependent resources with be released in CreateWindowSizeDependentResources.
00243         m_swapChain = nullptr;
00244         m_windowSizeChangeInProgress = true;
00245         CreateWindowSizeDependentResources();
00246     }
00247     else if (m_window->Bounds.Width != m_windowBounds.Width ||
00248         m_window->Bounds.Height != m_windowBounds.Height ||
00249         m_orientation != DisplayProperties::CurrentOrientation)
00250     {
00251         m_windowSizeChangeInProgress = true;
00252         CreateWindowSizeDependentResources();
00253     }
00254 }
00255
00256 // Allocate all memory resources that change on a window SizeChanged event.
00257 void DirectXBase::CreateWindowSizeDependentResources()
00258 {
00259     // Store the window bounds so the next time we get a SizeChanged event we can
00260     // avoid rebuilding everything if the size is identical.
00261     m_windowBounds = m_window->Bounds;
00262
00263     // Calculate the necessary swap chain and render target size in pixels.
00264     auto windowWidth = ConvertDipsToPixels(m_windowBounds.Width);
00265     auto windowHeight = ConvertDipsToPixels(m_windowBounds.Height);
00266
00267     // Swap width and height based on orientation.
00268     m_orientation = DisplayProperties::CurrentOrientation;
00269     bool swapDimensions = (
00270         m_orientation == DisplayOrientations::Portrait ||
00271         m_orientation == DisplayOrientations::PortraitFlipped
00272         );
00273     m_renderTargetSize.Width = swapDimensions ? windowHeight : windowWidth;
00274     m_renderTargetSize.Height = swapDimensions ? windowWidth : windowHeight;
00275
00276     // If the swap chain already exists, resize it.
00277     if (m_swapChain != nullptr)
00278     {
00279         // Existing swap chain needs to be resized.
00280         // Make sure that the dependent objects have been released.
00281         m_d3dContext->OMSetRenderTargets(0, nullptr, nullptr);
00282         m_d3dRenderTargetView = nullptr;
00283         m_d3dDepthStencilView = nullptr;
00284         m_d2dContext->SetTarget(nullptr);
00285         m_d2dTargetBitmap = nullptr;
00286         m_d2dTargetBitmapRight = nullptr;
00287         m_d3dRenderTargetViewRight = nullptr;
00288
00289         HRESULT hr = m_swapChain->ResizeBuffers(
00290             2,
00291             static_cast<UINT>(m_renderTargetSize.Width),
00292             static_cast<UINT>(m_renderTargetSize.Height),
00293             DXGI_FORMAT_B8G8R8A8_UNORM,
00294             0
00295             );
00296
00297         if (hr == DXGI_ERROR_DEVICE_REMOVED)
00298         {
00299             // If the device was removed for any reason, a new device and swapchain will need to be created.
00300             HandleDeviceLost();
00301
00302             // Everything is set up now. Do not continue execution of this method.
00303             return;
00304         }
00305         else
00306         {
00307             DX::ThrowIfFailed(hr);
00308         }
00309     }
00310     else    // Otherwise, create a new one.
00311     {
00312         // m_swapChain is nullptr either because it has never been created or because it has been
00313         // invalidated. Make sure that the dependent objects are also released.
00314         m_d3dContext->OMSetRenderTargets(0, nullptr, nullptr);
00315         m_d3dRenderTargetView = nullptr;
00316         m_d3dDepthStencilView = nullptr;
00317         m_d2dContext->SetTarget(nullptr);
00318         m_d2dTargetBitmap = nullptr;
00319         m_d3dRenderTargetViewRight = nullptr;
00320         m_d2dTargetBitmapRight = nullptr;
00321         m_d3dContext->Flush();
00322
00323         CheckStereoEnabledStatus();
00324
00325         // Allocate a descriptor.
00326         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00327         swapChainDesc.Width = static_cast<UINT>(m_renderTargetSize.Width); // Match the size of the window.
00328         swapChainDesc.Height = static_cast<UINT>(m_renderTargetSize.Height);
00329         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;           // This is the most common swapchain format.
00330         swapChainDesc.Stereo = m_stereoEnabled;
00331         swapChainDesc.SampleDesc.Count = 1;                          // Don't use multi-sampling.
00332         swapChainDesc.SampleDesc.Quality = 0;
00333         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00334         swapChainDesc.BufferCount = 2;                               // Use double buffering to minimize latency.
00335         swapChainDesc.Scaling = DXGI_SCALING_NONE;
00336         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Metro style apps must use this SwapEffect.
00337         swapChainDesc.Flags = 0;
00338
00339         // Once the desired swap chain description is configured, it must be created on the same adapter as our D3D Device.
00340
00341         // First, retrieve the underlying DXGI Device from the D3D Device.
00342         ComPtr<IDXGIDevice1> dxgiDevice;
00343         DX::ThrowIfFailed(
00344             m_d3dDevice.As(&dxgiDevice)
00345             );
00346
00347         // Identify the physical adapter (GPU or card) this device is running on.
00348         ComPtr<IDXGIAdapter> dxgiAdapter;
00349         DX::ThrowIfFailed(
00350             dxgiDevice->GetAdapter(&dxgiAdapter)
00351             );
00352
00353         // And obtain the factory object that created it.
00354         ComPtr<IDXGIFactory2> dxgiFactory;
00355         DX::ThrowIfFailed(
00356             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00357             );
00358
00359         // Obtain the final swap chain for this window from the DXGI factory.
00360         CoreWindow^ window = m_window.Get();
00361         DX::ThrowIfFailed(
00362             dxgiFactory->CreateSwapChainForCoreWindow(
00363                 m_d3dDevice.Get(),
00364                 reinterpret_cast<IUnknown*>(window),
00365                 &swapChainDesc,
00366                 nullptr,    // allow on all displays
00367                 &m_swapChain
00368                 )
00369             );
00370
00371         // Ensure that DXGI does not queue more than one frame at a time. This both reduces
00372         // latency and ensures that the application will only render after each VSync, minimizing
00373         // power consumption.
00374         DX::ThrowIfFailed(
00375             dxgiDevice->SetMaximumFrameLatency(1)
00376             );
00377     }
00378
00379     // Set the proper orientation for the swap chain, and generate 2D and
00380     // 3D matrix transformations for rendering to the rotated swap chain.
00381     // Note the rotation angle for the 2D and 3D transforms are different.
00382     // This is due to the difference in coordinate spaces.  Additionally,
00383     // the 3D matrix is specified explicitly to avoid rounding errors.
00384     DXGI_MODE_ROTATION rotation = DXGI_MODE_ROTATION_UNSPECIFIED;
00385     switch (m_orientation)
00386     {
00387         case DisplayOrientations::Landscape:
00388             rotation = DXGI_MODE_ROTATION_IDENTITY;
00389             m_rotationTransform2D = Matrix3x2F::Identity();
00390             XMStoreFloat4x4(&m_rotationTransform3D, XMMatrixIdentity());
00391             break;
00392
00393         case DisplayOrientations::Portrait:
00394             rotation = DXGI_MODE_ROTATION_ROTATE270;
00395             m_rotationTransform2D =
00396                 Matrix3x2F::Rotation(270.0f) *
00397                 Matrix3x2F::Translation(0.0f, m_windowBounds.Width);
00398             XMStoreFloat4x4(
00399                 &m_rotationTransform3D,
00400                 XMMATRIX( // 90-degree Z-rotation
00401                      0.0f, 1.0f, 0.0f, 0.0f,
00402                     -1.0f, 0.0f, 0.0f, 0.0f,
00403                      0.0f, 0.0f, 1.0f, 0.0f,
00404                      0.0f, 0.0f, 0.0f, 1.0f
00405                     )
00406                 );
00407             break;
00408
00409         case DisplayOrientations::LandscapeFlipped:
00410             rotation = DXGI_MODE_ROTATION_ROTATE180;
00411             m_rotationTransform2D =
00412                 Matrix3x2F::Rotation(180.0f) *
00413                 Matrix3x2F::Translation(m_windowBounds.Width, m_windowBounds.Height);
00414             XMStoreFloat4x4(
00415                 &m_rotationTransform3D,
00416                 XMMATRIX( // 180-degree Z-rotation
00417                     -1.0f,  0.0f, 0.0f, 0.0f,
00418                      0.0f, -1.0f, 0.0f, 0.0f,
00419                      0.0f,  0.0f, 1.0f, 0.0f,
00420                      0.0f,  0.0f, 0.0f, 1.0f
00421                     )
00422                 );
00423             break;
00424
00425         case DisplayOrientations::PortraitFlipped:
00426             rotation = DXGI_MODE_ROTATION_ROTATE90;
00427             m_rotationTransform2D =
00428                 Matrix3x2F::Rotation(90.0f) *
00429                 Matrix3x2F::Translation(m_windowBounds.Height, 0.0f);
00430             XMStoreFloat4x4(
00431                 &m_rotationTransform3D,
00432                 XMMATRIX( // 270-degree Z-rotation
00433                     0.0f, -1.0f, 0.0f, 0.0f,
00434                     1.0f,  0.0f, 0.0f, 0.0f,
00435                     0.0f,  0.0f, 1.0f, 0.0f,
00436                     0.0f,  0.0f, 0.0f, 1.0f
00437                     )
00438                 );
00439             break;
00440
00441         default:
00442             throw ref new Platform::FailureException();
00443             break;
00444     }
00445
00446     DX::ThrowIfFailed(
00447         m_swapChain->SetRotation(rotation)
00448         );
00449
00450     // Obtain the backbuffer for this window which will be the final 3D rendertarget.
00451     ComPtr<ID3D11Texture2D> backBuffer;
00452     DX::ThrowIfFailed(
00453         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00454         );
00455
00456     // Create a descriptor for the RenderTargetView.
00457     CD3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc(
00458         D3D11_RTV_DIMENSION_TEXTURE2DARRAY,
00459         DXGI_FORMAT_B8G8R8A8_UNORM,
00460         0,
00461         0,
00462         1
00463         );
00464
00465     // Create a view interface on the rendertarget to use on bind for mono or left eye view.
00466     DX::ThrowIfFailed(
00467         m_d3dDevice->CreateRenderTargetView(
00468             backBuffer.Get(),
00469             &renderTargetViewDesc,
00470             &m_d3dRenderTargetView
00471             )
00472         );
00473
00474     // Stereo swapchains have an arrayed resource, so create a second Render Target
00475     // for the right eye buffer.
00476     if (m_stereoEnabled)
00477     {
00478         CD3D11_RENDER_TARGET_VIEW_DESC renderTargetViewRightDesc(
00479             D3D11_RTV_DIMENSION_TEXTURE2DARRAY,
00480             DXGI_FORMAT_B8G8R8A8_UNORM,
00481             0,
00482             1,
00483             1
00484             );
00485
00486         DX::ThrowIfFailed(
00487             m_d3dDevice->CreateRenderTargetView(
00488                 backBuffer.Get(),
00489                 &renderTargetViewRightDesc,
00490                 &m_d3dRenderTargetViewRight
00491                 )
00492             );
00493     }
00494
00495     // Create a descriptor for the depth/stencil buffer.
00496     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00497         DXGI_FORMAT_D24_UNORM_S8_UINT,
00498         static_cast<UINT>(m_renderTargetSize.Width),
00499         static_cast<UINT>(m_renderTargetSize.Height),
00500         1,
00501         1,
00502         D3D11_BIND_DEPTH_STENCIL
00503         );
00504
00505     // Allocate a 2-D surface as the depth/stencil buffer.
00506     ComPtr<ID3D11Texture2D> depthStencil;
00507     DX::ThrowIfFailed(
00508         m_d3dDevice->CreateTexture2D(
00509             &depthStencilDesc,
00510             nullptr,
00511             &depthStencil
00512             )
00513         );
00514
00515     // Create a DepthStencil view on this surface to use on bind.
00516     auto viewDesc = CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D);
00517     DX::ThrowIfFailed(
00518         m_d3dDevice->CreateDepthStencilView(
00519             depthStencil.Get(),
00520             &viewDesc,
00521             &m_d3dDepthStencilView
00522             )
00523         );
00524
00525     // Create a viewport descriptor of the full window size.
00526     CD3D11_VIEWPORT viewport(
00527         0.0f,
00528         0.0f,
00529         m_renderTargetSize.Width,
00530         m_renderTargetSize.Height
00531         );
00532
00533     // Set the current viewport using the descriptor.
00534     m_d3dContext->RSSetViewports(1, &viewport);
00535
00536     // Now we set up the Direct2D render target bitmap linked to the swapchain.
00537     // Whenever we render to this bitmap, it will be directly rendered to the
00538     // swapchain associated with the window.
00539     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00540         BitmapProperties1(
00541             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00542             PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00543             m_dpi,
00544             m_dpi
00545             );
00546
00547     // Direct2D needs the dxgi version of the backbuffer surface pointer.
00548     ComPtr<IDXGIResource1> dxgiBackBuffer;
00549     DX::ThrowIfFailed(
00550         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00551         );
00552
00553     ComPtr<IDXGISurface2> dxgiSurface;
00554     DX::ThrowIfFailed(
00555         dxgiBackBuffer->CreateSubresourceSurface(0, &dxgiSurface)
00556         );
00557
00558     // Get a D2D surface from the DXGI back buffer to use as the D2D render target.
00559     DX::ThrowIfFailed(
00560         m_d2dContext->CreateBitmapFromDxgiSurface(
00561             dxgiSurface.Get(),
00562             &bitmapProperties,
00563             &m_d2dTargetBitmap
00564             )
00565         );
00566
00567     // Stereo swapchains have an arrayed resource, so create a second Target Bitmap
00568     // for the right eye buffer.
00569     if (m_stereoEnabled)
00570     {
00571         DX::ThrowIfFailed(
00572             dxgiBackBuffer->CreateSubresourceSurface(1, &dxgiSurface)
00573             );
00574         DX::ThrowIfFailed(
00575             m_d2dContext->CreateBitmapFromDxgiSurface(
00576                 dxgiSurface.Get(),
00577                 &bitmapProperties,
00578                 &m_d2dTargetBitmapRight
00579             )
00580         );
00581     }
00582
00583     // So now we can set the Direct2D render target.
00584     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00585
00586     // Set D2D text anti-alias mode to Grayscale to ensure proper rendering of text on intermediate surfaces.
00587     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00588 }
00589
00590 // Method to deliver the final image to the display.
00591 void DirectXBase::Present()
00592 {
00593     // The application may optionally specify "dirty" or "scroll" rects to improve efficiency
00594     // in certain scenarios.  In this sample, however, we do not utilize those features.
00595     DXGI_PRESENT_PARAMETERS parameters = {0};
00596     parameters.DirtyRectsCount = 0;
00597     parameters.pDirtyRects = nullptr;
00598     parameters.pScrollRect = nullptr;
00599     parameters.pScrollOffset = nullptr;
00600
00601     // The first argument instructs DXGI to block until VSync, putting the application
00602     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00603     // frames that will never be displayed to the screen.
00604     HRESULT hr = m_swapChain->Present1(1, 0, &parameters);
00605
00606     // If the device was removed either by a disconnect or a driver upgrade, we
00607     // must recreate all device resources.
00608     if (hr == DXGI_ERROR_DEVICE_REMOVED)
00609     {
00610         // Recreate the Device Resources.
00611         HandleDeviceLost();
00612     }
00613     else
00614     {
00615         DX::ThrowIfFailed(hr);
00616     }
00617
00618     if (m_windowSizeChangeInProgress)
00619     {
00620         // A window size change has been initiated and the app has just completed presenting
00621         // the first frame with the new size. Notify the resize manager so we can short
00622         // circuit any resize animation and prevent unnecessary delays.
00623         CoreWindowResizeManager::GetForCurrentView()->NotifyLayoutCompleted();
00624         m_windowSizeChangeInProgress = false;
00625     }
00626 }
00627
00628 // Method to convert a length in device-independent pixels (DIPs) to a length in physical pixels.
00629 float DirectXBase::ConvertDipsToPixels(float dips)
00630 {
00631     static const float dipsPerInch = 96.0f;
00632     return floor(dips * m_dpi / dipsPerInch + 0.5f); // Round to nearest integer.
00633 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text editing/C++/pch.h Source File

  • XAML text editing

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/ImageBrowserView.xaml.cpp Source File

  • Hilo C++
  • Hilo

ImageBrowserView.xaml.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 #include "ImageBrowserViewModel.h"
00009 #include "ImageNavigationData.h"
00010 #include "ImageBrowserView.xaml.h"
00011
00012 using namespace Hilo;
00013 using namespace Platform;
00014 using namespace Windows::UI::Xaml::Controls;
00015
00016 // See http://go.microsoft.com/fwlink/?LinkId=267278 for info on how Hilo creates pages and navigates to pages.
00017
00018 ImageBrowserView::ImageBrowserView()
00019 {
00020     this->NavigationCacheMode = Windows::UI::Xaml::Navigation::NavigationCacheMode::Required;
00021     InitializeComponent();
00022 }
00023
00024 void ImageBrowserView::OnPhotoItemClicked(Object^ sender, ItemClickEventArgs^ e)
00025 {
00026     auto photo = dynamic_cast<Photo^>(e->ClickedItem);
00027     if (nullptr !=  photo)
00028     {
00029         ImageNavigationData imageData(photo);
00030         HiloPage::NavigateToPage(PageType::Image, imageData.SerializeToString());
00031     }
00032 }
00033
00034 void ImageBrowserView::OnViewChangeCompleted(Object^ sender, SemanticZoomViewChangedEventArgs^ e)
00035 {
00036     bool displayAppBar = false;
00037
00038     if (!e->IsSourceZoomedInView)
00039     {
00040         displayAppBar = true;
00041         auto viewModel = dynamic_cast<ImageBrowserViewModel^>(DataContext);
00042         auto monthBlock = dynamic_cast<MonthBlock^>(e->SourceItem->Item);
00043         if (nullptr != monthBlock)
00044         {
00045             // Locate the first photo for selected month. This photo was previously cached by the view model.
00046             auto photo = viewModel->GetPhotoForYearAndMonth(monthBlock->Group->Year, monthBlock->Month);
00047             if (nullptr != photo)
00048             {
00049                 // Scroll the month groups grid to the first photo of the selected month.
00050                 MonthPhotosGridView->ScrollIntoView(photo);
00051             }
00052         }
00053     }
00054
00055     ImageBrowserViewBottomAppBar->Visibility = displayAppBar ? Windows::UI::Xaml::Visibility::Visible : Windows::UI::Xaml::Visibility::Collapsed;
00056 }
00057
00058 void Hilo::ImageBrowserView::OnZoomedOutGridPointerEntered(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ e)
00059 {
00060     auto grid = dynamic_cast<Grid^>(sender);
00061     if (grid != nullptr)
00062     {
00063         // Disable the SemanticZoom control from transitioning from the
00064         // zoomed-out view to the zoomed-in view when the user hovers over
00065         // a month that does not contain pictures.
00066         IMonthBlock^ monthBlock = dynamic_cast<IMonthBlock^>(grid->DataContext);
00067         if (monthBlock == nullptr || !monthBlock->HasPhotos)
00068         {
00069             SemanticZoom->CanChangeViews = false;
00070         }
00071         else
00072         {
00073             SemanticZoom->CanChangeViews = true;
00074         }
00075     }
00076 }
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Connecting with WebSockets/C++/Constants.cpp Source File

  • Connecting with WebSockets

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully qualified name for the class that implements the scenario" }
00021     { "UTF-8 text messages", "SDKSample.WebSocket.Scenario1" },
00022     { "Binary data stream", "SDKSample.WebSocket.Scenario2" }
00023 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Network status background/C++/NetworkStatusApp/App.xaml.h Source File

  • Network status background
  • NetworkStatusApp

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Compression/C++/Scenario2.xaml.h Source File

  • Compression

Scenario2.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.xaml.h
00013 // Declaration of the Scenario2 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario2.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
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 Scenario2 sealed
00031         {
00032         public:
00033             Scenario2();
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 Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00043             void Xpress_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00044             void XpressHuff_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00045             void Mszip_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00046             void Lzms_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047         };
00048     }
00049 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Sharing content target app/C++/MainPage.xaml.h Source File

  • Sharing content target app

MainPage.xaml.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 //
00009 // MainPage.xaml.h
00010 // Declaration of the MainPage.xaml class.
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include <agile.h>
00017 #include "MainPage.g.h"
00018 #include <agile.h>
00019
00020 #define DATA_FORMAT_NAME "http://schema.org/Book"
00021
00022 namespace ShareTarget
00023 {
00024     public enum class NotifyType
00025     {
00026         StatusMessage,
00027         ErrorMessage
00028     };
00029
00030   [Windows::Foundation::Metadata::WebHostHidden]
00031     public ref class MainPage sealed
00032     {
00033     public:
00034         MainPage();
00035
00036         void NotifyUser(Platform::String^ strmessage, NotifyType type);
00037         void NotifyUserBackgroundThread(Platform::String^ message, NotifyType type);
00038         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00039
00040     private:
00041         ~MainPage();
00042         Platform::Agile<Windows::ApplicationModel::DataTransfer::ShareTarget::ShareOperation> shareOperation;
00043         Platform::String^ sharedDataTitle;
00044         Platform::String^ sharedDataDescription;
00045         Platform::String^ shareQuickLinkId;
00046         Platform::String^ sharedText;
00047         Windows::Foundation::Uri^ sharedUri;
00048         Windows::Foundation::Collections::IVectorView<Windows::Storage::IStorageItem^>^ sharedStorageItems;
00049         Platform::String^ sharedCustomData;
00050         Platform::String^ sharedHtmlFormat;
00051         Windows::Foundation::Collections::IMapView<Platform::String^, Windows::Storage::Streams::RandomAccessStreamReference^>^ sharedResourceMap;
00052         Windows::Storage::Streams::IRandomAccessStreamReference^ sharedBitmapStreamRef;
00053         Windows::Storage::Streams::IRandomAccessStreamReference^ sharedThumbnailStreamRef;
00054
00055         void QuickLinkSectionLabel_Tapped(Platform::Object^ sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^ e);
00056         void AddQuickLink_Checked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00057         void AddQuickLink_Unchecked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00058         void ReportCompleted_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00059         void LongRunningShareLabel_Tapped(Platform::Object^ sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^ e);
00060         void ExpandLongRunningShareSection_Checked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061         void ExpandLongRunningShareSection_Unchecked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062         void ReportStarted_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063         void ReportDataRetrieved_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00064         void ReportSubmittedBackgroundTask_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00065         void ReportErrorButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00066         void Footer_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00067         void AddContentValue(Platform::String^ title);
00068         void AddContentValue(Platform::String^ title, Platform::String^ description);
00069     };
00070  }
Generated on Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DXGI swap chain rotation/C++/BasicCamera.cpp Source File

  • DXGI swap chain rotation

BasicCamera.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 "BasicCamera.h"
00010
00011 void BasicCamera::GetViewMatrix(_Out_ float4x4 *viewMatrix)
00012 {
00013     *viewMatrix = m_view;
00014 }
00015
00016 void BasicCamera::GetProjectionMatrix(_Out_ float4x4 *projectionMatrix)
00017 {
00018     *projectionMatrix = m_projection;
00019 }
00020
00021 // this method updates the view matrix based on new position and focus coordinates
00022 void BasicCamera::SetViewParameters(
00023     _In_ float3 eyePosition,    // the position of the camera
00024     _In_ float3 lookPosition,   // the point the camera should look at
00025     _In_ float3 up              // the durection vector for up
00026     )
00027 {
00028     m_position = eyePosition;
00029     m_direction = normalize(lookPosition - eyePosition);
00030     float3 zAxis = -m_direction;
00031     float3 xAxis = normalize(cross(up, zAxis));
00032     float3 yAxis = cross(zAxis, xAxis);
00033     float xOffset = -dot(xAxis, m_position);
00034     float yOffset = -dot(yAxis, m_position);
00035     float zOffset = -dot(zAxis, m_position);
00036     m_view = float4x4(
00037         xAxis.x, xAxis.y, xAxis.z, xOffset,
00038         yAxis.x, yAxis.y, yAxis.z, yOffset,
00039         zAxis.x, zAxis.y, zAxis.z, zOffset,
00040         0.0f,    0.0f,    0.0f,    1.0f
00041         );
00042 }
00043     // this method updates the projection matrix based on new parameters
00044 void BasicCamera::SetProjectionParameters(
00045     _In_ float minimumFieldOfView,  // the minimum horizontal or vertical field of view, in degrees
00046     _In_ float aspectRatio,         // the aspect ratio of the projection (width / height)
00047     _In_ float nearPlane,           // depth to map to 0
00048     _In_ float farPlane             // depth to map to 1
00049     )
00050 {
00051     float minScale = 1.0f / tan(minimumFieldOfView * PI_F / 360.0f);
00052     float xScale = 1.0f;
00053     float yScale = 1.0f;
00054     if (aspectRatio < 1.0f)
00055     {
00056         xScale = minScale;
00057         yScale = minScale * aspectRatio;
00058     }
00059     else
00060     {
00061         xScale = minScale / aspectRatio;
00062         yScale = minScale;
00063     }
00064     float zScale = farPlane / (farPlane - nearPlane);
00065     m_projection = float4x4(
00066         xScale, 0.0f,   0.0f,    0.0f,
00067         0.0f,   yScale, 0.0f,    0.0f,
00068         0.0f,   0.0f,   -zScale, -nearPlane*zScale,
00069         0.0f,   0.0f,   -1.0f,   0.0f
00070         );
00071 }
Generated on Sat Nov 23 2024 16:08:07 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/MediaExtensions/Invert/CopyModule.h Source File

  • Media extensions
  • MediaExtensions
  • Invert

CopyModule.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include "DirectXVideoTransform.h"
00004
00005 class CCopyModule : public DirectXVideoTransform
00006 {
00007     virtual void Invalidate(){}
00008
00009     virtual HRESULT Initialize(ID3D11Device *pDevice, UINT uiWidth, UINT uiHeight){ return S_OK; }
00010
00011     virtual HRESULT ProcessFrame(ID3D11Device *pDevice, ID3D11Texture2D *pInput, UINT uiInIndex, ID3D11Texture2D *pOutput, UINT uiOutIndex)
00012     {
00013         ComPtr<ID3D11DeviceContext> pContext;
00014         pDevice->GetImmediateContext(&pContext);
00015
00016         pContext->CopySubresourceRegion(pOutput, uiOutIndex, 0, 0, 0, pInput, uiInIndex, NULL);
00017
00018         return S_OK;
00019     }
00020 };
Generated on Sat Nov 23 2024 16:08:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: PlayToReceiver/C++/common/LayoutAwarePage.cpp Source File

  • PlayToReceiver
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:32 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Network information/C++/Constants.h Source File

  • Network information

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"Network Information Api");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044
00045
00046 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Portable device API/C++/S5_Events.xaml.h Source File

  • Portable device API

S5_Events.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 // S5_Events.xaml.h
00013 // Declaration of the S5_Events class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "S5_Events.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace PortableDeviceCPP
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 S5_Events sealed
00031         {
00032         public:
00033             S5_Events();
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             void Run_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041             void Trigger_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00042             void ShowDeviceSelectorAsync();
00043             void DeviceList_Tapped(Platform::Object^ sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^ e);
00044             void RegisterForDeviceEvents(Windows::Devices::Enumeration::DeviceInformation^ deviceInfo);
00045             void UnregisterForDeviceEvents();
00046             bool IsRegisteredForDeviceEvents()
00047             {
00048                 return ((_deviceEventSource != nullptr) && (_deviceEventCookie != nullptr));
00049             }
00050             void OnDeviceEventReceived(Platform::String^ senderDeviceId, Platform::String^ eventData);
00051             void CreateAndThenDeleteFolderOnDeviceAsync();
00052             Microsoft::WRL::ComPtr<IPortableDeviceValues> FillInPropertiesForFolder(Platform::String^ parentId);
00053
00054             MainPage^ rootPage;
00055             // Contains the device information used for populating the device selection list
00056             Windows::Devices::Enumeration::DeviceInformationCollection^ _deviceInfoCollection;
00057             // Contains the device event registration cookie
00058             Platform::String^ _deviceEventCookie;
00059             // Contains the device event source
00060             Microsoft::WRL::ComPtr<IPortableDevice> _deviceEventSource;
00061         };
00062     }
00063 }
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Context menu/C++/Constants.h Source File

  • Context menu

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"Context menu C++ sample");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041
00042     private:
00043         static Platform::Array<Scenario>^ scenariosInner;
00044     };
00045 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DatagramSocket/C++/pch.h Source File

  • DatagramSocket

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include "Sample-Utils\CppSamplesUtils.h"
00019 #include <ppltasks.h>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Real-time communication/C#,C++/Common/LayoutAwarePage.cs Source File

  • Real-time communication
  • C#,C++
  • Common

LayoutAwarePage.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.ComponentModel;
00014 using System.Linq;
00015 using Windows.Foundation;
00016 using Windows.Foundation.Collections;
00017 using Windows.UI.ViewManagement;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020
00021 namespace SDKTemplate.Common
00022 {
00023     /// <summary>
00024     /// Typical implementation of Page that provides several important conveniences:
00025     /// application view state to visual state mapping, GoBack and GoHome event handlers, and
00026     /// a default view model.
00027     /// </summary>
00028     [Windows.Foundation.Metadata.WebHostHidden]
00029     public class LayoutAwarePage : Page
00030     {
00031         /// <summary>
00032         /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00033         /// </summary>
00034         public static readonly DependencyProperty DefaultViewModelProperty =
00035             DependencyProperty.Register("DefaultViewModel", typeof(IObservableMap<String, Object>),
00036             typeof(LayoutAwarePage), null);
00037
00038         private List<Control> _layoutAwareControls;
00039
00040         /// <summary>
00041         /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00042         /// </summary>
00043         public LayoutAwarePage()
00044         {
00045             if (Windows.ApplicationModel.DesignMode.DesignModeEnabled) return;
00046
00047             // Create an empty default view model
00048             this.DefaultViewModel = new ObservableDictionary<String, Object>();
00049
00050             // Map application view state to visual state for this page when it is part of the visual tree
00051             this.Loaded += this.StartLayoutUpdates;
00052             this.Unloaded += this.StopLayoutUpdates;
00053         }
00054
00055         /// <summary>
00056         /// An implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00057         /// used as a trivial view model.
00058         /// </summary>
00059         protected IObservableMap<String, Object> DefaultViewModel
00060         {
00061             get
00062             {
00063                 return this.GetValue(DefaultViewModelProperty) as IObservableMap<String, Object>;
00064             }
00065
00066             set
00067             {
00068                 this.SetValue(DefaultViewModelProperty, value);
00069             }
00070         }
00071
00072         /// <summary>
00073         /// Invoked as an event handler to navigate backward in the page's associated
00074         /// <see cref="Frame"/> until it reaches the top of the navigation stack.
00075         /// </summary>
00076         /// <param name="sender">Instance that triggered the event.</param>
00077         /// <param name="e">Event data describing the conditions that led to the event.</param>
00078         protected virtual void GoHome(object sender, RoutedEventArgs e)
00079         {
00080             // Use the navigation frame to return to the topmost page
00081             if (this.Frame != null)
00082             {
00083                 while (this.Frame.CanGoBack) this.Frame.GoBack();
00084             }
00085         }
00086
00087         /// <summary>
00088         /// Invoked as an event handler to navigate backward in the page's associated
00089         /// <see cref="Frame"/> to go back one step on the navigation stack.
00090         /// </summary>
00091         /// <param name="sender">Instance that triggered the event.</param>
00092         /// <param name="e">Event data describing the conditions that led to the
00093         /// event.</param>
00094         protected virtual void GoBack(object sender, RoutedEventArgs e)
00095         {
00096             // Use the navigation frame to return to the previous page
00097             if (this.Frame != null && this.Frame.CanGoBack) this.Frame.GoBack();
00098         }
00099
00100         /// <summary>
00101         /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00102         /// <see cref="Control"/> within the page, to indicate that the sender should start
00103         /// receiving visual state management changes that correspond to application view state
00104         /// changes.
00105         /// </summary>
00106         /// <param name="sender">Instance of <see cref="Control"/> that supports visual state
00107         /// management corresponding to view states.</param>
00108         /// <param name="e">Event data that describes how the request was made.</param>
00109         /// <remarks>The current view state will immediately be used to set the corresponding
00110         /// visual state when layout updates are requested.  A corresponding
00111         /// <see cref="Unloaded"/> event handler connected to <see cref="StopLayoutUpdates"/>
00112         /// is strongly encouraged.  Instances of <see cref="LayoutAwarePage"/> automatically
00113         /// invoke these handlers in their Loaded and Unloaded events.</remarks>
00114         /// <seealso cref="DetermineVisualState"/>
00115         /// <seealso cref="InvalidateVisualState"/>
00116         public void StartLayoutUpdates(object sender, RoutedEventArgs e)
00117         {
00118             var control = sender as Control;
00119             if (control == null) return;
00120             if (this._layoutAwareControls == null)
00121             {
00122                 // Start listening to view state changes when there are controls interested in updates
00123                 Window.Current.SizeChanged += this.WindowSizeChanged;
00124                 this._layoutAwareControls = new List<Control>();
00125             }
00126             this._layoutAwareControls.Add(control);
00127
00128             // Set the initial visual state of the control
00129             VisualStateManager.GoToState(control, DetermineVisualState(ApplicationView.Value), false);
00130         }
00131
00132         private void WindowSizeChanged(object sender, Windows.UI.Core.WindowSizeChangedEventArgs e)
00133         {
00134             this.InvalidateVisualState();
00135         }
00136
00137         /// <summary>
00138         /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00139         /// <see cref="Control"/>, to indicate that the sender should start receiving visual
00140         /// state management changes that correspond to application view state changes.
00141         /// </summary>
00142         /// <param name="sender">Instance of <see cref="Control"/> that supports visual state
00143         /// management corresponding to view states.</param>
00144         /// <param name="e">Event data that describes how the request was made.</param>
00145         /// <remarks>The current view state will immediately be used to set the corresponding
00146         /// visual state when layout updates are requested.</remarks>
00147         /// <seealso cref="StartLayoutUpdates"/>
00148         public void StopLayoutUpdates(object sender, RoutedEventArgs e)
00149         {
00150             var control = sender as Control;
00151             if (control == null || this._layoutAwareControls == null) return;
00152             this._layoutAwareControls.Remove(control);
00153             if (this._layoutAwareControls.Count == 0)
00154             {
00155                 // Stop listening to view state changes when no controls are interested in updates
00156                 this._layoutAwareControls = null;
00157                 Window.Current.SizeChanged -= this.WindowSizeChanged;
00158             }
00159         }
00160
00161         /// <summary>
00162         /// Translates <see cref="ApplicationViewState"/> values into strings for visual state
00163         /// management within the page.  The default implementation uses the names of enum values.
00164         /// Subclasses may override this method to control the mapping scheme used.
00165         /// </summary>
00166         /// <param name="viewState">View state for which a visual state is desired.</param>
00167         /// <returns>Visual state name used to drive the
00168         /// <see cref="VisualStateManager"/></returns>
00169         /// <seealso cref="InvalidateVisualState"/>
00170         protected virtual string DetermineVisualState(ApplicationViewState viewState)
00171         {
00172             return viewState.ToString();
00173         }
00174
00175         /// <summary>
00176         /// Updates all controls that are listening for visual state changes with the correct
00177         /// visual state.
00178         /// </summary>
00179         /// <remarks>
00180         /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00181         /// signal that a different value may be returned even though the view state has not
00182         /// changed.
00183         /// </remarks>
00184         public void InvalidateVisualState()
00185         {
00186             if (this._layoutAwareControls != null)
00187             {
00188                 string visualState = DetermineVisualState(ApplicationView.Value);
00189                 foreach (var layoutAwareControl in this._layoutAwareControls)
00190                 {
00191                     VisualStateManager.GoToState(layoutAwareControl, visualState, false);
00192                 }
00193             }
00194         }
00195
00196         /// <summary>
00197         /// Implementation of IObservableMap that supports reentrancy for use as a default view
00198         /// model.
00199         /// </summary>
00200         private class ObservableDictionary<K, V> : IObservableMap<K, V>
00201         {
00202             private class ObservableDictionaryChangedEventArgs : IMapChangedEventArgs<K>
00203             {
00204                 public ObservableDictionaryChangedEventArgs(CollectionChange change, K key)
00205                 {
00206                     this.CollectionChange = change;
00207                     this.Key = key;
00208                 }
00209
00210                 public CollectionChange CollectionChange { get; private set; }
00211                 public K Key { get; private set; }
00212             }
00213
00214             private Dictionary<K, V> _dictionary = new Dictionary<K, V>();
00215             public event MapChangedEventHandler<K, V> MapChanged;
00216
00217             private void InvokeMapChanged(CollectionChange change, K key)
00218             {
00219                 var eventHandler = MapChanged;
00220                 if (eventHandler != null)
00221                 {
00222                     eventHandler(this, new ObservableDictionaryChangedEventArgs(CollectionChange.ItemInserted, key));
00223                 }
00224             }
00225
00226             public void Add(K key, V value)
00227             {
00228                 this._dictionary.Add(key, value);
00229                 this.InvokeMapChanged(CollectionChange.ItemInserted, key);
00230             }
00231
00232             public void Add(KeyValuePair<K, V> item)
00233             {
00234                 this.Add(item.Key, item.Value);
00235             }
00236
00237             public bool Remove(K key)
00238             {
00239                 if (this._dictionary.Remove(key))
00240                 {
00241                     this.InvokeMapChanged(CollectionChange.ItemRemoved, key);
00242                     return true;
00243                 }
00244                 return false;
00245             }
00246
00247             public bool Remove(KeyValuePair<K, V> item)
00248             {
00249                 V currentValue;
00250                 if (this._dictionary.TryGetValue(item.Key, out currentValue) &&
00251                     Object.Equals(item.Value, currentValue) && this._dictionary.Remove(item.Key))
00252                 {
00253                     this.InvokeMapChanged(CollectionChange.ItemRemoved, item.Key);
00254                     return true;
00255                 }
00256                 return false;
00257             }
00258
00259             public V this[K key]
00260             {
00261                 get
00262                 {
00263                     return this._dictionary[key];
00264                 }
00265                 set
00266                 {
00267                     this._dictionary[key] = value;
00268                     this.InvokeMapChanged(CollectionChange.ItemChanged, key);
00269                 }
00270             }
00271
00272             public void Clear()
00273             {
00274                 var priorKeys = this._dictionary.Keys.ToArray();
00275                 this._dictionary.Clear();
00276                 foreach (var key in priorKeys)
00277                 {
00278                     this.InvokeMapChanged(CollectionChange.ItemRemoved, key);
00279                 }
00280             }
00281
00282             public ICollection<K> Keys
00283             {
00284                 get { return this._dictionary.Keys; }
00285             }
00286
00287             public bool ContainsKey(K key)
00288             {
00289                 return this._dictionary.ContainsKey(key);
00290             }
00291
00292             public bool TryGetValue(K key, out V value)
00293             {
00294                 return this._dictionary.TryGetValue(key, out value);
00295             }
00296
00297             public ICollection<V> Values
00298             {
00299                 get { return this._dictionary.Values; }
00300             }
00301
00302             public bool Contains(KeyValuePair<K, V> item)
00303             {
00304                 return this._dictionary.Contains(item);
00305             }
00306
00307             public int Count
00308             {
00309                 get { return this._dictionary.Count; }
00310             }
00311
00312             public bool IsReadOnly
00313             {
00314                 get { return false; }
00315             }
00316
00317             public IEnumerator<KeyValuePair<K, V>> GetEnumerator()
00318             {
00319                 return this._dictionary.GetEnumerator();
00320             }
00321
00322             System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
00323             {
00324                 return this._dictionary.GetEnumerator();
00325             }
00326
00327             public void CopyTo(KeyValuePair<K, V>[] array, int arrayIndex)
00328             {
00329                 int arraySize = array.Length;
00330                 foreach (var pair in this._dictionary)
00331                 {
00332                     if (arrayIndex >= arraySize) break;
00333                     array[arrayIndex++] = pair;
00334                 }
00335             }
00336         }
00337     }
00338 }
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/Level.h Source File

  • DirectX 3D shooting game

Level.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 // Level:
00011 // This is an abstract class from which all of the levels of the game are derived.
00012 // Each level potentially overrides up to four methods:
00013 //     Initialize - (required) takes a list of objects and enables the objects that
00014 //         are active for the level as well as setting their positions and
00015 //         any animations associated with the objects.
00016 //     Update - this method is called once per time step and is expected to
00017 //         determine if the level has been completed.  The Level class provides
00018 //         a 'standard' Update method which checks each object that is a target
00019 //         and disables any active targets that have been hit.  It returns true
00020 //         once there are no active targets remaining.
00021 //     SaveState - method to save any Level specific state.  Default is defined as
00022 //         not saving any state.
00023 //     LoadState - method to restore any Level specific state.  Default is defined
00024 //         as not restoring any state.
00025
00026 #include "GameObject.h"
00027 #include "PersistentState.h"
00028
00029 ref class Level abstract
00030 {
00031 internal:
00032     virtual void Initialize(
00033         std::vector<GameObject^> objects
00034         ) = 0;
00035
00036     virtual bool Update(
00037         float time,
00038         float elapsedTime,
00039         float timeRemaining,
00040         std::vector<GameObject^> objects
00041         );
00042
00043     virtual void SaveState(PersistentState^ state);
00044     virtual void LoadState(PersistentState^ state);
00045
00046     Platform::String^ Objective();
00047     float TimeLimit();
00048
00049 protected private:
00050     Platform::String^ m_objective;
00051     float             m_timeLimit;
00052 };
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

CommandListRenderer Member List

This is the complete list of members for CommandListRenderer, including all inherited members.
__pad0__ | CommandListRenderer |
Clamp(float value, float low, float high) | CommandListRenderer | [inline, private, static]
CreateDeviceResources() override | CommandListRenderer | [virtual]
DrawPattern() | CommandListRenderer | [private]
HandlePointerDoubleTapped(Windows::Foundation::Point position) | CommandListRenderer | [private]
Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | CommandListRenderer | [virtual]
LinearInterpolate(float start, float end, float weight) | CommandListRenderer | [inline, private, static]
Load(_In_ Platform::String^entryPoint) | CommandListRenderer | [virtual]
m_blueBrush | CommandListRenderer | [private]
m_commandList | CommandListRenderer | [private]
m_gestureRecognizer | CommandListRenderer | [private]
m_imageBrush | CommandListRenderer | [private]
m_recenter | CommandListRenderer | [private]
m_recenterStartPosition | CommandListRenderer | [private]
m_recenterStartTime | CommandListRenderer | [private]
m_recenterStartZoom | CommandListRenderer | [private]
m_sampleOverlay | CommandListRenderer | [private]
m_viewPosition | CommandListRenderer | [private]
m_windowClosed | CommandListRenderer | [private]
m_windowVisible | CommandListRenderer | [private]
m_zoom | CommandListRenderer | [private]
OnActivated(_In_ Windows::ApplicationModel::Core::CoreApplicationView^applicationView, _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | CommandListRenderer | [private]
OnLogicalDpiChanged(_In_ Platform::Object^sender) | CommandListRenderer | [private]
OnManipulationUpdated(_In_ Windows::UI::Input::GestureRecognizer^recognizer, _In_ Windows::UI::Input::ManipulationUpdatedEventArgs^args) | CommandListRenderer | [private]
OnPointerMoved(_In_ Windows::UI::Core::CoreWindow^window, _In_ Windows::UI::Core::PointerEventArgs^args) | CommandListRenderer | [private]
OnPointerPressed(_In_ Windows::UI::Core::CoreWindow^window, _In_ Windows::UI::Core::PointerEventArgs^args) | CommandListRenderer | [private]
OnPointerReleased(_In_ Windows::UI::Core::CoreWindow^window, _In_ Windows::UI::Core::PointerEventArgs^args) | CommandListRenderer | [private]
OnPointerWheelChanged(_In_ Windows::UI::Core::CoreWindow^window, _In_ Windows::UI::Core::PointerEventArgs^args) | CommandListRenderer | [private]
OnResuming(_In_ Platform::Object^sender, _In_ Platform::Object^args) | CommandListRenderer | [private]
OnSuspending(_In_ Platform::Object^sender, _In_ Windows::ApplicationModel::SuspendingEventArgs^args) | CommandListRenderer | [private]
OnTapped(_In_ Windows::UI::Input::GestureRecognizer^recognizer, _In_ Windows::UI::Input::TappedEventArgs^args) | CommandListRenderer | [private]
OnVisibilityChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::VisibilityChangedEventArgs^args) | CommandListRenderer | [private]
OnWindowClosed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::CoreWindowEventArgs^args) | CommandListRenderer | [private]
OnWindowSizeChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::WindowSizeChangedEventArgs^args) | CommandListRenderer | [private]
Render() override | CommandListRenderer | [virtual]
Run() | CommandListRenderer | [virtual]
SetWindow(_In_ Windows::UI::Core::CoreWindow^window) | CommandListRenderer | [virtual]
Uninitialize() | CommandListRenderer | [virtual]
Update(float timeTotal) | CommandListRenderer | [private]
Generated on Sat Nov 23 2024 16:09:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Compass sensor/C++/common/LayoutAwarePage.cpp Source File

  • Compass sensor
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:30 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Compass sensor/C++/Scenario2.xaml.cpp Source File

  • Compass sensor

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 SDKSample::CompassCPP;
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::Devices::Sensors;
00025 using namespace Windows::Foundation;
00026 using namespace Windows::UI::Core;
00027 using namespace Platform;
00028
00029 Scenario2::Scenario2() : rootPage(MainPage::Current), desiredReportInterval(0)
00030 {
00031     InitializeComponent();
00032
00033     compass = Compass::GetDefault();
00034     if (compass != nullptr)
00035     {
00036         // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
00037         // This value will be used later to activate the sensor.
00038         uint32 minReportInterval = compass->MinimumReportInterval;
00039         desiredReportInterval = minReportInterval > 16 ? minReportInterval : 16;
00040
00041         // Set up a DispatchTimer
00042         TimeSpan span;
00043         span.Duration = static_cast<int32>(desiredReportInterval) * 10000;   // convert to 100ns ticks
00044         dispatcherTimer = ref new DispatcherTimer();
00045         dispatcherTimer->Interval = span;
00046         dispatcherTimer->Tick += ref new Windows::Foundation::EventHandler<Object^>(this, &Scenario2::DisplayCurrentReading);
00047     }
00048     else
00049     {
00050         rootPage->NotifyUser("No compass found", NotifyType::ErrorMessage);
00051     }
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 void Scenario2::OnNavigatedTo(NavigationEventArgs^ e)
00060 {
00061     ScenarioEnableButton->IsEnabled = true;
00062     ScenarioDisableButton->IsEnabled = false;
00063 }
00064
00065 /// <summary>
00066 /// Invoked when this page is no longer displayed.
00067 /// </summary>
00068 /// <param name="e"></param>
00069 void Scenario2::OnNavigatedFrom(NavigationEventArgs^ e)
00070 {
00071     if (ScenarioDisableButton->IsEnabled)
00072     {
00073         Window::Current->VisibilityChanged::remove(visibilityToken);
00074         dispatcherTimer->Stop();
00075
00076         // Restore the default report interval to release resources while the sensor is not in use
00077         compass->ReportInterval = 0;
00078     }
00079 }
00080
00081 /// <summary>
00082 /// This is the event handler for VisibilityChanged events. You would register for these notifications
00083 /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00084 /// </summary>
00085 /// <param name="sender"></param>
00086 /// <param name="e">
00087 /// Event data that can be examined for the current visibility state.
00088 /// </param>
00089 void Scenario2::VisibilityChanged(Object^ sender, VisibilityChangedEventArgs^ e)
00090 {
00091     // The app should watch for VisibilityChanged events to disable and re-enable sensor input as appropriate
00092     if (ScenarioDisableButton->IsEnabled)
00093     {
00094         if (e->Visible)
00095         {
00096             // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00097             dispatcherTimer->Start();
00098         }
00099         else
00100         {
00101             // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00102             dispatcherTimer->Stop();
00103         }
00104     }
00105 }
00106
00107 void Scenario2::DisplayCurrentReading(Object^ sender, Object^ e)
00108 {
00109     CompassReading^ reading = compass->GetCurrentReading();
00110     if (reading != nullptr)
00111     {
00112         ScenarioOutput_MagneticNorth->Text = reading->HeadingMagneticNorth.ToString();
00113         if (reading->HeadingTrueNorth != nullptr)
00114         {
00115             ScenarioOutput_TrueNorth->Text = reading->HeadingTrueNorth->Value.ToString();
00116         }
00117         else
00118         {
00119             ScenarioOutput_TrueNorth->Text = "No data";
00120         }
00121     }
00122 }
00123
00124 void Scenario2::ScenarioEnable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00125 {
00126     if (compass != nullptr)
00127     {
00128         visibilityToken = Window::Current->VisibilityChanged::add(ref new WindowVisibilityChangedEventHandler(this, &Scenario2::VisibilityChanged));
00129
00130         // Set the report interval to enable the sensor for polling
00131         compass->ReportInterval = desiredReportInterval;
00132
00133         dispatcherTimer->Start();
00134
00135         ScenarioEnableButton->IsEnabled = false;
00136         ScenarioDisableButton->IsEnabled = true;
00137     }
00138     else
00139     {
00140         rootPage->NotifyUser("No compass found", NotifyType::ErrorMessage);
00141     }
00142 }
00143
00144 void Scenario2::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     compass->ReportInterval = 0;
00152
00153     ScenarioEnableButton->IsEnabled = true;
00154     ScenarioDisableButton->IsEnabled = false;
00155 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::TileContent::TileSquareText02 Member List

This is the complete list of members for NotificationsExtensions::TileContent::TileSquareText02, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
Branding | NotificationsExtensions::TileContent::TileNotificationBase |
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
NotificationsExtensions::GetContent() | NotificationsExtensions::TileContent::TileSquareBase | [inline]
NotificationsExtensions::GetContent() | NotificationsExtensions::TileContent::TileSquareBase | [inline]
NotificationsExtensions::TileContent::TileNotificationBase::GetContent() | NotificationsExtensions::NotificationBase | [pure virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeBinding(string globalLang, string globalBaseUri, TileBranding globalBranding, bool globalAddImageQuery) | NotificationsExtensions::TileContent::TileSquareBase | [inline]
SerializeBinding(string globalLang, string globalBaseUri, TileBranding globalBranding, bool globalAddImageQuery) | NotificationsExtensions::TileContent::TileSquareBase | [inline]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextBodyWrap | NotificationsExtensions::TileContent::TileSquareText02 |
TextFields | NotificationsExtensions::NotificationBase |
TextHeading | NotificationsExtensions::TileContent::TileSquareText02 |
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileSquareBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileSquareBase | [inline]
TileSquareBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileSquareBase | [inline]
TileSquareText02() | NotificationsExtensions::TileContent::TileSquareText02 | [inline]
TileSquareText02() | NotificationsExtensions::TileContent::TileSquareText02 | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:43 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Device app for printers SDK/C++/BackgroundTask/pch.cpp Source File

  • Device app for printers SDK
  • BackgroundTask

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 Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D-Direct2D interop/C++/DirectXSample.h Source File

  • Direct3D-Direct2D interop

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
00010 // This header defines helper utilities to make DirectX APIs work with exceptions.
00011 namespace DX
00012 {
00013     inline void ThrowIfFailed(HRESULT hr)
00014     {
00015         if (FAILED(hr))
00016         {
00017             // Set a breakpoint on this line to catch DX API errors.
00018             throw Platform::Exception::CreateException(hr);
00019         }
00020     }
00021 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Audio Session (WASAPI)/C++/MFSampleGenerator.h Source File

  • Windows Audio Session (WASAPI)
  • C++

MFSampleGenerator.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 // MFSampleGenerator.h
00013 //
00014
00015 #include <windows.h>
00016 #include <mfapi.h>
00017 #include <mfidl.h>
00018 #include <mfreadwrite.h>
00019 #include <mferror.h>
00020 #include "MainPage.xaml.h"
00021
00022 using namespace Windows::Storage::Streams;
00023
00024 #define PREROLL_DURATION_SEC 3     // Arbitrary value for seconds of data in preroll buffer
00025
00026
00027 #pragma once
00028
00029 namespace SDKSample
00030 {
00031     namespace WASAPIAudio
00032     {
00033         class MFSampleGenerator :
00034             public IMFSourceReaderCallback
00035         {
00036         public:
00037             enum ReaderState
00038             {
00039                 ReaderStateStopped,
00040                 ReaderStatePreRoll,
00041                 ReaderStatePlaying,
00042                 ReaderStateEOS
00043             };
00044
00045             MFSampleGenerator();
00046
00047             // IUnknown
00048             STDMETHODIMP_ (ULONG) AddRef()
00049             {
00050                 return InterlockedIncrement(&m_Ref);
00051             }
00052
00053             STDMETHODIMP_ (ULONG) Release()
00054             {
00055                 LONG ref = InterlockedDecrement(&m_Ref);
00056
00057                 if (ref == 0)
00058                 {
00059                     delete this;
00060                 }
00061
00062                 return ref;
00063             }
00064
00065             STDMETHODIMP_ (HRESULT) QueryInterface(const IID &riid, void ** ppv)
00066             {
00067                 HRESULT hr = E_NOINTERFACE;
00068                 *ppv = NULL;
00069
00070                 if (riid == IID_IMFSourceReaderCallback)
00071                 {
00072                     *ppv = static_cast<IMFSourceReaderCallback *>(this);
00073                     ((IUnknown*) *ppv)->AddRef();
00074                     hr = S_OK;
00075                 }
00076
00077                 return hr;
00078             }
00079
00080             // IMFSourceReaderCallback
00081             STDMETHODIMP_ (HRESULT) OnEvent(_In_ DWORD dwStreamIndex, _In_ IMFMediaEvent *pEvent);
00082             STDMETHODIMP_ (HRESULT) OnFlush(_In_ DWORD dwStreamIndex);
00083             STDMETHODIMP_ (HRESULT) OnReadSample(_In_ HRESULT hrStatus, _In_ DWORD dwStreamIndex, _In_ DWORD dwStreamFlags, _In_ LONGLONG llTimestamp, _In_opt_ IMFSample *pSample);
00084
00085             // MFSampleGenerator
00086             HRESULT StartSource();
00087             void StopSource();
00088
00089             HRESULT Initialize( IRandomAccessStream^ stream, UINT32 FramesPerPeriod, WAVEFORMATEX *wfx );
00090             void Shutdown();
00091             HRESULT FillSampleBuffer( UINT32 BytesToRead, BYTE *Data, UINT32 *cbWritten );
00092             void Flush();
00093
00094             Platform::Boolean IsEOF()
00095             {
00096                 if ( ( m_SampleQueue == nullptr ) &&
00097                      ( m_ReaderState == ReaderStateEOS ) )
00098                     return true;
00099
00100                 return false;
00101             }
00102
00103         private:
00104             ~MFSampleGenerator();
00105
00106             HRESULT ConfigureStreams();
00107             HRESULT CreateAudioType( IMFMediaType **MediaType );
00108             HRESULT AddSamplesToQueue( IMFSample *MFSample );
00109             Platform::Boolean IsPreRollFilled();
00110
00111         private:
00112             volatile ULONG          m_Ref;
00113             IRandomAccessStream^    m_ContentStream;
00114             WAVEFORMATEX           *m_MixFormat;
00115             UINT32                  m_BytesPerPeriod;
00116             Platform::Boolean       m_IsInitialized;
00117
00118             IMFSourceReader        *m_MFSourceReader;
00119             IMFMediaType           *m_AudioMT;
00120             ReaderState             m_ReaderState;
00121
00122             RenderBuffer           *m_SampleQueue;
00123             RenderBuffer          **m_SampleQueueTail;
00124         };
00125     }
00126 }
00127
Generated on Sat Nov 23 2024 16:08:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: HttpClient/C++/App.xaml.cpp Source File

  • HttpClient

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D stereoscopic 3D/C++/BasicLoader.h Source File

  • Direct3D stereoscopic 3D

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 Sat Nov 23 2024 16:08:08 for Win8-Examples by doxygen 1.7.1


Win8-Examples: AtomPub/C++/MainPage.xaml.cpp Source File

  • AtomPub

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CryptoWinRT/C++/Scenario8.xaml.cpp Source File

  • CryptoWinRT

Scenario8.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 // Scenario8.xaml.cpp
00013 // Implementation of the Scenario8 class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario8.xaml.h"
00018
00019 using namespace SDKSample::CryptoWinRT;
00020
00021 using namespace Platform;
00022 using namespace Windows::Security::Cryptography;
00023 using namespace Windows::Security::Cryptography::Core;
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 Scenario8::Scenario8()
00030 {
00031     InitializeComponent();
00032     AlgorithmNames->SelectedIndex = 0;
00033     KeySizes->SelectedIndex = 0;
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 Scenario8::OnNavigatedTo(NavigationEventArgs^ e)
00042 {
00043     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00044     // as NotifyUser()
00045     rootPage = MainPage::Current;
00046 }
00047
00048 void SDKSample::CryptoWinRT::Scenario8::RunSample_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00049 {
00050     Scenario8Text->Text = "";
00051     String^ algName = AlgorithmNames->SelectionBoxItem->ToString();
00052     unsigned int KeySize;
00053     IBuffer^ blobOfPublicKey;
00054     IBuffer^ blobOfKeyPair;
00055     String^  cookie = "Some Data to sign";
00056     IBuffer^ Data = CryptographicBuffer::ConvertStringToBinary(cookie, BinaryStringEncoding::Utf16BE);
00057
00058     switch (KeySizes->SelectedIndex)
00059     {
00060     case 0:
00061         KeySize = 256;
00062         break;
00063     case 1:
00064         KeySize = 384;
00065         break;
00066     case 2:
00067         KeySize = 521;
00068         break;
00069     case 3:
00070         KeySize = 1024;
00071         break;
00072     case 4:
00073         KeySize = 2048;
00074         break;
00075     case 5:
00076         KeySize = 3072;
00077         break;
00078     case 6:
00079         KeySize = 4096;
00080         break;
00081     default:
00082         Scenario8Text->Text += "An invalid size was selected";
00083         return;
00084     }
00085
00086     // Create an AsymmetricKeyAlgorithmProvider object for the algorithm specified on input.
00087     AsymmetricKeyAlgorithmProvider^ Algorithm = AsymmetricKeyAlgorithmProvider::OpenAlgorithm(algName);
00088
00089     Scenario8Text->Text += "\n*** Sample Signature Algorithm\n";
00090     Scenario8Text->Text += "    Algorithm Name: " + Algorithm->AlgorithmName + "\n";
00091     Scenario8Text->Text += "    Key Size: " + KeySize + "\n";
00092
00093     CryptographicKey^ keyPair;
00094     IBuffer^ Signature;
00095
00096     try
00097     {
00098         // Generate a key pair.
00099         keyPair = Algorithm->CreateKeyPair(KeySize);
00100
00101         // Sign the data by using the generated key.
00102         Signature = CryptographicEngine::Sign(keyPair, Data);
00103     }
00104     catch (InvalidArgumentException^ e)
00105     {
00106         Scenario8Text->Text += "Exception: " + e->Message + "\n";
00107         Scenario8Text->Text += "An invalid Algorithm / Key Size pair was selected.\n";
00108         return;
00109     }
00110
00111     // Export the public key.
00112     blobOfPublicKey = keyPair->ExportPublicKey();
00113     blobOfKeyPair = keyPair->Export();
00114
00115     // Import the public key.
00116     CryptographicKey^ keyPublic = Algorithm->ImportPublicKey(blobOfPublicKey);
00117
00118     // Check the key size.
00119     if (keyPublic->KeySize != keyPair->KeySize)
00120     {
00121         Scenario8Text->Text += "ImportPublicKey failed!  The imported key's size did not match the original's!\n";
00122         return;
00123     }
00124     Scenario8Text->Text += "    The public key was successfully imported.\n";
00125
00126     // Import the key pair.
00127     keyPair = Algorithm->ImportKeyPair(blobOfKeyPair);
00128
00129     // Check the key size.
00130     if (keyPublic->KeySize != keyPair->KeySize)
00131     {
00132         Scenario8Text->Text += "ImportKeyPair failed!  The imported key's size did not match the original's!\n";
00133         return;
00134     }
00135     Scenario8Text->Text += "    The key pair was successfully imported.\n";
00136
00137     // Verify the signature by using the public key.
00138     if (!CryptographicEngine::VerifySignature(keyPublic, Data, Signature))
00139     {
00140         Scenario8Text->Text += "Signature verification failed!";
00141         return;
00142     }
00143 }
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Scheduled notifications/C#,C++/ScenarioInput2.xaml.cpp Source File

  • Scheduled notifications
  • C#,C++

ScenarioInput2.xaml.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 //
00009 // Scenario2Input.xaml.cpp
00010 // Implementation of the Scenario2Input class.
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioInput2.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace ScheduledNotificationsSampleCPP;
00018
00019 using namespace Platform;
00020 using namespace Windows::UI::Notifications;
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::Navigation;
00025
00026 ScenarioInput2::ScenarioInput2()
00027 {
00028     InitializeComponent();
00029     scheduledNotificationsBinding = ref new NotificationDataSource();
00030     ItemGridView->ItemsSource = scheduledNotificationsBinding->Items;
00031
00032     RefreshListButton->Click += ref new RoutedEventHandler(this, &ScenarioInput2::RefreshList_Click);
00033     RemoveButton->Click += ref new RoutedEventHandler(this, &ScenarioInput2::Remove_Click);
00034 }
00035
00036 ScenarioInput2::~ScenarioInput2()
00037 {
00038 }
00039
00040 void ScenarioInput2::RefreshList_Click(Object^ sender, RoutedEventArgs^ e)
00041 {
00042     RefreshListView();
00043 }
00044
00045 void ScenarioInput2::Remove_Click(Object^ sender, RoutedEventArgs^ e)
00046 {
00047     auto items = ItemGridView->SelectedItems;
00048     int a = items->Size;
00049     for (unsigned int i = 0; i < items->Size; i++)
00050     {
00051         auto item = dynamic_cast<NotificationData^>(items->GetAt(i));
00052         String^ itemId = item->ItemId;
00053         if (item->get_IsTile())
00054         {
00055             auto updater = TileUpdateManager::CreateTileUpdaterForApplication();
00056             auto scheduled = updater->GetScheduledTileNotifications();
00057             for (unsigned int j = 0; j < scheduled->Size; j++)
00058             {
00059                 if (scheduled->GetAt(j)->Id == itemId)
00060                 {
00061                     updater->RemoveFromSchedule(scheduled->GetAt(j));
00062                 }
00063             }
00064         }
00065         else
00066         {
00067             auto notifier = ToastNotificationManager::CreateToastNotifier();
00068             auto scheduled = notifier->GetScheduledToastNotifications();
00069             for (unsigned int j = 0; j < scheduled->Size; j++)
00070             {
00071                 if (scheduled->GetAt(j)->Id == itemId)
00072                 {
00073                     try
00074                     {
00075                         notifier->RemoveFromSchedule(scheduled->GetAt(j));
00076                     }
00077                     catch (...)
00078                     {
00079                     }
00080                 }
00081             }
00082         }
00083     }
00084
00085     rootPage->NotifyUser("Removed selected scheduled notifications", NotifyType::StatusMessage);
00086     RefreshListView();
00087 }
00088
00089 void ScenarioInput2::RefreshListView()
00090 {
00091     scheduledNotificationsBinding->Refresh();
00092 }
00093
00094
00095 #pragma region Template-Related Code - Do not remove
00096 void ScenarioInput2::OnNavigatedTo(NavigationEventArgs^ e)
00097 {
00098     // Get a pointer to our main page.
00099     rootPage = dynamic_cast<MainPage^>(e->Parameter);
00100     RefreshListView();
00101 }
00102 #pragma endregion
00103
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Portable device API/C++/App.xaml.h Source File

  • Portable device API

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/MeshObject.h Source File

  • DirectX 3D shooting game

MeshObject.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 // MeshObject:
00011 // This class is the generic (abstract) representation of D3D11 Indexed triangle
00012 // list.  Each of the derived classes is just the constructor for the specific
00013 // geometry primitive.  This abstract class does not place any requirements on
00014 // the format of the geometry directly.
00015 // The primary method of the MeshObject is Render.  The default implementation
00016 // just sets the IndexBuffer, VertexBuffer and topology to a TriangleList and
00017 // makes a  DrawIndexed call on the context.  It assumes all other state has
00018 // already been set on the context.
00019
00020 ref class MeshObject abstract
00021 {
00022 internal:
00023     MeshObject();
00024
00025     virtual void Render(_In_ ID3D11DeviceContext *context);
00026
00027 protected private:
00028     Microsoft::WRL::ComPtr<ID3D11Buffer>  m_vertexBuffer;
00029     Microsoft::WRL::ComPtr<ID3D11Buffer>  m_indexBuffer;
00030     int                                   m_vertexCount;
00031     int                                   m_indexCount;
00032 };
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application resources and localization/C++/Scenario6.xaml.h Source File

  • Application resources and localization

Scenario6.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 // Scenario6.xaml.h
00013 // Declaration of the Scenario6 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario6.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace ApplicationResources
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 Scenario6 sealed
00031         {
00032         public:
00033             Scenario6();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void Scenario6Button_Show_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/PhotoPathComparer.h Source File

  • Hilo C++
  • Hilo

PhotoPathComparer.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
00009 namespace Hilo
00010 {
00011     interface class IPhoto;
00012
00013     // The PhotoPathComparer struct provides a comparison operator for Hilo images.
00014     struct PhotoPathComparer : public std::equal_to<IPhoto^>
00015     {
00016         bool operator()(IPhoto^ left, IPhoto^ right) const;
00017     };
00018 }
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX touch input/C++/DirectXBase.h Source File

  • DirectX touch input

DirectXBase.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 "DirectXSample.h"
00011
00012 // Helper class that initializes DirectX APIs for both 2D and 3D rendering.
00013 // Some of the code in this class may be omitted if only 2D or only 3D rendering is being used.
00014 ref class DirectXBase abstract
00015 {
00016 internal:
00017     DirectXBase();
00018
00019     virtual void Initialize(Windows::UI::Core::CoreWindow^ window, float dpi);
00020     virtual void HandleDeviceLost();
00021     virtual void CreateDeviceIndependentResources();
00022     virtual void CreateDeviceResources();
00023     virtual void SetDpi(float dpi);
00024     virtual void UpdateForWindowSizeChange();
00025     virtual void CreateWindowSizeDependentResources();
00026     virtual void Render() = 0;
00027     virtual void Present();
00028     void ValidateDevice();
00029
00030 protected private:
00031     Platform::Agile<Windows::UI::Core::CoreWindow>  m_window;
00032
00033     // DirectWrite & Windows Imaging Component Objects.
00034     Microsoft::WRL::ComPtr<IDWriteFactory1>         m_dwriteFactory;
00035     Microsoft::WRL::ComPtr<IWICImagingFactory2>     m_wicFactory;
00036
00037     // DirectX Core Objects. Required for 2D and 3D.
00038     Microsoft::WRL::ComPtr<ID3D11Device1>           m_d3dDevice;
00039     Microsoft::WRL::ComPtr<ID3D11DeviceContext1>    m_d3dContext;
00040     Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00041     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00042
00043     // Direct2D Rendering Objects. Required for 2D.
00044     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00046     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00047     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmap;
00048
00049     // Direct3D Rendering Objects. Required for 3D.
00050     Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00051
00052     // Cached renderer properties.
00053     D3D_FEATURE_LEVEL                               m_featureLevel;
00054     Windows::Foundation::Size                       m_renderTargetSize;
00055     Windows::Foundation::Rect                       m_windowBounds;
00056     float                                           m_dpi;
00057     bool                                            m_windowSizeChangeInProgress;
00058 };
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

MediaExtensionsCS::ScenarioInput4 Member List

This is the complete list of members for MediaExtensionsCS::ScenarioInput4, including all inherited members.
__pad0__ | Element |
AcceptChildNode(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^childXmlNode) override | Page | [virtual]
AddChild(_In_ Element^element) | Element |
AddSibling(_In_ Element^element) | Element |
BindResource(_In_ Element^rootElement) | Element | [virtual]
Create(_In_ Document^document, _In_ Windows::Data::Xml::Dom::IXmlNode^xmlNode) | Element | [static]
Draw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
GetFirstChild() | Element | [inline]
GetName() | Element | [inline]
GetNextSibling() | Element | [inline]
GetOpacity() | Element | [inline, virtual]
GetParent() | Element | [inline]
GetSize() | Element | [inline]
Initialize(_In_ Document^document, _In_ Windows::Data::Xml::Dom::XmlElement^xmlElement) | Element | [virtual]
Measure(_In_ Document^document, D2D1_SIZE_F const &parentSize, _Out_ D2D1_RECT_F *bounds) | Element | [virtual]
OnNavigatedFrom(NavigationEventArgs e) | MediaExtensionsCS::ScenarioInput4 | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | MediaExtensionsCS::ScenarioInput4 | [inline, protected]
OpenFisheye_Click(object sender, RoutedEventArgs e) | MediaExtensionsCS::ScenarioInput4 | [inline, private]
OpenGrayscale_Click(object sender, RoutedEventArgs e) | MediaExtensionsCS::ScenarioInput4 | [inline, private]
OpenInvert_Click(object sender, RoutedEventArgs e) | MediaExtensionsCS::ScenarioInput4 | [inline, private]
OpenPinch_Click(object sender, RoutedEventArgs e) | MediaExtensionsCS::ScenarioInput4 | [inline, private]
OpenVideoWithPolarEffect(string effectName) | MediaExtensionsCS::ScenarioInput4 | [inline, private]
OpenWarp_Click(object sender, RoutedEventArgs e) | MediaExtensionsCS::ScenarioInput4 | [inline, private]
outputVideo | MediaExtensionsCS::ScenarioInput4 | [private]
PrepareToDraw(_In_ Document^document, D2D1::Matrix3x2F const &transform) | Element | [virtual]
ReleaseParent() | Element | [virtual]
rootPage | MediaExtensionsCS::ScenarioInput4 | [private]
rootPage_OutputFrameLoaded(object sender, object e) | MediaExtensionsCS::ScenarioInput4 | [inline, private]
ScenarioInput4() | MediaExtensionsCS::ScenarioInput4 | [inline]
Stop_Click(object sender, RoutedEventArgs e) | MediaExtensionsCS::ScenarioInput4 | [inline, private]
Generated on Sat Nov 23 2024 16:09:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Folder enumeration/C++/Scenario3.xaml.cpp Source File

  • Folder enumeration

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 SDKSample::FolderEnumeration;
00020
00021 using namespace concurrency;
00022 using namespace Platform;
00023 using namespace Platform::Collections;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Windows::Storage;
00027 using namespace Windows::Storage::BulkAccess;
00028 using namespace Windows::Storage::FileProperties;
00029 using namespace Windows::Storage::Search;
00030 using namespace Windows::UI;
00031 using namespace Windows::UI::Xaml;
00032 using namespace Windows::UI::Xaml::Controls;
00033 using namespace Windows::UI::Xaml::Navigation;
00034
00035 String^ Scenario3::CopyrightProperty = "System.Copyright";
00036 String^ Scenario3::ColorSpaceProperty = "System.Image.ColorSpace";
00037
00038 Scenario3::Scenario3()
00039 {
00040     InitializeComponent();
00041     GetFilesButton->Click += ref new RoutedEventHandler(this, &Scenario3::GetFilesButton_Click);
00042 }
00043
00044 String^ Scenario3::GetPropertyDisplayValue(Object^ property)
00045 {
00046     String^ value;
00047     if (property == nullptr || property->ToString() == "")
00048     {
00049         value = "none";
00050     }
00051     else
00052     {
00053         value = property->ToString();
00054     }
00055
00056     return value;
00057 }
00058
00059 void Scenario3::GetFilesButton_Click(Object^ sender, RoutedEventArgs^ e)
00060 {
00061     // Reset output.
00062     OutputPanel->Children->Clear();
00063
00064     // Set up file type filter.
00065     auto fileTypeFilter = ref new Vector<String^>();
00066     fileTypeFilter->Append(".jpg");
00067     fileTypeFilter->Append(".png");
00068     fileTypeFilter->Append(".bmp");
00069     fileTypeFilter->Append(".gif");
00070
00071     // Create query options.
00072     auto queryOptions = ref new QueryOptions(CommonFileQuery::OrderByName, fileTypeFilter);
00073
00074     // Set up property prefetch - use the PropertyPrefetchOptions for top-level properties
00075     // and a vector for additional properties.
00076     auto propertyNames = ref new Vector<String^>();
00077     propertyNames->Append(CopyrightProperty);
00078     propertyNames->Append(ColorSpaceProperty);
00079     queryOptions->SetPropertyPrefetch(PropertyPrefetchOptions::ImageProperties, propertyNames);
00080
00081     // Set up thumbnail prefetch if needed, e.g. when creating a picture gallery view.
00082     /*
00083     const UINT requestedSize = 190;
00084     const ThumbnailMode thumbnailMode = ThumbnailMode::PicturesView;
00085     const ThumbnailOptions thumbnailOptions = ThumbnailOptions::UseCurrentScale;
00086     queryOptions->SetThumbnailPrefetch(thumbnailMode, requestedSize, thumbnailOptions);
00087     */
00088
00089     // Set up the query and retrieve files.
00090     auto query = KnownFolders::PicturesLibrary->CreateFileQueryWithOptions(queryOptions);
00091     create_task(query->GetFilesAsync()).then([=](IVectorView<StorageFile^>^ files)
00092     {
00093         std::for_each(begin(files), end(files), [=](StorageFile^ file)
00094         {
00095             // Create UI elements for the output and fill in the contents when they are available.
00096             OutputPanel->Children->Append(CreateHeaderTextBlock(file->Name));
00097             TextBlock^ imagePropTextBlock = CreateLineItemTextBlock();
00098             OutputPanel->Children->Append(imagePropTextBlock);
00099             TextBlock^ copyrightTextBlock = CreateLineItemTextBlock();
00100             OutputPanel->Children->Append(copyrightTextBlock);
00101             TextBlock^ colorspaceTextBlock = CreateLineItemTextBlock();
00102             OutputPanel->Children->Append(colorspaceTextBlock);
00103
00104             // GetImagePropertiesAsync will return synchronously when prefetching has been able to
00105             // retrieve the properties in advance.
00106             create_task(file->Properties->GetImagePropertiesAsync()).then([=](ImageProperties^ properties)
00107             {
00108                 imagePropTextBlock->Text = "Dimensions: " + properties->Width + "x" + properties->Height;
00109             });
00110
00111             // Similarly, extra properties are retrieved asynchronously but may
00112             // return immediately when prefetching has fulfilled its task.
00113             create_task(file->Properties->RetrievePropertiesAsync(propertyNames)).then([=](IMap<String^, Object^>^ extraProperties)
00114             {
00115                 copyrightTextBlock->Text = "Copyright: " + GetPropertyDisplayValue(extraProperties->Lookup(CopyrightProperty));
00116                 colorspaceTextBlock->Text = "Color space: " + GetPropertyDisplayValue(extraProperties->Lookup(ColorSpaceProperty));
00117             });
00118
00119             // Thumbnails can also be retrieved and used.
00120             /*
00121             create_task(file->GetThumbnailAsync(thumbnailMode, requestedSize, thumbnailOptions)).then([=](StorageItemThumbnail^ thumbnail)
00122             {
00123                 // Use the thumbnail.
00124             });
00125             */
00126         });
00127     });
00128 }
00129
00130 TextBlock^ Scenario3::CreateHeaderTextBlock(String^ contents)
00131 {
00132     TextBlock^ textBlock = ref new TextBlock();
00133     textBlock->Text = contents;
00134     textBlock->Style = static_cast<Xaml::Style^>(Application::Current->Resources->Lookup("H2Style"));
00135     textBlock->TextWrapping = TextWrapping::Wrap;
00136     return textBlock;
00137 }
00138
00139 TextBlock^ Scenario3::CreateLineItemTextBlock()
00140 {
00141     TextBlock^ textBlock = ref new TextBlock();
00142     textBlock->Style = static_cast<Xaml::Style^>(Application::Current->Resources->Lookup("BasicTextStyle"));
00143     textBlock->TextWrapping = TextWrapping::Wrap;
00144     Thickness margin = textBlock->Margin;
00145     margin.Left = 20;
00146     textBlock->Margin = margin;
00147     return textBlock;
00148 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows account authorization/C++/HttpRequest.cpp Source File

  • Windows account authorization

HttpRequest.cpp

Go to the documentation of this file.
00001 //-----------------------------------------------------------------------
00002 //
00003 //  Copyright (C) Microsoft Corporation.  All rights reserved.
00004 //
00005 //
00006 // THIS CODE AND INFORMATION ARE PROVIDED AS-IS WITHOUT WARRANTY OF ANY
00007 // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
00008 // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00009 // PARTICULAR PURPOSE.
00010 //-----------------------------------------------------------------------
00011 #include "pch.h"
00012 #include "HttpRequest.h"
00013 #include <robuffer.h>
00014 #include <shcore.h>
00015
00016 using namespace concurrency;
00017 using namespace Microsoft::WRL;
00018 using namespace Platform;
00019 using namespace std;
00020 using namespace Web;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Storage::Streams;
00023
00024 // Implementation of IXMLHTTPRequest2Callback used when only the complete response is needed.
00025 // When processing chunks of response data as they are received, use HttpRequestBuffersCallback instead.
00026 class HttpRequestStringCallback
00027     : public RuntimeClass<RuntimeClassFlags<ClassicCom>, IXMLHTTPRequest2Callback, FtmBase>
00028 {
00029 public:
00030     HttpRequestStringCallback(IXMLHTTPRequest2* httpRequest,
00031         cancellation_token ct = concurrency::cancellation_token::none()) :
00032         request(httpRequest), cancellationToken(ct)
00033     {
00034         // Register a callback function that aborts the HTTP operation when
00035         // the cancellation token is canceled.
00036         if (cancellationToken != cancellation_token::none())
00037         {
00038             registrationToken = cancellationToken.register_callback([this]()
00039             {
00040                 if (request != nullptr)
00041                 {
00042                     request->Abort();
00043                 }
00044             });
00045         }
00046     }
00047
00048     // Called when the HTTP request is being redirected to a new URL.
00049     IFACEMETHODIMP OnRedirect(IXMLHTTPRequest2*, PCWSTR)
00050     {
00051         return S_OK;
00052     }
00053
00054     // Called when HTTP headers have been received and processed.
00055     IFACEMETHODIMP OnHeadersAvailable(IXMLHTTPRequest2*, DWORD statusCode, PCWSTR reasonPhrase)
00056     {
00057         HRESULT hr = S_OK;
00058
00059         // We must not propagate exceptions back to IXHR2.
00060         try
00061         {
00062             this->statusCode = statusCode;
00063             this->reasonPhrase = reasonPhrase;
00064         }
00065         catch (std::bad_alloc&)
00066         {
00067             hr = E_OUTOFMEMORY;
00068         }
00069
00070         return hr;
00071     }
00072
00073     // Called when a portion of the entity body has been received.
00074     IFACEMETHODIMP OnDataAvailable(IXMLHTTPRequest2*, ISequentialStream*)
00075     {
00076         return S_OK;
00077     }
00078
00079     // Called when the entire entity response has been received.
00080     IFACEMETHODIMP OnResponseReceived(IXMLHTTPRequest2*, ISequentialStream* responseStream)
00081     {
00082         wstring wstr;
00083         HRESULT hr = ReadUtf8StringFromSequentialStream(responseStream, wstr);
00084
00085         // We must not propagate exceptions back to IXHR2.
00086         try
00087         {
00088             completionEvent.set(make_tuple<HRESULT, wstring>(move(hr), move(wstr)));
00089         }
00090         catch (std::bad_alloc&)
00091         {
00092             hr = E_OUTOFMEMORY;
00093         }
00094
00095         return hr;
00096     }
00097
00098     // Simulate the functionality of DataReader.ReadString().
00099     // This is needed because DataReader requires IRandomAccessStream and this
00100     // code has an ISequentialStream that does not have a conversion to IRandomAccessStream like IStream does.
00101     HRESULT ReadUtf8StringFromSequentialStream(ISequentialStream* readStream, wstring& str)
00102     {
00103         // Convert the response to Unicode wstring.
00104         HRESULT hr;
00105
00106         // Holds the response as a Unicode string.
00107         wstringstream ss;
00108
00109         while (true)
00110         {
00111             ULONG cb;
00112             char buffer[4096];
00113
00114             // Read the response as a UTF-8 string.  Since UTF-8 characters are 1-4 bytes long,
00115             // we need to make sure we only read an integral number of characters.  So we'll
00116             // start with 4093 bytes.
00117             hr = readStream->Read(buffer, sizeof(buffer) - 3, &cb);
00118             if (FAILED(hr) || (cb == 0))
00119             {
00120                 break; // Error or no more data to process, exit loop.
00121             }
00122
00123             if (cb == sizeof(buffer) - 3)
00124             {
00125                 ULONG subsequentBytesRead;
00126                 unsigned int i, cl;
00127
00128                 // Find the first byte of the last UTF-8 character in the buffer.
00129                 for (i = cb - 1; (i >= 0) && ((buffer[i] & 0xC0) == 0x80); i--);
00130
00131                 // Calculate the number of subsequent bytes in the UTF-8 character.
00132                 if (((unsigned char)buffer[i]) < 0x80)
00133                 {
00134                     cl = 1;
00135                 }
00136                 else if (((unsigned char)buffer[i]) < 0xE0)
00137                 {
00138                     cl = 2;
00139                 }
00140                 else if (((unsigned char)buffer[i]) < 0xF0)
00141                 {
00142                     cl = 3;
00143                 }
00144                 else
00145                 {
00146                     cl = 4;
00147                 }
00148
00149                 // Read any remaining bytes.
00150                 if (cb < i + cl)
00151                 {
00152                     hr = readStream->Read(buffer + cb, i + cl - cb, &subsequentBytesRead);
00153                     if (FAILED(hr))
00154                     {
00155                         break; // Error, exit loop.
00156                     }
00157                     cb += subsequentBytesRead;
00158                 }
00159             }
00160
00161             // First determine the size required to store the Unicode string.
00162             int const sizeRequired = MultiByteToWideChar(CP_UTF8, 0, buffer, cb, nullptr, 0);
00163             if (sizeRequired == 0)
00164             {
00165                 // Invalid UTF-8.
00166                 hr = HRESULT_FROM_WIN32(GetLastError());
00167                 break;
00168             }
00169             unique_ptr<char16[]> wstr(new(std::nothrow) char16[sizeRequired + 1]);
00170             if (wstr.get() == nullptr)
00171             {
00172                 hr = E_OUTOFMEMORY;
00173                 break;
00174             }
00175
00176             // Convert the string from UTF-8 to UTF-16LE.  This can never fail, since
00177             // the previous call above succeeded.
00178             MultiByteToWideChar(CP_UTF8, 0, buffer, cb, wstr.get(), sizeRequired);
00179             wstr[sizeRequired] = L'\0'; // Terminate the string.
00180             ss << wstr.get(); // Write the string to the stream.
00181         }
00182
00183         str = SUCCEEDED(hr) ? ss.str() : wstring();
00184         return (SUCCEEDED(hr)) ? S_OK : hr; // Don't return S_FALSE.
00185     }
00186
00187     // Called when an error occurs during the HTTP request.
00188     IFACEMETHODIMP OnError(IXMLHTTPRequest2*, HRESULT hrError)
00189     {
00190         HRESULT hr = S_OK;
00191
00192         // We must not propagate exceptions back to IXHR2.
00193         try
00194         {
00195             completionEvent.set(make_tuple<HRESULT, wstring>(move(hrError), wstring()));
00196         }
00197         catch (std::bad_alloc&)
00198         {
00199             hr = E_OUTOFMEMORY;
00200         }
00201
00202         return hr;
00203     }
00204
00205     // Retrieves the completion event for the HTTP operation.
00206     task_completion_event<tuple<HRESULT, wstring>> const& GetCompletionEvent() const
00207     {
00208         return completionEvent;
00209     }
00210
00211     int GetStatusCode() const
00212     {
00213         return statusCode;
00214     }
00215
00216     wstring GetReasonPhrase() const
00217     {
00218         return reasonPhrase;
00219     }
00220
00221 private:
00222     ~HttpRequestStringCallback()
00223     {
00224         // Unregister the callback.
00225         if (cancellationToken != cancellation_token::none())
00226         {
00227             cancellationToken.deregister_callback(registrationToken);
00228         }
00229     }
00230
00231     // Signals that the download operation was canceled.
00232     cancellation_token cancellationToken;
00233
00234     // Used to unregister the cancellation token callback.
00235     cancellation_token_registration registrationToken;
00236
00237     // The IXMLHTTPRequest2 that processes the HTTP request.
00238     ComPtr<IXMLHTTPRequest2> request;
00239
00240     // Task completion event that is set when the
00241     // download operation completes.
00242     task_completion_event<tuple<HRESULT, wstring>> completionEvent;
00243
00244     int statusCode;
00245     wstring reasonPhrase;
00246 };
00247
00248 // Copy bytes from the sequential stream into the buffer provided until
00249 // we reach the end of one or the other.
00250 unsigned int Web::Details::HttpRequestBuffersCallback::ReadData(
00251     _Out_writes_(outputBufferSize) byte* outputBuffer,
00252     unsigned int outputBufferSize)
00253 {
00254     // Lock the data event while doing the read, to ensure that any bytes we don't read will
00255     // result in the correct event getting triggered.
00256     concurrency::critical_section::scoped_lock lock(dataEventLock);
00257
00258     ULONG bytesRead;
00259     CheckHResult(dataStream.Get()->Read(outputBuffer, outputBufferSize, &bytesRead));
00260     if (bytesRead < outputBufferSize)
00261     {
00262         // We need to reset the data event, which we can only do by creating a new one.
00263         dataEvent = task_completion_event<void>();
00264     }
00265
00266     return bytesRead;
00267 }
00268
00269 // Create a task that completes when data is available, in an exception-safe way.
00270 task<void> Web::Details::HttpRequestBuffersCallback::CreateDataTask()
00271 {
00272     concurrency::critical_section::scoped_lock lock(dataEventLock);
00273     return create_task(dataEvent, cancellationToken);
00274 }
00275
00276 HttpRequest::HttpRequest() : responseComplete(true), statusCode(200)
00277 {
00278 }
00279
00280 // Start a download of the specified URI using the specified method.  The returned task produces the
00281 // HTTP response text.  The status code and reason can be read with GetStatusCode() and GetReasonPhrase().
00282 task<wstring> HttpRequest::DownloadAsync(PCWSTR httpMethod, PCWSTR uri, cancellation_token cancellationToken,
00283     PCWSTR contentType, IStream* postStream, uint64 postStreamSizeToSend)
00284 {
00285     // Create an IXMLHTTPRequest2 object.
00286     ComPtr<IXMLHTTPRequest2> xhr;
00287     CheckHResult(CoCreateInstance(CLSID_XmlHttpRequest, nullptr, CLSCTX_INPROC, IID_PPV_ARGS(&xhr)));
00288
00289     // Create callback.
00290     auto stringCallback = Make<HttpRequestStringCallback>(xhr.Get(), cancellationToken);
00291     CheckHResult(stringCallback ? S_OK : E_OUTOFMEMORY);
00292
00293     auto completionTask = create_task(stringCallback->GetCompletionEvent());
00294
00295     // Create a request.
00296     CheckHResult(xhr->Open(httpMethod, uri, stringCallback.Get(), nullptr, nullptr, nullptr, nullptr));
00297
00298     if (postStream != nullptr && contentType != nullptr)
00299     {
00300         CheckHResult(xhr->SetRequestHeader(L"Content-Type", contentType));
00301     }
00302
00303     // Send the request.
00304     CheckHResult(xhr->Send(postStream, postStreamSizeToSend));
00305
00306     // Return a task that completes when the HTTP operation completes.
00307     // We pass the callback to the continuation because the lifetime of the
00308     // callback must exceed the operation to ensure that cancellation
00309     // works correctly.
00310     return completionTask.then([this, stringCallback](tuple<HRESULT, wstring> resultTuple)
00311     {
00312         // If the GET operation failed, throw an Exception.
00313         CheckHResult(std::get<0>(resultTuple));
00314
00315         statusCode = stringCallback->GetStatusCode();
00316         reasonPhrase = stringCallback->GetReasonPhrase();
00317
00318         return std::get<1>(resultTuple);
00319     });
00320 }
00321
00322 // Start an HTTP GET on the specified URI.  The returned task completes once the entire response
00323 // has been received, and the task produces the HTTP response text.  The status code and reason
00324 // can be read with GetStatusCode() and GetReasonPhrase().
00325 task<wstring> HttpRequest::GetAsync(Uri^ uri, cancellation_token cancellationToken)
00326 {
00327     return DownloadAsync(L"GET",
00328                          uri->AbsoluteUri->Data(),
00329                          cancellationToken,
00330                          nullptr,
00331                          nullptr,
00332                          0);
00333 }
00334
00335 void HttpRequest::CreateMemoryStream(IStream **stream)
00336 {
00337     auto randomAccessStream = ref new Windows::Storage::Streams::InMemoryRandomAccessStream();
00338     CheckHResult(CreateStreamOverRandomAccessStream(randomAccessStream, IID_PPV_ARGS(stream)));
00339 }
00340
00341 // Start an HTTP POST on the specified URI, using a string body.  The returned task produces the
00342 // HTTP response text.  The status code and reason can be read with GetStatusCode() and GetReasonPhrase().
00343 task<wstring> HttpRequest::PostAsync(Uri^ uri, const wstring& body, cancellation_token cancellationToken)
00344 {
00345     int length = 0;
00346     ComPtr<IStream> postStream;
00347     CreateMemoryStream(&postStream);
00348
00349     if (body.length() > 0)
00350     {
00351         // Get the required buffer size.
00352         int size = WideCharToMultiByte(CP_UTF8,                         // UTF-8
00353                                        0,                               // Conversion type
00354                                        body.c_str(),                    // Unicode string to convert
00355                                        static_cast<int>(body.length()), // Size
00356                                        nullptr,                         // Output buffer
00357                                        0,                               // Output buffer size
00358                                        nullptr,
00359                                        nullptr);
00360         CheckHResult((size != 0) ? S_OK : HRESULT_FROM_WIN32(GetLastError()));
00361
00362         std::unique_ptr<char[]> tempData(new char[size]);
00363         length = WideCharToMultiByte(CP_UTF8,                         // UTF-8
00364                                      0,                               // Conversion type
00365                                      body.c_str(),                    // Unicode string to convert
00366                                      static_cast<int>(body.length()), // Size
00367                                      tempData.get(),                  // Output buffer
00368                                      size,                            // Output buffer size
00369                                      nullptr,
00370                                      nullptr);
00371         CheckHResult((length != 0) ? S_OK : HRESULT_FROM_WIN32(GetLastError()));
00372         CheckHResult(postStream->Write(tempData.get(), length, nullptr));
00373     }
00374
00375     return DownloadAsync(L"POST",
00376                          uri->AbsoluteUri->Data(),
00377                          cancellationToken,
00378                          L"text/plain;charset=utf-8",
00379                          postStream.Get(),
00380                          length);
00381 }
00382
00383 // Start an HTTP POST on the specified URI, using a stream body.  The returned task produces the
00384 // HTTP response text.  The status code and reason can be read with GetStatusCode() and GetReasonPhrase().
00385 task<wstring> HttpRequest::PostAsync(Uri^ uri, PCWSTR contentType, IStream* postStream,
00386     uint64 postStreamSizeToSend, cancellation_token cancellationToken)
00387 {
00388     return DownloadAsync(L"POST",
00389                          uri->AbsoluteUri->Data(),
00390                          cancellationToken,
00391                          contentType,
00392                          postStream,
00393                          postStreamSizeToSend);
00394 }
00395
00396 // Send a request but don't return the response.  Instead, let the caller read it with ReadAsync().
00397 task<void> HttpRequest::SendAsync(const wstring& httpMethod, Uri^ uri, cancellation_token cancellationToken)
00398 {
00399     // Create an IXMLHTTPRequest2 object.
00400     ComPtr<IXMLHTTPRequest2> xhr;
00401     CheckHResult(CoCreateInstance(CLSID_XmlHttpRequest, nullptr, CLSCTX_INPROC, IID_PPV_ARGS(&xhr)));
00402
00403     // Create callback.
00404     buffersCallback = Make<Web::Details::HttpRequestBuffersCallback>(xhr.Get(), cancellationToken);
00405     CheckHResult(buffersCallback ? S_OK : E_OUTOFMEMORY);
00406
00407     ComPtr<IXMLHTTPRequest2Callback> xhrCallback;
00408     CheckHResult(buffersCallback.As(&xhrCallback));
00409
00410     // Open and send the request.
00411     CheckHResult(xhr->Open(httpMethod.c_str(),
00412                            uri->AbsoluteUri->Data(),
00413                            xhrCallback.Get(),
00414                            nullptr,
00415                            nullptr,
00416                            nullptr,
00417                            nullptr));
00418
00419     responseComplete = false;
00420
00421     CheckHResult(xhr->Send(nullptr, 0));
00422
00423     // Return a task that completes when the HTTP operation completes.
00424     // Since buffersCallback holds a reference on the callback, the lifetime of the callback will exceed
00425     // the operation and ensure that cancellation works correctly.
00426     return buffersCallback->CreateDataTask().then([this]()
00427     {
00428         CheckHResult(buffersCallback->GetError());
00429
00430         statusCode = buffersCallback->GetStatusCode();
00431         reasonPhrase = buffersCallback->GetReasonPhrase();
00432     });
00433 }
00434
00435 // Read a chunk of data from the HTTP response, up to a specified length or until we reach the end
00436 // of the response, and store the value in the provided buffer.  This is useful for large content,
00437 // enabling the streaming of the result.
00438 task<void> HttpRequest::ReadAsync(Windows::Storage::Streams::IBuffer^ readBuffer, unsigned int offsetInBuffer,
00439     unsigned int requestedBytesToRead)
00440 {
00441     if (offsetInBuffer + requestedBytesToRead > readBuffer->Capacity)
00442     {
00443         throw ref new InvalidArgumentException();
00444     }
00445
00446     // Return a task that completes when a read completes.
00447     // We pass the callback to the continuation because the lifetime of the
00448     // callback must exceed the operation to ensure that cancellation
00449     // works correctly.
00450     return buffersCallback->CreateDataTask().then([this, readBuffer, offsetInBuffer, requestedBytesToRead]()
00451     {
00452         CheckHResult(buffersCallback->GetError());
00453
00454         // Get a pointer to the location to copy data into.
00455         ComPtr<IBufferByteAccess> bufferByteAccess;
00456         CheckHResult(reinterpret_cast<IUnknown*>(readBuffer)->QueryInterface(IID_PPV_ARGS(&bufferByteAccess)));
00457         byte* outputBuffer; // Returned internal pointer, do not free this value.
00458         CheckHResult(bufferByteAccess->Buffer(&outputBuffer));
00459
00460         // Copy bytes from the sequential stream into the buffer provided until
00461         // we reach the end of one or the other.
00462         readBuffer->Length = buffersCallback->ReadData(outputBuffer + offsetInBuffer, requestedBytesToRead);
00463         if (buffersCallback->IsResponseReceived() && (readBuffer->Length < requestedBytesToRead))
00464         {
00465             responseComplete = true;
00466         }
00467     });
00468 }
Generated on Sat Nov 23 2024 16:07:58 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite custom text renderer/C++/SampleOverlay.cpp Source File

  • DirectWrite custom text renderer

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 Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::UI::ViewManagement;
00015 using namespace Windows::Graphics::Display;
00016 using namespace D2D1;
00017
00018 SampleOverlay::SampleOverlay() :
00019     m_drawOverlay(true)
00020 {
00021 }
00022
00023 void SampleOverlay::Initialize(
00024     _In_ ID2D1Device*         d2dDevice,
00025     _In_ ID2D1DeviceContext*  d2dContext,
00026     _In_ IWICImagingFactory*  wicFactory,
00027     _In_ IDWriteFactory*      dwriteFactory,
00028     _In_ Platform::String^    caption
00029     )
00030 {
00031     m_wicFactory = wicFactory;
00032     m_dwriteFactory = dwriteFactory;
00033     m_sampleName = caption;
00034     m_d2dDevice = d2dDevice;
00035     m_d2dContext = d2dContext;
00036     m_padding = 3.0f;
00037     m_textVerticalOffset = 5.0f;
00038     m_logoSize = D2D1::SizeF(0.0f, 0.0f);
00039     m_overlayWidth = 0.0f;
00040
00041     ComPtr<ID2D1Factory> factory;
00042     d2dDevice->GetFactory(&factory);
00043
00044     DX::ThrowIfFailed(
00045         factory.As(&m_d2dFactory)
00046         );
00047
00048     ResetDirectXResources();
00049 }
00050
00051 void SampleOverlay::ResetDirectXResources()
00052 {
00053     DX::ThrowIfFailed(
00054         m_d2dContext->CreateSolidColorBrush(ColorF(ColorF::White), &m_whiteBrush)
00055         );
00056
00057     ComPtr<IWICBitmapDecoder> wicBitmapDecoder;
00058     DX::ThrowIfFailed(
00059         m_wicFactory->CreateDecoderFromFilename(
00060             L"windowsbig-sdk.png",
00061             nullptr,
00062             GENERIC_READ,
00063             WICDecodeMetadataCacheOnDemand,
00064             &wicBitmapDecoder
00065             )
00066         );
00067
00068     ComPtr<IWICBitmapFrameDecode> wicBitmapFrame;
00069     DX::ThrowIfFailed(
00070         wicBitmapDecoder->GetFrame(0, &wicBitmapFrame)
00071         );
00072
00073     ComPtr<IWICFormatConverter> wicFormatConverter;
00074     DX::ThrowIfFailed(
00075         m_wicFactory->CreateFormatConverter(&wicFormatConverter)
00076         );
00077
00078     DX::ThrowIfFailed(
00079         wicFormatConverter->Initialize(
00080             wicBitmapFrame.Get(),
00081             GUID_WICPixelFormat32bppPBGRA,
00082             WICBitmapDitherTypeNone,
00083             nullptr,
00084             0.0,
00085             WICBitmapPaletteTypeCustom  // the BGRA format has no palette so this value is ignored
00086             )
00087         );
00088
00089     double dpiX = 96.0f;
00090     double dpiY = 96.0f;
00091     DX::ThrowIfFailed(
00092         wicFormatConverter->GetResolution(&dpiX, &dpiY)
00093         );
00094
00095     DX::ThrowIfFailed(
00096         m_d2dContext->CreateBitmapFromWicBitmap(
00097             wicFormatConverter.Get(),
00098             BitmapProperties(
00099                 PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00100                 static_cast<float>(dpiX),
00101                 static_cast<float>(dpiY)
00102                 ),
00103             &m_logoBitmap
00104             )
00105         );
00106
00107     m_logoSize = m_logoBitmap->GetSize();
00108
00109     ComPtr<IDWriteTextFormat> nameTextFormat;
00110     DX::ThrowIfFailed(
00111         m_dwriteFactory->CreateTextFormat(
00112             L"Segoe UI",
00113             nullptr,
00114             DWRITE_FONT_WEIGHT_LIGHT,
00115             DWRITE_FONT_STYLE_NORMAL,
00116             DWRITE_FONT_STRETCH_NORMAL,
00117             36.0f,
00118             L"en-US",
00119             &nameTextFormat
00120             )
00121         );
00122
00123     DX::ThrowIfFailed(
00124         nameTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)
00125         );
00126
00127     DX::ThrowIfFailed(
00128         nameTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)
00129         );
00130
00131     DX::ThrowIfFailed(
00132         m_dwriteFactory->CreateTextLayout(
00133             m_sampleName->Data(),
00134             m_sampleName->Length(),
00135             nameTextFormat.Get(),
00136             4096.0f,
00137             4096.0f,
00138             &m_textLayout
00139             )
00140         );
00141
00142     DWRITE_TEXT_METRICS metrics = {0};
00143     DX::ThrowIfFailed(
00144         m_textLayout->GetMetrics(&metrics)
00145         );
00146
00147     m_overlayWidth = m_padding * 3.0f + m_logoSize.width + metrics.width;
00148
00149     DX::ThrowIfFailed(
00150         m_d2dFactory->CreateDrawingStateBlock(&m_stateBlock)
00151         );
00152
00153     UpdateForWindowSizeChange();
00154 }
00155
00156 void SampleOverlay::UpdateForWindowSizeChange()
00157 {
00158     if (CoreWindow::GetForCurrentThread()->Bounds.Width < m_overlayWidth)
00159     {
00160         m_drawOverlay = false;
00161     }
00162     else
00163     {
00164         m_drawOverlay = true;
00165     }
00166 }
00167
00168 void SampleOverlay::Render()
00169 {
00170     if (m_drawOverlay)
00171     {
00172         m_d2dContext->SaveDrawingState(m_stateBlock.Get());
00173
00174         m_d2dContext->BeginDraw();
00175         m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00176         m_d2dContext->DrawBitmap(
00177             m_logoBitmap.Get(),
00178             D2D1::RectF(m_padding, 0.0f, m_logoSize.width + m_padding, m_logoSize.height)
00179             );
00180
00181         m_d2dContext->DrawTextLayout(
00182             Point2F(m_logoSize.width + 2.0f * m_padding, m_textVerticalOffset),
00183             m_textLayout.Get(),
00184             m_whiteBrush.Get()
00185             );
00186
00187         // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00188         // is lost. It will be handled during the next call to Present.
00189         HRESULT hr = m_d2dContext->EndDraw();
00190         if (hr != D2DERR_RECREATE_TARGET)
00191         {
00192             DX::ThrowIfFailed(hr);
00193         }
00194
00195         m_d2dContext->RestoreDrawingState(m_stateBlock.Get());
00196     }
00197 }
00198
00199 float SampleOverlay::GetTitleHeightInDips()
00200 {
00201     return m_logoSize.height;
00202 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML FlipView control/C++/SampleDataSource.cpp Source File

  • XAML FlipView control

SampleDataSource.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002
00003 //
00004 // Scenario1.xaml.cpp
00005 // Implementation of the Scenario1 class
00006 //
00007
00008 #include "pch.h"
00009 #include "Scenario1.xaml.h"
00010 #include "SampleDataSource.h"
00011
00012 using namespace SDKSample::FlipViewData;
00013
00014 SampleDataItem::SampleDataItem(Platform::String^ titile, Platform::String^ type, Platform::String^ picture):_title(titile),_type(type),_picture(picture)
00015 {
00016 }
00017
Generated on Sat Nov 23 2024 16:08:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Search contract/C++/Scenario2.xaml.h Source File

  • Search contract

Scenario2.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.xaml.h
00013 // Declaration of the Scenario2 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario2.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 #pragma warning(push)
00023 #pragma warning(disable:4451) // Warns about possible invalid marshaling of objects across threads. In this case, the warning doesn't apply because the SearchPane object is only accessed from the UI thread.
00024 namespace SDKSample
00025 {
00026     namespace SearchContract
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 Scenario2 sealed
00033         {
00034         public:
00035             Scenario2();
00036
00037         protected:
00038             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00039             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00040             void OnSearchPaneSuggestionsRequested(Windows::ApplicationModel::Search::SearchPane^ sender, Windows::ApplicationModel::Search::SearchPaneSuggestionsRequestedEventArgs^ e);
00041
00042         private:
00043             Windows::ApplicationModel::Search::SearchPane^ searchPane;
00044             Windows::Foundation::EventRegistrationToken token;
00045         };
00046     }
00047 }
00048 #pragma warning(pop) // Reenable warning 4451
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/MediaExtensions/GeometricSource/StdAfx.h Source File

  • Media extensions
  • MediaExtensions
  • GeometricSource

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 // Windows Header Files:
00009 #include <windows.h>
00010 #include <mfapi.h>
00011 #include <mfidl.h>
00012 #include <mfapi.h>
00013 #include <mferror.h>
00014 #include <d3d11.h>
00015
00016 #include <assert.h>
00017
00018 #include <tchar.h>
00019 #include <Strsafe.h>
00020 #include <objidl.h>
00021 #include <new>
00022
00023 #include <wrl\client.h>
00024 #include <wrl\implements.h>
00025 #include <wrl\ftm.h>
00026 #include <wrl\event.h>
00027 #include <wrl\wrappers\corewrappers.h>
00028 #include <windows.media.h>
00029
00030 using namespace Microsoft::WRL;
00031 using namespace Microsoft::WRL::Wrappers;
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML personality animations/C++/Scenario1.xaml.cpp Source File

  • XAML personality animations

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::PersonalityAnimations;
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::UI::Xaml::Media::Animation;
00025
00026 Scenario1::Scenario1()
00027 {
00028     InitializeComponent();
00029     PopIn->IsEnabled = false;
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 void Scenario1::OnNavigatedTo(NavigationEventArgs^ e)
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     rootPage = MainPage::Current;
00042 }
00043
00044 void Scenario1::PopInClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00045 {
00046   PopInStoryboard->Begin();
00047         PopIn->IsEnabled = false;
00048         PopOut->IsEnabled = true;
00049 }
00050
00051 void Scenario1::PopOutClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00052 {
00053   PopOutStoryboard->Begin();
00054         PopIn->IsEnabled = true;
00055         PopOut->IsEnabled = false;
00056 }
00057
Generated on Sat Nov 23 2024 16:07:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D command list/C++/SampleOverlay.cpp Source File

  • Direct2D command list

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 Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::UI::ViewManagement;
00015 using namespace Windows::Graphics::Display;
00016 using namespace D2D1;
00017
00018 SampleOverlay::SampleOverlay() :
00019     m_drawOverlay(true)
00020 {
00021 }
00022
00023 void SampleOverlay::Initialize(
00024     _In_ ID2D1Device*         d2dDevice,
00025     _In_ ID2D1DeviceContext*  d2dContext,
00026     _In_ IWICImagingFactory*  wicFactory,
00027     _In_ IDWriteFactory*      dwriteFactory,
00028     _In_ Platform::String^    caption
00029     )
00030 {
00031     m_wicFactory = wicFactory;
00032     m_dwriteFactory = dwriteFactory;
00033     m_sampleName = caption;
00034     m_d2dDevice = d2dDevice;
00035     m_d2dContext = d2dContext;
00036     m_padding = 3.0f;
00037     m_textVerticalOffset = 5.0f;
00038     m_logoSize = D2D1::SizeF(0.0f, 0.0f);
00039     m_overlayWidth = 0.0f;
00040
00041     ComPtr<ID2D1Factory> factory;
00042     d2dDevice->GetFactory(&factory);
00043
00044     DX::ThrowIfFailed(
00045         factory.As(&m_d2dFactory)
00046         );
00047
00048     ResetDirectXResources();
00049 }
00050
00051 void SampleOverlay::ResetDirectXResources()
00052 {
00053     DX::ThrowIfFailed(
00054         m_d2dContext->CreateSolidColorBrush(ColorF(ColorF::White), &m_whiteBrush)
00055         );
00056
00057     ComPtr<IWICBitmapDecoder> wicBitmapDecoder;
00058     DX::ThrowIfFailed(
00059         m_wicFactory->CreateDecoderFromFilename(
00060             L"windowsbig-sdk.png",
00061             nullptr,
00062             GENERIC_READ,
00063             WICDecodeMetadataCacheOnDemand,
00064             &wicBitmapDecoder
00065             )
00066         );
00067
00068     ComPtr<IWICBitmapFrameDecode> wicBitmapFrame;
00069     DX::ThrowIfFailed(
00070         wicBitmapDecoder->GetFrame(0, &wicBitmapFrame)
00071         );
00072
00073     ComPtr<IWICFormatConverter> wicFormatConverter;
00074     DX::ThrowIfFailed(
00075         m_wicFactory->CreateFormatConverter(&wicFormatConverter)
00076         );
00077
00078     DX::ThrowIfFailed(
00079         wicFormatConverter->Initialize(
00080             wicBitmapFrame.Get(),
00081             GUID_WICPixelFormat32bppPBGRA,
00082             WICBitmapDitherTypeNone,
00083             nullptr,
00084             0.0,
00085             WICBitmapPaletteTypeCustom  // the BGRA format has no palette so this value is ignored
00086             )
00087         );
00088
00089     double dpiX = 96.0f;
00090     double dpiY = 96.0f;
00091     DX::ThrowIfFailed(
00092         wicFormatConverter->GetResolution(&dpiX, &dpiY)
00093         );
00094
00095     DX::ThrowIfFailed(
00096         m_d2dContext->CreateBitmapFromWicBitmap(
00097             wicFormatConverter.Get(),
00098             BitmapProperties(
00099                 PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00100                 static_cast<float>(dpiX),
00101                 static_cast<float>(dpiY)
00102                 ),
00103             &m_logoBitmap
00104             )
00105         );
00106
00107     m_logoSize = m_logoBitmap->GetSize();
00108
00109     ComPtr<IDWriteTextFormat> nameTextFormat;
00110     DX::ThrowIfFailed(
00111         m_dwriteFactory->CreateTextFormat(
00112             L"Segoe UI",
00113             nullptr,
00114             DWRITE_FONT_WEIGHT_LIGHT,
00115             DWRITE_FONT_STYLE_NORMAL,
00116             DWRITE_FONT_STRETCH_NORMAL,
00117             36.0f,
00118             L"en-US",
00119             &nameTextFormat
00120             )
00121         );
00122
00123     DX::ThrowIfFailed(
00124         nameTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)
00125         );
00126
00127     DX::ThrowIfFailed(
00128         nameTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)
00129         );
00130
00131     DX::ThrowIfFailed(
00132         m_dwriteFactory->CreateTextLayout(
00133             m_sampleName->Data(),
00134             m_sampleName->Length(),
00135             nameTextFormat.Get(),
00136             4096.0f,
00137             4096.0f,
00138             &m_textLayout
00139             )
00140         );
00141
00142     DWRITE_TEXT_METRICS metrics = {0};
00143     DX::ThrowIfFailed(
00144         m_textLayout->GetMetrics(&metrics)
00145         );
00146
00147     m_overlayWidth = m_padding * 3.0f + m_logoSize.width + metrics.width;
00148
00149     DX::ThrowIfFailed(
00150         m_d2dFactory->CreateDrawingStateBlock(&m_stateBlock)
00151         );
00152
00153     UpdateForWindowSizeChange();
00154 }
00155
00156 void SampleOverlay::UpdateForWindowSizeChange()
00157 {
00158     if (CoreWindow::GetForCurrentThread()->Bounds.Width < m_overlayWidth)
00159     {
00160         m_drawOverlay = false;
00161     }
00162     else
00163     {
00164         m_drawOverlay = true;
00165     }
00166 }
00167
00168 void SampleOverlay::Render()
00169 {
00170     if (m_drawOverlay)
00171     {
00172         m_d2dContext->SaveDrawingState(m_stateBlock.Get());
00173
00174         m_d2dContext->BeginDraw();
00175         m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00176         m_d2dContext->DrawBitmap(
00177             m_logoBitmap.Get(),
00178             D2D1::RectF(m_padding, 0.0f, m_logoSize.width + m_padding, m_logoSize.height)
00179             );
00180
00181         m_d2dContext->DrawTextLayout(
00182             Point2F(m_logoSize.width + 2.0f * m_padding, m_textVerticalOffset),
00183             m_textLayout.Get(),
00184             m_whiteBrush.Get()
00185             );
00186
00187         // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00188         // is lost. It will be handled during the next call to Present.
00189         HRESULT hr = m_d2dContext->EndDraw();
00190         if (hr != D2DERR_RECREATE_TARGET)
00191         {
00192             DX::ThrowIfFailed(hr);
00193         }
00194
00195         m_d2dContext->RestoreDrawingState(m_stateBlock.Get());
00196     }
00197 }
00198
00199 float SampleOverlay::GetTitleHeightInDips()
00200 {
00201     return m_logoSize.height;
00202 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Scheduled notifications/C#,C++/NotificationData.h Source File

  • Scheduled notifications
  • C#,C++

NotificationData.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <collection.h>
00004
00005 namespace ScheduledNotificationsSampleCPP
00006 {
00007   [Windows::UI::Xaml::Data::Bindable]
00008   [Windows::Foundation::Metadata::WebHostHidden]
00009   public ref class NotificationData sealed
00010     {
00011     public:
00012         NotificationData(void);
00013
00014         property Platform::String^ ItemType { Platform::String^ get(); void set(Platform::String^ value); }
00015         property Platform::String^ ItemId { Platform::String^ get(); void set(Platform::String^ value); }
00016         property Platform::String^ DueTime { Platform::String^ get(); void set(Platform::String^ value); }
00017         property Platform::String^ InputString { Platform::String^ get(); void set(Platform::String^ value); }
00018     bool get_IsTile(void);
00019         void set_IsTile(bool isTile);
00020
00021         event Windows::UI::Xaml::Data::PropertyChangedEventHandler^ PropertyChanged;
00022
00023     protected:
00024         void OnPropertyChanged(Platform::String^ propertyName);
00025
00026     private:
00027         Platform::String^ _itemType;
00028         Platform::String^ _itemId;
00029         Platform::String^ _dueTime;
00030         Platform::String^ _inputString;
00031         bool _isTile;
00032     };
00033
00034     public ref class NotificationDataSource sealed
00035     {
00036         public:
00037             NotificationDataSource();
00038             property Windows::Foundation::Collections::IObservableVector<Object^>^ Items
00039             {
00040                 Windows::Foundation::Collections::IObservableVector<Object^>^ get();
00041             }
00042             void Clear();
00043             void LoadData();
00044             void Refresh();
00045         private:
00046             void AddItem(Platform::String^ itemType, Platform::String^ itemId, Platform::String^ dueTime, Platform::String^ inputString, bool isTile);
00047             Platform::Collections::Vector<Object^>^ _items;
00048             Windows::Globalization::DateTimeFormatting::DateTimeFormatter^ _formatter;
00049     };
00050 }
Generated on Sat Nov 23 2024 16:08:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Geolocation/C++/App.xaml.h Source File

  • Geolocation

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media Play To/C++/pch.h Source File

  • Media Play To

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: HttpClient/C++/Scenario2.xaml.cpp Source File

  • HttpClient

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 SDKSample::HttpClientSample;
00020
00021 using namespace concurrency;
00022 using namespace Platform;
00023 using namespace Windows::Foundation;
00024 using namespace Windows::Security::Cryptography;
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::Navigation;
00029
00030 Scenario2::Scenario2()
00031 {
00032     InitializeComponent();
00033
00034     this->readBuffer = ref new Buffer(1000);
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 Scenario2::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
00050 void SDKSample::HttpClientSample::Scenario2::Start_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00051 {
00052     Helpers::ScenarioStarted(StartButton, CancelButton);
00053     rootPage->NotifyUser("In progress", NotifyType::StatusMessage);
00054     OutputField->Text = "";
00055
00056     // 'AddressField' is a disabled text box, so the value is considered trusted input. When enabling the
00057     // text box make sure to validate user input (e.g., by catching exceptions with TryGetUri as shown in scenario 1).
00058     auto resourceAddress = ref new Uri(AddressField->Text);
00059
00060     cancellationTokenSource = cancellation_token_source();
00061
00062     // Do an asynchronous GET.  We need to use use_current() with the continuations since the tasks are completed on
00063     // background threads and we need to run on the UI thread to update the UI.
00064     httpRequest.SendAsync(L"GET", resourceAddress, cancellationTokenSource.get_token()).then([this]()
00065     {
00066         OutputField->Text = httpRequest.GetStatusCode() + " " +
00067             ref new String(httpRequest.GetReasonPhrase().c_str()) + "\n";
00068
00069         return Scenario2ReadData();
00070     }, task_continuation_context::use_current()).then([this](task<void> previousTask)
00071     {
00072         rootPage->NotifyUser("Completed", NotifyType::StatusMessage);
00073
00074         Helpers::ScenarioCompleted(StartButton, CancelButton);
00075
00076         try
00077         {
00078             previousTask.get();
00079         }
00080         catch (const task_canceled&)
00081         {
00082             rootPage->NotifyUser("Request canceled.", NotifyType::ErrorMessage);
00083         }
00084         catch (Exception^ ex)
00085         {
00086             rootPage->NotifyUser(ex->Message, NotifyType::ErrorMessage);
00087         }
00088     }, task_continuation_context::use_current());
00089 }
00090
00091 task<void> SDKSample::HttpClientSample::Scenario2::Scenario2ReadData()
00092 {
00093     // Do an asynchronous read.  We need to use use_current() with the continuations since the tasks are completed on
00094     // background threads and we need to run on the UI thread to update the UI.
00095     return httpRequest.ReadAsync(readBuffer, 0, readBuffer->Capacity).then([this](task<void> readTask)
00096     {
00097         // If the read failed, throw an exception so we don't start another read.
00098         readTask.get();
00099
00100         OutputField->Text += "Bytes read from stream: " + readBuffer->Length + "\n";
00101
00102         // Use the buffer contents for something.  We can't safely display it as a string though, since encodings
00103         // like UTF-8 and UTF-16 have a variable number of bytes per character and so the last bytes in the buffer
00104         // may not contain a whole character.   Instead, we'll convert the bytes to hex and display the result.
00105         String^ responseBodyAsText = CryptographicBuffer::EncodeToHexString(readBuffer);
00106         OutputField->Text += responseBodyAsText + "\n";
00107
00108         // Continue reading until the response is complete.  When done, return previousTask that is complete.
00109         return httpRequest.IsResponseComplete() ? readTask : Scenario2ReadData();
00110     }, task_continuation_context::use_current());
00111 }
00112
00113 void SDKSample::HttpClientSample::Scenario2::Cancel_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00114 {
00115     cancellationTokenSource.cancel();
00116 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playlist/C++/Add.xaml.h Source File

  • Playlist

Add.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 // Add.xaml.h
00013 // Declaration of the Add class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Add.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace Playlists
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 Add sealed
00031         {
00032         public:
00033             Add();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void PickPlaylistButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040             void PickAudioButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         };
00042     }
00043 }
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Edge gesture invocation/C++/ScenarioInput1.xaml.cpp Source File

  • Edge gesture invocation

ScenarioInput1.xaml.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 //
00009 // ScenarioInput1.xaml.cpp
00010 // Implementation of the ScenarioInput1 class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioInput1.xaml.h"
00015
00016 using namespace EdgeGestureSample;
00017
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::UI::ViewManagement;
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
00031 ScenarioInput1::ScenarioInput1()
00032 {
00033     InitializeComponent();
00034 }
00035
00036 ScenarioInput1::~ScenarioInput1()
00037 {
00038 }
00039
00040 #pragma region Template-Related Code - Do not remove
00041 void ScenarioInput1::OnNavigatedTo(NavigationEventArgs^ e)
00042 {
00043     // Get a pointer to our main page.
00044     rootPage = dynamic_cast<MainPage^>(e->Parameter);
00045
00046     // We want to be notified when the OutputFrame is loaded so we can get to the content.
00047     _frameLoadedToken = rootPage->OutputFrameLoaded += ref new Windows::Foundation::EventHandler<Platform::Object^>(this, &ScenarioInput1::rootPage_OutputFrameLoaded);
00048 }
00049
00050 void ScenarioInput1::OnNavigatedFrom(NavigationEventArgs^ e)
00051 {
00052     rootPage->RightTapped -= RightClickEventToken;
00053     EdgeGesture^ edgeGesture = Windows::UI::Input::EdgeGesture::GetForCurrentView();
00054     edgeGesture->Starting -= EdgeGestureStartingEventToken;
00055     edgeGesture->Completed -= EdgeGestureCompletedEventToken;
00056     edgeGesture->Canceled -= EdgeGestureCanceledEventToken;
00057
00058     rootPage->OutputFrameLoaded -= _frameLoadedToken;
00059 }
00060
00061 #pragma endregion
00062
00063 #pragma region Use this code if you need access to elements in the output frame - otherwise delete
00064 void ScenarioInput1::rootPage_OutputFrameLoaded(Object^ sender, Object^ e)
00065 {
00066     // Get a pointer to the content within the OutputFrame.
00067     Page^ outputFrame = dynamic_cast<Page^>(rootPage->OutputFrame->Content);
00068
00069     outputText = dynamic_cast<TextBlock^>(outputFrame->FindName("OutputText"));
00070
00071     InitializeEdgeGestureHandlers();
00072 }
00073
00074 #pragma endregion
00075
00076 #pragma region Event handlers
00077
00078 void ScenarioInput1::OnStarting(EdgeGesture^ sender, EdgeGestureEventArgs^ e)
00079 {
00080     outputText->Text = "Invoking with touch.";
00081 }
00082
00083 void ScenarioInput1::OnCompleted(EdgeGesture^ sender, EdgeGestureEventArgs^ e)
00084 {
00085     // Determine whether it was touch or keyboard invocation
00086     if (e->Kind == Windows::UI::Input::EdgeGestureKind::Touch)
00087     {
00088         outputText->Text = "Invoked with touch.";
00089     }
00090     else if (e->Kind == Windows::UI::Input::EdgeGestureKind::Keyboard)
00091     {
00092         outputText->Text = "Invoked with keyboard.";
00093     }
00094     else if (e->Kind == Windows::UI::Input::EdgeGestureKind::Mouse)
00095     {
00096         outputText->Text = "Invoked with right-click.";
00097     }
00098 }
00099
00100 void ScenarioInput1::OnCanceled(EdgeGesture^ sender, EdgeGestureEventArgs^ e)
00101 {
00102     outputText->Text = "Canceled with touch.";
00103 }
00104
00105 void ScenarioInput1::OnContextMenu(Object^ sender, RightTappedRoutedEventArgs^ e)
00106 {
00107     outputText->Text = "Invoked with right-click.";
00108 }
00109
00110 void ScenarioInput1::InitializeEdgeGestureHandlers()
00111 {
00112     EdgeGesture^ edgeGesture = Windows::UI::Input::EdgeGesture::GetForCurrentView();
00113
00114     EdgeGestureStartingEventToken = edgeGesture->Starting += ref new TypedEventHandler<EdgeGesture^, EdgeGestureEventArgs^>(this, &ScenarioInput1::OnStarting);
00115     EdgeGestureCompletedEventToken = edgeGesture->Completed += ref new TypedEventHandler<EdgeGesture^, EdgeGestureEventArgs^>(this, &ScenarioInput1::OnCompleted);
00116     EdgeGestureCanceledEventToken = edgeGesture->Canceled += ref new TypedEventHandler<EdgeGesture^, EdgeGestureEventArgs^>(this, &ScenarioInput1::OnCanceled);
00117
00118     RightClickEventToken = rootPage->RightTapped += ref new RightTappedEventHandler(this, &ScenarioInput1::OnContextMenu);
00119
00120     outputText->Text = "Sample initialized and events registered.";
00121 }
00122
00123 #pragma endregion
Generated on Sat Nov 23 2024 16:07:59 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML data binding/C++/Team.cpp Source File

  • XAML data binding

Team.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 //
00009 // Team.cpp
00010 // Implementation of the Team class
00011 //
00012
00013 #include "pch.h"
00014 #include "Team.h"
00015
00016 using namespace SDKSample::DataBinding;
00017
00018 using namespace Platform;
00019 using namespace Platform::Collections;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Globalization::NumberFormatting;
00023 using namespace Windows::UI::Xaml::Media;
00024
00025 Team::Team()
00026 {
00027   _propBag = ref new PropertySet();
00028 }
00029
00030 Teams::Teams()
00031 {
00032   _propBag = ref new PropertySet();
00033   _items = ref new Platform::Collections::Vector<Object^>();
00034
00035   auto team0 = ref new Team();
00036   team0->Name = "The Reds";
00037   team0->City = "Liverpool";
00038   team0->Color = ref new SolidColorBrush(Windows::UI::Colors::Green);
00039   this->Insert("0", team0);
00040   _items->Append(team0);
00041
00042   auto team1 = ref new Team();
00043   team1->Name = "The Red Devils";
00044   team1->City = "Manchester";
00045   team1->Color = ref new SolidColorBrush(Windows::UI::Colors::Yellow);
00046   this->Insert("1", team1);
00047   _items->Append(team1);
00048
00049   auto team2 = ref new Team();
00050   team2->Name = "The Blues";
00051   team2->City = "London";
00052   team2->Color = ref new SolidColorBrush(Windows::UI::Colors::Orange);
00053   this->Insert("2", team2);
00054   _items->Append(team2);
00055
00056   auto team3 = ref new Team();
00057   team3->Name = "The Gunners";
00058   team3->City = "London";
00059   team3->Color = ref new SolidColorBrush(Windows::UI::Colors::Red);
00060   team3->Insert("Gaffer","le Professeur");
00061   team3->Insert("Skipper","Mr Gooner");
00062   this->Insert("3", team3);
00063   _items->Append(team3);
00064 }
00065
00066 TeamGroup::TeamGroup(String^ name)
00067 {
00068   _name = name;
00069   _items = ref new Platform::Collections::Vector<Object^>();
00070 }
00071
00072 TeamDataSource::TeamDataSource()
00073 {
00074   _itemGroups = ref new Platform::Collections::Vector<Object^>();
00075
00076   auto liverpoolVector = ref new TeamGroup("Liverpool");
00077   auto manchesterVector = ref new TeamGroup("Manchester");
00078   auto londonVector = ref new TeamGroup("London");
00079
00080   auto team0 = ref new Team();
00081   team0->Name = "The Reds";
00082   team0->City = "Liverpool";
00083   team0->Color = ref new SolidColorBrush(Windows::UI::Colors::Green);
00084   liverpoolVector->Items->Append(team0);
00085
00086   auto team1 = ref new Team();
00087   team1->Name = "The Red Devils";
00088   team1->City = "Manchester";
00089   team1->Color = ref new SolidColorBrush(Windows::UI::Colors::Yellow);
00090   manchesterVector->Items->Append(team1);
00091
00092   auto team2 = ref new Team();
00093   team2->Name = "The Blues";
00094   team2->City = "London";
00095   team2->Color = ref new SolidColorBrush(Windows::UI::Colors::Orange);
00096   londonVector->Items->Append(team2);
00097
00098   auto team3 = ref new Team();
00099   team3->Name = "The Gunners";
00100   team3->City = "London";
00101   team3->Color = ref new SolidColorBrush(Windows::UI::Colors::Red);
00102   team3->Insert("Gaffer","le Professeur");
00103   team3->Insert("Skipper","Mr Gooner");
00104   londonVector->Items->Append(team3);
00105
00106   _itemGroups->Append(liverpoolVector);
00107   _itemGroups->Append(manchesterVector);
00108   _itemGroups->Append(londonVector);
00109 }
00110
00111
00112
Generated on Sat Nov 23 2024 16:08:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::BackgroundTaskSample Member List

This is the complete list of members for SDKSample::BackgroundTaskSample, including all inherited members.
RegisterBackgroundTask(String^taskEntryPoint, String^name, IBackgroundTrigger^trigger, IBackgroundCondition^condition) | SDKSample::BackgroundTaskSample | [static]
SampleBackgroundTaskWithConditionRegistered | SDKSample::BackgroundTaskSample | [static]
UnregisterBackgroundTasks(String^name) | SDKSample::BackgroundTaskSample | [static]
UpdateBackgroundTaskStatus(Platform::String^name, bool registered) | SDKSample::BackgroundTaskSample | [static]
Generated on Sat Nov 23 2024 16:09:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D bump mapping/C++/pch.h Source File

  • Direct3D bump mapping

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 <d3d11_1.h>
00012 #include <d2d1_1.h>
00013 #include <d2d1effects.h>
00014 #include <dwrite_1.h>
00015 #include <wincodec.h>
00016 #include <agile.h>
00017 #include "BasicMath.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Search contract/C++/Scenario6.xaml.h Source File

  • Search contract

Scenario6.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 // Scenario6.xaml.h
00013 // Declaration of the Scenario6 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario6.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 #pragma warning(push)
00023 #pragma warning(disable:4451) // Warns about possible invalid marshaling of objects across threads. In this case, the warning doesn't apply because the SearchPane object is only accessed from the UI thread.
00024 namespace SDKSample
00025 {
00026     namespace SearchContract
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 Scenario6 sealed
00033         {
00034         public:
00035             Scenario6();
00036
00037         protected:
00038             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00039             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00040             void AddSuggestionFromNode(Windows::Data::Xml::Dom::IXmlNode^ node, Windows::ApplicationModel::Search::SearchSuggestionCollection^ suggestions);
00041             void GetSuggestions(Windows::Data::Xml::Dom::XmlDocument^ doc, Windows::ApplicationModel::Search::SearchPaneSuggestionsRequest^ request);
00042             void OnSearchPaneSuggestionsRequested(Windows::ApplicationModel::Search::SearchPane^ sender, Windows::ApplicationModel::Search::SearchPaneSuggestionsRequestedEventArgs^ e);
00043             void OnResultSuggestionChosen(Windows::ApplicationModel::Search::SearchPane^ sender, Windows::ApplicationModel::Search::SearchPaneResultSuggestionChosenEventArgs^ e);
00044
00045         private:
00046             Windows::ApplicationModel::Search::SearchPane^ searchPane;
00047             Windows::Foundation::EventRegistrationToken suggestionsRequestedToken, resultSuggestionChosenToken;
00048             concurrency::cancellation_token_source cts;
00049         };
00050     }
00051 }
00052 #pragma warning(pop) // Reenable warning 4451
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C#,C++/MediaExtensions/Mpeg1Source/Parse.cpp Source File

  • Media extensions
  • C#,C++
  • MediaExtensions
  • Mpeg1Source

Parse.cpp

Go to the documentation of this file.
00001 //////////////////////////////////////////////////////////////////////////
00002 //
00003 // Parse.cpp
00004 // MPEG-1 parsing code.
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 #include "MPEG1Src.h"
00016 #include "Parse.h"
00017
00018 // HAS_FLAG: Test if 'b' contains a specified bit flag
00019 #define HAS_FLAG(b, flag) (((b) & (flag)) == (flag))
00020
00021 #define htonl(x)   ((((x) >> 24) & 0x000000FFL) | \
00022     (((x) >>  8) & 0x0000FF00L) | \
00023     (((x) <<  8) & 0x00FF0000L) | \
00024     (((x) << 24) & 0xFF000000L))
00025
00026 // MAKE_WORD: Convert two bytes into a WORD
00027 inline WORD MAKE_WORD(BYTE b1, BYTE b2)
00028 {
00029     return ((b1 << 8) | b2);
00030 }
00031
00032 // MAKE_DWORD_HOSTORDER:
00033 // Convert the first 4 bytes of an array into a DWORD in host order (ie, no byte swapping).
00034 inline DWORD MAKE_DWORD_HOSTORDER(const BYTE *pData)
00035 {
00036     return ((DWORD*)pData)[0];
00037 }
00038
00039 // MAKE_DWORD:
00040 // Convert the first 4 bytes of an array into a DWORD in MPEG-1 stream byte order.
00041 inline DWORD MAKE_DWORD(const BYTE *pData)
00042 {
00043     return htonl( MAKE_DWORD_HOSTORDER(pData) );
00044 }
00045
00046
00047 //-------------------------------------------------------------------
00048 // AdvanceBufferPointer
00049 // Advances a byte array pointer.
00050 //
00051 // pData: The array pointer.
00052 // cbBufferSize: The array size. On output, the size remaining.
00053 // cbAdvance: Number of bytes to advance the pointer.
00054 //
00055 // This function is just a helper for keeping a valid pointer as we
00056 // walk through a buffer.
00057 //-------------------------------------------------------------------
00058
00059 inline HRESULT AdvanceBufferPointer(const BYTE* &pData, DWORD &cbBufferSize, DWORD cbAdvance)
00060 {
00061     assert(cbBufferSize >= cbAdvance);
00062     if (cbBufferSize < cbAdvance)
00063     {
00064         return E_FAIL;
00065     }
00066     cbBufferSize -= cbAdvance;
00067     pData += cbAdvance;
00068     return S_OK;
00069 }
00070
00071 // ValidateBufferSize:
00072 // Fails if cbBufferSize < cbMinRequiredSize.
00073 inline HRESULT ValidateBufferSize(DWORD cbBufferSize, DWORD cbMinRequiredSize)
00074 {
00075     return (cbBufferSize >= cbMinRequiredSize? S_OK : E_FAIL);
00076 }
00077
00078 // Forward declarations.
00079 HRESULT ParseStreamData(const BYTE *pData, MPEG1StreamHeader& header);
00080 HRESULT ParseStreamId(BYTE id, StreamType *pType, BYTE *pStreamNum);
00081 HRESULT ParsePTS(const BYTE *pData, LONGLONG *pPTS);
00082
00083 HRESULT GetFrameRate(BYTE frameRateCode, MFRatio *pRatio);
00084 HRESULT GetPixelAspectRatio(BYTE pixelAspectCode, MFRatio *pRatio);
00085
00086 HRESULT GetAudioBitRate(MPEG1AudioLayer layer, BYTE index, DWORD *pdwBitRate);
00087 HRESULT GetSamplingFrequency(BYTE code, DWORD *pdwSamplesPerSec);
00088
00089
00090 //-------------------------------------------------------------------
00091 // Buffer class
00092 //-------------------------------------------------------------------
00093
00094
00095 Buffer::Buffer() : m_begin(0), m_end(0), m_count(0), m_allocated(0), m_pArray(NULL)
00096 {
00097 }
00098
00099
00100 //-------------------------------------------------------------------
00101 // Initalize
00102 // Sets the initial buffer size.
00103 //-------------------------------------------------------------------
00104
00105 HRESULT Buffer::Initalize(DWORD cbSize)
00106 {
00107     HRESULT hr = SetSize(cbSize);
00108     if (SUCCEEDED(hr))
00109     {
00110         ZeroMemory(Ptr(), cbSize);
00111     }
00112     return hr;
00113 }
00114
00115
00116 //-------------------------------------------------------------------
00117 // DataPtr
00118 // Returns a pointer to the start of the buffer.
00119 //-------------------------------------------------------------------
00120
00121 BYTE* Buffer::DataPtr()
00122 {
00123     return Ptr() + m_begin;
00124 }
00125
00126
00127 //-------------------------------------------------------------------
00128 // DataSize
00129 // Returns the size of the buffer.
00130 //
00131 // Note: The "size" is determined by the start and end pointers.
00132 // The memory allocated for the buffer can be larger.
00133 //-------------------------------------------------------------------
00134
00135 DWORD Buffer::DataSize() const
00136 {
00137     assert(m_end >= m_begin);
00138
00139     return m_end - m_begin;
00140 }
00141
00142 // Reserves memory for the array, but does not increase the count.
00143 HRESULT Buffer::Allocate(DWORD alloc)
00144 {
00145     HRESULT hr = S_OK;
00146     if (alloc > m_allocated)
00147     {
00148         BYTE *pTmp = new BYTE[alloc];
00149         if (pTmp)
00150         {
00151             ZeroMemory(pTmp, alloc);
00152
00153             assert(m_count <= m_allocated);
00154
00155             // Copy the elements to the re-allocated array.
00156             for (DWORD i = 0; i < m_count; i++)
00157             {
00158                 pTmp[i] = m_pArray[i];
00159             }
00160
00161             delete [] m_pArray;
00162
00163             m_pArray = pTmp;
00164             m_allocated = alloc;
00165         }
00166         else
00167         {
00168             hr = E_OUTOFMEMORY;
00169         }
00170     }
00171     return hr;
00172 }
00173
00174 // Changes the count, and grows the array if needed.
00175 HRESULT Buffer::SetSize(DWORD count)
00176 {
00177     assert (m_count <= m_allocated);
00178
00179     HRESULT hr = S_OK;
00180     if (count > m_allocated)
00181     {
00182         hr = Allocate(count);
00183     }
00184     if (SUCCEEDED(hr))
00185     {
00186         m_count = count;
00187     }
00188     return hr;
00189 }
00190
00191
00192 //-------------------------------------------------------------------
00193 // Reserve
00194 // Reserves additional bytes of memory for the buffer.
00195 //
00196 // This method does *not* increase the value returned by DataSize().
00197 //
00198 // After this method returns, the value of DataPtr() might change,
00199 // so do not cache the old value.
00200 //-------------------------------------------------------------------
00201
00202 HRESULT Buffer::Reserve(DWORD cb)
00203 {
00204     if (cb > MAXDWORD - DataSize())
00205     {
00206         return E_INVALIDARG; // Overflow
00207     }
00208
00209     HRESULT hr = S_OK;
00210
00211     // If this would push the end position past the end of the array,
00212     // then we need to copy up the data to start of the array. We might
00213     // also need to realloc the array.
00214
00215     if (cb > m_count - m_end)
00216     {
00217         // New end position would be past the end of the array.
00218         // Check if we need to grow the array.
00219
00220         if (cb > CurrentFreeSize())
00221         {
00222             // Array needs to grow
00223             hr = SetSize(DataSize() + cb);
00224         }
00225
00226         if (SUCCEEDED(hr))
00227         {
00228             MoveMemory(Ptr(), DataPtr(), DataSize());
00229
00230             // Reset begin and end.
00231             m_end = DataSize(); // Update m_end first before resetting m_begin!
00232             m_begin = 0;
00233         }
00234     }
00235
00236     assert(CurrentFreeSize() >= cb);
00237
00238     return hr;
00239 }
00240
00241
00242 //-------------------------------------------------------------------
00243 // MoveStart
00244 // Moves the start of the buffer by cb bytes.
00245 //
00246 // Call this method after consuming data from the buffer.
00247 //-------------------------------------------------------------------
00248
00249 HRESULT Buffer::MoveStart(DWORD cb)
00250 {
00251     // Cannot advance pass the end of the buffer.
00252     if (cb > DataSize())
00253     {
00254         return E_INVALIDARG;
00255     }
00256
00257     m_begin += cb;
00258     return S_OK;
00259 }
00260
00261
00262 //-------------------------------------------------------------------
00263 // MoveEnd
00264 // Moves end position of the buffer.
00265 //-------------------------------------------------------------------
00266
00267 HRESULT Buffer::MoveEnd(DWORD cb)
00268 {
00269     HRESULT hr = S_OK;
00270
00271     hr = Reserve(cb);
00272
00273     if (SUCCEEDED(hr))
00274     {
00275         m_end += cb;
00276     }
00277     return hr;
00278 }
00279
00280
00281 //-------------------------------------------------------------------
00282 // CurrentFreeSize (private)
00283 //
00284 // Returns the size of the array minus the size of the data.
00285 //-------------------------------------------------------------------
00286
00287 DWORD Buffer::CurrentFreeSize() const
00288 {
00289     assert(m_count >= DataSize());
00290     return m_count - DataSize();
00291 }
00292
00293
00294 //-------------------------------------------------------------------
00295 // Parser class
00296 //-------------------------------------------------------------------
00297
00298
00299 Parser::Parser() : m_SCR(0), m_muxRate(0), m_pHeader(NULL), m_bHasPacketHeader(FALSE), m_bEOS(FALSE)
00300 {
00301     ZeroMemory(&m_curPacketHeader, sizeof(m_curPacketHeader));
00302 }
00303
00304 Parser::~Parser()
00305 {
00306     CoTaskMemFree(m_pHeader);
00307 }
00308
00309 //-------------------------------------------------------------------
00310 // GetSystemHeader class
00311 //
00312 // Returns a copy of the system header.
00313 // Do not call this method unless HasSystemHeader() returns TRUE.
00314 //
00315 // The caller must free the returned structure by calling
00316 // CoTaskMemFree.
00317 //-------------------------------------------------------------------
00318
00319 HRESULT Parser::GetSystemHeader(MPEG1SystemHeader **ppHeader)
00320 {
00321     if (ppHeader == NULL)
00322     {
00323         return E_POINTER;
00324     }
00325
00326     if (!HasSystemHeader())
00327     {
00328         return E_FAIL;
00329     }
00330
00331     assert(m_pHeader->cbSize > 0);
00332
00333     MPEG1SystemHeader *pHeader = (MPEG1SystemHeader*)CoTaskMemAlloc(m_pHeader->cbSize);
00334     if (pHeader == NULL)
00335     {
00336         return E_OUTOFMEMORY;
00337     }
00338
00339     CopyMemory(pHeader, m_pHeader, m_pHeader->cbSize);
00340
00341     *ppHeader = pHeader;
00342     return S_OK;
00343 }
00344
00345
00346 //-------------------------------------------------------------------
00347 // ParseBytes
00348 // Parses as much data as possible from the pData buffer, and returns
00349 // the amount of data parsed in pAte (*pAte <= cbLen).
00350 //
00351 // Return values:
00352 //      S_OK: The method consumed some data (*pAte > 0).
00353 //      S_FALSE: The method did not consume any data (*pAte == 0).
00354 //      [or an error code]
00355 //
00356 // If the method returns S_FALSE, the caller must allocate a larger
00357 // buffer and pass in more data.
00358 //-------------------------------------------------------------------
00359
00360 HRESULT Parser::ParseBytes(const BYTE *pData, DWORD cbLen, DWORD *pAte)
00361 {
00362     *pAte = 0;
00363
00364     if (cbLen < 4)
00365     {
00366         return S_FALSE;
00367     }
00368
00369     HRESULT hr = S_OK;
00370     DWORD cbLengthToStartCode = 0;  // How much we skip to reach the next start code.
00371     DWORD cbParsed = 0;             // How much we parse after the start code.
00372
00373     m_bHasPacketHeader = FALSE;
00374
00375     hr = FindNextStartCode(pData, cbLen, &cbLengthToStartCode);
00376
00377     if (hr == S_OK)
00378     {
00379         cbLen -= cbLengthToStartCode;
00380         pData += cbLengthToStartCode;
00381
00382         switch (MAKE_DWORD(pData))
00383         {
00384         case MPEG1_PACK_START_CODE:
00385             // Start of pack.
00386             hr = ParsePackHeader(pData, cbLen, &cbParsed);
00387             break;
00388
00389         case MPEG1_SYSTEM_HEADER_CODE:
00390             // Start of system header.
00391             hr = ParseSystemHeader(pData, cbLen, &cbParsed);
00392             break;
00393
00394         case MPEG1_STOP_CODE:
00395             // Stop code, end of stream.
00396             cbParsed = sizeof(DWORD);
00397             hr = OnEndOfStream();
00398             break;
00399
00400         default:
00401             // Start of packet.
00402             hr = ParsePacketHeader(pData, cbLen, &cbParsed);
00403             break;
00404
00405         }
00406     }
00407
00408     if (hr == S_OK)
00409     {
00410         *pAte = cbLengthToStartCode + cbParsed;
00411     }
00412     return hr;
00413 };
00414
00415
00416 //-------------------------------------------------------------------
00417 // FindNextStartCode
00418 // Looks for the next start code in the buffer.
00419 //
00420 // pData: Pointer to the buffer.
00421 // cbLen: Size of the buffer.
00422 // pAte: Receives the number of bytes *before* the start code.
00423 //
00424 // If no start code is found, the method returns S_FALSE.
00425 //-------------------------------------------------------------------
00426
00427 HRESULT Parser::FindNextStartCode(const BYTE *pData, DWORD cbLen, DWORD *pAte)
00428 {
00429     HRESULT hr = S_FALSE;
00430
00431     DWORD cbLeft = cbLen;
00432
00433     while (cbLeft > 4)
00434     {
00435         if ( (MAKE_DWORD_HOSTORDER(pData) & 0x00FFFFFF) == 0x00010000 )
00436         {
00437             hr = S_OK;
00438             break;
00439         }
00440
00441         cbLeft -= 4;
00442         pData += 4;
00443     }
00444     *pAte = (cbLen - cbLeft);
00445     return hr;
00446 }
00447
00448
00449 //-------------------------------------------------------------------
00450 // ParsePackHeader
00451 // Parses the start of an MPEG-1 pack.
00452 //-------------------------------------------------------------------
00453
00454 HRESULT Parser::ParsePackHeader(const BYTE *pData, DWORD cbLen, DWORD *pAte)
00455 {
00456     assert( MAKE_DWORD(pData) == MPEG1_PACK_START_CODE );
00457
00458     if (cbLen < MPEG1_PACK_HEADER_SIZE)
00459     {
00460         return S_FALSE; // Not enough data yet.
00461     }
00462
00463     // Check marker bits
00464     if ( ((pData[4] & 0xF1) != 0x21) ||
00465         ((pData[6] & 0x01) != 0x01) ||
00466         ((pData[8] & 0x01) != 0x01) ||
00467         ((pData[9] & 0x80) != 0x80) ||
00468         ((pData[11] & 0x01) != 0x01) )
00469     {
00470         return E_FAIL;
00471     }
00472
00473
00474     // Calculate the SCR.
00475     LONGLONG scr = ( (pData[8] & 0xFE) >> 1) |
00476         ( (pData[7]) << 7) |
00477         ( (pData[6] & 0xFE) << 14) |
00478         ( (pData[5]) << 22) |
00479         ( (pData[4] & 0x0E) << 29);
00480
00481     DWORD muxRate = ( (pData[11] & 0xFE) >> 1) |
00482         ( (pData[10]) << 7) |
00483         ( (pData[9] & 0x7F) << 15);
00484
00485
00486     m_SCR = scr;
00487     m_muxRate = muxRate;
00488
00489     *pAte = MPEG1_PACK_HEADER_SIZE;
00490
00491     return S_OK;
00492 }
00493
00494
00495 //-------------------------------------------------------------------
00496 // ParseSystemHeader.
00497 // Parses the MPEG-1 system header.
00498 //
00499 // NOTES:
00500 // The system header optionally appears after the pack header.
00501 // The first pack must contain a system header.
00502 // Subsequent packs may contain a system header.
00503 //-------------------------------------------------------------------
00504
00505 HRESULT Parser::ParseSystemHeader(const BYTE *pData, DWORD cbLen, DWORD *pAte)
00506 {
00507     assert( MAKE_DWORD(pData) == MPEG1_SYSTEM_HEADER_CODE );
00508
00509     if (cbLen < MPEG1_SYSTEM_HEADER_MIN_SIZE)
00510     {
00511         return S_FALSE; // Not enough data yet.
00512     }
00513
00514     // Find the total header length.
00515     DWORD cbHeaderLen = MPEG1_SYSTEM_HEADER_PREFIX +  MAKE_WORD(pData[4], pData[5]);
00516
00517     if (cbHeaderLen < MPEG1_SYSTEM_HEADER_MIN_SIZE - MPEG1_SYSTEM_HEADER_PREFIX)
00518     {
00519         return E_FAIL;  // Invalid value.
00520     }
00521
00522     if (cbLen < cbHeaderLen)
00523     {
00524         return S_FALSE; // Not enough data yet.
00525     }
00526
00527     // We have enough data to parse the header.
00528
00529     HRESULT hr = S_OK;
00530
00531     // Did we already see a system header?
00532     if (!HasSystemHeader())
00533     {
00534         // This is the first time we've seen the header. Parse it.
00535
00536         // Calculate the number of stream info's in the header.
00537         DWORD cStreamInfo = (cbHeaderLen - MPEG1_SYSTEM_HEADER_MIN_SIZE) / MPEG1_SYSTEM_HEADER_STREAM;
00538
00539         // Calculate the structure size.
00540         DWORD cbSize = sizeof(MPEG1SystemHeader);
00541         if (cStreamInfo > 1)
00542         {
00543             cbSize += sizeof(MPEG1StreamHeader) * (cStreamInfo - 1);
00544         }
00545
00546         // Allocate room for the header.
00547         m_pHeader = (MPEG1SystemHeader*)CoTaskMemAlloc(cbSize);
00548         if (m_pHeader == NULL)
00549         {
00550             hr = E_OUTOFMEMORY;
00551         }
00552
00553         if (SUCCEEDED(hr))
00554         {
00555             m_pHeader->cbSize = cbSize;
00556         }
00557
00558         // Check marker bits
00559         if (SUCCEEDED(hr))
00560         {
00561             if ( ((pData[6] & 0x80) != 0x80) ||
00562                 ((pData[8] & 0x01) != 0x01) ||
00563                 ((pData[10] & 0x20) != 0x20) ||
00564                 (pData[11] != 0xFF) )
00565             {
00566                 hr = E_FAIL;  // Invalid bits.
00567             }
00568         }
00569
00570         if (SUCCEEDED(hr))
00571         {
00572             m_pHeader->rateBound = ((pData[6] & 0x7F) << 16) | (pData[7] << 8) | (pData[8] >> 1);
00573             m_pHeader->cAudioBound = pData[9] >> 2;
00574             m_pHeader->bFixed = HAS_FLAG(pData[9], 0x02);
00575             m_pHeader->bCSPS = HAS_FLAG(pData[9], 0x01);
00576             m_pHeader->bAudioLock = HAS_FLAG(pData[10], 0x80);
00577             m_pHeader->bVideoLock = HAS_FLAG(pData[10], 0x40);
00578             m_pHeader->cVideoBound = pData[10] & 0x1F;
00579             m_pHeader->cStreams = cStreamInfo;
00580
00581             // Parse the stream information.
00582             const BYTE *pStreamInfo = pData + MPEG1_SYSTEM_HEADER_MIN_SIZE;
00583
00584             for (DWORD i = 0; i < cStreamInfo; i++)
00585             {
00586                 hr = ParseStreamData(pStreamInfo, m_pHeader->streams[i]);
00587
00588                 if (FAILED(hr))
00589                 {
00590                     break;
00591                 }
00592
00593                 pStreamInfo += MPEG1_SYSTEM_HEADER_STREAM;
00594             }
00595         }
00596     }
00597
00598     if (SUCCEEDED(hr))
00599     {
00600         *pAte = cbHeaderLen;
00601     }
00602
00603     if (FAILED(hr))
00604     {
00605         CoTaskMemFree(m_pHeader);
00606         m_pHeader = NULL;
00607     }
00608
00609     return hr;
00610 }
00611
00612 //-------------------------------------------------------------------
00613 // ParsePacketHeader
00614 //
00615 // Parses the packet header.
00616 //
00617 // If the method returns S_OK, then HasPacket() returns TRUE and the
00618 // caller can start parsing the packet.
00619 //-------------------------------------------------------------------
00620
00621 HRESULT Parser::ParsePacketHeader(const BYTE *pData, DWORD cbLen, DWORD *pAte)
00622 {
00623     if (!HasSystemHeader())
00624     {
00625         return E_FAIL; // We should not get a packet before the first system header.
00626     }
00627
00628     if (cbLen < MPEG1_PACKET_HEADER_MIN_SIZE)
00629     {
00630         return S_FALSE; // Not enough data yet.
00631     }
00632
00633     // Before we parse anything else in the packet header, look for the header length.
00634     DWORD cbPacketLen = MAKE_WORD(pData[4], pData[5]) + MPEG1_PACKET_HEADER_MIN_SIZE;
00635
00636     // We want enough data for the maximum packet header OR the total packet size, whichever is less.
00637     if (cbLen < cbPacketLen && cbLen < MPEG1_PACKET_HEADER_MAX_SIZE)
00638     {
00639         return S_FALSE; // Not enough data yet.
00640     }
00641
00642     // Make sure the start code is 0x000001xx
00643     if ((MAKE_DWORD(pData) & 0xFFFFFF00) != MPEG1_START_CODE_PREFIX)
00644     {
00645         return E_FAIL;
00646     }
00647
00648     HRESULT hr = S_OK;
00649     BYTE id = 0;
00650     StreamType type = StreamType_Unknown;
00651     BYTE num = 0;
00652     BOOL bHasPTS = FALSE;
00653
00654     ZeroMemory(&m_curPacketHeader, sizeof(m_curPacketHeader));
00655
00656     // Find the stream ID.
00657     id = pData[3];
00658     hr = ParseStreamId(id, &type, &num);
00659     if (FAILED(hr))
00660     {
00661         return hr;
00662     }
00663
00664
00665     DWORD cbLeft = cbPacketLen - MPEG1_PACKET_HEADER_MIN_SIZE;
00666     pData = pData + MPEG1_PACKET_HEADER_MIN_SIZE;
00667     DWORD cbPadding = 0;
00668     LONGLONG pts = 0;
00669
00670     // Go past the stuffing bytes.
00671     while ((cbLeft > 0) && (*pData == 0xFF))
00672     {
00673         AdvanceBufferPointer(pData, cbLeft, 1);
00674         ++cbPadding;
00675     }
00676
00677     // Check for invalid number of stuffing bytes.
00678     if (cbPadding > MPEG1_PACKET_HEADER_MAX_STUFFING_BYTE)
00679     {
00680         hr = E_FAIL;
00681     }
00682
00683     // The next bits are:
00684     // (optional) STD buffer size (2 bytes)
00685     // union
00686     // {
00687     //      PTS (5 bytes)
00688     //      PTS + DTS (10 bytes)
00689     //      '0000 1111' (1 bytes)
00690     // }
00691
00692     if (SUCCEEDED(hr))
00693     {
00694         hr = ValidateBufferSize(cbLeft, 1);
00695     }
00696
00697     if (SUCCEEDED(hr))
00698     {
00699         if ((*pData & 0xC0) == 0x40)
00700         {
00701             // Skip STD buffer size.
00702             hr = AdvanceBufferPointer(pData, cbLeft, 2);
00703         }
00704     }
00705
00706     if (SUCCEEDED(hr))
00707     {
00708         hr = ValidateBufferSize(cbLeft, 1);
00709     }
00710
00711     if (SUCCEEDED(hr))
00712     {
00713         if ((*pData & 0xF1) == 0x21)
00714         {
00715             // PTS
00716             hr = ValidateBufferSize(cbLeft, 5);
00717
00718             if (SUCCEEDED(hr))
00719             {
00720                 ParsePTS(pData, &pts);
00721                 bHasPTS = TRUE;
00722
00723                 hr = AdvanceBufferPointer(pData, cbLeft, 5);
00724             }
00725         }
00726         else if ((*pData & 0xF1) == 0x31)
00727         {
00728             // PTS + DTS
00729             hr = ValidateBufferSize(cbLeft, 10);
00730
00731             // Parse PTS but skip DTS.
00732             if (SUCCEEDED(hr))
00733             {
00734                 ParsePTS(pData, &pts);
00735                 bHasPTS = TRUE;
00736
00737                 hr = AdvanceBufferPointer(pData, cbLeft, 10);
00738             }
00739         }
00740         else if ((*pData) == 0x0F)
00741         {
00742             hr = AdvanceBufferPointer(pData, cbLeft, 1);
00743         }
00744         else
00745         {
00746             hr = E_FAIL; // Unexpected bit field
00747         }
00748     }
00749
00750     if (SUCCEEDED(hr))
00751     {
00752         m_curPacketHeader.stream_id = id;
00753         m_curPacketHeader.type = type;
00754         m_curPacketHeader.number = num;
00755         m_curPacketHeader.cbPacketSize = cbPacketLen;
00756         m_curPacketHeader.cbPayload = cbLeft;
00757         m_curPacketHeader.bHasPTS = bHasPTS;
00758         m_curPacketHeader.PTS = pts;
00759
00760         // Client can read the packet now.
00761         m_bHasPacketHeader = TRUE;
00762
00763         *pAte = cbPacketLen - cbLeft;
00764     }
00765
00766     return hr;
00767 }
00768
00769 //-------------------------------------------------------------------
00770 // OnEndOfStream
00771 // Called when the parser reaches the MPEG-1 stop code.
00772 //
00773 // Note: Obviously the parser is not guaranteed to see a stop code
00774 // before the client reaches the end of the source data. The client
00775 // must be prepared to handle that case.
00776 //-------------------------------------------------------------------
00777
00778 HRESULT Parser::OnEndOfStream()
00779 {
00780     m_bEOS = TRUE;
00781     ClearPacket();
00782
00783     return S_OK;
00784 }
00785
00786
00787 //-------------------------------------------------------------------
00788 // Static functions
00789 //-------------------------------------------------------------------
00790
00791
00792 //-------------------------------------------------------------------
00793 // ParsePTS
00794 // Parse the 33-bit Presentation Time Stamp (PTS)
00795 //-------------------------------------------------------------------
00796
00797 HRESULT ParsePTS(const BYTE *pData, LONGLONG *pPTS)
00798 {
00799     BYTE byte1 = pData[0];
00800     WORD word1 = MAKE_WORD(pData[1], pData[2]);
00801     WORD word2 = MAKE_WORD(pData[3], pData[4]);
00802
00803     // Check marker bits.
00804     // The first byte can be '0010xxx1' or '0x11xxxx1'
00805     if (((byte1 & 0xE1) != 0x21) ||
00806         ((word1 & 0x01) != 0x01) ||
00807         ((word2 & 0x01) != 0x01) )
00808     {
00809         return E_FAIL;
00810     }
00811
00812     LARGE_INTEGER li;
00813
00814     // The PTS is 33 bits, so bit 32 goes in the high-order DWORD
00815     li.HighPart = (byte1 & 0x08) >> 3;
00816
00817     li.LowPart = (static_cast<DWORD>(byte1 & 0x06) << 29) |
00818         (static_cast<DWORD>(word1 & 0xFFFE) << 14) |
00819         (static_cast<DWORD>(word2) >> 1);
00820
00821     *pPTS = li.QuadPart;
00822     return S_OK;
00823 }
00824
00825
00826 //-------------------------------------------------------------------
00827 // ParseStreamData
00828 // Parses the stream information (for one stream) in the system
00829 // header.
00830 //-------------------------------------------------------------------
00831
00832 HRESULT ParseStreamData(const BYTE *pStreamInfo, MPEG1StreamHeader& header)
00833 {
00834     // Check marker bits.
00835     if ( (pStreamInfo[1] & 0xC0) != 0xC0 )
00836     {
00837         return E_FAIL; // Invalid bits
00838     }
00839
00840     HRESULT hr = S_OK;
00841     BYTE id = 0;
00842     BYTE num = 0;
00843     DWORD bound = 0;
00844     StreamType type = StreamType_Unknown;
00845
00846     // The id is a stream code plus (for some types) a stream number, bitwise-OR'd.
00847
00848     id = pStreamInfo[0];
00849
00850     hr = ParseStreamId(id, &type, &num);
00851     if (FAILED(hr))
00852     {
00853         return hr;
00854     }
00855
00856     // Calculate STD bound.
00857     bound = pStreamInfo[2] | ((pStreamInfo[1] & 0x1F) << 8);
00858
00859     if (pStreamInfo[1] & 0x20)
00860     {
00861         bound *= 1024;
00862     }
00863     else
00864     {
00865         bound *= 128;
00866     }
00867
00868     header.stream_id = id;
00869     header.type = type;
00870     header.number = num;
00871     header.sizeBound = bound;
00872
00873     return S_OK;
00874 }
00875
00876
00877
00878 //-------------------------------------------------------------------
00879 // ParseStreamId
00880 // Parses an MPEG-1 stream ID.
00881 //
00882 // Note:
00883 // The id is a stream code, plus (for some types) a stream number,
00884 // bitwise-OR'd. This function returns the type and the stream number.
00885 //
00886 // See ISO/EIC 11172-1, sec 2.4.4.2
00887 //-------------------------------------------------------------------
00888
00889 HRESULT ParseStreamId(BYTE id, StreamType *pType, BYTE *pStreamNum)
00890 {
00891     StreamType type = StreamType_Unknown;
00892     BYTE num = 0;
00893
00894     switch (id)
00895     {
00896     case MPEG1_STREAMTYPE_ALL_AUDIO:
00897         type = StreamType_AllAudio;
00898         break;
00899
00900     case MPEG1_STREAMTYPE_ALL_VIDEO:
00901         type = StreamType_AllVideo;
00902         break;
00903
00904     case MPEG1_STREAMTYPE_RESERVED:
00905         type = StreamType_Reserved;
00906         break;
00907
00908     case MPEG1_STREAMTYPE_PRIVATE1:
00909         type = StreamType_Private1;
00910         break;
00911
00912     case MPEG1_STREAMTYPE_PADDING:
00913         type = StreamType_Padding;
00914         break;
00915
00916     case MPEG1_STREAMTYPE_PRIVATE2:
00917         type = StreamType_Private2;
00918         break;
00919
00920     default:
00921         if ((id & 0xE0) == MPEG1_STREAMTYPE_AUDIO_MASK)
00922         {
00923             type = StreamType_Audio;
00924             num = id & 0x1F;
00925         }
00926         else if ((id & 0xF0) == MPEG1_STREAMTYPE_VIDEO_MASK)
00927         {
00928             type = StreamType_Video;
00929             num = id & 0x0F;
00930         }
00931         else if ((id & 0xF0) == MPEG1_STREAMTYPE_DATA_MASK)
00932         {
00933             type = StreamType_Data;
00934             num = id & 0x0F;
00935         }
00936         else
00937         {
00938             return E_FAIL; // Unknown stream ID code.
00939         }
00940     }
00941
00942     *pType = type;
00943     *pStreamNum = num;
00944     return S_OK;
00945 }
00946
00947
00948 //-------------------------------------------------------------------
00949 // ReadVideoSequenceHeader
00950 // Parses a video sequence header.
00951 //
00952 // Call Parser::HasPacket() to ensure that pData points to the start
00953 // of a payload, and call Parser::PacketHeader() to verify it is a
00954 // video packet.
00955 //-------------------------------------------------------------------
00956
00957 HRESULT ReadVideoSequenceHeader(
00958     _In_reads_bytes_(cbData) const BYTE *pData,
00959     DWORD cbData,
00960     MPEG1VideoSeqHeader& seqHeader,
00961     _Out_ DWORD *pAte
00962     )
00963 {
00964     DWORD cbPadding = 0;
00965
00966     if (pAte == nullptr || pData == nullptr)
00967     {
00968         return E_INVALIDARG;
00969     }
00970
00971     *pAte = 0;
00972
00973     // Skip to the sequence header code.
00974     while ( (cbPadding + 4) <= cbData && ((DWORD*)pData)[0] == 0 )
00975     {
00976         pData += 4;
00977         cbPadding += 4;
00978     }
00979
00980     cbData -= cbPadding;
00981
00982     // Check for the minimum size buffer.
00983     if (cbData < MPEG1_VIDEO_SEQ_HEADER_MIN_SIZE)
00984     {
00985         *pAte = cbPadding;
00986         return S_FALSE;
00987     }
00988
00989     // Validate the sequence header code.
00990     if (MAKE_DWORD(pData) != MPEG1_SEQUENCE_HEADER_CODE)
00991     {
00992         return E_FAIL;
00993     }
00994
00995     // Calculate the actual required size.
00996     DWORD cbRequired = MPEG1_VIDEO_SEQ_HEADER_MIN_SIZE;
00997
00998     // Look for quantization matrices.
00999     if ( HAS_FLAG(pData[11], 0x02) )
01000     {
01001         // Intra quantization matrix is TRUE.
01002         cbRequired += 64;
01003     }
01004     // Intra is FALSE, look for non-intra flag
01005     else if ( HAS_FLAG(pData[11], 0x01) )
01006     {
01007         cbRequired += 64;
01008     }
01009
01010     if (cbData < cbRequired)
01011     {
01012         return S_FALSE;
01013     }
01014
01015     ZeroMemory(&seqHeader, sizeof(seqHeader));
01016
01017     // Check the marker bit.
01018     if ( !HAS_FLAG(pData[10], 0x20) )
01019     {
01020         return E_FAIL;
01021     }
01022
01023     BYTE parCode = pData[7] >> 4;
01024     BYTE frameRateCode = pData[7] & 0x0F;
01025
01026     if (FAILED(GetPixelAspectRatio(parCode, &seqHeader.pixelAspectRatio)))
01027     {
01028         return E_FAIL;
01029     }
01030
01031     if (FAILED(GetFrameRate(frameRateCode, &seqHeader.frameRate)))
01032     {
01033         return E_FAIL;
01034     }
01035
01036     seqHeader.width = (pData[4] << 4) | (pData[5] >> 4) ;
01037     seqHeader.height = ((pData[5] & 0x0F) << 8) | (pData[6]);
01038     seqHeader.bitRate = (pData[8] << 10) | (pData[9] << 2) | (pData[10] >> 6);
01039
01040     if (seqHeader.bitRate == 0)
01041     {
01042         return E_FAIL;  // Not allowed.
01043     }
01044     else if (seqHeader.bitRate == 0x3FFFF)
01045     {
01046         seqHeader.bitRate = 0; // Variable bit-rate.
01047     }
01048     else
01049     {
01050         seqHeader.bitRate = seqHeader.bitRate * 400; // Units of 400 bps
01051     }
01052
01053     seqHeader.cbVBV_Buffer = ( ((pData[10] & 0x1F) << 5) | (pData[11] >> 3) ) * 2048;
01054     seqHeader.bConstrained = HAS_FLAG(pData[11], 0x04);
01055
01056     seqHeader.cbHeader = cbRequired;
01057     CopyMemory(seqHeader.header, pData, cbRequired);
01058
01059     *pAte = cbRequired + cbPadding;
01060
01061     return S_OK;
01062 }
01063
01064
01065
01066 //-------------------------------------------------------------------
01067 // GetFrameRate
01068 // Returns the frame rate from the picture_rate field of the sequence
01069 // header.
01070 //
01071 // See ISO/IEC 11172-2, 2.4.3.2 "Sequence Header"
01072 //-------------------------------------------------------------------
01073
01074 HRESULT GetFrameRate(BYTE frameRateCode, MFRatio *pRatio)
01075 {
01076     MFRatio frameRates[] =
01077     {
01078         { 0, 0 },           // invalid
01079         { 24000, 1001 },    // 23.976 fps
01080         { 24, 1 },
01081         { 25, 1 },
01082         { 30000, 1001 },    // 29.97 fps
01083         { 50, 1 },
01084         { 60000, 1001 },    // 59.94 fps
01085         { 60, 1 }
01086     };
01087
01088     if (frameRateCode < 1 || frameRateCode >= ARRAYSIZE(frameRates))
01089     {
01090         return MF_E_INVALIDTYPE;
01091     }
01092
01093     pRatio->Numerator = frameRates[frameRateCode].Numerator;
01094     pRatio->Denominator = frameRates[frameRateCode].Denominator;
01095
01096     return S_OK;
01097 }
01098
01099 //-------------------------------------------------------------------
01100 // GetPixelAspectRatio
01101 // Returns the pixel aspect ratio (PAR) from the pel_aspect_ratio
01102 // field of the sequence header.
01103 //
01104 // See ISO/IEC 11172-2, 2.4.3.2 "Sequence Header"
01105 //-------------------------------------------------------------------
01106
01107 HRESULT GetPixelAspectRatio(BYTE pixelAspectCode, MFRatio *pRatio)
01108 {
01109     DWORD height[] = { 0, 10000, 6735, 7031, 7615, 8055, 8437, 8935, 9157,
01110         9815, 10255, 10695, 10950, 11575, 12015 };
01111
01112     const DWORD width = 10000;
01113
01114     if (pixelAspectCode < 1 || pixelAspectCode >= ARRAYSIZE(height))
01115     {
01116         return MF_E_INVALIDTYPE;
01117     }
01118
01119     pRatio->Numerator = height[pixelAspectCode];
01120     pRatio->Denominator = width;
01121
01122     return S_OK;
01123
01124 }
01125
01126
01127 //-------------------------------------------------------------------
01128 // ReadAudioFrameHeader
01129 // Parses an audio frame header.
01130 //
01131 // Call Parser::HasPacket() to ensure that pData points to the start
01132 // of a payload, and call Parser::PacketHeader() to verify it is an
01133 // audio packet.
01134 //-------------------------------------------------------------------
01135
01136 HRESULT ReadAudioFrameHeader(
01137     const BYTE *pData,
01138     DWORD cbData,
01139     MPEG1AudioFrameHeader& audioHeader,
01140     DWORD *pAte
01141     )
01142 {
01143     HRESULT hr = S_OK;
01144     MPEG1AudioFrameHeader header;
01145     ZeroMemory(&header, sizeof(header));
01146
01147     BYTE bitRateIndex = 0;
01148     BYTE samplingIndex = 0;
01149
01150     *pAte = 0;
01151
01152     if (cbData < MPEG1_AUDIO_FRAME_HEADER_SIZE)
01153     {
01154         return S_FALSE;
01155     }
01156
01157
01158     if (pData[0] != 0xFF)
01159     {
01160         return E_FAIL;
01161     }
01162
01163     if (!HAS_FLAG(pData[1], 0xF8))
01164     {
01165         return E_FAIL;
01166     }
01167
01168     // Layer bits
01169     switch (pData[1] & 0x06)
01170     {
01171     case 0x00:
01172         return E_FAIL;
01173
01174     case 0x06:
01175         header.layer = MPEG1_Audio_Layer1;
01176         break;
01177
01178     case 0x04:
01179         header.layer = MPEG1_Audio_Layer2;
01180         break;
01181
01182     case 0x02:
01183         header.layer = MPEG1_Audio_Layer3;
01184         break;
01185
01186     default:
01187         return E_UNEXPECTED; // Cannot actually happen, given our bitmask above.
01188     }
01189
01190     bitRateIndex = (pData[2] & 0xF0) >> 4;
01191     samplingIndex = (pData[2] & 0x0C) >> 2;
01192
01193     // Bit rate.
01194     // Note: Accoring to ISO/IEC 11172-3, some combinations of bitrate and
01195     // mode are not valid. However, this is up to the decoder to validate.
01196     hr = GetAudioBitRate(header.layer, bitRateIndex, &header.dwBitRate);
01197
01198     // Sampling frequency.
01199     if (SUCCEEDED(hr))
01200     {
01201         hr = GetSamplingFrequency(samplingIndex, &header.dwSamplesPerSec);
01202     }
01203
01204     if (SUCCEEDED(hr))
01205     {
01206         header.mode = static_cast<MPEG1AudioMode>((pData[3] & 0xC0) >> 6);
01207         header.modeExtension = (pData[3] & 0x30) >> 4;
01208         header.emphasis = (pData[3] & 0x03);
01209
01210         // Parse the various bit flags.
01211         if (HAS_FLAG(pData[1], 0x01))
01212         {
01213             header.wFlags |= MPEG1_AUDIO_PROTECTION_BIT;
01214         }
01215         if (HAS_FLAG(pData[2], 0x01))
01216         {
01217             header.wFlags |= MPEG1_AUDIO_PRIVATE_BIT;
01218         }
01219         if (HAS_FLAG(pData[3], 0x08))
01220         {
01221             header.wFlags |= MPEG1_AUDIO_COPYRIGHT_BIT;
01222         }
01223         if (HAS_FLAG(pData[3], 0x04))
01224         {
01225             header.wFlags |= MPEG1_AUDIO_ORIGINAL_BIT;
01226         }
01227
01228         if (header.mode == MPEG1_Audio_SingleChannel)
01229         {
01230             header.nChannels = 1;
01231         }
01232         else
01233         {
01234             header.nChannels = 2;
01235         }
01236
01237         header.nBlockAlign = 1;
01238
01239         CopyMemory(&audioHeader, &header, sizeof(audioHeader));
01240     }
01241
01242     return  hr;
01243
01244 };
01245
01246
01247 //-------------------------------------------------------------------
01248 // GetAudioBitRate
01249 // Returns the audio bit rate in KBits per second, from the
01250 // bitrate_index field of the audio frame header.
01251 //
01252 // See ISO/IEC 11172-3, 2.4.2.3, "Header"
01253 //-------------------------------------------------------------------
01254
01255 HRESULT GetAudioBitRate(MPEG1AudioLayer layer, BYTE index, DWORD *pdwBitRate)
01256 {
01257     const DWORD MAX_BITRATE_INDEX = 14;
01258
01259     // Table of bit rates.
01260     const DWORD bitrate[3][ (MAX_BITRATE_INDEX+1) ] =
01261     {
01262         { 0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448 },    // Layer I
01263         { 0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384 },       // Layer II
01264         { 0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320 }         // Layer III
01265     };
01266
01267     if (layer < MPEG1_Audio_Layer1 || layer > MPEG1_Audio_Layer3)
01268     {
01269         return E_INVALIDARG;
01270     }
01271     if (index > MAX_BITRATE_INDEX)
01272     {
01273         return E_INVALIDARG;
01274     }
01275
01276     *pdwBitRate = bitrate[layer][index];
01277
01278     return S_OK;
01279 }
01280
01281 //-------------------------------------------------------------------
01282 // GetSamplingFrequency
01283 // Returns the sampling frequency in samples per second, from the
01284 // sampling_frequency field of the audio frame header.
01285 //
01286 // See ISO/IEC 11172-3, 2.4.2.3, "Header"
01287 //-------------------------------------------------------------------
01288
01289 inline HRESULT GetSamplingFrequency(BYTE code, DWORD *pdwSamplesPerSec)
01290 {
01291     switch (code)
01292     {
01293     case 0:
01294         *pdwSamplesPerSec = 44100;
01295         break;
01296     case 1:
01297         *pdwSamplesPerSec = 48000;
01298         break;
01299     case 2:
01300         *pdwSamplesPerSec = 32000;
01301         break;
01302     default:
01303         return E_FAIL;
01304     }
01305     return S_OK;
01306 }
01307
Generated on Sat Nov 23 2024 16:08:21 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Sharing content source app/C++/common/LayoutAwarePage.cpp Source File

  • Sharing content source app
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:32 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Device enumeration/C++/MainPage.xaml.h Source File

  • Device enumeration

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:46 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::TileContent::TileSquareText01 Member List

This is the complete list of members for NotificationsExtensions::TileContent::TileSquareText01, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
Branding | NotificationsExtensions::TileContent::TileNotificationBase |
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
NotificationsExtensions::GetContent() | NotificationsExtensions::TileContent::TileSquareBase | [inline]
NotificationsExtensions::GetContent() | NotificationsExtensions::TileContent::TileSquareBase | [inline]
NotificationsExtensions::TileContent::TileNotificationBase::GetContent() | NotificationsExtensions::NotificationBase | [pure virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeBinding(string globalLang, string globalBaseUri, TileBranding globalBranding, bool globalAddImageQuery) | NotificationsExtensions::TileContent::TileSquareBase | [inline]
SerializeBinding(string globalLang, string globalBaseUri, TileBranding globalBranding, bool globalAddImageQuery) | NotificationsExtensions::TileContent::TileSquareBase | [inline]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextBody1 | NotificationsExtensions::TileContent::TileSquareText01 |
TextBody2 | NotificationsExtensions::TileContent::TileSquareText01 |
TextBody3 | NotificationsExtensions::TileContent::TileSquareText01 |
TextFields | NotificationsExtensions::NotificationBase |
TextHeading | NotificationsExtensions::TileContent::TileSquareText01 |
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileSquareBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileSquareBase | [inline]
TileSquareBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileSquareBase | [inline]
TileSquareText01() | NotificationsExtensions::TileContent::TileSquareText01 | [inline]
TileSquareText01() | NotificationsExtensions::TileContent::TileSquareText01 | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:43 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Custom driver access/C++/app_cpp/pch.cpp Source File

  • Custom driver access
  • app_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 Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/DirectXBase.cpp Source File

  • XAML DirectX 3D shooting game

DirectXBase.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 "DirectXBase.h"
00010 #include "windows.ui.xaml.media.dxinterop.h"
00011
00012 using namespace Windows::UI::Core;
00013 using namespace Windows::Foundation;
00014 using namespace Microsoft::WRL;
00015 using namespace Windows::Graphics::Display;
00016 using namespace Windows::UI::Xaml::Controls;
00017 using namespace D2D1;
00018 using namespace DirectX;
00019
00020 // Constructor.
00021 DirectXBase::DirectXBase() :
00022     m_dpi(-1.0f)
00023 {
00024 }
00025
00026 // Initialize the DirectX resources required to run.
00027 void DirectXBase::Initialize(
00028     CoreWindow^ window,
00029     SwapChainBackgroundPanel^ swapChainPanel,
00030     float dpi
00031     )
00032 {
00033     m_window = window;
00034     m_swapChainPanel = swapChainPanel;
00035
00036     CreateDeviceIndependentResources();
00037     CreateDeviceResources();
00038     SetDpi(dpi);
00039
00040     DisplayProperties::StereoEnabledChanged +=
00041         ref new DisplayPropertiesEventHandler(this, &DirectXBase::OnStereoEnabledChanged);
00042 }
00043
00044 // Recreate all device resources and set them back to the current state.
00045 void DirectXBase::HandleDeviceLost()
00046 {
00047     float dpi = m_dpi;
00048     m_dpi = -1.0f;
00049     m_windowBounds.Width = 0;
00050     m_windowBounds.Height = 0;
00051     m_swapChain = nullptr;
00052
00053     // Make sure the rendering state has been released.
00054     m_d3dContext->OMSetRenderTargets(0, nullptr, nullptr);
00055     m_d3dDepthStencilView = nullptr;
00056     m_d3dRenderTargetView = nullptr;
00057     m_d3dRenderTargetViewRight = nullptr;
00058
00059     m_d2dContext->SetTarget(nullptr);
00060     m_d2dTargetBitmap = nullptr;
00061     m_d2dTargetBitmapRight = nullptr;
00062     m_d2dContext = nullptr;
00063     m_d2dDevice = nullptr;
00064
00065     m_d3dContext->Flush();
00066
00067     CreateDeviceResources();
00068     SetDpi(dpi);
00069 }
00070
00071 // These are the resources required independent of the device.
00072 void DirectXBase::CreateDeviceIndependentResources()
00073 {
00074     D2D1_FACTORY_OPTIONS options;
00075     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00076
00077 #if defined(_DEBUG)
00078     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00079     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00080 #endif
00081
00082     DX::ThrowIfFailed(
00083         D2D1CreateFactory(
00084             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00085             __uuidof(ID2D1Factory1),
00086             &options,
00087             &m_d2dFactory
00088             )
00089         );
00090
00091     DX::ThrowIfFailed(
00092         DWriteCreateFactory(
00093             DWRITE_FACTORY_TYPE_SHARED,
00094             __uuidof(IDWriteFactory),
00095             &m_dwriteFactory
00096             )
00097         );
00098
00099     DX::ThrowIfFailed(
00100         CoCreateInstance(
00101             CLSID_WICImagingFactory,
00102             nullptr,
00103             CLSCTX_INPROC_SERVER,
00104             IID_PPV_ARGS(&m_wicFactory)
00105             )
00106         );
00107 }
00108
00109 // These are the resources that depend on the device.
00110 void DirectXBase::CreateDeviceResources()
00111 {
00112     // This flag adds support for surfaces with a different color channel ordering
00113     // than the API default. It is required for compatibility with Direct2D.
00114     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00115     ComPtr<IDXGIDevice> dxgiDevice;
00116
00117 #if defined(_DEBUG)
00118     // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00119     creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00120 #endif
00121
00122     // This array defines the set of DirectX hardware feature levels this app will support.
00123     // Note the ordering should be preserved.
00124     // Don't forget to declare your application's minimum required feature level in its
00125     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00126     D3D_FEATURE_LEVEL featureLevels[] =
00127     {
00128         D3D_FEATURE_LEVEL_11_1,
00129         D3D_FEATURE_LEVEL_11_0,
00130         D3D_FEATURE_LEVEL_10_1,
00131         D3D_FEATURE_LEVEL_10_0,
00132         D3D_FEATURE_LEVEL_9_3,
00133         D3D_FEATURE_LEVEL_9_2,
00134         D3D_FEATURE_LEVEL_9_1
00135     };
00136
00137     // Create the Direct3D 11 API device object and a corresponding context.
00138     ComPtr<ID3D11Device> device;
00139     ComPtr<ID3D11DeviceContext> context;
00140     DX::ThrowIfFailed(
00141         D3D11CreateDevice(
00142             nullptr,                    // Specify nullptr to use the default adapter.
00143             D3D_DRIVER_TYPE_HARDWARE,
00144             0,
00145             creationFlags,              // Set debug and Direct2D compatibility flags.
00146             featureLevels,              // List of feature levels this app can support.
00147             ARRAYSIZE(featureLevels),
00148             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Metro style apps.
00149             &device,                    // Returns the Direct3D device created.
00150             &m_featureLevel,            // Returns feature level of device created.
00151             &context                    // Returns the device immediate context.
00152             )
00153         );
00154
00155     // Get the Direct3D 11.1 API device and context interfaces.
00156     DX::ThrowIfFailed(
00157         device.As(&m_d3dDevice)
00158         );
00159
00160     DX::ThrowIfFailed(
00161         context.As(&m_d3dContext)
00162         );
00163
00164     // Get the underlying DXGI device of the Direct3D device.
00165     DX::ThrowIfFailed(
00166         m_d3dDevice.As(&dxgiDevice)
00167         );
00168
00169     // Create the Direct2D device object and a corresponding context.
00170     DX::ThrowIfFailed(
00171         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00172         );
00173
00174     DX::ThrowIfFailed(
00175         m_d2dDevice->CreateDeviceContext(
00176             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00177             &m_d2dContext
00178             )
00179         );
00180 }
00181
00182 // Event handler for StereoEnabled changes.
00183 // This is called whenever the Stereo changes.
00184 void DirectXBase::OnStereoEnabledChanged(
00185     _In_ Platform::Object^ /* sender */
00186     )
00187 {
00188     UpdateForWindowSizeChange();
00189 }
00190
00191 // Helps track the DPI in the helper class.
00192 // This is called in the dpiChanged event handler in the view class.
00193 void DirectXBase::SetDpi(float dpi)
00194 {
00195     if (dpi != m_dpi)
00196     {
00197         // Save the DPI of this display in our class.
00198         m_dpi = dpi;
00199
00200         // Update Direct2D's stored DPI.
00201         m_d2dContext->SetDpi(m_dpi, m_dpi);
00202
00203         // Often a DPI change implies a window size change. In some cases Windows will issue
00204         // both a size changed event and a DPI changed event. In this case, the resulting bounds
00205         // will not change, and the window resize code will only be executed once.
00206         UpdateForWindowSizeChange();
00207     }
00208 }
00209
00210 void DirectXBase::CheckStereoEnabledStatus()
00211 {
00212     // first, retrieve the underlying DXGI Device from the D3D Device
00213     ComPtr<IDXGIDevice1> dxgiDevice;
00214     DX::ThrowIfFailed(
00215         m_d3dDevice.As(&dxgiDevice)
00216         );
00217
00218     // next, get the associated adapter from the DXGI Device
00219     ComPtr<IDXGIAdapter> dxgiAdapter;
00220     DX::ThrowIfFailed(
00221         dxgiDevice->GetAdapter(&dxgiAdapter)
00222         );
00223
00224     // next, get the parent factory from the DXGI adapter
00225     ComPtr<IDXGIFactory2> dxgiFactory;
00226     DX::ThrowIfFailed(
00227         dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00228         );
00229
00230     m_stereoEnabled = dxgiFactory->IsWindowedStereoEnabled() ? true : false;
00231 }
00232
00233 // This routine is called in the event handler for the view SizeChanged event.
00234 void DirectXBase::UpdateForWindowSizeChange()
00235 {
00236     // Only handle window size changed if there is no pending DPI change.
00237     if (m_dpi != DisplayProperties::LogicalDpi)
00238     {
00239         return;
00240     }
00241
00242     bool previousStereoState = m_stereoEnabled;
00243     CheckStereoEnabledStatus();
00244     if (previousStereoState != m_stereoEnabled)
00245     {
00246         // Swap chain needs to be recreated so release the existing one.
00247         // The rest of the dependent resources with be released in CreateWindowSizeDependentResources.
00248         m_swapChain = nullptr;
00249         CreateWindowSizeDependentResources();
00250     }
00251     else if (m_window->Bounds.Width != m_windowBounds.Width ||
00252         m_window->Bounds.Height != m_windowBounds.Height ||
00253         m_orientation != DisplayProperties::CurrentOrientation)
00254     {
00255         CreateWindowSizeDependentResources();
00256     }
00257 }
00258
00259 // Allocate all memory resources that change on a window SizeChanged event.
00260 void DirectXBase::CreateWindowSizeDependentResources()
00261 {
00262     // Store the window bounds so the next time we get a SizeChanged event we can
00263     // avoid rebuilding everything if the size is identical.
00264     m_windowBounds = m_window->Bounds;
00265
00266     // Calculate the necessary swap chain and render target size in pixels.
00267     auto windowWidth = ConvertDipsToPixels(m_windowBounds.Width);
00268     auto windowHeight = ConvertDipsToPixels(m_windowBounds.Height);
00269
00270     // Swap width and height based on orientation.
00271     m_orientation = DisplayProperties::CurrentOrientation;
00272     bool swapDimensions = (
00273         m_orientation == DisplayOrientations::Portrait ||
00274         m_orientation == DisplayOrientations::PortraitFlipped
00275         );
00276     m_renderTargetSize.Width = swapDimensions ? windowHeight : windowWidth;
00277     m_renderTargetSize.Height = swapDimensions ? windowWidth : windowHeight;
00278
00279     // If the swap chain already exists, resize it.
00280     if (m_swapChain != nullptr)
00281     {
00282         // Existing swap chain needs to be resized
00283         // make sure that the depend objects have been released.
00284         m_d3dContext->OMSetRenderTargets(0, nullptr, nullptr);
00285         m_d3dRenderTargetView = nullptr;
00286         m_d3dDepthStencilView = nullptr;
00287         m_d2dContext->SetTarget(nullptr);
00288         m_d2dTargetBitmap = nullptr;
00289         m_d2dTargetBitmapRight = nullptr;
00290         m_d3dRenderTargetViewRight = nullptr;
00291
00292         HRESULT hr = m_swapChain->ResizeBuffers(
00293             2,
00294             static_cast<UINT>(m_renderTargetSize.Width),
00295             static_cast<UINT>(m_renderTargetSize.Height),
00296             DXGI_FORMAT_B8G8R8A8_UNORM,
00297             0
00298             );
00299
00300         if (hr == DXGI_ERROR_DEVICE_REMOVED)
00301         {
00302             // If the device was removed for any reason, a new device and swapchain will need to be created.
00303             HandleDeviceLost();
00304
00305             // Everything is set up now. Do not continue execution of this method.
00306             return;
00307         }
00308         else
00309         {
00310             DX::ThrowIfFailed(hr);
00311         }
00312     }
00313     else    // Otherwise, create a new one.
00314     {
00315         // m_swapChain is nullptr either because it has never been created or because it has been
00316         // invalidated. Make sure that the dependent objects are also released.
00317         m_d3dContext->OMSetRenderTargets(0, nullptr, nullptr);
00318         m_d3dRenderTargetView = nullptr;
00319         m_d3dDepthStencilView = nullptr;
00320         m_d2dContext->SetTarget(nullptr);
00321         m_d2dTargetBitmap = nullptr;
00322         m_d3dRenderTargetViewRight = nullptr;
00323         m_d2dTargetBitmapRight = nullptr;
00324         m_d3dContext->Flush();
00325
00326         CheckStereoEnabledStatus();
00327
00328         // Allocate a descriptor.
00329         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00330         swapChainDesc.Width = static_cast<UINT>(m_renderTargetSize.Width); // Match the size of the window.
00331         swapChainDesc.Height = static_cast<UINT>(m_renderTargetSize.Height);
00332         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;           // this is the most common swapchain format
00333         swapChainDesc.Stereo = m_stereoEnabled;
00334         swapChainDesc.SampleDesc.Count = 1;                          // don't use multi-sampling
00335         swapChainDesc.SampleDesc.Quality = 0;
00336         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00337         swapChainDesc.BufferCount = 2;                               // use double buffering to enable flip
00338         swapChainDesc.Scaling = DXGI_SCALING_STRETCH;                // Required to be STRETCH for Composition
00339         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // all Metro style apps must use this SwapEffect
00340         swapChainDesc.Flags = 0;
00341
00342         // Once the desired swap chain description is configured, it must be created on the same adapter as our D3D Device
00343
00344         // First, retrieve the underlying DXGI Device from the D3D Device.
00345         ComPtr<IDXGIDevice1> dxgiDevice;
00346         DX::ThrowIfFailed(
00347             m_d3dDevice.As(&dxgiDevice)
00348             );
00349
00350         // Identify the physical adapter (GPU or card) this device is running on.
00351         ComPtr<IDXGIAdapter> dxgiAdapter;
00352         DX::ThrowIfFailed(
00353             dxgiDevice->GetAdapter(&dxgiAdapter)
00354             );
00355
00356         // And obtain the factory object that created it.
00357         ComPtr<IDXGIFactory2> dxgiFactory;
00358         DX::ThrowIfFailed(
00359             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00360             );
00361
00362         // Create the swap chain and then associate it with the SwapChainBackgroundPanel.
00363         DX::ThrowIfFailed(
00364             dxgiFactory->CreateSwapChainForComposition(
00365                 m_d3dDevice.Get(),
00366                 &swapChainDesc,
00367                 nullptr,    // allow on all displays
00368                 &m_swapChain
00369                 )
00370             );
00371
00372         ComPtr<ISwapChainBackgroundPanelNative> dxRootPanelAsNative;
00373
00374         // set the swap chain on the SwapChainBackgroundPanel
00375         reinterpret_cast<IUnknown*>(m_swapChainPanel)->QueryInterface(__uuidof(ISwapChainBackgroundPanelNative), (void**)&dxRootPanelAsNative);
00376
00377         DX::ThrowIfFailed(
00378             dxRootPanelAsNative->SetSwapChain(m_swapChain.Get())
00379             );
00380
00381         // Ensure that DXGI does not queue more than one frame at a time. This both reduces
00382         // latency and ensures that the application will only render after each VSync, minimizing
00383         // power consumption.
00384         DX::ThrowIfFailed(
00385             dxgiDevice->SetMaximumFrameLatency(1)
00386             );
00387     }
00388
00389     // Set the proper orientation for the swap chain, and generate 2D and
00390     // 3D matrix transformations for rendering to the rotated swap chain.
00391     // Note the rotation angle for the 2D and 3D transforms are different.
00392     // This is due to the difference in coordinate spaces.  Additionally,
00393     // the 3D matrix is specified explicitly to avoid rounding errors.
00394     DXGI_MODE_ROTATION rotation = DXGI_MODE_ROTATION_UNSPECIFIED;
00395     switch (m_orientation)
00396     {
00397         case DisplayOrientations::Landscape:
00398             rotation = DXGI_MODE_ROTATION_IDENTITY;
00399             m_rotationTransform2D = Matrix3x2F::Identity();
00400             XMStoreFloat4x4(&m_rotationTransform3D, XMMatrixIdentity());
00401             break;
00402
00403         case DisplayOrientations::Portrait:
00404             rotation = DXGI_MODE_ROTATION_ROTATE270;
00405             m_rotationTransform2D =
00406                 Matrix3x2F::Rotation(270.0f) *
00407                 Matrix3x2F::Translation(0.0f, m_windowBounds.Width);
00408             XMStoreFloat4x4(
00409                 &m_rotationTransform3D,
00410                 XMMATRIX( // 90-degree Z-rotation
00411                      0.0f, 1.0f, 0.0f, 0.0f,
00412                     -1.0f, 0.0f, 0.0f, 0.0f,
00413                      0.0f, 0.0f, 1.0f, 0.0f,
00414                      0.0f, 0.0f, 0.0f, 1.0f
00415                     )
00416                 );
00417             break;
00418
00419         case DisplayOrientations::LandscapeFlipped:
00420             rotation = DXGI_MODE_ROTATION_ROTATE180;
00421             m_rotationTransform2D =
00422                 Matrix3x2F::Rotation(180.0f) *
00423                 Matrix3x2F::Translation(m_windowBounds.Width, m_windowBounds.Height);
00424             XMStoreFloat4x4(
00425                 &m_rotationTransform3D,
00426                 XMMATRIX( // 180-degree Z-rotation
00427                     -1.0f,  0.0f, 0.0f, 0.0f,
00428                      0.0f, -1.0f, 0.0f, 0.0f,
00429                      0.0f,  0.0f, 1.0f, 0.0f,
00430                      0.0f,  0.0f, 0.0f, 1.0f
00431                     )
00432                 );
00433             break;
00434
00435         case DisplayOrientations::PortraitFlipped:
00436             rotation = DXGI_MODE_ROTATION_ROTATE90;
00437             m_rotationTransform2D =
00438                 Matrix3x2F::Rotation(90.0f) *
00439                 Matrix3x2F::Translation(m_windowBounds.Height, 0.0f);
00440             XMStoreFloat4x4(
00441                 &m_rotationTransform3D,
00442                 XMMATRIX( // 270-degree Z-rotation
00443                     0.0f, -1.0f, 0.0f, 0.0f,
00444                     1.0f,  0.0f, 0.0f, 0.0f,
00445                     0.0f,  0.0f, 1.0f, 0.0f,
00446                     0.0f,  0.0f, 0.0f, 1.0f
00447                     )
00448                 );
00449             break;
00450
00451         default:
00452             throw ref new Platform::FailureException();
00453             break;
00454     }
00455
00456     DX::ThrowIfFailed(
00457         m_swapChain->SetRotation(rotation)
00458         );
00459
00460     // Obtain the backbuffer for this window which will be the final 3D rendertarget.
00461     ComPtr<ID3D11Texture2D> backBuffer;
00462     DX::ThrowIfFailed(
00463         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00464         );
00465
00466     // Create a descriptor for the RenderTargetView.
00467     CD3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc(
00468         D3D11_RTV_DIMENSION_TEXTURE2DARRAY,
00469         DXGI_FORMAT_B8G8R8A8_UNORM,
00470         0,
00471         0,
00472         1
00473         );
00474
00475     // Create a view interface on the rendertarget to use on bind for mono or left eye view.
00476     DX::ThrowIfFailed(
00477         m_d3dDevice->CreateRenderTargetView(
00478             backBuffer.Get(),
00479             &renderTargetViewDesc,
00480             &m_d3dRenderTargetView
00481             )
00482         );
00483
00484     // Stereo swapchains have an arrayed resource, so create a second Render Target
00485     // for the right eye buffer.
00486     if (m_stereoEnabled)
00487     {
00488         CD3D11_RENDER_TARGET_VIEW_DESC renderTargetViewRightDesc(
00489             D3D11_RTV_DIMENSION_TEXTURE2DARRAY,
00490             DXGI_FORMAT_B8G8R8A8_UNORM,
00491             0,
00492             1,
00493             1
00494             );
00495
00496         DX::ThrowIfFailed(
00497             m_d3dDevice->CreateRenderTargetView(
00498                 backBuffer.Get(),
00499                 &renderTargetViewRightDesc,
00500                 &m_d3dRenderTargetViewRight
00501                 )
00502             );
00503     }
00504
00505     // Create a descriptor for the depth/stencil buffer.
00506     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00507         DXGI_FORMAT_D24_UNORM_S8_UINT,
00508         static_cast<UINT>(m_renderTargetSize.Width),
00509         static_cast<UINT>(m_renderTargetSize.Height),
00510         1,
00511         1,
00512         D3D11_BIND_DEPTH_STENCIL
00513         );
00514
00515     // Allocate a 2-D surface as the depth/stencil buffer.
00516     ComPtr<ID3D11Texture2D> depthStencil;
00517     DX::ThrowIfFailed(
00518         m_d3dDevice->CreateTexture2D(
00519             &depthStencilDesc,
00520             nullptr,
00521             &depthStencil
00522             )
00523         );
00524
00525     // Create a DepthStencil view on this surface to use on bind.
00526     auto viewDesc = CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D);
00527     DX::ThrowIfFailed(
00528         m_d3dDevice->CreateDepthStencilView(
00529             depthStencil.Get(),
00530             &viewDesc,
00531             &m_d3dDepthStencilView
00532             )
00533         );
00534
00535     // Create a viewport descriptor of the full window size.
00536     CD3D11_VIEWPORT viewport(
00537         0.0f,
00538         0.0f,
00539         m_renderTargetSize.Width,
00540         m_renderTargetSize.Height
00541         );
00542
00543     // Set the current viewport using the descriptor.
00544     m_d3dContext->RSSetViewports(1, &viewport);
00545
00546     // Now we set up the Direct2D render target bitmap linked to the swapchain.
00547     // Whenever we render to this bitmap, it will be directly rendered to the
00548     // swapchain associated with the window.
00549     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00550         BitmapProperties1(
00551             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00552             PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00553             m_dpi,
00554             m_dpi
00555             );
00556
00557     // Direct2D needs the dxgi version of the backbuffer surface pointer.
00558     ComPtr<IDXGIResource1> dxgiBackBuffer;
00559     DX::ThrowIfFailed(
00560         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00561         );
00562
00563     ComPtr<IDXGISurface2> dxgiSurface;
00564     DX::ThrowIfFailed(
00565         dxgiBackBuffer->CreateSubresourceSurface(0, &dxgiSurface)
00566         );
00567
00568     // Get a D2D surface from the DXGI back buffer to use as the D2D render target.
00569     DX::ThrowIfFailed(
00570         m_d2dContext->CreateBitmapFromDxgiSurface(
00571             dxgiSurface.Get(),
00572             &bitmapProperties,
00573             &m_d2dTargetBitmap
00574             )
00575         );
00576
00577     // Stereo swapchains have an arrayed resource, so create a second Target Bitmap
00578     // for the right eye buffer.
00579     if (m_stereoEnabled)
00580     {
00581         DX::ThrowIfFailed(
00582             dxgiBackBuffer->CreateSubresourceSurface(1, &dxgiSurface)
00583             );
00584         DX::ThrowIfFailed(
00585             m_d2dContext->CreateBitmapFromDxgiSurface(
00586                 dxgiSurface.Get(),
00587                 &bitmapProperties,
00588                 &m_d2dTargetBitmapRight
00589             )
00590         );
00591     }
00592
00593     // So now we can set the Direct2D render target.
00594     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00595
00596     // Set D2D text anti-alias mode to Grayscale to ensure proper rendering of text on intermediate surfaces.
00597     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00598 }
00599
00600 // Method to deliver the final image to the display.
00601 void DirectXBase::Present()
00602 {
00603     // The application may optionally specify "dirty" or "scroll" rects to improve efficiency
00604     // in certain scenarios.  In this sample, however, we do not utilize those features.
00605     DXGI_PRESENT_PARAMETERS parameters = {0};
00606     parameters.DirtyRectsCount = 0;
00607     parameters.pDirtyRects = nullptr;
00608     parameters.pScrollRect = nullptr;
00609     parameters.pScrollOffset = nullptr;
00610
00611     // The first argument instructs DXGI to block until VSync, putting the application
00612     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00613     // frames that will never be displayed to the screen.
00614     HRESULT hr = m_swapChain->Present1(1, 0, &parameters);
00615
00616     // If the device was removed either by a disconnect or a driver upgrade, we
00617     // must recreate all device resources.
00618     if (hr == DXGI_ERROR_DEVICE_REMOVED)
00619     {
00620         // Send notifications via the DeviceLost event to any registered handlers.
00621         DeviceLost();
00622         // Recreate the Device Resources.
00623         HandleDeviceLost();
00624         // Send notifications via the DeviceReset event to any registered handlers.
00625         DeviceReset();
00626     }
00627     else
00628     {
00629         DX::ThrowIfFailed(hr);
00630     }
00631 }
00632
00633 // Method to convert a length in device-independent pixels (DIPs) to a length in physical pixels.
00634 float DirectXBase::ConvertDipsToPixels(float dips)
00635 {
00636     static const float dipsPerInch = 96.0f;
00637     return floor(dips * m_dpi / dipsPerInch + 0.5f); // Round to nearest integer.
00638 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D resource loading/C++/texconv/BC6HBC7.cpp Source File

  • Direct3D resource loading
  • texconv

BC6HBC7.cpp

Go to the documentation of this file.
00001 //-------------------------------------------------------------------------------------
00002 // BC6HBC7.cpp
00003 //
00004 // Block-compression (BC) functionality for BC6H and BC7 (DirectX 11 texture compression)
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 #include "directxtexp.h"
00015
00016 #include "BC.h"
00017
00018 namespace DirectX
00019 {
00020
00021 //-------------------------------------------------------------------------------------
00022 // Constants
00023 //-------------------------------------------------------------------------------------
00024
00025 static const float fEpsilon = (0.25f / 64.0f) * (0.25f / 64.0f);
00026 static const float pC3[] = { 2.0f/2.0f, 1.0f/2.0f, 0.0f/2.0f };
00027 static const float pD3[] = { 0.0f/2.0f, 1.0f/2.0f, 2.0f/2.0f };
00028 static const float pC4[] = { 3.0f/3.0f, 2.0f/3.0f, 1.0f/3.0f, 0.0f/3.0f };
00029 static const float pD4[] = { 0.0f/3.0f, 1.0f/3.0f, 2.0f/3.0f, 3.0f/3.0f };
00030
00031 const int g_aWeights2[] = {0, 21, 43, 64};
00032 const int g_aWeights3[] = {0, 9, 18, 27, 37, 46, 55, 64};
00033 const int g_aWeights4[] = {0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64};
00034
00035 // Partition, Shape, Pixel (index into 4x4 block)
00036 static const uint8_t g_aPartitionTable[3][64][16] =
00037 {
00038     {   // 1 Region case has no subsets (all 0)
00039         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00040         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00041         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00042         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00043         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00044         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00045         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00046         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00047         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00048         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00049         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00050         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00051         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00052         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00053         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00054         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00055         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00056         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00057         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00058         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00059         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00060         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00061         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00062         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00063         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00064         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00065         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00066         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00067         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00068         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00069         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00070         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00071         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00072         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00073         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00074         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00075         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00076         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00077         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00078         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00079         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00080         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00081         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00082         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00083         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00084         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00085         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00086         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00087         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00088         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00089         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00090         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00091         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00092         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00093         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00094         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00095         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00096         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00097         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00098         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00099         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00100         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00101         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
00102         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
00103     },
00104
00105     {   // BC6H/BC7 Partition Set for 2 Subsets
00106         { 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1 }, // Shape 0
00107         { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 }, // Shape 1
00108         { 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1 }, // Shape 2
00109         { 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1 }, // Shape 3
00110         { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1 }, // Shape 4
00111         { 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1 }, // Shape 5
00112         { 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1 }, // Shape 6
00113         { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1 }, // Shape 7
00114         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1 }, // Shape 8
00115         { 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, // Shape 9
00116         { 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1 }, // Shape 10
00117         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1 }, // Shape 11
00118         { 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, // Shape 12
00119         { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 }, // Shape 13
00120         { 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, // Shape 14
00121         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1 }, // Shape 15
00122         { 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1 }, // Shape 16
00123         { 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, // Shape 17
00124         { 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0 }, // Shape 18
00125         { 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0 }, // Shape 19
00126         { 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, // Shape 20
00127         { 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0 }, // Shape 21
00128         { 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0 }, // Shape 22
00129         { 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1 }, // Shape 23
00130         { 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0 }, // Shape 24
00131         { 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0 }, // Shape 25
00132         { 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0 }, // Shape 26
00133         { 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0 }, // Shape 27
00134         { 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0 }, // Shape 28
00135         { 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0 }, // Shape 29
00136         { 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0 }, // Shape 30
00137         { 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0 }, // Shape 31
00138
00139         // BC7 Partition Set for 2 Subsets (second-half)
00140         { 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1 }, // Shape 32
00141         { 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1 }, // Shape 33
00142         { 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0 }, // Shape 34
00143         { 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0 }, // Shape 35
00144         { 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0 }, // Shape 36
00145         { 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0 }, // Shape 37
00146         { 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1 }, // Shape 38
00147         { 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1 }, // Shape 39
00148         { 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0 }, // Shape 40
00149         { 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0 }, // Shape 41
00150         { 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0 }, // Shape 42
00151         { 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0 }, // Shape 43
00152         { 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0 }, // Shape 44
00153         { 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1 }, // Shape 45
00154         { 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1 }, // Shape 46
00155         { 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0 }, // Shape 47
00156         { 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0 }, // Shape 48
00157         { 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0 }, // Shape 49
00158         { 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0 }, // Shape 50
00159         { 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0 }, // Shape 51
00160         { 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1 }, // Shape 52
00161         { 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1 }, // Shape 53
00162         { 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0 }, // Shape 54
00163         { 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0 }, // Shape 55
00164         { 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1 }, // Shape 56
00165         { 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1 }, // Shape 57
00166         { 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1 }, // Shape 58
00167         { 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1 }, // Shape 59
00168         { 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1 }, // Shape 60
00169         { 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0 }, // Shape 61
00170         { 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0 }, // Shape 62
00171         { 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1 }  // Shape 63
00172     },
00173
00174     {   // BC7 Partition Set for 3 Subsets
00175         { 0, 0, 1, 1, 0, 0, 1, 1, 0, 2, 2, 1, 2, 2, 2, 2 }, // Shape 0
00176         { 0, 0, 0, 1, 0, 0, 1, 1, 2, 2, 1, 1, 2, 2, 2, 1 }, // Shape 1
00177         { 0, 0, 0, 0, 2, 0, 0, 1, 2, 2, 1, 1, 2, 2, 1, 1 }, // Shape 2
00178         { 0, 2, 2, 2, 0, 0, 2, 2, 0, 0, 1, 1, 0, 1, 1, 1 }, // Shape 3
00179         { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 1, 1, 2, 2 }, // Shape 4
00180         { 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 2, 2, 0, 0, 2, 2 }, // Shape 5
00181         { 0, 0, 2, 2, 0, 0, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1 }, // Shape 6
00182         { 0, 0, 1, 1, 0, 0, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1 }, // Shape 7
00183         { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2 }, // Shape 8
00184         { 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2 }, // Shape 9
00185         { 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2 }, // Shape 10
00186         { 0, 0, 1, 2, 0, 0, 1, 2, 0, 0, 1, 2, 0, 0, 1, 2 }, // Shape 11
00187         { 0, 1, 1, 2, 0, 1, 1, 2, 0, 1, 1, 2, 0, 1, 1, 2 }, // Shape 12
00188         { 0, 1, 2, 2, 0, 1, 2, 2, 0, 1, 2, 2, 0, 1, 2, 2 }, // Shape 13
00189         { 0, 0, 1, 1, 0, 1, 1, 2, 1, 1, 2, 2, 1, 2, 2, 2 }, // Shape 14
00190         { 0, 0, 1, 1, 2, 0, 0, 1, 2, 2, 0, 0, 2, 2, 2, 0 }, // Shape 15
00191         { 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 2, 1, 1, 2, 2 }, // Shape 16
00192         { 0, 1, 1, 1, 0, 0, 1, 1, 2, 0, 0, 1, 2, 2, 0, 0 }, // Shape 17
00193         { 0, 0, 0, 0, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2 }, // Shape 18
00194         { 0, 0, 2, 2, 0, 0, 2, 2, 0, 0, 2, 2, 1, 1, 1, 1 }, // Shape 19
00195         { 0, 1, 1, 1, 0, 1, 1, 1, 0, 2, 2, 2, 0, 2, 2, 2 }, // Shape 20
00196         { 0, 0, 0, 1, 0, 0, 0, 1, 2, 2, 2, 1, 2, 2, 2, 1 }, // Shape 21
00197         { 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 2, 2, 0, 1, 2, 2 }, // Shape 22
00198         { 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 1, 0, 2, 2, 1, 0 }, // Shape 23
00199         { 0, 1, 2, 2, 0, 1, 2, 2, 0, 0, 1, 1, 0, 0, 0, 0 }, // Shape 24
00200         { 0, 0, 1, 2, 0, 0, 1, 2, 1, 1, 2, 2, 2, 2, 2, 2 }, // Shape 25
00201         { 0, 1, 1, 0, 1, 2, 2, 1, 1, 2, 2, 1, 0, 1, 1, 0 }, // Shape 26
00202         { 0, 0, 0, 0, 0, 1, 1, 0, 1, 2, 2, 1, 1, 2, 2, 1 }, // Shape 27
00203         { 0, 0, 2, 2, 1, 1, 0, 2, 1, 1, 0, 2, 0, 0, 2, 2 }, // Shape 28
00204         { 0, 1, 1, 0, 0, 1, 1, 0, 2, 0, 0, 2, 2, 2, 2, 2 }, // Shape 29
00205         { 0, 0, 1, 1, 0, 1, 2, 2, 0, 1, 2, 2, 0, 0, 1, 1 }, // Shape 30
00206         { 0, 0, 0, 0, 2, 0, 0, 0, 2, 2, 1, 1, 2, 2, 2, 1 }, // Shape 31
00207         { 0, 0, 0, 0, 0, 0, 0, 2, 1, 1, 2, 2, 1, 2, 2, 2 }, // Shape 32
00208         { 0, 2, 2, 2, 0, 0, 2, 2, 0, 0, 1, 2, 0, 0, 1, 1 }, // Shape 33
00209         { 0, 0, 1, 1, 0, 0, 1, 2, 0, 0, 2, 2, 0, 2, 2, 2 }, // Shape 34
00210         { 0, 1, 2, 0, 0, 1, 2, 0, 0, 1, 2, 0, 0, 1, 2, 0 }, // Shape 35
00211         { 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 0, 0, 0, 0 }, // Shape 36
00212         { 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0 }, // Shape 37
00213         { 0, 1, 2, 0, 2, 0, 1, 2, 1, 2, 0, 1, 0, 1, 2, 0 }, // Shape 38
00214         { 0, 0, 1, 1, 2, 2, 0, 0, 1, 1, 2, 2, 0, 0, 1, 1 }, // Shape 39
00215         { 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 0, 0, 0, 0, 1, 1 }, // Shape 40
00216         { 0, 1, 0, 1, 0, 1, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2 }, // Shape 41
00217         { 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 2, 1, 2, 1, 2, 1 }, // Shape 42
00218         { 0, 0, 2, 2, 1, 1, 2, 2, 0, 0, 2, 2, 1, 1, 2, 2 }, // Shape 43
00219         { 0, 0, 2, 2, 0, 0, 1, 1, 0, 0, 2, 2, 0, 0, 1, 1 }, // Shape 44
00220         { 0, 2, 2, 0, 1, 2, 2, 1, 0, 2, 2, 0, 1, 2, 2, 1 }, // Shape 45
00221         { 0, 1, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 0, 1, 0, 1 }, // Shape 46
00222         { 0, 0, 0, 0, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1 }, // Shape 47
00223         { 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 2, 2, 2 }, // Shape 48
00224         { 0, 2, 2, 2, 0, 1, 1, 1, 0, 2, 2, 2, 0, 1, 1, 1 }, // Shape 49
00225         { 0, 0, 0, 2, 1, 1, 1, 2, 0, 0, 0, 2, 1, 1, 1, 2 }, // Shape 50
00226         { 0, 0, 0, 0, 2, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2 }, // Shape 51
00227         { 0, 2, 2, 2, 0, 1, 1, 1, 0, 1, 1, 1, 0, 2, 2, 2 }, // Shape 52
00228         { 0, 0, 0, 2, 1, 1, 1, 2, 1, 1, 1, 2, 0, 0, 0, 2 }, // Shape 53
00229         { 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 2, 2, 2, 2 }, // Shape 54
00230         { 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 1, 2, 2, 1, 1, 2 }, // Shape 55
00231         { 0, 1, 1, 0, 0, 1, 1, 0, 2, 2, 2, 2, 2, 2, 2, 2 }, // Shape 56
00232         { 0, 0, 2, 2, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 2, 2 }, // Shape 57
00233         { 0, 0, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2, 0, 0, 2, 2 }, // Shape 58
00234         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 1, 2 }, // Shape 59
00235         { 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 1 }, // Shape 60
00236         { 0, 2, 2, 2, 1, 2, 2, 2, 0, 2, 2, 2, 1, 2, 2, 2 }, // Shape 61
00237         { 0, 1, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 }, // Shape 62
00238         { 0, 1, 1, 1, 2, 0, 1, 1, 2, 2, 0, 1, 2, 2, 2, 0 }  // Shape 63
00239     }
00240 };
00241
00242 // Partition, Shape, Fixup
00243 static const uint8_t g_aFixUp[3][64][3] =
00244 {
00245     {   // No fix-ups for 1st subset for BC6H or BC7
00246         { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0},
00247         { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0},
00248         { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0},
00249         { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0},
00250         { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0},
00251         { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0},
00252         { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0},
00253         { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0},
00254         { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0},
00255         { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0},
00256         { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0},
00257         { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0},
00258         { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0},
00259         { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0},
00260         { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0},
00261         { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}
00262     },
00263
00264     {   // BC6H/BC7 Partition Set Fixups for 2 Subsets
00265         { 0,15, 0}, { 0,15, 0}, { 0,15, 0}, { 0,15, 0},
00266         { 0,15, 0}, { 0,15, 0}, { 0,15, 0}, { 0,15, 0},
00267         { 0,15, 0}, { 0,15, 0}, { 0,15, 0}, { 0,15, 0},
00268         { 0,15, 0}, { 0,15, 0}, { 0,15, 0}, { 0,15, 0},
00269         { 0,15, 0}, { 0, 2, 0}, { 0, 8, 0}, { 0, 2, 0},
00270         { 0, 2, 0}, { 0, 8, 0}, { 0, 8, 0}, { 0,15, 0},
00271         { 0, 2, 0}, { 0, 8, 0}, { 0, 2, 0}, { 0, 2, 0},
00272         { 0, 8, 0}, { 0, 8, 0}, { 0, 2, 0}, { 0, 2, 0},
00273
00274         // BC7 Partition Set Fixups for 2 Subsets (second-half)
00275         { 0,15, 0}, { 0,15, 0}, { 0, 6, 0}, { 0, 8, 0},
00276         { 0, 2, 0}, { 0, 8, 0}, { 0,15, 0}, { 0,15, 0},
00277         { 0, 2, 0}, { 0, 8, 0}, { 0, 2, 0}, { 0, 2, 0},
00278         { 0, 2, 0}, { 0,15, 0}, { 0,15, 0}, { 0, 6, 0},
00279         { 0, 6, 0}, { 0, 2, 0}, { 0, 6, 0}, { 0, 8, 0},
00280         { 0,15, 0}, { 0,15, 0}, { 0, 2, 0}, { 0, 2, 0},
00281         { 0,15, 0}, { 0,15, 0}, { 0,15, 0}, { 0,15, 0},
00282         { 0,15, 0}, { 0, 2, 0}, { 0, 2, 0}, { 0,15, 0}
00283     },
00284
00285     {   // BC7 Partition Set Fixups for 3 Subsets
00286         { 0, 3,15}, { 0, 3, 8}, { 0,15, 8}, { 0,15, 3},
00287         { 0, 8,15}, { 0, 3,15}, { 0,15, 3}, { 0,15, 8},
00288         { 0, 8,15}, { 0, 8,15}, { 0, 6,15}, { 0, 6,15},
00289         { 0, 6,15}, { 0, 5,15}, { 0, 3,15}, { 0, 3, 8},
00290         { 0, 3,15}, { 0, 3, 8}, { 0, 8,15}, { 0,15, 3},
00291         { 0, 3,15}, { 0, 3, 8}, { 0, 6,15}, { 0,10, 8},
00292         { 0, 5, 3}, { 0, 8,15}, { 0, 8, 6}, { 0, 6,10},
00293         { 0, 8,15}, { 0, 5,15}, { 0,15,10}, { 0,15, 8},
00294         { 0, 8,15}, { 0,15, 3}, { 0, 3,15}, { 0, 5,10},
00295         { 0, 6,10}, { 0,10, 8}, { 0, 8, 9}, { 0,15,10},
00296         { 0,15, 6}, { 0, 3,15}, { 0,15, 8}, { 0, 5,15},
00297         { 0,15, 3}, { 0,15, 6}, { 0,15, 6}, { 0,15, 8},
00298         { 0, 3,15}, { 0,15, 3}, { 0, 5,15}, { 0, 5,15},
00299         { 0, 5,15}, { 0, 8,15}, { 0, 5,15}, { 0,10,15},
00300         { 0, 5,15}, { 0,10,15}, { 0, 8,15}, { 0,13,15},
00301         { 0,15, 3}, { 0,12,15}, { 0, 3,15}, { 0, 3, 8}
00302     }
00303 };
00304
00305 // BC6H Compression
00306 const D3DX_BC6H::ModeDescriptor D3DX_BC6H::ms_aDesc[14][82] =
00307 {
00308     {   // 0x00 - 10 5 5 5
00309         { M, 0}, { M, 1}, {GY, 4}, {BY, 4}, {BZ, 4}, {RW, 0}, {RW, 1}, {RW, 2}, {RW, 3}, {RW, 4},
00310         {RW, 5}, {RW, 6}, {RW, 7}, {RW, 8}, {RW, 9}, {GW, 0}, {GW, 1}, {GW, 2}, {GW, 3}, {GW, 4},
00311         {GW, 5}, {GW, 6}, {GW, 7}, {GW, 8}, {GW, 9}, {BW, 0}, {BW, 1}, {BW, 2}, {BW, 3}, {BW, 4},
00312         {BW, 5}, {BW, 6}, {BW, 7}, {BW, 8}, {BW, 9}, {RX, 0}, {RX, 1}, {RX, 2}, {RX, 3}, {RX, 4},
00313         {GZ, 4}, {GY, 0}, {GY, 1}, {GY, 2}, {GY, 3}, {GX, 0}, {GX, 1}, {GX, 2}, {GX, 3}, {GX, 4},
00314         {BZ, 0}, {GZ, 0}, {GZ, 1}, {GZ, 2}, {GZ, 3}, {BX, 0}, {BX, 1}, {BX, 2}, {BX, 3}, {BX, 4},
00315         {BZ, 1}, {BY, 0}, {BY, 1}, {BY, 2}, {BY, 3}, {RY, 0}, {RY, 1}, {RY, 2}, {RY, 3}, {RY, 4},
00316         {BZ, 2}, {RZ, 0}, {RZ, 1}, {RZ, 2}, {RZ, 3}, {RZ, 4}, {BZ, 3}, { D, 0}, { D, 1}, { D, 2},
00317         { D, 3}, { D, 4},
00318     },
00319
00320     {   // 0x01 - 7 6 6 6
00321         { M, 0}, { M, 1}, {GY, 5}, {GZ, 4}, {GZ, 5}, {RW, 0}, {RW, 1}, {RW, 2}, {RW, 3}, {RW, 4},
00322         {RW, 5}, {RW, 6}, {BZ, 0}, {BZ, 1}, {BY, 4}, {GW, 0}, {GW, 1}, {GW, 2}, {GW, 3}, {GW, 4},
00323         {GW, 5}, {GW, 6}, {BY, 5}, {BZ, 2}, {GY, 4}, {BW, 0}, {BW, 1}, {BW, 2}, {BW, 3}, {BW, 4},
00324         {BW, 5}, {BW, 6}, {BZ, 3}, {BZ, 5}, {BZ, 4}, {RX, 0}, {RX, 1}, {RX, 2}, {RX, 3}, {RX, 4},
00325         {RX, 5}, {GY, 0}, {GY, 1}, {GY, 2}, {GY, 3}, {GX, 0}, {GX, 1}, {GX, 2}, {GX, 3}, {GX, 4},
00326         {GX, 5}, {GZ, 0}, {GZ, 1}, {GZ, 2}, {GZ, 3}, {BX, 0}, {BX, 1}, {BX, 2}, {BX, 3}, {BX, 4},
00327         {BX, 5}, {BY, 0}, {BY, 1}, {BY, 2}, {BY, 3}, {RY, 0}, {RY, 1}, {RY, 2}, {RY, 3}, {RY, 4},
00328         {RY, 5}, {RZ, 0}, {RZ, 1}, {RZ, 2}, {RZ, 3}, {RZ, 4}, {RZ, 5}, { D, 0}, { D, 1}, { D, 2},
00329         { D, 3}, { D, 4},
00330     },
00331
00332     {   // 0x02 - 11 5 4 4
00333         { M, 0}, { M, 1}, { M, 2}, { M, 3}, { M, 4}, {RW, 0}, {RW, 1}, {RW, 2}, {RW, 3}, {RW, 4},
00334         {RW, 5}, {RW, 6}, {RW, 7}, {RW, 8}, {RW, 9}, {GW, 0}, {GW, 1}, {GW, 2}, {GW, 3}, {GW, 4},
00335         {GW, 5}, {GW, 6}, {GW, 7}, {GW, 8}, {GW, 9}, {BW, 0}, {BW, 1}, {BW, 2}, {BW, 3}, {BW, 4},
00336         {BW, 5}, {BW, 6}, {BW, 7}, {BW, 8}, {BW, 9}, {RX, 0}, {RX, 1}, {RX, 2}, {RX, 3}, {RX, 4},
00337         {RW,10}, {GY, 0}, {GY, 1}, {GY, 2}, {GY, 3}, {GX, 0}, {GX, 1}, {GX, 2}, {GX, 3}, {GW,10},
00338         {BZ, 0}, {GZ, 0}, {GZ, 1}, {GZ, 2}, {GZ, 3}, {BX, 0}, {BX, 1}, {BX, 2}, {BX, 3}, {BW,10},
00339         {BZ, 1}, {BY, 0}, {BY, 1}, {BY, 2}, {BY, 3}, {RY, 0}, {RY, 1}, {RY, 2}, {RY, 3}, {RY, 4},
00340         {BZ, 2}, {RZ, 0}, {RZ, 1}, {RZ, 2}, {RZ, 3}, {RZ, 4}, {BZ, 3}, { D, 0}, { D, 1}, { D, 2},
00341         { D, 3}, { D, 4},
00342     },
00343
00344     {   // 0x06 - 11 4 5 4
00345         { M, 0}, { M, 1}, { M, 2}, { M, 3}, { M, 4}, {RW, 0}, {RW, 1}, {RW, 2}, {RW, 3}, {RW, 4},
00346         {RW, 5}, {RW, 6}, {RW, 7}, {RW, 8}, {RW, 9}, {GW, 0}, {GW, 1}, {GW, 2}, {GW, 3}, {GW, 4},
00347         {GW, 5}, {GW, 6}, {GW, 7}, {GW, 8}, {GW, 9}, {BW, 0}, {BW, 1}, {BW, 2}, {BW, 3}, {BW, 4},
00348         {BW, 5}, {BW, 6}, {BW, 7}, {BW, 8}, {BW, 9}, {RX, 0}, {RX, 1}, {RX, 2}, {RX, 3}, {RW,10},
00349         {GZ, 4}, {GY, 0}, {GY, 1}, {GY, 2}, {GY, 3}, {GX, 0}, {GX, 1}, {GX, 2}, {GX, 3}, {GX, 4},
00350         {GW,10}, {GZ, 0}, {GZ, 1}, {GZ, 2}, {GZ, 3}, {BX, 0}, {BX, 1}, {BX, 2}, {BX, 3}, {BW,10},
00351         {BZ, 1}, {BY, 0}, {BY, 1}, {BY, 2}, {BY, 3}, {RY, 0}, {RY, 1}, {RY, 2}, {RY, 3}, {BZ, 0},
00352         {BZ, 2}, {RZ, 0}, {RZ, 1}, {RZ, 2}, {RZ, 3}, {GY, 4}, {BZ, 3}, { D, 0}, { D, 1}, { D, 2},
00353         { D, 3}, { D, 4},
00354     },
00355
00356     {   // 0x0a - 11 4 4 5
00357         { M, 0}, { M, 1}, { M, 2}, { M, 3}, { M, 4}, {RW, 0}, {RW, 1}, {RW, 2}, {RW, 3}, {RW, 4},
00358         {RW, 5}, {RW, 6}, {RW, 7}, {RW, 8}, {RW, 9}, {GW, 0}, {GW, 1}, {GW, 2}, {GW, 3}, {GW, 4},
00359         {GW, 5}, {GW, 6}, {GW, 7}, {GW, 8}, {GW, 9}, {BW, 0}, {BW, 1}, {BW, 2}, {BW, 3}, {BW, 4},
00360         {BW, 5}, {BW, 6}, {BW, 7}, {BW, 8}, {BW, 9}, {RX, 0}, {RX, 1}, {RX, 2}, {RX, 3}, {RW,10},
00361         {BY, 4}, {GY, 0}, {GY, 1}, {GY, 2}, {GY, 3}, {GX, 0}, {GX, 1}, {GX, 2}, {GX, 3}, {GW,10},
00362         {BZ, 0}, {GZ, 0}, {GZ, 1}, {GZ, 2}, {GZ, 3}, {BX, 0}, {BX, 1}, {BX, 2}, {BX, 3}, {BX, 4},
00363         {BW,10}, {BY, 0}, {BY, 1}, {BY, 2}, {BY, 3}, {RY, 0}, {RY, 1}, {RY, 2}, {RY, 3}, {BZ, 1},
00364         {BZ, 2}, {RZ, 0}, {RZ, 1}, {RZ, 2}, {RZ, 3}, {BZ, 4}, {BZ, 3}, { D, 0}, { D, 1}, { D, 2},
00365         { D, 3}, { D, 4},
00366     },
00367
00368     {   // 0x0e - 9 5 5 5
00369         { M, 0}, { M, 1}, { M, 2}, { M, 3}, { M, 4}, {RW, 0}, {RW, 1}, {RW, 2}, {RW, 3}, {RW, 4},
00370         {RW, 5}, {RW, 6}, {RW, 7}, {RW, 8}, {BY, 4}, {GW, 0}, {GW, 1}, {GW, 2}, {GW, 3}, {GW, 4},
00371         {GW, 5}, {GW, 6}, {GW, 7}, {GW, 8}, {GY, 4}, {BW, 0}, {BW, 1}, {BW, 2}, {BW, 3}, {BW, 4},
00372         {BW, 5}, {BW, 6}, {BW, 7}, {BW, 8}, {BZ, 4}, {RX, 0}, {RX, 1}, {RX, 2}, {RX, 3}, {RX, 4},
00373         {GZ, 4}, {GY, 0}, {GY, 1}, {GY, 2}, {GY, 3}, {GX, 0}, {GX, 1}, {GX, 2}, {GX, 3}, {GX, 4},
00374         {BZ, 0}, {GZ, 0}, {GZ, 1}, {GZ, 2}, {GZ, 3}, {BX, 0}, {BX, 1}, {BX, 2}, {BX, 3}, {BX, 4},
00375         {BZ, 1}, {BY, 0}, {BY, 1}, {BY, 2}, {BY, 3}, {RY, 0}, {RY, 1}, {RY, 2}, {RY, 3}, {RY, 4},
00376         {BZ, 2}, {RZ, 0}, {RZ, 1}, {RZ, 2}, {RZ, 3}, {RZ, 4}, {BZ, 3}, { D, 0}, { D, 1}, { D, 2},
00377         { D, 3}, { D, 4},
00378     },
00379
00380     {   // 0x12 - 8 6 5 5
00381         { M, 0}, { M, 1}, { M, 2}, { M, 3}, { M, 4}, {RW, 0}, {RW, 1}, {RW, 2}, {RW, 3}, {RW, 4},
00382         {RW, 5}, {RW, 6}, {RW, 7}, {GZ, 4}, {BY, 4}, {GW, 0}, {GW, 1}, {GW, 2}, {GW, 3}, {GW, 4},
00383         {GW, 5}, {GW, 6}, {GW, 7}, {BZ, 2}, {GY, 4}, {BW, 0}, {BW, 1}, {BW, 2}, {BW, 3}, {BW, 4},
00384         {BW, 5}, {BW, 6}, {BW, 7}, {BZ, 3}, {BZ, 4}, {RX, 0}, {RX, 1}, {RX, 2}, {RX, 3}, {RX, 4},
00385         {RX, 5}, {GY, 0}, {GY, 1}, {GY, 2}, {GY, 3}, {GX, 0}, {GX, 1}, {GX, 2}, {GX, 3}, {GX, 4},
00386         {BZ, 0}, {GZ, 0}, {GZ, 1}, {GZ, 2}, {GZ, 3}, {BX, 0}, {BX, 1}, {BX, 2}, {BX, 3}, {BX, 4},
00387         {BZ, 1}, {BY, 0}, {BY, 1}, {BY, 2}, {BY, 3}, {RY, 0}, {RY, 1}, {RY, 2}, {RY, 3}, {RY, 4},
00388         {RY, 5}, {RZ, 0}, {RZ, 1}, {RZ, 2}, {RZ, 3}, {RZ, 4}, {RZ, 5}, { D, 0}, { D, 1}, { D, 2},
00389         { D, 3}, { D, 4},
00390     },
00391
00392     {   // 0x16 - 8 5 6 5
00393         { M, 0}, { M, 1}, { M, 2}, { M, 3}, { M, 4}, {RW, 0}, {RW, 1}, {RW, 2}, {RW, 3}, {RW, 4},
00394         {RW, 5}, {RW, 6}, {RW, 7}, {BZ, 0}, {BY, 4}, {GW, 0}, {GW, 1}, {GW, 2}, {GW, 3}, {GW, 4},
00395         {GW, 5}, {GW, 6}, {GW, 7}, {GY, 5}, {GY, 4}, {BW, 0}, {BW, 1}, {BW, 2}, {BW, 3}, {BW, 4},
00396         {BW, 5}, {BW, 6}, {BW, 7}, {GZ, 5}, {BZ, 4}, {RX, 0}, {RX, 1}, {RX, 2}, {RX, 3}, {RX, 4},
00397         {GZ, 4}, {GY, 0}, {GY, 1}, {GY, 2}, {GY, 3}, {GX, 0}, {GX, 1}, {GX, 2}, {GX, 3}, {GX, 4},
00398         {GX, 5}, {GZ, 0}, {GZ, 1}, {GZ, 2}, {GZ, 3}, {BX, 0}, {BX, 1}, {BX, 2}, {BX, 3}, {BX, 4},
00399         {BZ, 1}, {BY, 0}, {BY, 1}, {BY, 2}, {BY, 3}, {RY, 0}, {RY, 1}, {RY, 2}, {RY, 3}, {RY, 4},
00400         {BZ, 2}, {RZ, 0}, {RZ, 1}, {RZ, 2}, {RZ, 3}, {RZ, 4}, {BZ, 3}, { D, 0}, { D, 1}, { D, 2},
00401         { D, 3}, { D, 4},
00402     },
00403
00404     {   // 0x1a - 8 5 5 6
00405         { M, 0}, { M, 1}, { M, 2}, { M, 3}, { M, 4}, {RW, 0}, {RW, 1}, {RW, 2}, {RW, 3}, {RW, 4},
00406         {RW, 5}, {RW, 6}, {RW, 7}, {BZ, 1}, {BY, 4}, {GW, 0}, {GW, 1}, {GW, 2}, {GW, 3}, {GW, 4},
00407         {GW, 5}, {GW, 6}, {GW, 7}, {BY, 5}, {GY, 4}, {BW, 0}, {BW, 1}, {BW, 2}, {BW, 3}, {BW, 4},
00408         {BW, 5}, {BW, 6}, {BW, 7}, {BZ, 5}, {BZ, 4}, {RX, 0}, {RX, 1}, {RX, 2}, {RX, 3}, {RX, 4},
00409         {GZ, 4}, {GY, 0}, {GY, 1}, {GY, 2}, {GY, 3}, {GX, 0}, {GX, 1}, {GX, 2}, {GX, 3}, {GX, 4},
00410         {BZ, 0}, {GZ, 0}, {GZ, 1}, {GZ, 2}, {GZ, 3}, {BX, 0}, {BX, 1}, {BX, 2}, {BX, 3}, {BX, 4},
00411         {BX, 5}, {BY, 0}, {BY, 1}, {BY, 2}, {BY, 3}, {RY, 0}, {RY, 1}, {RY, 2}, {RY, 3}, {RY, 4},
00412         {BZ, 2}, {RZ, 0}, {RZ, 1}, {RZ, 2}, {RZ, 3}, {RZ, 4}, {BZ, 3}, { D, 0}, { D, 1}, { D, 2},
00413         { D, 3}, { D, 4},
00414     },
00415
00416     {   // 0x1e - 6 6 6 6
00417         { M, 0}, { M, 1}, { M, 2}, { M, 3}, { M, 4}, {RW, 0}, {RW, 1}, {RW, 2}, {RW, 3}, {RW, 4},
00418         {RW, 5}, {GZ, 4}, {BZ, 0}, {BZ, 1}, {BY, 4}, {GW, 0}, {GW, 1}, {GW, 2}, {GW, 3}, {GW, 4},
00419         {GW, 5}, {GY, 5}, {BY, 5}, {BZ, 2}, {GY, 4}, {BW, 0}, {BW, 1}, {BW, 2}, {BW, 3}, {BW, 4},
00420         {BW, 5}, {GZ, 5}, {BZ, 3}, {BZ, 5}, {BZ, 4}, {RX, 0}, {RX, 1}, {RX, 2}, {RX, 3}, {RX, 4},
00421         {RX, 5}, {GY, 0}, {GY, 1}, {GY, 2}, {GY, 3}, {GX, 0}, {GX, 1}, {GX, 2}, {GX, 3}, {GX, 4},
00422         {GX, 5}, {GZ, 0}, {GZ, 1}, {GZ, 2}, {GZ, 3}, {BX, 0}, {BX, 1}, {BX, 2}, {BX, 3}, {BX, 4},
00423         {BX, 5}, {BY, 0}, {BY, 1}, {BY, 2}, {BY, 3}, {RY, 0}, {RY, 1}, {RY, 2}, {RY, 3}, {RY, 4},
00424         {RY, 5}, {RZ, 0}, {RZ, 1}, {RZ, 2}, {RZ, 3}, {RZ, 4}, {RZ, 5}, { D, 0}, { D, 1}, { D, 2},
00425         { D, 3}, { D, 4},
00426     },
00427
00428     {   // 0x03 - 10 10
00429         { M, 0}, { M, 1}, { M, 2}, { M, 3}, { M, 4}, {RW, 0}, {RW, 1}, {RW, 2}, {RW, 3}, {RW, 4},
00430         {RW, 5}, {RW, 6}, {RW, 7}, {RW, 8}, {RW, 9}, {GW, 0}, {GW, 1}, {GW, 2}, {GW, 3}, {GW, 4},
00431         {GW, 5}, {GW, 6}, {GW, 7}, {GW, 8}, {GW, 9}, {BW, 0}, {BW, 1}, {BW, 2}, {BW, 3}, {BW, 4},
00432         {BW, 5}, {BW, 6}, {BW, 7}, {BW, 8}, {BW, 9}, {RX, 0}, {RX, 1}, {RX, 2}, {RX, 3}, {RX, 4},
00433         {RX, 5}, {RX, 6}, {RX, 7}, {RX, 8}, {RX, 9}, {GX, 0}, {GX, 1}, {GX, 2}, {GX, 3}, {GX, 4},
00434         {GX, 5}, {GX, 6}, {GX, 7}, {GX, 8}, {GX, 9}, {BX, 0}, {BX, 1}, {BX, 2}, {BX, 3}, {BX, 4},
00435         {BX, 5}, {BX, 6}, {BX, 7}, {BX, 8}, {BX, 9}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0},
00436         {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0},
00437         {NA, 0}, {NA, 0},
00438     },
00439
00440     {   // 0x07 - 11 9
00441         { M, 0}, { M, 1}, { M, 2}, { M, 3}, { M, 4}, {RW, 0}, {RW, 1}, {RW, 2}, {RW, 3}, {RW, 4},
00442         {RW, 5}, {RW, 6}, {RW, 7}, {RW, 8}, {RW, 9}, {GW, 0}, {GW, 1}, {GW, 2}, {GW, 3}, {GW, 4},
00443         {GW, 5}, {GW, 6}, {GW, 7}, {GW, 8}, {GW, 9}, {BW, 0}, {BW, 1}, {BW, 2}, {BW, 3}, {BW, 4},
00444         {BW, 5}, {BW, 6}, {BW, 7}, {BW, 8}, {BW, 9}, {RX, 0}, {RX, 1}, {RX, 2}, {RX, 3}, {RX, 4},
00445         {RX, 5}, {RX, 6}, {RX, 7}, {RX, 8}, {RW,10}, {GX, 0}, {GX, 1}, {GX, 2}, {GX, 3}, {GX, 4},
00446         {GX, 5}, {GX, 6}, {GX, 7}, {GX, 8}, {GW,10}, {BX, 0}, {BX, 1}, {BX, 2}, {BX, 3}, {BX, 4},
00447         {BX, 5}, {BX, 6}, {BX, 7}, {BX, 8}, {BW,10}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0},
00448         {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0},
00449         {NA, 0}, {NA, 0},
00450     },
00451
00452     {   // 0x0b - 12 8
00453         { M, 0}, { M, 1}, { M, 2}, { M, 3}, { M, 4}, {RW, 0}, {RW, 1}, {RW, 2}, {RW, 3}, {RW, 4},
00454         {RW, 5}, {RW, 6}, {RW, 7}, {RW, 8}, {RW, 9}, {GW, 0}, {GW, 1}, {GW, 2}, {GW, 3}, {GW, 4},
00455         {GW, 5}, {GW, 6}, {GW, 7}, {GW, 8}, {GW, 9}, {BW, 0}, {BW, 1}, {BW, 2}, {BW, 3}, {BW, 4},
00456         {BW, 5}, {BW, 6}, {BW, 7}, {BW, 8}, {BW, 9}, {RX, 0}, {RX, 1}, {RX, 2}, {RX, 3}, {RX, 4},
00457         {RX, 5}, {RX, 6}, {RX, 7}, {RW,11}, {RW,10}, {GX, 0}, {GX, 1}, {GX, 2}, {GX, 3}, {GX, 4},
00458         {GX, 5}, {GX, 6}, {GX, 7}, {GW,11}, {GW,10}, {BX, 0}, {BX, 1}, {BX, 2}, {BX, 3}, {BX, 4},
00459         {BX, 5}, {BX, 6}, {BX, 7}, {BW,11}, {BW,10}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0},
00460         {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0},
00461         {NA, 0}, {NA, 0},
00462     },
00463
00464     {   // 0x0f - 16 4
00465         { M, 0}, { M, 1}, { M, 2}, { M, 3}, { M, 4}, {RW, 0}, {RW, 1}, {RW, 2}, {RW, 3}, {RW, 4},
00466         {RW, 5}, {RW, 6}, {RW, 7}, {RW, 8}, {RW, 9}, {GW, 0}, {GW, 1}, {GW, 2}, {GW, 3}, {GW, 4},
00467         {GW, 5}, {GW, 6}, {GW, 7}, {GW, 8}, {GW, 9}, {BW, 0}, {BW, 1}, {BW, 2}, {BW, 3}, {BW, 4},
00468         {BW, 5}, {BW, 6}, {BW, 7}, {BW, 8}, {BW, 9}, {RX, 0}, {RX, 1}, {RX, 2}, {RX, 3}, {RW,15},
00469         {RW,14}, {RW,13}, {RW,12}, {RW,11}, {RW,10}, {GX, 0}, {GX, 1}, {GX, 2}, {GX, 3}, {GW,15},
00470         {GW,14}, {GW,13}, {GW,12}, {GW,11}, {GW,10}, {BX, 0}, {BX, 1}, {BX, 2}, {BX, 3}, {BW,15},
00471         {BW,14}, {BW,13}, {BW,12}, {BW,11}, {BW,10}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0},
00472         {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0}, {NA, 0},
00473         {NA, 0}, {NA, 0},
00474     },
00475 };
00476
00477 // Mode, Partitions, Transformed, IndexPrec, RGBAPrec
00478 const D3DX_BC6H::ModeInfo D3DX_BC6H::ms_aInfo[] =
00479 {
00480     {0x00, 1, true,  3, LDRColorA(10,10,10,0), LDRColorA( 5, 5, 5,0), LDRColorA(5,5,5,0), LDRColorA(5,5,5,0)}, // Mode 0
00481     {0x01, 1, true,  3, LDRColorA( 7, 7, 7,0), LDRColorA( 6, 6, 6,0), LDRColorA(6,6,6,0), LDRColorA(6,6,6,0)}, // Mode 1
00482     {0x02, 1, true,  3, LDRColorA(11,11,11,0), LDRColorA( 5, 4, 4,0), LDRColorA(5,4,4,0), LDRColorA(5,4,4,0)}, // Mode 2
00483     {0x06, 1, true,  3, LDRColorA(11,11,11,0), LDRColorA( 4, 5, 4,0), LDRColorA(4,5,4,0), LDRColorA(4,5,4,0)}, // Mode 3
00484     {0x0a, 1, true,  3, LDRColorA(11,11,11,0), LDRColorA( 4, 4, 5,0), LDRColorA(4,4,5,0), LDRColorA(4,4,5,0)}, // Mode 4
00485     {0x0e, 1, true,  3, LDRColorA( 9, 9, 9,0), LDRColorA( 5, 5, 5,0), LDRColorA(5,5,5,0), LDRColorA(5,5,5,0)}, // Mode 5
00486     {0x12, 1, true,  3, LDRColorA( 8, 8, 8,0), LDRColorA( 6, 5, 5,0), LDRColorA(6,5,5,0), LDRColorA(6,5,5,0)}, // Mode 6
00487     {0x16, 1, true,  3, LDRColorA( 8, 8, 8,0), LDRColorA( 5, 6, 5,0), LDRColorA(5,6,5,0), LDRColorA(5,6,5,0)}, // Mode 7
00488     {0x1a, 1, true,  3, LDRColorA( 8, 8, 8,0), LDRColorA( 5, 5, 6,0), LDRColorA(5,5,6,0), LDRColorA(5,5,6,0)}, // Mode 8
00489     {0x1e, 1, false, 3, LDRColorA( 6, 6, 6,0), LDRColorA( 6, 6, 6,0), LDRColorA(6,6,6,0), LDRColorA(6,6,6,0)}, // Mode 9
00490     {0x03, 0, false, 4, LDRColorA(10,10,10,0), LDRColorA(10,10,10,0), LDRColorA(0,0,0,0), LDRColorA(0,0,0,0)}, // Mode 10
00491     {0x07, 0, true,  4, LDRColorA(11,11,11,0), LDRColorA( 9, 9, 9,0), LDRColorA(0,0,0,0), LDRColorA(0,0,0,0)}, // Mode 11
00492     {0x0b, 0, true,  4, LDRColorA(12,12,12,0), LDRColorA( 8, 8, 8,0), LDRColorA(0,0,0,0), LDRColorA(0,0,0,0)}, // Mode 12
00493     {0x0f, 0, true,  4, LDRColorA(16,16,16,0), LDRColorA( 4, 4, 4,0), LDRColorA(0,0,0,0), LDRColorA(0,0,0,0)}, // Mode 13
00494 };
00495
00496 const int D3DX_BC6H::ms_aModeToInfo[] =
00497 {
00498      0, // 0x00
00499      1, // 0x01
00500      2, // 0x02
00501     10, // 0x03
00502     -1, // 0x04
00503     -1, // 0x05
00504      3, // 0x06
00505     11, // 0x07
00506     -1, // 0x08
00507     -1, // 0x09
00508      4, // 0x0a
00509     12, // 0x0b
00510     -1, // 0x0c
00511     -1, // 0x0d
00512      5, // 0x0e
00513     13, // 0x0f
00514     -1, // 0x10
00515     -1, // 0x11
00516      6, // 0x12
00517     -1, // 0x13
00518     -1, // 0x14
00519     -1, // 0x15
00520      7, // 0x16
00521     -1, // 0x17
00522     -1, // 0x18
00523     -1, // 0x19
00524      8, // 0x1a
00525     -1, // 0x1b
00526     -1, // 0x1c
00527     -1, // 0x1d
00528      9, // 0x1e
00529     -1, // 0x1f
00530 };
00531
00532 // BC7 compression: uPartitions, uPartitionBits, uPBits, uRotationBits, uIndexModeBits, uIndexPrec, uIndexPrec2, RGBAPrec, RGBAPrecWithP
00533 const D3DX_BC7::ModeInfo D3DX_BC7::ms_aInfo[] =
00534 {
00535     {2, 4, 6, 0, 0, 3, 0, LDRColorA(4,4,4,0), LDRColorA(5,5,5,0)},
00536         // Mode 0: Color only, 3 Subsets, RGBP 4441 (unique P-bit), 3-bit indecies, 16 partitions
00537     {1, 6, 2, 0, 0, 3, 0, LDRColorA(6,6,6,0), LDRColorA(7,7,7,0)},
00538         // Mode 1: Color only, 2 Subsets, RGBP 6661 (shared P-bit), 3-bit indecies, 64 partitions
00539     {2, 6, 0, 0, 0, 2, 0, LDRColorA(5,5,5,0), LDRColorA(5,5,5,0)},
00540         // Mode 2: Color only, 3 Subsets, RGB 555, 2-bit indecies, 64 partitions
00541     {1, 6, 4, 0, 0, 2, 0, LDRColorA(7,7,7,0), LDRColorA(8,8,8,0)},
00542         // Mode 3: Color only, 2 Subsets, RGBP 7771 (unique P-bit), 2-bits indecies, 64 partitions
00543     {0, 0, 0, 2, 1, 2, 3, LDRColorA(5,5,5,6), LDRColorA(5,5,5,6)},
00544         // Mode 4: Color w/ Separate Alpha, 1 Subset, RGB 555, A6, 16x2/16x3-bit indices, 2-bit rotation, 1-bit index selector
00545     {0, 0, 0, 2, 0, 2, 2, LDRColorA(7,7,7,8), LDRColorA(7,7,7,8)},
00546         // Mode 5: Color w/ Separate Alpha, 1 Subset, RGB 777, A8, 16x2/16x2-bit indices, 2-bit rotation
00547     {0, 0, 2, 0, 0, 4, 0, LDRColorA(7,7,7,7), LDRColorA(8,8,8,8)},
00548         // Mode 6: Color+Alpha, 1 Subset, RGBAP 77771 (unique P-bit), 16x4-bit indecies
00549     {1, 6, 4, 0, 0, 2, 0, LDRColorA(5,5,5,5), LDRColorA(6,6,6,6)}
00550         // Mode 7: Color+Alpha, 2 Subsets, RGBAP 55551 (unique P-bit), 2-bit indices, 64 partitions
00551 };
00552
00553
00554 //-------------------------------------------------------------------------------------
00555 // Helper functions
00556 //-------------------------------------------------------------------------------------
00557 template< class T >
00558 inline static void Swap( T& a, T& b )
00559 {
00560     T temp = a;
00561     a = b;
00562     b = temp;
00563 }
00564
00565 inline static bool IsFixUpOffset(_In_range_(0,2) size_t uPartitions, _In_range_(0,63) size_t uShape, _In_range_(0,15) size_t uOffset)
00566 {
00567     assert(uPartitions < 3 && uShape < 64 && uOffset < 16);
00568     _Analysis_assume_(uPartitions < 3 && uShape < 64 && uOffset < 16);
00569     for(size_t p = 0; p <= uPartitions; p++)
00570     {
00571         if(uOffset == g_aFixUp[uPartitions][uShape][p])
00572         {
00573             return true;
00574         }
00575     }
00576     return false;
00577 }
00578
00579 inline static float ErrorMetricRGB(_In_ const LDRColorA& a, _In_ const LDRColorA& b)
00580 {
00581     float er = float(a.r) - float(b.r);
00582     float eg = float(a.g) - float(b.g);
00583     float eb = float(a.b) - float(b.b);
00584     // weigh the components nonuniformly
00585     //er *= 0.299;
00586     //eg *= 0.587;
00587     //eb *= 0.114;
00588     return er*er + eg*eg + eb*eb;
00589 }
00590
00591 inline static float ErrorMetricAlpha(_In_ const LDRColorA& a, _In_ const LDRColorA& b)
00592 {
00593     float ea = float(a.a) - float(b.a);
00594     return ea*ea;
00595 }
00596
00597 inline static float ErrorMetric(_In_ const LDRColorA& a, _In_ const LDRColorA& b)
00598 {
00599     return ErrorMetricRGB(a, b) + ErrorMetricAlpha(a, b);
00600 }
00601
00602 inline static void TransformForward(_Inout_updates_all_(BC6H_MAX_REGIONS) INTEndPntPair aEndPts[])
00603 {
00604     aEndPts[0].B -= aEndPts[0].A;
00605     aEndPts[1].A -= aEndPts[0].A;
00606     aEndPts[1].B -= aEndPts[0].A;
00607 }
00608
00609 inline static void TransformInverse(_Inout_updates_all_(BC6H_MAX_REGIONS) INTEndPntPair aEndPts[], _In_ const LDRColorA& Prec, _In_ bool bSigned)
00610 {
00611     INTColor WrapMask((1 << Prec.r) - 1, (1 << Prec.g) - 1, (1 << Prec.b) - 1);
00612     aEndPts[0].B += aEndPts[0].A; aEndPts[0].B &= WrapMask;
00613     aEndPts[1].A += aEndPts[0].A; aEndPts[1].A &= WrapMask;
00614     aEndPts[1].B += aEndPts[0].A; aEndPts[1].B &= WrapMask;
00615     if(bSigned)
00616     {
00617         aEndPts[0].B.SignExtend(Prec);
00618         aEndPts[1].A.SignExtend(Prec);
00619         aEndPts[1].B.SignExtend(Prec);
00620     }
00621 }
00622
00623 inline static float Norm(_In_ const INTColor& a, _In_ const INTColor& b)
00624 {
00625     float dr = float(a.r) - float(b.r);
00626     float dg = float(a.g) - float(b.g);
00627     float db = float(a.b) - float(b.b);
00628     return dr * dr + dg * dg + db * db;
00629 }
00630
00631 // return # of bits needed to store n. handle signed or unsigned cases properly
00632 inline static int NBits(_In_ int n, _In_ bool bIsSigned)
00633 {
00634     int nb;
00635     if(n == 0)
00636     {
00637         return 0; // no bits needed for 0, signed or not
00638     }
00639     else if(n > 0)
00640     {
00641         for(nb = 0; n; ++nb, n >>= 1);
00642         return nb + (bIsSigned ? 1 : 0);
00643     }
00644     else
00645     {
00646         assert(bIsSigned);
00647         for(nb = 0; n < -1; ++nb, n >>= 1) ;
00648         return nb + 1;
00649     }
00650 }
00651
00652
00653 //-------------------------------------------------------------------------------------
00654 static float OptimizeRGB(_In_reads_(NUM_PIXELS_PER_BLOCK) const HDRColorA* const pPoints,
00655                          _Out_ HDRColorA* pX, _Out_ HDRColorA* pY,
00656                          _In_ size_t cSteps, _In_ size_t cPixels, _In_reads_(cPixels) const size_t* pIndex)
00657 {
00658     float fError = FLT_MAX;
00659     const float *pC = (3 == cSteps) ? pC3 : pC4;
00660     const float *pD = (3 == cSteps) ? pD3 : pD4;
00661
00662     // Find Min and Max points, as starting point
00663     HDRColorA X(1.0f, 1.0f, 1.0f, 0.0f);
00664     HDRColorA Y(0.0f, 0.0f, 0.0f, 0.0f);
00665
00666     for(size_t iPoint = 0; iPoint < cPixels; iPoint++)
00667     {
00668         if(pPoints[pIndex[iPoint]].r < X.r) X.r = pPoints[pIndex[iPoint]].r;
00669         if(pPoints[pIndex[iPoint]].g < X.g) X.g = pPoints[pIndex[iPoint]].g;
00670         if(pPoints[pIndex[iPoint]].b < X.b) X.b = pPoints[pIndex[iPoint]].b;
00671         if(pPoints[pIndex[iPoint]].r > Y.r) Y.r = pPoints[pIndex[iPoint]].r;
00672         if(pPoints[pIndex[iPoint]].g > Y.g) Y.g = pPoints[pIndex[iPoint]].g;
00673         if(pPoints[pIndex[iPoint]].b > Y.b) Y.b = pPoints[pIndex[iPoint]].b;
00674     }
00675
00676     // Diagonal axis
00677     HDRColorA AB;
00678     AB.r = Y.r - X.r;
00679     AB.g = Y.g - X.g;
00680     AB.b = Y.b - X.b;
00681
00682     float fAB = AB.r * AB.r + AB.g * AB.g + AB.b * AB.b;
00683
00684     // Single color block.. no need to root-find
00685     if(fAB < FLT_MIN)
00686     {
00687         pX->r = X.r; pX->g = X.g; pX->b = X.b;
00688         pY->r = Y.r; pY->g = Y.g; pY->b = Y.b;
00689         return 0.0f;
00690     }
00691
00692     // Try all four axis directions, to determine which diagonal best fits data
00693     float fABInv = 1.0f / fAB;
00694
00695     HDRColorA Dir;
00696     Dir.r = AB.r * fABInv;
00697     Dir.g = AB.g * fABInv;
00698     Dir.b = AB.b * fABInv;
00699
00700     HDRColorA Mid;
00701     Mid.r = (X.r + Y.r) * 0.5f;
00702     Mid.g = (X.g + Y.g) * 0.5f;
00703     Mid.b = (X.b + Y.b) * 0.5f;
00704
00705     float fDir[4];
00706     fDir[0] = fDir[1] = fDir[2] = fDir[3] = 0.0f;
00707
00708     for(size_t iPoint = 0; iPoint < cPixels; iPoint++)
00709     {
00710         HDRColorA Pt;
00711         Pt.r = (pPoints[pIndex[iPoint]].r - Mid.r) * Dir.r;
00712         Pt.g = (pPoints[pIndex[iPoint]].g - Mid.g) * Dir.g;
00713         Pt.b = (pPoints[pIndex[iPoint]].b - Mid.b) * Dir.b;
00714
00715         float f;
00716         f = Pt.r + Pt.g + Pt.b; fDir[0] += f * f;
00717         f = Pt.r + Pt.g - Pt.b; fDir[1] += f * f;
00718         f = Pt.r - Pt.g + Pt.b; fDir[2] += f * f;
00719         f = Pt.r - Pt.g - Pt.b; fDir[3] += f * f;
00720     }
00721
00722     float fDirMax = fDir[0];
00723     size_t  iDirMax = 0;
00724
00725     for(size_t iDir = 1; iDir < 4; iDir++)
00726     {
00727         if(fDir[iDir] > fDirMax)
00728         {
00729             fDirMax = fDir[iDir];
00730             iDirMax = iDir;
00731         }
00732     }
00733
00734     if(iDirMax & 2) Swap( X.g, Y.g );
00735     if(iDirMax & 1) Swap( X.b, Y.b );
00736
00737     // Two color block.. no need to root-find
00738     if(fAB < 1.0f / 4096.0f)
00739     {
00740         pX->r = X.r; pX->g = X.g; pX->b = X.b;
00741         pY->r = Y.r; pY->g = Y.g; pY->b = Y.b;
00742         return 0.0f;
00743     }
00744
00745     // Use Newton's Method to find local minima of sum-of-squares error.
00746     float fSteps = (float) (cSteps - 1);
00747
00748     for(size_t iIteration = 0; iIteration < 8; iIteration++)
00749     {
00750         // Calculate new steps
00751         HDRColorA pSteps[4];
00752
00753         for(size_t iStep = 0; iStep < cSteps; iStep++)
00754         {
00755             pSteps[iStep].r = X.r * pC[iStep] + Y.r * pD[iStep];
00756             pSteps[iStep].g = X.g * pC[iStep] + Y.g * pD[iStep];
00757             pSteps[iStep].b = X.b * pC[iStep] + Y.b * pD[iStep];
00758         }
00759
00760         // Calculate color direction
00761         Dir.r = Y.r - X.r;
00762         Dir.g = Y.g - X.g;
00763         Dir.b = Y.b - X.b;
00764
00765         float fLen = (Dir.r * Dir.r + Dir.g * Dir.g + Dir.b * Dir.b);
00766
00767         if(fLen < (1.0f / 4096.0f))
00768             break;
00769
00770         float fScale = fSteps / fLen;
00771
00772         Dir.r *= fScale;
00773         Dir.g *= fScale;
00774         Dir.b *= fScale;
00775
00776         // Evaluate function, and derivatives
00777         float d2X = 0.0f, d2Y = 0.0f;
00778         HDRColorA dX(0.0f, 0.0f, 0.0f, 0.0f), dY(0.0f, 0.0f, 0.0f, 0.0f);
00779
00780         for(size_t iPoint = 0; iPoint < cPixels; iPoint++)
00781         {
00782             float fDot = (pPoints[pIndex[iPoint]].r - X.r) * Dir.r +
00783                 (pPoints[pIndex[iPoint]].g - X.g) * Dir.g +
00784                 (pPoints[pIndex[iPoint]].b - X.b) * Dir.b;
00785
00786             size_t iStep;
00787             if(fDot <= 0.0f)
00788                 iStep = 0;
00789             if(fDot >= fSteps)
00790                 iStep = cSteps - 1;
00791             else
00792                 iStep = size_t(fDot + 0.5f);
00793
00794             HDRColorA Diff;
00795             Diff.r = pSteps[iStep].r - pPoints[pIndex[iPoint]].r;
00796             Diff.g = pSteps[iStep].g - pPoints[pIndex[iPoint]].g;
00797             Diff.b = pSteps[iStep].b - pPoints[pIndex[iPoint]].b;
00798
00799             float fC = pC[iStep] * (1.0f / 8.0f);
00800             float fD = pD[iStep] * (1.0f / 8.0f);
00801
00802             d2X  += fC * pC[iStep];
00803             dX.r += fC * Diff.r;
00804             dX.g += fC * Diff.g;
00805             dX.b += fC * Diff.b;
00806
00807             d2Y  += fD * pD[iStep];
00808             dY.r += fD * Diff.r;
00809             dY.g += fD * Diff.g;
00810             dY.b += fD * Diff.b;
00811         }
00812
00813         // Move endpoints
00814         if(d2X > 0.0f)
00815         {
00816             float f = -1.0f / d2X;
00817
00818             X.r += dX.r * f;
00819             X.g += dX.g * f;
00820             X.b += dX.b * f;
00821         }
00822
00823         if(d2Y > 0.0f)
00824         {
00825             float f = -1.0f / d2Y;
00826
00827             Y.r += dY.r * f;
00828             Y.g += dY.g * f;
00829             Y.b += dY.b * f;
00830         }
00831
00832         if((dX.r * dX.r < fEpsilon) && (dX.g * dX.g < fEpsilon) && (dX.b * dX.b < fEpsilon) &&
00833             (dY.r * dY.r < fEpsilon) && (dY.g * dY.g < fEpsilon) && (dY.b * dY.b < fEpsilon))
00834         {
00835             break;
00836         }
00837     }
00838
00839     pX->r = X.r; pX->g = X.g; pX->b = X.b;
00840     pY->r = Y.r; pY->g = Y.g; pY->b = Y.b;
00841     return fError;
00842 }
00843
00844
00845 //-------------------------------------------------------------------------------------
00846 static float OptimizeRGBA(_In_reads_(NUM_PIXELS_PER_BLOCK) const HDRColorA* const pPoints,
00847                           _Out_ HDRColorA* pX, _Out_ HDRColorA* pY,
00848                           _In_ size_t cSteps, _In_ size_t cPixels, _In_reads_(cPixels) const size_t* pIndex)
00849 {
00850     float fError = FLT_MAX;
00851     const float *pC = (3 == cSteps) ? pC3 : pC4;
00852     const float *pD = (3 == cSteps) ? pD3 : pD4;
00853
00854     // Find Min and Max points, as starting point
00855     HDRColorA X(1.0f, 1.0f, 1.0f, 1.0f);
00856     HDRColorA Y(0.0f, 0.0f, 0.0f, 0.0f);
00857
00858     for(size_t iPoint = 0; iPoint < cPixels; iPoint++)
00859     {
00860         if(pPoints[pIndex[iPoint]].r < X.r) X.r = pPoints[pIndex[iPoint]].r;
00861         if(pPoints[pIndex[iPoint]].g < X.g) X.g = pPoints[pIndex[iPoint]].g;
00862         if(pPoints[pIndex[iPoint]].b < X.b) X.b = pPoints[pIndex[iPoint]].b;
00863         if(pPoints[pIndex[iPoint]].a < X.a) X.a = pPoints[pIndex[iPoint]].a;
00864         if(pPoints[pIndex[iPoint]].r > Y.r) Y.r = pPoints[pIndex[iPoint]].r;
00865         if(pPoints[pIndex[iPoint]].g > Y.g) Y.g = pPoints[pIndex[iPoint]].g;
00866         if(pPoints[pIndex[iPoint]].b > Y.b) Y.b = pPoints[pIndex[iPoint]].b;
00867         if(pPoints[pIndex[iPoint]].a > Y.a) Y.a = pPoints[pIndex[iPoint]].a;
00868     }
00869
00870     // Diagonal axis
00871     HDRColorA AB = Y - X;
00872     float fAB = AB * AB;
00873
00874     // Single color block.. no need to root-find
00875     if(fAB < FLT_MIN)
00876     {
00877         *pX = X;
00878         *pY = Y;
00879         return 0.0f;
00880     }
00881
00882     // Try all four axis directions, to determine which diagonal best fits data
00883     float fABInv = 1.0f / fAB;
00884     HDRColorA Dir = AB * fABInv;
00885     HDRColorA Mid = (X + Y) * 0.5f;
00886
00887     float fDir[8];
00888     fDir[0] = fDir[1] = fDir[2] = fDir[3] = fDir[4] = fDir[5] = fDir[6] = fDir[7] = 0.0f;
00889
00890     for(size_t iPoint = 0; iPoint < cPixels; iPoint++)
00891     {
00892         HDRColorA Pt;
00893         Pt.r = (pPoints[pIndex[iPoint]].r - Mid.r) * Dir.r;
00894         Pt.g = (pPoints[pIndex[iPoint]].g - Mid.g) * Dir.g;
00895         Pt.b = (pPoints[pIndex[iPoint]].b - Mid.b) * Dir.b;
00896         Pt.a = (pPoints[pIndex[iPoint]].a - Mid.a) * Dir.a;
00897
00898         float f;
00899         f = Pt.r + Pt.g + Pt.b + Pt.a; fDir[0] += f * f;
00900         f = Pt.r + Pt.g + Pt.b - Pt.a; fDir[1] += f * f;
00901         f = Pt.r + Pt.g - Pt.b + Pt.a; fDir[2] += f * f;
00902         f = Pt.r + Pt.g - Pt.b - Pt.a; fDir[3] += f * f;
00903         f = Pt.r - Pt.g + Pt.b + Pt.a; fDir[4] += f * f;
00904         f = Pt.r - Pt.g + Pt.b - Pt.a; fDir[5] += f * f;
00905         f = Pt.r - Pt.g - Pt.b + Pt.a; fDir[6] += f * f;
00906         f = Pt.r - Pt.g - Pt.b - Pt.a; fDir[7] += f * f;
00907     }
00908
00909     float fDirMax = fDir[0];
00910     size_t  iDirMax = 0;
00911
00912     for(size_t iDir = 1; iDir < 8; iDir++)
00913     {
00914         if(fDir[iDir] > fDirMax)
00915         {
00916             fDirMax = fDir[iDir];
00917             iDirMax = iDir;
00918         }
00919     }
00920
00921     if(iDirMax & 4) Swap(X.g, Y.g);
00922     if(iDirMax & 2) Swap(X.b, Y.b);
00923     if(iDirMax & 1) Swap(X.a, Y.a);
00924
00925     // Two color block.. no need to root-find
00926     if(fAB < 1.0f / 4096.0f)
00927     {
00928         *pX = X;
00929         *pY = Y;
00930         return 0.0f;
00931     }
00932
00933     // Use Newton's Method to find local minima of sum-of-squares error.
00934     float fSteps = (float) (cSteps - 1);
00935
00936     for(size_t iIteration = 0; iIteration < 8 && fError > 0.0f; iIteration++)
00937     {
00938         // Calculate new steps
00939         HDRColorA pSteps[BC7_MAX_INDICES];
00940
00941         LDRColorA aSteps[BC7_MAX_INDICES];
00942         LDRColorA lX, lY;
00943         lX = (X * 255.0f).ToLDRColorA();
00944         lY = (Y * 255.0f).ToLDRColorA();
00945
00946         for(size_t iStep = 0; iStep < cSteps; iStep++)
00947         {
00948             pSteps[iStep] = X * pC[iStep] + Y * pD[iStep];
00949             //LDRColorA::Interpolate(lX, lY, i, i, wcprec, waprec, aSteps[i]);
00950         }
00951
00952         // Calculate color direction
00953         Dir = Y - X;
00954         float fLen = Dir * Dir;
00955         if(fLen < (1.0f / 4096.0f))
00956             break;
00957
00958         float fScale = fSteps / fLen;
00959         Dir *= fScale;
00960
00961         // Evaluate function, and derivatives
00962         float d2X = 0.0f, d2Y = 0.0f;
00963         HDRColorA dX(0.0f, 0.0f, 0.0f, 0.0f), dY(0.0f, 0.0f, 0.0f, 0.0f);
00964
00965         for(size_t iPoint = 0; iPoint < cPixels; ++iPoint)
00966         {
00967             float fDot = (pPoints[pIndex[iPoint]] - X) * Dir;
00968             size_t iStep;
00969             if(fDot <= 0.0f)
00970                 iStep = 0;
00971             if(fDot >= fSteps)
00972                 iStep = cSteps - 1;
00973             else
00974                 iStep = size_t(fDot + 0.5f);
00975
00976             HDRColorA Diff = pSteps[iStep] - pPoints[pIndex[iPoint]];
00977             float fC = pC[iStep] * (1.0f / 8.0f);
00978             float fD = pD[iStep] * (1.0f / 8.0f);
00979
00980             d2X  += fC * pC[iStep];
00981             dX += Diff * fC;
00982
00983             d2Y  += fD * pD[iStep];
00984             dY += Diff * fD;
00985         }
00986
00987         // Move endpoints
00988         if(d2X > 0.0f)
00989         {
00990             float f = -1.0f / d2X;
00991             X += dX * f;
00992         }
00993
00994         if(d2Y > 0.0f)
00995         {
00996             float f = -1.0f / d2Y;
00997             Y += dY * f;
00998         }
00999
01000         if((dX * dX < fEpsilon) && (dY * dY < fEpsilon))
01001             break;
01002     }
01003
01004     *pX = X;
01005     *pY = Y;
01006     return fError;
01007 }
01008
01009
01010 //-------------------------------------------------------------------------------------
01011 #pragma warning(disable: 4616 6001 6297)
01012
01013 static float ComputeError(_Inout_ const LDRColorA& pixel, _In_reads_(1 << uIndexPrec) const LDRColorA aPalette[],
01014                           _In_ uint8_t uIndexPrec, _In_ uint8_t uIndexPrec2, _Out_opt_ size_t* pBestIndex = nullptr, _Out_opt_ size_t* pBestIndex2 = nullptr)
01015 {
01016     const size_t uNumIndices = 1 << uIndexPrec;
01017     const size_t uNumIndices2 = 1 << uIndexPrec2;
01018     float fTotalErr = 0;
01019     float fBestErr = FLT_MAX;
01020
01021     if(pBestIndex)
01022         *pBestIndex = 0;
01023     if(pBestIndex2)
01024         *pBestIndex2 = 0;
01025
01026     if(uIndexPrec2 == 0)
01027     {
01028         for(register size_t i = 0; i < uNumIndices && fBestErr > 0; i++)
01029         {
01030             float fErr = ErrorMetric(pixel, aPalette[i]);
01031             if(fErr > fBestErr) // error increased, so we're done searching
01032                 break;
01033             if(fErr < fBestErr)
01034             {
01035                 fBestErr = fErr;
01036                 if(pBestIndex)
01037                     *pBestIndex = i;
01038             }
01039         }
01040         fTotalErr += fBestErr;
01041     }
01042     else
01043     {
01044         for(register size_t i = 0; i < uNumIndices && fBestErr > 0; i++)
01045         {
01046             float fErr = ErrorMetricRGB(pixel, aPalette[i]);
01047             if(fErr > fBestErr) // error increased, so we're done searching
01048                 break;
01049             if(fErr < fBestErr)
01050             {
01051                 fBestErr = fErr;
01052                 if(pBestIndex)
01053                     *pBestIndex = i;
01054             }
01055         }
01056         fTotalErr += fBestErr;
01057         fBestErr = FLT_MAX;
01058         for(register size_t i = 0; i < uNumIndices2 && fBestErr > 0; i++)
01059         {
01060             float fErr = ErrorMetricAlpha(pixel, aPalette[i]);
01061             if(fErr > fBestErr) // error increased, so we're done searching
01062                 break;
01063             if(fErr < fBestErr)
01064             {
01065                 fBestErr = fErr;
01066                 if(pBestIndex2)
01067                     *pBestIndex2 = i;
01068             }
01069         }
01070         fTotalErr += fBestErr;
01071     }
01072
01073     return fTotalErr;
01074 }
01075
01076
01077 inline static void FillWithErrorColors( _Out_writes_(NUM_PIXELS_PER_BLOCK) HDRColorA* pOut )
01078 {
01079     for(size_t i = 0; i < NUM_PIXELS_PER_BLOCK; ++i)
01080     {
01081 #ifdef _DEBUG
01082         // Use Magenta in debug as a highly-visible error color
01083         pOut[i] = HDRColorA(1.0f, 0.0f, 1.0f, 1.0f);
01084 #else
01085         // In production use, default to black
01086         pOut[i] = HDRColorA(0.0f, 0.0f, 0.0f, 1.0f);
01087 #endif
01088     }
01089 }
01090
01091
01092 //-------------------------------------------------------------------------------------
01093 // BC6H Compression
01094 //-------------------------------------------------------------------------------------
01095 _Use_decl_annotations_
01096 void D3DX_BC6H::Decode(bool bSigned, HDRColorA* pOut) const
01097 {
01098     assert(pOut );
01099
01100     size_t uStartBit = 0;
01101     uint8_t uMode = GetBits(uStartBit, 2);
01102     if(uMode != 0x00 && uMode != 0x01)
01103     {
01104         uMode = (GetBits(uStartBit, 3) << 2) | uMode;
01105     }
01106
01107     assert( uMode < 32 );
01108     _Analysis_assume_( uMode < 32 );
01109
01110     if ( ms_aModeToInfo[uMode] >= 0 )
01111     {
01112         assert(ms_aModeToInfo[uMode] < ARRAYSIZE(ms_aInfo));
01113         _Analysis_assume_(ms_aModeToInfo[uMode] < ARRAYSIZE(ms_aInfo));
01114         const ModeDescriptor* desc = ms_aDesc[ms_aModeToInfo[uMode]];
01115
01116         assert(ms_aModeToInfo[uMode] < ARRAYSIZE(ms_aDesc));
01117         _Analysis_assume_(ms_aModeToInfo[uMode] < ARRAYSIZE(ms_aDesc));
01118         const ModeInfo& info = ms_aInfo[ms_aModeToInfo[uMode]];
01119
01120         INTEndPntPair aEndPts[BC6H_MAX_REGIONS];
01121         memset(aEndPts, 0, BC6H_MAX_REGIONS * 2 * sizeof(INTColor));
01122         uint32_t uShape = 0;
01123
01124         // Read header
01125         const size_t uHeaderBits = info.uPartitions > 0 ? 82 : 65;
01126         while(uStartBit < uHeaderBits)
01127         {
01128             size_t uCurBit = uStartBit;
01129             if(GetBit(uStartBit))
01130             {
01131                 switch(desc[uCurBit].m_eField)
01132                 {
01133                 case D:  uShape |= 1 << uint32_t(desc[uCurBit].m_uBit); break;
01134                 case RW: aEndPts[0].A.r |= 1 << uint32_t(desc[uCurBit].m_uBit); break;
01135                 case RX: aEndPts[0].B.r |= 1 << uint32_t(desc[uCurBit].m_uBit); break;
01136                 case RY: aEndPts[1].A.r |= 1 << uint32_t(desc[uCurBit].m_uBit); break;
01137                 case RZ: aEndPts[1].B.r |= 1 << uint32_t(desc[uCurBit].m_uBit); break;
01138                 case GW: aEndPts[0].A.g |= 1 << uint32_t(desc[uCurBit].m_uBit); break;
01139                 case GX: aEndPts[0].B.g |= 1 << uint32_t(desc[uCurBit].m_uBit); break;
01140                 case GY: aEndPts[1].A.g |= 1 << uint32_t(desc[uCurBit].m_uBit); break;
01141                 case GZ: aEndPts[1].B.g |= 1 << uint32_t(desc[uCurBit].m_uBit); break;
01142                 case BW: aEndPts[0].A.b |= 1 << uint32_t(desc[uCurBit].m_uBit); break;
01143                 case BX: aEndPts[0].B.b |= 1 << uint32_t(desc[uCurBit].m_uBit); break;
01144                 case BY: aEndPts[1].A.b |= 1 << uint32_t(desc[uCurBit].m_uBit); break;
01145                 case BZ: aEndPts[1].B.b |= 1 << uint32_t(desc[uCurBit].m_uBit); break;
01146                 default:
01147                     {
01148 #ifdef _DEBUG
01149                         OutputDebugStringA( "BC6H: Invalid header bits encountered during decoding\n" );
01150 #endif
01151                         FillWithErrorColors( pOut );
01152                         return;
01153                     }
01154                 }
01155             }
01156         }
01157
01158         assert( uShape < 64 );
01159         _Analysis_assume_( uShape < 64 );
01160
01161         // Sign extend necessary end points
01162         if(bSigned)
01163         {
01164             aEndPts[0].A.SignExtend(info.RGBAPrec[0][0]);
01165         }
01166         if(bSigned || info.bTransformed)
01167         {
01168             assert( info.uPartitions < BC6H_MAX_REGIONS );
01169             _Analysis_assume_( info.uPartitions < BC6H_MAX_REGIONS );
01170             for(size_t p = 0; p <= info.uPartitions; ++p)
01171             {
01172                 if(p != 0)
01173                 {
01174                     aEndPts[p].A.SignExtend(info.RGBAPrec[p][0]);
01175                 }
01176                 aEndPts[p].B.SignExtend(info.RGBAPrec[p][1]);
01177             }
01178         }
01179
01180         // Inverse transform the end points
01181         if(info.bTransformed)
01182         {
01183             TransformInverse(aEndPts, info.RGBAPrec[0][0], bSigned);
01184         }
01185
01186         // Read indices
01187         for(size_t i = 0; i < NUM_PIXELS_PER_BLOCK; ++i)
01188         {
01189             size_t uNumBits = IsFixUpOffset(info.uPartitions, uShape, i) ? info.uIndexPrec-1 : info.uIndexPrec;
01190             if ( uStartBit + uNumBits > 128 )
01191             {
01192 #ifdef _DEBUG
01193                 OutputDebugStringA( "BC6H: Invalid block encountered during decoding\n" );
01194 #endif
01195                 FillWithErrorColors( pOut );
01196                 return;
01197             }
01198             uint8_t uIndex = GetBits(uStartBit, uNumBits);
01199
01200             if ( uIndex >= ((info.uPartitions > 0) ? 8 : 16) )
01201             {
01202 #ifdef _DEBUG
01203                 OutputDebugStringA( "BC6H: Invalid index encountered during decoding\n" );
01204 #endif
01205                 FillWithErrorColors( pOut );
01206                 return;
01207             }
01208
01209             size_t uRegion = g_aPartitionTable[info.uPartitions][uShape][i];
01210             assert( uRegion < BC6H_MAX_REGIONS );
01211             _Analysis_assume_( uRegion < BC6H_MAX_REGIONS );
01212
01213             // Unquantize endpoints and interpolate
01214             int r1 = Unquantize(aEndPts[uRegion].A.r, info.RGBAPrec[0][0].r, bSigned);
01215             int g1 = Unquantize(aEndPts[uRegion].A.g, info.RGBAPrec[0][0].g, bSigned);
01216             int b1 = Unquantize(aEndPts[uRegion].A.b, info.RGBAPrec[0][0].b, bSigned);
01217             int r2 = Unquantize(aEndPts[uRegion].B.r, info.RGBAPrec[0][0].r, bSigned);
01218             int g2 = Unquantize(aEndPts[uRegion].B.g, info.RGBAPrec[0][0].g, bSigned);
01219             int b2 = Unquantize(aEndPts[uRegion].B.b, info.RGBAPrec[0][0].b, bSigned);
01220             const int* aWeights = info.uPartitions > 0 ? g_aWeights3 : g_aWeights4;
01221             INTColor fc;
01222             fc.r = FinishUnquantize((r1 * (BC67_WEIGHT_MAX - aWeights[uIndex]) + r2 * aWeights[uIndex] + BC67_WEIGHT_ROUND) >> BC67_WEIGHT_SHIFT, bSigned);
01223             fc.g = FinishUnquantize((g1 * (BC67_WEIGHT_MAX - aWeights[uIndex]) + g2 * aWeights[uIndex] + BC67_WEIGHT_ROUND) >> BC67_WEIGHT_SHIFT, bSigned);
01224             fc.b = FinishUnquantize((b1 * (BC67_WEIGHT_MAX - aWeights[uIndex]) + b2 * aWeights[uIndex] + BC67_WEIGHT_ROUND) >> BC67_WEIGHT_SHIFT, bSigned);
01225
01226             PackedVector::HALF rgb[3];
01227             fc.ToF16(rgb, bSigned);
01228
01229             pOut[i].r = PackedVector::XMConvertHalfToFloat( rgb[0] );
01230             pOut[i].g = PackedVector::XMConvertHalfToFloat( rgb[1] );
01231             pOut[i].b = PackedVector::XMConvertHalfToFloat( rgb[2] );
01232             pOut[i].a = 1.0f;
01233         }
01234     }
01235     else
01236     {
01237 #ifdef _DEBUG
01238         OutputDebugStringA( "BC6H: Invalid mode encountered during decoding\n" );
01239 #endif
01240         FillWithErrorColors( pOut );
01241     }
01242 }
01243
01244 _Use_decl_annotations_
01245 void D3DX_BC6H::Encode(bool bSigned, const HDRColorA* const pIn)
01246 {
01247     assert( pIn );
01248
01249     EncodeParams EP(pIn, bSigned);
01250
01251     for(EP.uMode = 0; EP.uMode < ARRAYSIZE(ms_aInfo) && EP.fBestErr > 0; ++EP.uMode)
01252     {
01253         const uint8_t uShapes = ms_aInfo[EP.uMode].uPartitions ? 32 : 1;
01254         // Number of rough cases to look at. reasonable values of this are 1, uShapes/4, and uShapes
01255         // uShapes/4 gets nearly all the cases; you can increase that a bit (say by 3 or 4) if you really want to squeeze the last bit out
01256         const size_t uItems = std::max<size_t>(1, uShapes >> 2);
01257         float afRoughMSE[BC6H_MAX_SHAPES];
01258         uint8_t auShape[BC6H_MAX_SHAPES];
01259
01260         // pick the best uItems shapes and refine these.
01261         for(EP.uShape = 0; EP.uShape < uShapes; ++EP.uShape)
01262         {
01263             size_t uShape = EP.uShape;
01264             afRoughMSE[uShape] = RoughMSE(&EP);
01265             auShape[uShape] = static_cast<uint8_t>(uShape);
01266         }
01267
01268         // Bubble up the first uItems items
01269         for(register size_t i = 0; i < uItems; i++)
01270         {
01271             for(register size_t j = i + 1; j < uShapes; j++)
01272             {
01273                 if(afRoughMSE[i] > afRoughMSE[j])
01274                 {
01275                     Swap(afRoughMSE[i], afRoughMSE[j]);
01276                     Swap(auShape[i], auShape[j]);
01277                 }
01278             }
01279         }
01280
01281         for(size_t i = 0; i < uItems && EP.fBestErr > 0; i++)
01282         {
01283             EP.uShape = auShape[i];
01284             Refine(&EP);
01285         }
01286     }
01287 }
01288
01289
01290 //-------------------------------------------------------------------------------------
01291 _Use_decl_annotations_
01292 int D3DX_BC6H::Quantize(int iValue, int prec, bool bSigned)
01293 {
01294     assert(prec > 1); // didn't bother to make it work for 1
01295     int q, s = 0;
01296     if(bSigned)
01297     {
01298         assert(iValue >= -F16MAX && iValue <= F16MAX);
01299         if(iValue < 0)
01300         {
01301             s = 1;
01302             iValue = -iValue;
01303         }
01304         q = (prec >= 16) ? iValue : (iValue << (prec-1)) / (F16MAX+1);
01305         if(s)
01306             q = -q;
01307         assert (q > -(1 << (prec-1)) && q < (1 << (prec-1)));
01308     }
01309     else
01310     {
01311         assert(iValue >= 0 && iValue <= F16MAX);
01312         q = (prec >= 15) ? iValue : (iValue << prec) / (F16MAX+1);
01313         assert (q >= 0 && q < (1 << prec));
01314     }
01315
01316     return q;
01317 }
01318
01319 _Use_decl_annotations_
01320 int D3DX_BC6H::Unquantize(int comp, uint8_t uBitsPerComp, bool bSigned)
01321 {
01322     int unq = 0, s = 0;
01323     if(bSigned)
01324     {
01325         if(uBitsPerComp >= 16)
01326         {
01327             unq = comp;
01328         }
01329         else
01330         {
01331             if(comp < 0)
01332             {
01333                 s = 1;
01334                 comp = -comp;
01335             }
01336
01337             if(comp == 0) unq = 0;
01338             else if(comp >= ((1 << (uBitsPerComp - 1)) - 1)) unq = 0x7FFF;
01339             else unq = ((comp << 15) + 0x4000) >> (uBitsPerComp-1);
01340
01341             if(s) unq = -unq;
01342         }
01343     }
01344     else
01345     {
01346         if(uBitsPerComp >= 15) unq = comp;
01347         else if(comp == 0) unq = 0;
01348         else if(comp == ((1 << uBitsPerComp) - 1)) unq = 0xFFFF;
01349         else unq = ((comp << 16) + 0x8000) >> uBitsPerComp;
01350     }
01351
01352     return unq;
01353 }
01354
01355 _Use_decl_annotations_
01356 int D3DX_BC6H::FinishUnquantize(int comp, bool bSigned)
01357 {
01358     if(bSigned)
01359     {
01360         return (comp < 0) ? -(((-comp) * 31) >> 5) : (comp * 31) >> 5;  // scale the magnitude by 31/32
01361     }
01362     else
01363     {
01364         return (comp * 31) >> 6;                                        // scale the magnitude by 31/64
01365     }
01366 }
01367
01368
01369 //-------------------------------------------------------------------------------------
01370 _Use_decl_annotations_
01371 bool D3DX_BC6H::EndPointsFit(const EncodeParams* pEP, const INTEndPntPair aEndPts[])
01372 {
01373     assert( pEP );
01374     const bool bTransformed = ms_aInfo[pEP->uMode].bTransformed;
01375     const bool bIsSigned = pEP->bSigned;
01376     const LDRColorA& Prec0 = ms_aInfo[pEP->uMode].RGBAPrec[0][0];
01377     const LDRColorA& Prec1 = ms_aInfo[pEP->uMode].RGBAPrec[0][1];
01378     const LDRColorA& Prec2 = ms_aInfo[pEP->uMode].RGBAPrec[1][0];
01379     const LDRColorA& Prec3 = ms_aInfo[pEP->uMode].RGBAPrec[1][1];
01380
01381     INTColor aBits[4];
01382     aBits[0].r = NBits(aEndPts[0].A.r, bIsSigned);
01383     aBits[0].g = NBits(aEndPts[0].A.g, bIsSigned);
01384     aBits[0].b = NBits(aEndPts[0].A.b, bIsSigned);
01385     aBits[1].r = NBits(aEndPts[0].B.r, bTransformed || bIsSigned);
01386     aBits[1].g = NBits(aEndPts[0].B.g, bTransformed || bIsSigned);
01387     aBits[1].b = NBits(aEndPts[0].B.b, bTransformed || bIsSigned);
01388     if(aBits[0].r > Prec0.r || aBits[1].r > Prec1.r ||
01389        aBits[0].g > Prec0.g || aBits[1].g > Prec1.g ||
01390        aBits[0].b > Prec0.b || aBits[1].b > Prec1.b)
01391         return false;
01392
01393     if(ms_aInfo[pEP->uMode].uPartitions)
01394     {
01395         aBits[2].r = NBits(aEndPts[1].A.r, bTransformed || bIsSigned);
01396         aBits[2].g = NBits(aEndPts[1].A.g, bTransformed || bIsSigned);
01397         aBits[2].b = NBits(aEndPts[1].A.b, bTransformed || bIsSigned);
01398         aBits[3].r = NBits(aEndPts[1].B.r, bTransformed || bIsSigned);
01399         aBits[3].g = NBits(aEndPts[1].B.g, bTransformed || bIsSigned);
01400         aBits[3].b = NBits(aEndPts[1].B.b, bTransformed || bIsSigned);
01401
01402         if(aBits[2].r > Prec2.r || aBits[3].r > Prec3.r ||
01403            aBits[2].g > Prec2.g || aBits[3].g > Prec3.g ||
01404            aBits[2].b > Prec2.b || aBits[3].b > Prec3.b)
01405             return false;
01406     }
01407
01408     return true;
01409 }
01410
01411 _Use_decl_annotations_
01412 void D3DX_BC6H::GeneratePaletteQuantized(const EncodeParams* pEP, const INTEndPntPair& endPts, INTColor aPalette[]) const
01413 {
01414     assert( pEP );
01415     const size_t uIndexPrec = ms_aInfo[pEP->uMode].uIndexPrec;
01416     const size_t uNumIndices = 1 << uIndexPrec;
01417     assert( uNumIndices > 0 );
01418     _Analysis_assume_( uNumIndices > 0 );
01419     const LDRColorA& Prec = ms_aInfo[pEP->uMode].RGBAPrec[0][0];
01420
01421     // scale endpoints
01422     INTEndPntPair unqEndPts;
01423     unqEndPts.A.r = Unquantize(endPts.A.r, Prec.r, pEP->bSigned);
01424     unqEndPts.A.g = Unquantize(endPts.A.g, Prec.g, pEP->bSigned);
01425     unqEndPts.A.b = Unquantize(endPts.A.b, Prec.b, pEP->bSigned);
01426     unqEndPts.B.r = Unquantize(endPts.B.r, Prec.r, pEP->bSigned);
01427     unqEndPts.B.g = Unquantize(endPts.B.g, Prec.g, pEP->bSigned);
01428     unqEndPts.B.b = Unquantize(endPts.B.b, Prec.b, pEP->bSigned);
01429
01430     // interpolate
01431     const int* aWeights = nullptr;
01432     switch(uIndexPrec)
01433     {
01434     case 3: aWeights = g_aWeights3; assert(uNumIndices <= 8); _Analysis_assume_(uNumIndices <= 8); break;
01435     case 4: aWeights = g_aWeights4; assert(uNumIndices <= 16); _Analysis_assume_(uNumIndices <= 16); break;
01436     default: assert(false); for(size_t i=0; i < uNumIndices; ++i) aPalette[i] = INTColor(0,0,0); return;
01437     }
01438
01439     for (size_t i = 0; i < uNumIndices; ++i)
01440     {
01441         aPalette[i].r = FinishUnquantize(
01442             (unqEndPts.A.r * (BC67_WEIGHT_MAX - aWeights[i]) + unqEndPts.B.r * aWeights[i] + BC67_WEIGHT_ROUND) >> BC67_WEIGHT_SHIFT,
01443             pEP->bSigned);
01444         aPalette[i].g = FinishUnquantize(
01445             (unqEndPts.A.g * (BC67_WEIGHT_MAX - aWeights[i]) + unqEndPts.B.g * aWeights[i] + BC67_WEIGHT_ROUND) >> BC67_WEIGHT_SHIFT,
01446             pEP->bSigned);
01447         aPalette[i].b = FinishUnquantize(
01448             (unqEndPts.A.b * (BC67_WEIGHT_MAX - aWeights[i]) + unqEndPts.B.b * aWeights[i] + BC67_WEIGHT_ROUND) >> BC67_WEIGHT_SHIFT,
01449             pEP->bSigned);
01450     }
01451 }
01452
01453 // given a collection of colors and quantized endpoints, generate a palette, choose best entries, and return a single toterr
01454 _Use_decl_annotations_
01455 float D3DX_BC6H::MapColorsQuantized(const EncodeParams* pEP, const INTColor aColors[], size_t np, const INTEndPntPair &endPts) const
01456 {
01457     assert( pEP );
01458
01459     const uint8_t uIndexPrec = ms_aInfo[pEP->uMode].uIndexPrec;
01460     const uint8_t uNumIndices = 1 << uIndexPrec;
01461     INTColor aPalette[BC6H_MAX_INDICES];
01462     GeneratePaletteQuantized(pEP, endPts, aPalette);
01463
01464     float fTotErr = 0;
01465     for(size_t i = 0; i < np; ++i)
01466     {
01467         float fBestErr = Norm(aColors[i], aPalette[0]);
01468         for(int j = 1; j < uNumIndices && fBestErr > 0; ++j)
01469         {
01470             float fErr = Norm(aColors[i], aPalette[j]);
01471             if(fErr > fBestErr) break;     // error increased, so we're done searching
01472             if(fErr < fBestErr) fBestErr = fErr;
01473         }
01474         fTotErr += fBestErr;
01475     }
01476     return fTotErr;
01477 }
01478
01479 _Use_decl_annotations_
01480 float D3DX_BC6H::PerturbOne(const EncodeParams* pEP, const INTColor aColors[], size_t np, uint8_t ch,
01481                             const INTEndPntPair& oldEndPts, INTEndPntPair& newEndPts, float fOldErr, int do_b) const
01482 {
01483     assert( pEP );
01484     uint8_t uPrec;
01485     switch(ch)
01486     {
01487     case 0: uPrec = ms_aInfo[pEP->uMode].RGBAPrec[0][0].r; break;
01488     case 1: uPrec = ms_aInfo[pEP->uMode].RGBAPrec[0][0].g; break;
01489     case 2: uPrec = ms_aInfo[pEP->uMode].RGBAPrec[0][0].b; break;
01490     default: assert(false); newEndPts = oldEndPts; return FLT_MAX;
01491     }
01492     INTEndPntPair tmpEndPts;
01493     float fMinErr = fOldErr;
01494     int beststep = 0;
01495
01496     // copy real endpoints so we can perturb them
01497     tmpEndPts = newEndPts = oldEndPts;
01498
01499     // do a logarithmic search for the best error for this endpoint (which)
01500     for(int step = 1 << (uPrec-1); step; step >>= 1)
01501     {
01502         bool bImproved = false;
01503         for(int sign = -1; sign <= 1; sign += 2)
01504         {
01505             if(do_b == 0)
01506             {
01507                 tmpEndPts.A[ch] = newEndPts.A[ch] + sign * step;
01508                 if(tmpEndPts.A[ch] < 0 || tmpEndPts.A[ch] >= (1 << uPrec))
01509                     continue;
01510             }
01511             else
01512             {
01513                 tmpEndPts.B[ch] = newEndPts.B[ch] + sign * step;
01514                 if(tmpEndPts.B[ch] < 0 || tmpEndPts.B[ch] >= (1 << uPrec))
01515                     continue;
01516             }
01517
01518             float fErr = MapColorsQuantized(pEP, aColors, np, tmpEndPts);
01519
01520             if(fErr < fMinErr)
01521             {
01522                 bImproved = true;
01523                 fMinErr = fErr;
01524                 beststep = sign * step;
01525             }
01526         }
01527         // if this was an improvement, move the endpoint and continue search from there
01528         if(bImproved)
01529         {
01530             if(do_b == 0)
01531                 newEndPts.A[ch] += beststep;
01532             else
01533                 newEndPts.B[ch] += beststep;
01534         }
01535     }
01536     return fMinErr;
01537 }
01538
01539 _Use_decl_annotations_
01540 void D3DX_BC6H::OptimizeOne(const EncodeParams* pEP, const INTColor aColors[], size_t np, float aOrgErr,
01541                             const INTEndPntPair &aOrgEndPts, INTEndPntPair &aOptEndPts) const
01542 {
01543     assert( pEP );
01544     float aOptErr = aOrgErr;
01545     aOptEndPts.A = aOrgEndPts.A;
01546     aOptEndPts.B = aOrgEndPts.B;
01547
01548     INTEndPntPair new_a, new_b;
01549     INTEndPntPair newEndPts;
01550     int do_b;
01551
01552     // now optimize each channel separately
01553     for(uint8_t ch = 0; ch < 3; ++ch)
01554     {
01555         // figure out which endpoint when perturbed gives the most improvement and start there
01556         // if we just alternate, we can easily end up in a local minima
01557         float fErr0 = PerturbOne(pEP, aColors, np, ch, aOptEndPts, new_a, aOptErr, 0);  // perturb endpt A
01558         float fErr1 = PerturbOne(pEP, aColors, np, ch, aOptEndPts, new_b, aOptErr, 1);  // perturb endpt B
01559
01560         if(fErr0 < fErr1)
01561         {
01562             if(fErr0 >= aOptErr) continue;
01563             aOptEndPts.A[ch] = new_a.A[ch];
01564             aOptErr = fErr0;
01565             do_b = 1;   // do B next
01566         }
01567         else
01568         {
01569             if(fErr1 >= aOptErr) continue;
01570             aOptEndPts.B[ch] = new_b.B[ch];
01571             aOptErr = fErr1;
01572             do_b = 0;   // do A next
01573         }
01574
01575         // now alternate endpoints and keep trying until there is no improvement
01576         for(;;)
01577         {
01578             float fErr = PerturbOne(pEP, aColors, np, ch, aOptEndPts, newEndPts, aOptErr, do_b);
01579             if(fErr >= aOptErr)
01580                 break;
01581             if(do_b == 0)
01582                 aOptEndPts.A[ch] = newEndPts.A[ch];
01583             else
01584                 aOptEndPts.B[ch] = newEndPts.B[ch];
01585             aOptErr = fErr;
01586             do_b = 1 - do_b;  // now move the other endpoint
01587         }
01588     }
01589 }
01590
01591 _Use_decl_annotations_
01592 void D3DX_BC6H::OptimizeEndPoints(const EncodeParams* pEP, const float aOrgErr[], const INTEndPntPair aOrgEndPts[], INTEndPntPair aOptEndPts[]) const
01593 {
01594     assert( pEP );
01595     const uint8_t uPartitions = ms_aInfo[pEP->uMode].uPartitions;
01596     assert( uPartitions < BC6H_MAX_REGIONS );
01597     _Analysis_assume_( uPartitions < BC6H_MAX_REGIONS );
01598     INTColor aPixels[NUM_PIXELS_PER_BLOCK];
01599
01600     for(size_t p = 0; p <= uPartitions; ++p)
01601     {
01602         // collect the pixels in the region
01603         size_t np = 0;
01604         for(size_t i = 0; i < NUM_PIXELS_PER_BLOCK; ++i)
01605         {
01606             if(g_aPartitionTable[p][pEP->uShape][i] == p)
01607             {
01608                 aPixels[np++] = pEP->aIPixels[i];
01609             }
01610         }
01611
01612         OptimizeOne(pEP, aPixels, np, aOrgErr[p], aOrgEndPts[p], aOptEndPts[p]);
01613     }
01614 }
01615
01616 // Swap endpoints as needed to ensure that the indices at fix up have a 0 high-order bit
01617 _Use_decl_annotations_
01618 void D3DX_BC6H::SwapIndices(const EncodeParams* pEP, INTEndPntPair aEndPts[], size_t aIndices[])
01619 {
01620     assert( pEP );
01621     const size_t uPartitions = ms_aInfo[pEP->uMode].uPartitions;
01622     const size_t uNumIndices = 1 << ms_aInfo[pEP->uMode].uIndexPrec;
01623     const size_t uHighIndexBit = uNumIndices >> 1;
01624
01625     assert( uPartitions < BC6H_MAX_REGIONS && pEP->uShape < BC6H_MAX_SHAPES );
01626     _Analysis_assume_( uPartitions < BC6H_MAX_REGIONS && pEP->uShape < BC6H_MAX_SHAPES );
01627
01628     for(size_t p = 0; p <= uPartitions; ++p)
01629     {
01630         size_t i = g_aFixUp[uPartitions][pEP->uShape][p];
01631         assert(g_aPartitionTable[uPartitions][pEP->uShape][i] == p);
01632         if(aIndices[i] & uHighIndexBit)
01633         {
01634             // high bit is set, swap the aEndPts and indices for this region
01635             Swap(aEndPts[p].A, aEndPts[p].B);
01636
01637             for(size_t j = 0; j < NUM_PIXELS_PER_BLOCK; ++j)
01638                 if(g_aPartitionTable[uPartitions][pEP->uShape][j] == p)
01639                     aIndices[j] = uNumIndices - 1 - aIndices[j];
01640         }
01641     }
01642 }
01643
01644 // assign indices given a tile, shape, and quantized endpoints, return toterr for each region
01645 _Use_decl_annotations_
01646 void D3DX_BC6H::AssignIndices(const EncodeParams* pEP, const INTEndPntPair aEndPts[], size_t aIndices[], float aTotErr[]) const
01647 {
01648     assert( pEP );
01649     const uint8_t uPartitions = ms_aInfo[pEP->uMode].uPartitions;
01650     const uint8_t uNumIndices = 1 << ms_aInfo[pEP->uMode].uIndexPrec;
01651
01652     assert( uPartitions < BC6H_MAX_REGIONS && pEP->uShape < BC6H_MAX_SHAPES );
01653     _Analysis_assume_( uPartitions < BC6H_MAX_REGIONS && pEP->uShape < BC6H_MAX_SHAPES );
01654
01655     // build list of possibles
01656     INTColor aPalette[BC6H_MAX_REGIONS][BC6H_MAX_INDICES];
01657
01658     for(size_t p = 0; p <= uPartitions; ++p)
01659     {
01660         GeneratePaletteQuantized(pEP, aEndPts[p], aPalette[p]);
01661         aTotErr[p] = 0;
01662     }
01663
01664     for(size_t i = 0; i < NUM_PIXELS_PER_BLOCK; ++i)
01665     {
01666         const uint8_t uRegion = g_aPartitionTable[uPartitions][pEP->uShape][i];
01667         assert( uRegion < BC6H_MAX_REGIONS );
01668         _Analysis_assume_( uRegion < BC6H_MAX_REGIONS );
01669         float fBestErr = Norm(pEP->aIPixels[i], aPalette[uRegion][0]);
01670         aIndices[i] = 0;
01671
01672         for(uint8_t j = 1; j < uNumIndices && fBestErr > 0; ++j)
01673         {
01674             float fErr = Norm(pEP->aIPixels[i], aPalette[uRegion][j]);
01675             if(fErr > fBestErr) break;  // error increased, so we're done searching
01676             if(fErr < fBestErr)
01677             {
01678                 fBestErr = fErr;
01679                 aIndices[i] = j;
01680             }
01681         }
01682         aTotErr[uRegion] += fBestErr;
01683     }
01684 }
01685
01686 _Use_decl_annotations_
01687 void D3DX_BC6H::QuantizeEndPts(const EncodeParams* pEP, INTEndPntPair* aQntEndPts) const
01688 {
01689     assert( pEP && aQntEndPts );
01690     const INTEndPntPair* aUnqEndPts = pEP->aUnqEndPts[pEP->uShape];
01691     const LDRColorA& Prec = ms_aInfo[pEP->uMode].RGBAPrec[0][0];
01692     const uint8_t uPartitions = ms_aInfo[pEP->uMode].uPartitions;
01693     assert( uPartitions < BC6H_MAX_REGIONS );
01694     _Analysis_assume_( uPartitions < BC6H_MAX_REGIONS );
01695
01696     for(size_t p = 0; p <= uPartitions; ++p)
01697     {
01698         aQntEndPts[p].A.r = Quantize(aUnqEndPts[p].A.r, Prec.r, pEP->bSigned);
01699         aQntEndPts[p].A.g = Quantize(aUnqEndPts[p].A.g, Prec.g, pEP->bSigned);
01700         aQntEndPts[p].A.b = Quantize(aUnqEndPts[p].A.b, Prec.b, pEP->bSigned);
01701         aQntEndPts[p].B.r = Quantize(aUnqEndPts[p].B.r, Prec.r, pEP->bSigned);
01702         aQntEndPts[p].B.g = Quantize(aUnqEndPts[p].B.g, Prec.g, pEP->bSigned);
01703         aQntEndPts[p].B.b = Quantize(aUnqEndPts[p].B.b, Prec.b, pEP->bSigned);
01704     }
01705 }
01706
01707 _Use_decl_annotations_
01708 void D3DX_BC6H::EmitBlock(const EncodeParams* pEP, const INTEndPntPair aEndPts[], const size_t aIndices[])
01709 {
01710     assert( pEP );
01711     const uint8_t uRealMode = ms_aInfo[pEP->uMode].uMode;
01712     const uint8_t uPartitions = ms_aInfo[pEP->uMode].uPartitions;
01713     const uint8_t uIndexPrec = ms_aInfo[pEP->uMode].uIndexPrec;
01714     const size_t uHeaderBits = uPartitions > 0 ? 82 : 65;
01715     const ModeDescriptor* desc = ms_aDesc[pEP->uMode];
01716     size_t uStartBit = 0;
01717
01718     while(uStartBit < uHeaderBits)
01719     {
01720         switch(desc[uStartBit].m_eField)
01721         {
01722         case M:  SetBit(uStartBit, uint8_t(uRealMode >> desc[uStartBit].m_uBit) & 0x01); break;
01723         case D:  SetBit(uStartBit, uint8_t(pEP->uShape >> desc[uStartBit].m_uBit) & 0x01); break;
01724         case RW: SetBit(uStartBit, uint8_t(aEndPts[0].A.r >> desc[uStartBit].m_uBit) & 0x01); break;
01725         case RX: SetBit(uStartBit, uint8_t(aEndPts[0].B.r >> desc[uStartBit].m_uBit) & 0x01); break;
01726         case RY: SetBit(uStartBit, uint8_t(aEndPts[1].A.r >> desc[uStartBit].m_uBit) & 0x01); break;
01727         case RZ: SetBit(uStartBit, uint8_t(aEndPts[1].B.r >> desc[uStartBit].m_uBit) & 0x01); break;
01728         case GW: SetBit(uStartBit, uint8_t(aEndPts[0].A.g >> desc[uStartBit].m_uBit) & 0x01); break;
01729         case GX: SetBit(uStartBit, uint8_t(aEndPts[0].B.g >> desc[uStartBit].m_uBit) & 0x01); break;
01730         case GY: SetBit(uStartBit, uint8_t(aEndPts[1].A.g >> desc[uStartBit].m_uBit) & 0x01); break;
01731         case GZ: SetBit(uStartBit, uint8_t(aEndPts[1].B.g >> desc[uStartBit].m_uBit) & 0x01); break;
01732         case BW: SetBit(uStartBit, uint8_t(aEndPts[0].A.b >> desc[uStartBit].m_uBit) & 0x01); break;
01733         case BX: SetBit(uStartBit, uint8_t(aEndPts[0].B.b >> desc[uStartBit].m_uBit) & 0x01); break;
01734         case BY: SetBit(uStartBit, uint8_t(aEndPts[1].A.b >> desc[uStartBit].m_uBit) & 0x01); break;
01735         case BZ: SetBit(uStartBit, uint8_t(aEndPts[1].B.b >> desc[uStartBit].m_uBit) & 0x01); break;
01736         default: assert(false);
01737         }
01738     }
01739
01740     for(size_t i = 0; i < NUM_PIXELS_PER_BLOCK; ++i)
01741     {
01742         if(IsFixUpOffset(ms_aInfo[pEP->uMode].uPartitions, pEP->uShape, i))
01743             SetBits(uStartBit, uIndexPrec - 1, static_cast<uint8_t>( aIndices[i] ));
01744         else
01745             SetBits(uStartBit, uIndexPrec, static_cast<uint8_t>( aIndices[i] ));
01746     }
01747     assert(uStartBit == 128);
01748 }
01749
01750 _Use_decl_annotations_
01751 void D3DX_BC6H::Refine(EncodeParams* pEP)
01752 {
01753     assert( pEP );
01754     const uint8_t uPartitions = ms_aInfo[pEP->uMode].uPartitions;
01755     assert( uPartitions < BC6H_MAX_REGIONS );
01756     _Analysis_assume_( uPartitions < BC6H_MAX_REGIONS );
01757
01758     const bool bTransformed = ms_aInfo[pEP->uMode].bTransformed;
01759     float aOrgErr[BC6H_MAX_REGIONS], aOptErr[BC6H_MAX_REGIONS];
01760     INTEndPntPair aOrgEndPts[BC6H_MAX_REGIONS], aOptEndPts[BC6H_MAX_REGIONS];
01761     size_t aOrgIdx[NUM_PIXELS_PER_BLOCK], aOptIdx[NUM_PIXELS_PER_BLOCK];
01762
01763     QuantizeEndPts(pEP, aOrgEndPts);
01764     AssignIndices(pEP, aOrgEndPts, aOrgIdx, aOrgErr);
01765     SwapIndices(pEP, aOrgEndPts, aOrgIdx);
01766
01767     if(bTransformed) TransformForward(aOrgEndPts);
01768     if(EndPointsFit(pEP, aOrgEndPts))
01769     {
01770         if(bTransformed) TransformInverse(aOrgEndPts, ms_aInfo[pEP->uMode].RGBAPrec[0][0], pEP->bSigned);
01771         OptimizeEndPoints(pEP, aOrgErr, aOrgEndPts, aOptEndPts);
01772         AssignIndices(pEP, aOptEndPts, aOptIdx, aOptErr);
01773         SwapIndices(pEP, aOptEndPts, aOptIdx);
01774
01775         float fOrgTotErr = 0.0f, fOptTotErr = 0.0f;
01776         for(size_t p = 0; p <= uPartitions; ++p)
01777         {
01778             fOrgTotErr += aOrgErr[p];
01779             fOptTotErr += aOptErr[p];
01780         }
01781
01782         if(bTransformed) TransformForward(aOptEndPts);
01783         if(EndPointsFit(pEP, aOptEndPts) && fOptTotErr < fOrgTotErr && fOptTotErr < pEP->fBestErr)
01784         {
01785             pEP->fBestErr = fOptTotErr;
01786             EmitBlock(pEP, aOptEndPts, aOptIdx);
01787         }
01788         else if(fOrgTotErr < pEP->fBestErr)
01789         {
01790             // either it stopped fitting when we optimized it, or there was no improvement
01791             // so go back to the unoptimized endpoints which we know will fit
01792             if(bTransformed) TransformForward(aOrgEndPts);
01793             pEP->fBestErr = fOrgTotErr;
01794             EmitBlock(pEP, aOrgEndPts, aOrgIdx);
01795         }
01796     }
01797 }
01798
01799 _Use_decl_annotations_
01800 void D3DX_BC6H::GeneratePaletteUnquantized(const EncodeParams* pEP, size_t uRegion, INTColor aPalette[])
01801 {
01802     assert( pEP );
01803     assert( uRegion < BC6H_MAX_REGIONS && pEP->uShape < BC6H_MAX_SHAPES );
01804     _Analysis_assume_( uRegion < BC6H_MAX_REGIONS && pEP->uShape < BC6H_MAX_SHAPES );
01805     const INTEndPntPair& endPts = pEP->aUnqEndPts[pEP->uShape][uRegion];
01806     const uint8_t uIndexPrec = ms_aInfo[pEP->uMode].uIndexPrec;
01807     const uint8_t uNumIndices = 1 << uIndexPrec;
01808     assert(uNumIndices > 0);
01809     _Analysis_assume_(uNumIndices > 0);
01810
01811     const int* aWeights = nullptr;
01812     switch(uIndexPrec)
01813     {
01814     case 3: aWeights = g_aWeights3; assert(uNumIndices <= 8); _Analysis_assume_(uNumIndices <= 8); break;
01815     case 4: aWeights = g_aWeights4; assert(uNumIndices <= 16); _Analysis_assume_(uNumIndices <= 16); break;
01816     default: assert(false); for(size_t i = 0; i < uNumIndices; ++i) aPalette[i] = INTColor(0,0,0); return;
01817     }
01818
01819     for(register size_t i = 0; i < uNumIndices; ++i)
01820     {
01821         aPalette[i].r = (endPts.A.r * (BC67_WEIGHT_MAX - aWeights[i]) + endPts.B.r * aWeights[i] + BC67_WEIGHT_ROUND) >> BC67_WEIGHT_SHIFT;
01822         aPalette[i].g = (endPts.A.g * (BC67_WEIGHT_MAX - aWeights[i]) + endPts.B.g * aWeights[i] + BC67_WEIGHT_ROUND) >> BC67_WEIGHT_SHIFT;
01823         aPalette[i].b = (endPts.A.b * (BC67_WEIGHT_MAX - aWeights[i]) + endPts.B.b * aWeights[i] + BC67_WEIGHT_ROUND) >> BC67_WEIGHT_SHIFT;
01824     }
01825 }
01826
01827 _Use_decl_annotations_
01828 float D3DX_BC6H::MapColors(const EncodeParams* pEP, size_t uRegion, size_t np, const size_t* auIndex) const
01829 {
01830     assert( pEP );
01831     const uint8_t uIndexPrec = ms_aInfo[pEP->uMode].uIndexPrec;
01832     const uint8_t uNumIndices = 1 << uIndexPrec;
01833     INTColor aPalette[BC6H_MAX_INDICES];
01834     GeneratePaletteUnquantized(pEP, uRegion, aPalette);
01835
01836     float fTotalErr = 0.0f;
01837     for(size_t i = 0; i < np; ++i)
01838     {
01839         float fBestErr = Norm(pEP->aIPixels[auIndex[i]], aPalette[0]);
01840         for(uint8_t j = 1; j < uNumIndices && fBestErr > 0.0f; ++j)
01841         {
01842             float fErr = Norm(pEP->aIPixels[auIndex[i]], aPalette[j]);
01843             if(fErr > fBestErr) break;      // error increased, so we're done searching
01844             if(fErr < fBestErr) fBestErr = fErr;
01845         }
01846         fTotalErr += fBestErr;
01847     }
01848
01849     return fTotalErr;
01850 }
01851
01852 _Use_decl_annotations_
01853 float D3DX_BC6H::RoughMSE(EncodeParams* pEP) const
01854 {
01855     assert( pEP );
01856     assert( pEP->uShape < BC6H_MAX_SHAPES);
01857     _Analysis_assume_( pEP->uShape < BC6H_MAX_SHAPES);
01858
01859     INTEndPntPair* aEndPts = pEP->aUnqEndPts[pEP->uShape];
01860
01861     const uint8_t uPartitions = ms_aInfo[pEP->uMode].uPartitions;
01862     assert( uPartitions < BC6H_MAX_REGIONS );
01863     _Analysis_assume_( uPartitions < BC6H_MAX_REGIONS );
01864
01865     size_t auPixIdx[NUM_PIXELS_PER_BLOCK];
01866
01867     float fError = 0.0f;
01868     for(size_t p = 0; p <= uPartitions; ++p)
01869     {
01870         size_t np = 0;
01871         for(register size_t i = 0; i < NUM_PIXELS_PER_BLOCK; ++i)
01872         {
01873             if(g_aPartitionTable[uPartitions][pEP->uShape][i] == p)
01874             {
01875                 auPixIdx[np++] = i;
01876             }
01877         }
01878
01879         // handle simple cases
01880         assert(np > 0);
01881         if(np == 1)
01882         {
01883             aEndPts[p].A = pEP->aIPixels[auPixIdx[0]];
01884             aEndPts[p].B = pEP->aIPixels[auPixIdx[0]];
01885             continue;
01886         }
01887         else if(np == 2)
01888         {
01889             aEndPts[p].A = pEP->aIPixels[auPixIdx[0]];
01890             aEndPts[p].B = pEP->aIPixels[auPixIdx[1]];
01891             continue;
01892         }
01893
01894         HDRColorA epA, epB;
01895         OptimizeRGB(pEP->aHDRPixels, &epA, &epB, 4, np, auPixIdx);
01896         aEndPts[p].A.Set(epA, pEP->bSigned);
01897         aEndPts[p].B.Set(epB, pEP->bSigned);
01898         if(pEP->bSigned)
01899         {
01900             aEndPts[p].A.Clamp(-F16MAX, F16MAX);
01901             aEndPts[p].B.Clamp(-F16MAX, F16MAX);
01902         }
01903         else
01904         {
01905             aEndPts[p].A.Clamp(0, F16MAX);
01906             aEndPts[p].B.Clamp(0, F16MAX);
01907         }
01908
01909         fError += MapColors(pEP, p, np, auPixIdx);
01910     }
01911
01912     return fError;
01913 }
01914
01915
01916
01917 //-------------------------------------------------------------------------------------
01918 // BC7 Compression
01919 //-------------------------------------------------------------------------------------
01920 _Use_decl_annotations_
01921 void D3DX_BC7::Decode(HDRColorA* pOut) const
01922 {
01923     assert( pOut );
01924
01925     size_t uFirst = 0;
01926     while(uFirst < 128 && !GetBit(uFirst)) {}
01927     uint8_t uMode = uint8_t(uFirst - 1);
01928
01929     if(uMode < 8)
01930     {
01931         const uint8_t uPartitions = ms_aInfo[uMode].uPartitions;
01932         assert( uPartitions < BC7_MAX_REGIONS );
01933         _Analysis_assume_( uPartitions < BC7_MAX_REGIONS );
01934
01935         const uint8_t uNumEndPts = (uPartitions + 1) << 1;
01936         const uint8_t uIndexPrec = ms_aInfo[uMode].uIndexPrec;
01937         const uint8_t uIndexPrec2 = ms_aInfo[uMode].uIndexPrec2;
01938         register size_t i;
01939         size_t uStartBit = uMode + 1;
01940         uint8_t P[6];
01941         uint8_t uShape = GetBits(uStartBit, ms_aInfo[uMode].uPartitionBits);
01942         assert( uShape < BC7_MAX_SHAPES );
01943         _Analysis_assume_( uShape < BC7_MAX_SHAPES );
01944
01945         uint8_t uRotation = GetBits(uStartBit, ms_aInfo[uMode].uRotationBits);
01946         assert( uRotation < 4 );
01947
01948         uint8_t uIndexMode = GetBits(uStartBit, ms_aInfo[uMode].uIndexModeBits);
01949         assert( uIndexMode < 2 );
01950
01951         LDRColorA c[BC7_MAX_REGIONS << 1];
01952         const LDRColorA RGBAPrec = ms_aInfo[uMode].RGBAPrec;
01953         const LDRColorA RGBAPrecWithP = ms_aInfo[uMode].RGBAPrecWithP;
01954
01955         assert( uNumEndPts <= (BC7_MAX_REGIONS << 1) );
01956
01957         // Red channel
01958         for(i = 0; i < uNumEndPts; i++)
01959         {
01960             if ( uStartBit + RGBAPrec.r > 128 )
01961             {
01962 #ifdef _DEBUG
01963                 OutputDebugStringA( "BC7: Invalid block encountered during decoding\n" );
01964 #endif
01965                 FillWithErrorColors( pOut );
01966                 return;
01967             }
01968
01969             c[i].r = GetBits(uStartBit, RGBAPrec.r);
01970         }
01971
01972         // Green channel
01973         for(i = 0; i < uNumEndPts; i++)
01974         {
01975             if ( uStartBit + RGBAPrec.g > 128 )
01976             {
01977 #ifdef _DEBUG
01978                 OutputDebugStringA( "BC7: Invalid block encountered during decoding\n" );
01979 #endif
01980                 FillWithErrorColors( pOut );
01981                 return;
01982             }
01983
01984              c[i].g = GetBits(uStartBit, RGBAPrec.g);
01985         }
01986
01987         // Blue channel
01988         for(i = 0; i < uNumEndPts; i++)
01989         {
01990             if ( uStartBit + RGBAPrec.b > 128 )
01991             {
01992 #ifdef _DEBUG
01993                 OutputDebugStringA( "BC7: Invalid block encountered during decoding\n" );
01994 #endif
01995                 FillWithErrorColors( pOut );
01996                 return;
01997             }
01998
01999             c[i].b = GetBits(uStartBit, RGBAPrec.b);
02000         }
02001
02002         // Alpha channel
02003         for(i = 0; i < uNumEndPts; i++)
02004         {
02005             if ( uStartBit + RGBAPrec.a > 128 )
02006             {
02007 #ifdef _DEBUG
02008                 OutputDebugStringA( "BC7: Invalid block encountered during decoding\n" );
02009 #endif
02010                 FillWithErrorColors( pOut );
02011                 return;
02012             }
02013
02014             c[i].a = RGBAPrec.a ? GetBits(uStartBit, RGBAPrec.a) : 255;
02015         }
02016
02017         // P-bits
02018         assert( ms_aInfo[uMode].uPBits <= 6 );
02019         _Analysis_assume_( ms_aInfo[uMode].uPBits <= 6 );
02020         for(i = 0; i < ms_aInfo[uMode].uPBits; i++)
02021         {
02022             if ( uStartBit > 127 )
02023             {
02024 #ifdef _DEBUG
02025                 OutputDebugStringA( "BC7: Invalid block encountered during decoding\n" );
02026 #endif
02027                 FillWithErrorColors( pOut );
02028                 return;
02029             }
02030
02031             P[i] = GetBit(uStartBit);
02032         }
02033
02034         if(ms_aInfo[uMode].uPBits)
02035         {
02036             for(i = 0; i < uNumEndPts; i++)
02037             {
02038                 size_t pi = i * ms_aInfo[uMode].uPBits / uNumEndPts;
02039                 for(register uint8_t ch = 0; ch < BC7_NUM_CHANNELS; ch++)
02040                 {
02041                     if(RGBAPrec[ch] != RGBAPrecWithP[ch])
02042                     {
02043                         c[i][ch] = (c[i][ch] << 1) | P[pi];
02044                     }
02045                 }
02046             }
02047         }
02048
02049         for(i = 0; i < uNumEndPts; i++)
02050         {
02051             c[i] = Unquantize(c[i], RGBAPrecWithP);
02052         }
02053
02054         uint8_t w1[NUM_PIXELS_PER_BLOCK], w2[NUM_PIXELS_PER_BLOCK];
02055
02056         // read color indices
02057         for(i = 0; i < NUM_PIXELS_PER_BLOCK; i++)
02058         {
02059             size_t uNumBits = IsFixUpOffset(ms_aInfo[uMode].uPartitions, uShape, i) ? uIndexPrec - 1 : uIndexPrec;
02060             if ( uStartBit + uNumBits > 128 )
02061             {
02062 #ifdef _DEBUG
02063                 OutputDebugStringA( "BC7: Invalid block encountered during decoding\n" );
02064 #endif
02065                 FillWithErrorColors( pOut );
02066                 return;
02067             }
02068             w1[i] = GetBits(uStartBit, uNumBits);
02069         }
02070
02071         // read alpha indices
02072         if(uIndexPrec2)
02073         {
02074             for(i = 0; i < NUM_PIXELS_PER_BLOCK; i++)
02075             {
02076                 size_t uNumBits = i ? uIndexPrec2 : uIndexPrec2 - 1;
02077                 if ( uStartBit + uNumBits > 128 )
02078                 {
02079 #ifdef _DEBUG
02080                     OutputDebugStringA( "BC7: Invalid block encountered during decoding\n" );
02081 #endif
02082                     FillWithErrorColors( pOut );
02083                     return;
02084                 }
02085                 w2[i] = GetBits(uStartBit, uNumBits );
02086             }
02087         }
02088
02089         for(i = 0; i < NUM_PIXELS_PER_BLOCK; ++i)
02090         {
02091             uint8_t uRegion = g_aPartitionTable[uPartitions][uShape][i];
02092             LDRColorA outPixel;
02093             if(uIndexPrec2 == 0)
02094             {
02095                 LDRColorA::Interpolate(c[uRegion << 1], c[(uRegion << 1) + 1], w1[i], w1[i], uIndexPrec, uIndexPrec, outPixel);
02096             }
02097             else
02098             {
02099                 if(uIndexMode == 0)
02100                 {
02101                     LDRColorA::Interpolate(c[uRegion << 1], c[(uRegion << 1) + 1], w1[i], w2[i], uIndexPrec, uIndexPrec2, outPixel);
02102                 }
02103                 else
02104                 {
02105                     LDRColorA::Interpolate(c[uRegion << 1], c[(uRegion << 1) + 1], w2[i], w1[i], uIndexPrec2, uIndexPrec, outPixel);
02106                 }
02107             }
02108
02109             switch(uRotation)
02110             {
02111             case 1: Swap(outPixel.r, outPixel.a); break;
02112             case 2: Swap(outPixel.g, outPixel.a); break;
02113             case 3: Swap(outPixel.b, outPixel.a); break;
02114             }
02115
02116             pOut[i] = HDRColorA(outPixel);
02117         }
02118     }
02119     else
02120     {
02121 #ifdef _DEBUG
02122         OutputDebugStringA( "BC7: Invalid mode encountered during decoding\n" );
02123 #endif
02124         FillWithErrorColors( pOut );
02125     }
02126 }
02127
02128 _Use_decl_annotations_
02129 void D3DX_BC7::Encode(const HDRColorA* const pIn)
02130 {
02131     assert( pIn );
02132
02133     D3DX_BC7 final = *this;
02134     EncodeParams EP(pIn);
02135     float fMSEBest = FLT_MAX;
02136
02137     for(size_t i = 0; i < NUM_PIXELS_PER_BLOCK; ++i)
02138     {
02139         EP.aLDRPixels[i].r = uint8_t( std::max<float>( 0.0f, std::min<float>( 255.0f, pIn[i].r * 255.0f + 0.01f ) ) );
02140         EP.aLDRPixels[i].g = uint8_t( std::max<float>( 0.0f, std::min<float>( 255.0f, pIn[i].g * 255.0f + 0.01f ) ) );
02141         EP.aLDRPixels[i].b = uint8_t( std::max<float>( 0.0f, std::min<float>( 255.0f, pIn[i].b * 255.0f + 0.01f ) ) );
02142         EP.aLDRPixels[i].a = uint8_t( std::max<float>( 0.0f, std::min<float>( 255.0f, pIn[i].a * 255.0f + 0.01f ) ) );
02143     }
02144
02145     for(EP.uMode = 0; EP.uMode < 8 && fMSEBest > 0; ++EP.uMode)
02146     {
02147         const size_t uShapes = 1 << ms_aInfo[EP.uMode].uPartitionBits;
02148         const size_t uNumRots = 1 << ms_aInfo[EP.uMode].uRotationBits;
02149         const size_t uNumIdxMode = 1 << ms_aInfo[EP.uMode].uIndexModeBits;
02150         // Number of rough cases to look at. reasonable values of this are 1, uShapes/4, and uShapes
02151         // uShapes/4 gets nearly all the cases; you can increase that a bit (say by 3 or 4) if you really want to squeeze the last bit out
02152         const size_t uItems = std::max<size_t>(1, uShapes >> 2);
02153         float afRoughMSE[BC7_MAX_SHAPES];
02154         size_t auShape[BC7_MAX_SHAPES];
02155
02156         for(size_t r = 0; r < uNumRots && fMSEBest > 0; ++r)
02157         {
02158             switch(r)
02159             {
02160             case 1: for(register size_t i = 0; i < NUM_PIXELS_PER_BLOCK; i++) Swap(EP.aLDRPixels[i].r, EP.aLDRPixels[i].a); break;
02161             case 2: for(register size_t i = 0; i < NUM_PIXELS_PER_BLOCK; i++) Swap(EP.aLDRPixels[i].g, EP.aLDRPixels[i].a); break;
02162             case 3: for(register size_t i = 0; i < NUM_PIXELS_PER_BLOCK; i++) Swap(EP.aLDRPixels[i].b, EP.aLDRPixels[i].a); break;
02163             }
02164
02165             for(size_t im = 0; im < uNumIdxMode && fMSEBest > 0; ++im)
02166             {
02167                 // pick the best uItems shapes and refine these.
02168                 for(size_t s = 0; s < uShapes; s++)
02169                 {
02170                     afRoughMSE[s] = RoughMSE(&EP, s, im);
02171                     auShape[s] = s;
02172                 }
02173
02174                 // Bubble up the first uItems items
02175                 for(size_t i = 0; i < uItems; i++)
02176                 {
02177                     for(size_t j = i + 1; j < uShapes; j++)
02178                     {
02179                         if(afRoughMSE[i] > afRoughMSE[j])
02180                         {
02181                             Swap(afRoughMSE[i], afRoughMSE[j]);
02182                             Swap(auShape[i], auShape[j]);
02183                         }
02184                     }
02185                 }
02186
02187                 for(size_t i = 0; i < uItems && fMSEBest > 0; i++)
02188                 {
02189                     float fMSE = Refine(&EP, auShape[i], r, im);
02190                     if(fMSE < fMSEBest)
02191                     {
02192                         final = *this;
02193                         fMSEBest = fMSE;
02194                     }
02195                 }
02196             }
02197
02198             switch(r)
02199             {
02200             case 1: for(register size_t i = 0; i < NUM_PIXELS_PER_BLOCK; i++) Swap(EP.aLDRPixels[i].r, EP.aLDRPixels[i].a); break;
02201             case 2: for(register size_t i = 0; i < NUM_PIXELS_PER_BLOCK; i++) Swap(EP.aLDRPixels[i].g, EP.aLDRPixels[i].a); break;
02202             case 3: for(register size_t i = 0; i < NUM_PIXELS_PER_BLOCK; i++) Swap(EP.aLDRPixels[i].b, EP.aLDRPixels[i].a); break;
02203             }
02204         }
02205     }
02206
02207     *this = final;
02208 }
02209
02210
02211 //-------------------------------------------------------------------------------------
02212 _Use_decl_annotations_
02213 void D3DX_BC7::GeneratePaletteQuantized(const EncodeParams* pEP, size_t uIndexMode, const LDREndPntPair& endPts, LDRColorA aPalette[]) const
02214 {
02215     assert( pEP );
02216     const size_t uIndexPrec = uIndexMode ? ms_aInfo[pEP->uMode].uIndexPrec2 : ms_aInfo[pEP->uMode].uIndexPrec;
02217     const size_t uIndexPrec2 = uIndexMode ? ms_aInfo[pEP->uMode].uIndexPrec : ms_aInfo[pEP->uMode].uIndexPrec2;
02218     const size_t uNumIndices = 1 << uIndexPrec;
02219     const size_t uNumIndices2 = 1 << uIndexPrec2;
02220     assert( uNumIndices > 0 && uNumIndices2 > 0 );
02221     _Analysis_assume_( uNumIndices > 0 && uNumIndices2 > 0 );
02222     assert( (uNumIndices <= BC7_MAX_INDICES) && (uNumIndices2 <= BC7_MAX_INDICES) );
02223     _Analysis_assume_( (uNumIndices <= BC7_MAX_INDICES) && (uNumIndices2 <= BC7_MAX_INDICES) );
02224
02225     LDRColorA a = Unquantize(endPts.A, ms_aInfo[pEP->uMode].RGBAPrecWithP);
02226     LDRColorA b = Unquantize(endPts.B, ms_aInfo[pEP->uMode].RGBAPrecWithP);
02227     if(uIndexPrec2 == 0)
02228     {
02229         for(register size_t i = 0; i < uNumIndices; i++)
02230             LDRColorA::Interpolate(a, b, i, i, uIndexPrec, uIndexPrec, aPalette[i]);
02231     }
02232     else
02233     {
02234         for(register size_t i = 0; i < uNumIndices; i++)
02235             LDRColorA::InterpolateRGB(a, b, i, uIndexPrec, aPalette[i]);
02236         for(register size_t i = 0; i < uNumIndices2; i++)
02237             LDRColorA::InterpolateA(a, b, i, uIndexPrec2, aPalette[i]);
02238     }
02239 }
02240
02241 _Use_decl_annotations_
02242 float D3DX_BC7::PerturbOne(const EncodeParams* pEP, const LDRColorA aColors[], size_t np, size_t uIndexMode, size_t ch,
02243                            const LDREndPntPair &oldEndPts, LDREndPntPair &newEndPts, float fOldErr, uint8_t do_b) const
02244 {
02245     assert( pEP );
02246     const int prec = ms_aInfo[pEP->uMode].RGBAPrecWithP[ch];
02247     LDREndPntPair tmp_endPts = newEndPts = oldEndPts;
02248     float fMinErr = fOldErr;
02249     uint8_t* pnew_c = (do_b ? &newEndPts.B[ch] : &newEndPts.A[ch]);
02250     uint8_t* ptmp_c = (do_b ? &tmp_endPts.B[ch] : &tmp_endPts.A[ch]);
02251
02252     // do a logarithmic search for the best error for this endpoint (which)
02253     for(int step = 1 << (prec-1); step; step >>= 1)
02254     {
02255         bool bImproved = false;
02256         int beststep = 0;
02257         for(int sign = -1; sign <= 1; sign += 2)
02258         {
02259             int tmp = int(*pnew_c) + sign * step;
02260             if(tmp < 0 || tmp >= (1 << prec))
02261                 continue;
02262             else
02263                 *ptmp_c = (uint8_t) tmp;
02264
02265             float fTotalErr = MapColors(pEP, aColors, np, uIndexMode, tmp_endPts, fMinErr);
02266             if(fTotalErr < fMinErr)
02267             {
02268                 bImproved = true;
02269                 fMinErr = fTotalErr;
02270                 beststep = sign * step;
02271             }
02272         }
02273
02274         // if this was an improvement, move the endpoint and continue search from there
02275         if(bImproved)
02276             *pnew_c = uint8_t(int(*pnew_c) + beststep);
02277     }
02278     return fMinErr;
02279 }
02280
02281 // perturb the endpoints at least -3 to 3.
02282 // always ensure endpoint ordering is preserved (no need to overlap the scan)
02283 _Use_decl_annotations_
02284 void D3DX_BC7::Exhaustive(const EncodeParams* pEP, const LDRColorA aColors[], size_t np, size_t uIndexMode, size_t ch,
02285                           float& fOrgErr, LDREndPntPair& optEndPt) const
02286 {
02287     assert( pEP );
02288     const uint8_t uPrec = ms_aInfo[pEP->uMode].RGBAPrecWithP[ch];
02289     LDREndPntPair tmpEndPt;
02290     if(fOrgErr == 0)
02291         return;
02292
02293     int delta = 5;
02294
02295     // ok figure out the range of A and B
02296     tmpEndPt = optEndPt;
02297     int alow = std::max<int>(0, int(optEndPt.A[ch]) - delta);
02298     int ahigh = std::min<int>((1 << uPrec) - 1, int(optEndPt.A[ch]) + delta);
02299     int blow = std::max<int>(0, int(optEndPt.B[ch]) - delta);
02300     int bhigh = std::min<int>((1 << uPrec) - 1, int(optEndPt.B[ch]) + delta);
02301     int amin = 0;
02302     int bmin = 0;
02303
02304     float fBestErr = fOrgErr;
02305     if(optEndPt.A[ch] <= optEndPt.B[ch])
02306     {
02307         // keep a <= b
02308         for(int a = alow; a <= ahigh; ++a)
02309         {
02310             for(int b = std::max<int>(a, blow); b < bhigh; ++b)
02311             {
02312                 tmpEndPt.A[ch] = (uint8_t) a;
02313                 tmpEndPt.B[ch] = (uint8_t) b;
02314
02315                 float fErr = MapColors(pEP, aColors, np, uIndexMode, tmpEndPt, fBestErr);
02316                 if(fErr < fBestErr)
02317                 {
02318                     amin = a;
02319                     bmin = b;
02320                     fBestErr = fErr;
02321                 }
02322             }
02323         }
02324     }
02325     else
02326     {
02327         // keep b <= a
02328         for(int b = blow; b < bhigh; ++b)
02329         {
02330             for(int a = std::max<int>(b, alow); a <= ahigh; ++a)
02331             {
02332                 tmpEndPt.A[ch] = (uint8_t) a;
02333                 tmpEndPt.B[ch] = (uint8_t) b;
02334
02335                 float fErr = MapColors(pEP, aColors, np, uIndexMode, tmpEndPt, fBestErr);
02336                 if(fErr < fBestErr)
02337                 {
02338                     amin = a;
02339                     bmin = b;
02340                     fBestErr = fErr;
02341                 }
02342             }
02343         }
02344     }
02345
02346     if(fBestErr < fOrgErr)
02347     {
02348         optEndPt.A[ch] = (uint8_t) amin;
02349         optEndPt.B[ch] = (uint8_t) bmin;
02350         fOrgErr = fBestErr;
02351     }
02352 }
02353
02354 _Use_decl_annotations_
02355 void D3DX_BC7::OptimizeOne(const EncodeParams* pEP, const LDRColorA aColors[], size_t np, size_t uIndexMode,
02356                            float fOrgErr, const LDREndPntPair& org, LDREndPntPair& opt) const
02357 {
02358     assert( pEP );
02359
02360     float fOptErr = fOrgErr;
02361     opt = org;
02362
02363     LDREndPntPair new_a, new_b;
02364     LDREndPntPair newEndPts;
02365     uint8_t do_b;
02366
02367     // now optimize each channel separately
02368     for(size_t ch = 0; ch < BC7_NUM_CHANNELS; ++ch)
02369     {
02370         if(ms_aInfo[pEP->uMode].RGBAPrecWithP[ch] == 0)
02371             continue;
02372
02373         // figure out which endpoint when perturbed gives the most improvement and start there
02374         // if we just alternate, we can easily end up in a local minima
02375         float fErr0 = PerturbOne(pEP, aColors, np, uIndexMode, ch, opt, new_a, fOptErr, 0); // perturb endpt A
02376         float fErr1 = PerturbOne(pEP, aColors, np, uIndexMode, ch, opt, new_b, fOptErr, 1); // perturb endpt B
02377
02378         uint8_t& copt_a = opt.A[ch];
02379         uint8_t& copt_b = opt.B[ch];
02380         uint8_t& cnew_a = new_a.A[ch];
02381         uint8_t& cnew_b = new_a.B[ch];
02382
02383         if(fErr0 < fErr1)
02384         {
02385             if(fErr0 >= fOptErr)
02386                 continue;
02387             copt_a = cnew_a;
02388             fOptErr = fErr0;
02389             do_b = 1;   // do B next
02390         }
02391         else
02392         {
02393             if(fErr1 >= fOptErr)
02394                 continue;
02395             copt_b = cnew_b;
02396             fOptErr = fErr1;
02397             do_b = 0;   // do A next
02398         }
02399
02400         // now alternate endpoints and keep trying until there is no improvement
02401         for( ; ; )
02402         {
02403             float fErr = PerturbOne(pEP, aColors, np, uIndexMode, ch, opt, newEndPts, fOptErr, do_b);
02404             if(fErr >= fOptErr)
02405                 break;
02406             if(do_b == 0)
02407                 copt_a = cnew_a;
02408             else
02409                 copt_b = cnew_b;
02410             fOptErr = fErr;
02411             do_b = 1 - do_b;  // now move the other endpoint
02412         }
02413     }
02414
02415     // finally, do a small exhaustive search around what we think is the global minima to be sure
02416     for(size_t ch = 0; ch < BC7_NUM_CHANNELS; ch++)
02417         Exhaustive(pEP, aColors, np, uIndexMode, ch, fOptErr, opt);
02418 }
02419
02420 _Use_decl_annotations_
02421 void D3DX_BC7::OptimizeEndPoints(const EncodeParams* pEP, size_t uShape, size_t uIndexMode, const float afOrgErr[],
02422                                  const LDREndPntPair aOrgEndPts[], LDREndPntPair aOptEndPts[]) const
02423 {
02424     assert( pEP );
02425     const uint8_t uPartitions = ms_aInfo[pEP->uMode].uPartitions;
02426     assert( uPartitions < BC7_MAX_REGIONS && uShape < BC7_MAX_SHAPES );
02427     _Analysis_assume_( uPartitions < BC7_MAX_REGIONS && uShape < BC7_MAX_SHAPES );
02428
02429     LDRColorA aPixels[NUM_PIXELS_PER_BLOCK];
02430
02431     for(size_t p = 0; p <= uPartitions; ++p)
02432     {
02433         // collect the pixels in the region
02434         size_t np = 0;
02435         for(register size_t i = 0; i < NUM_PIXELS_PER_BLOCK; ++i)
02436             if(g_aPartitionTable[uPartitions][uShape][i] == p)
02437                 aPixels[np++] = pEP->aLDRPixels[i];
02438
02439         OptimizeOne(pEP, aPixels, np, uIndexMode, afOrgErr[p], aOrgEndPts[p], aOptEndPts[p]);
02440     }
02441 }
02442
02443 _Use_decl_annotations_
02444 void D3DX_BC7::AssignIndices(const EncodeParams* pEP, size_t uShape, size_t uIndexMode, LDREndPntPair endPts[], size_t aIndices[], size_t aIndices2[],
02445                              float afTotErr[]) const
02446 {
02447     assert( pEP );
02448     assert( uShape < BC7_MAX_SHAPES );
02449     _Analysis_assume_( uShape < BC7_MAX_SHAPES );
02450
02451     const uint8_t uPartitions = ms_aInfo[pEP->uMode].uPartitions;
02452     assert( uPartitions < BC7_MAX_REGIONS );
02453     _Analysis_assume_( uPartitions < BC7_MAX_REGIONS );
02454
02455     const uint8_t uIndexPrec = uIndexMode ? ms_aInfo[pEP->uMode].uIndexPrec2 : ms_aInfo[pEP->uMode].uIndexPrec;
02456     const uint8_t uIndexPrec2 = uIndexMode ? ms_aInfo[pEP->uMode].uIndexPrec : ms_aInfo[pEP->uMode].uIndexPrec2;
02457     const uint8_t uNumIndices = 1 << uIndexPrec;
02458     const uint8_t uNumIndices2 = 1 << uIndexPrec2;
02459
02460     assert( (uNumIndices <= BC7_MAX_INDICES) && (uNumIndices2 <= BC7_MAX_INDICES) );
02461     _Analysis_assume_( (uNumIndices <= BC7_MAX_INDICES) && (uNumIndices2 <= BC7_MAX_INDICES) );
02462
02463     const uint8_t uHighestIndexBit = uNumIndices >> 1;
02464     const uint8_t uHighestIndexBit2 = uNumIndices2 >> 1;
02465     LDRColorA aPalette[BC7_MAX_REGIONS][BC7_MAX_INDICES];
02466
02467     // build list of possibles
02468     LDREndPntPair adjusted_endPts;
02469     for(size_t p = 0; p <= uPartitions; p++)
02470     {
02471         GeneratePaletteQuantized(pEP, uIndexMode, endPts[p], aPalette[p]);
02472         afTotErr[p] = 0;
02473     }
02474
02475     for(register size_t i = 0; i < NUM_PIXELS_PER_BLOCK; i++)
02476     {
02477         uint8_t uRegion = g_aPartitionTable[uPartitions][uShape][i];
02478         assert( uRegion < BC7_MAX_REGIONS );
02479         _Analysis_assume_( uRegion < BC7_MAX_REGIONS );
02480         afTotErr[uRegion] += ComputeError(pEP->aLDRPixels[i], aPalette[uRegion], uIndexPrec, uIndexPrec2, &(aIndices[i]), &(aIndices2[i]));
02481     }
02482
02483     // swap endpoints as needed to ensure that the indices at index_positions have a 0 high-order bit
02484     if(uIndexPrec2 == 0)
02485     {
02486         for(register size_t p = 0; p <= uPartitions; p++)
02487         {
02488             if(aIndices[g_aFixUp[uPartitions][uShape][p]] & uHighestIndexBit)
02489             {
02490                 Swap(endPts[p].A, endPts[p].B);
02491                 for(register size_t i = 0; i < NUM_PIXELS_PER_BLOCK; i++)
02492                     if(g_aPartitionTable[uPartitions][uShape][i] == p)
02493                         aIndices[i] = uNumIndices - 1 - aIndices[i];
02494             }
02495             assert((aIndices[g_aFixUp[uPartitions][uShape][p]] & uHighestIndexBit) == 0);
02496         }
02497     }
02498     else
02499     {
02500         for(register size_t p = 0; p <= uPartitions; p++)
02501         {
02502             if(aIndices[g_aFixUp[uPartitions][uShape][p]] & uHighestIndexBit)
02503             {
02504                 Swap(endPts[p].A.r, endPts[p].B.r);
02505                 Swap(endPts[p].A.g, endPts[p].B.g);
02506                 Swap(endPts[p].A.b, endPts[p].B.b);
02507                 for(register size_t i = 0; i < NUM_PIXELS_PER_BLOCK; i++)
02508                     if(g_aPartitionTable[uPartitions][uShape][i] == p)
02509                         aIndices[i] = uNumIndices - 1 - aIndices[i];
02510             }
02511             assert((aIndices[g_aFixUp[uPartitions][uShape][p]] & uHighestIndexBit) == 0);
02512
02513             if(aIndices2[0] & uHighestIndexBit2)
02514             {
02515                 Swap(endPts[p].A.a, endPts[p].B.a);
02516                 for(register size_t i = 0; i < NUM_PIXELS_PER_BLOCK; i++)
02517                     aIndices2[i] = uNumIndices2 - 1 - aIndices2[i];
02518             }
02519             assert((aIndices2[0] & uHighestIndexBit2) == 0);
02520         }
02521     }
02522 }
02523
02524 _Use_decl_annotations_
02525 void D3DX_BC7::EmitBlock(const EncodeParams* pEP, size_t uShape, size_t uRotation, size_t uIndexMode, const LDREndPntPair aEndPts[], const size_t aIndex[], const size_t aIndex2[])
02526 {
02527     assert( pEP );
02528     const uint8_t uPartitions = ms_aInfo[pEP->uMode].uPartitions;
02529     assert( uPartitions < BC7_MAX_REGIONS );
02530     _Analysis_assume_( uPartitions < BC7_MAX_REGIONS );
02531
02532     const size_t uPBits = ms_aInfo[pEP->uMode].uPBits;
02533     const size_t uIndexPrec = ms_aInfo[pEP->uMode].uIndexPrec;
02534     const size_t uIndexPrec2 = ms_aInfo[pEP->uMode].uIndexPrec2;
02535     const LDRColorA RGBAPrec = ms_aInfo[pEP->uMode].RGBAPrec;
02536     const LDRColorA RGBAPrecWithP = ms_aInfo[pEP->uMode].RGBAPrecWithP;
02537     register size_t i;
02538     size_t uStartBit = 0;
02539     SetBits(uStartBit, pEP->uMode, 0);
02540     SetBits(uStartBit, 1, 1);
02541     SetBits(uStartBit, ms_aInfo[pEP->uMode].uRotationBits, static_cast<uint8_t>( uRotation ));
02542     SetBits(uStartBit, ms_aInfo[pEP->uMode].uIndexModeBits, static_cast<uint8_t>( uIndexMode ));
02543     SetBits(uStartBit, ms_aInfo[pEP->uMode].uPartitionBits, static_cast<uint8_t>( uShape ));
02544
02545     if(uPBits)
02546     {
02547         const size_t uNumEP = (1 + uPartitions) << 1;
02548         uint8_t aPVote[BC7_MAX_REGIONS << 1] = {0,0,0,0,0,0};
02549         uint8_t aCount[BC7_MAX_REGIONS << 1] = {0,0,0,0,0,0};
02550         for(uint8_t ch = 0; ch < BC7_NUM_CHANNELS; ch++)
02551         {
02552             uint8_t ep = 0;
02553             for(i = 0; i <= uPartitions; i++)
02554             {
02555                 if(RGBAPrec[ch] == RGBAPrecWithP[ch])
02556                 {
02557                     SetBits(uStartBit, RGBAPrec[ch], aEndPts[i].A[ch]);
02558                     SetBits(uStartBit, RGBAPrec[ch], aEndPts[i].B[ch]);
02559                 }
02560                 else
02561                 {
02562                     SetBits(uStartBit, RGBAPrec[ch], aEndPts[i].A[ch] >> 1);
02563                     SetBits(uStartBit, RGBAPrec[ch], aEndPts[i].B[ch] >> 1);
02564                     size_t idx = ep++ * uPBits / uNumEP;
02565                     assert(idx < (BC7_MAX_REGIONS << 1));
02566                     _Analysis_assume_(idx < (BC7_MAX_REGIONS << 1));
02567                     aPVote[idx] += aEndPts[i].A[ch] & 0x01;
02568                     aCount[idx]++;
02569                     idx = ep++ * uPBits / uNumEP;
02570                     assert(idx < (BC7_MAX_REGIONS << 1));
02571                     _Analysis_assume_(idx < (BC7_MAX_REGIONS << 1));
02572                     aPVote[idx] += aEndPts[i].B[ch] & 0x01;
02573                     aCount[idx]++;
02574                 }
02575             }
02576         }
02577
02578         for(i = 0; i < uPBits; i++)
02579         {
02580             SetBits(uStartBit, 1, aPVote[i] > (aCount[i] >> 1) ? 1 : 0);
02581         }
02582     }
02583     else
02584     {
02585         for(size_t ch = 0; ch < BC7_NUM_CHANNELS; ch++)
02586         {
02587             for(i = 0; i <= uPartitions; i++)
02588             {
02589                 SetBits(uStartBit, RGBAPrec[ch], aEndPts[i].A[ch] );
02590                 SetBits(uStartBit, RGBAPrec[ch], aEndPts[i].B[ch] );
02591             }
02592         }
02593     }
02594
02595     const size_t* aI1 = uIndexMode ? aIndex2 : aIndex;
02596     const size_t* aI2 = uIndexMode ? aIndex : aIndex2;
02597     for(i = 0; i < NUM_PIXELS_PER_BLOCK; i++)
02598     {
02599         if(IsFixUpOffset(ms_aInfo[pEP->uMode].uPartitions, uShape, i))
02600             SetBits(uStartBit, uIndexPrec - 1, static_cast<uint8_t>( aI1[i] ));
02601         else
02602             SetBits(uStartBit, uIndexPrec, static_cast<uint8_t>( aI1[i] ));
02603     }
02604     if(uIndexPrec2)
02605         for(i = 0; i < NUM_PIXELS_PER_BLOCK; i++)
02606             SetBits(uStartBit, i ? uIndexPrec2 : uIndexPrec2 - 1, static_cast<uint8_t>( aI2[i] ));
02607
02608     assert(uStartBit == 128);
02609 }
02610
02611 _Use_decl_annotations_
02612 float D3DX_BC7::Refine(const EncodeParams* pEP, size_t uShape, size_t uRotation, size_t uIndexMode)
02613 {
02614     assert( pEP );
02615     assert( uShape < BC7_MAX_SHAPES );
02616     _Analysis_assume_( uShape < BC7_MAX_SHAPES );
02617     const LDREndPntPair* aEndPts = pEP->aEndPts[uShape];
02618
02619     const size_t uPartitions = ms_aInfo[pEP->uMode].uPartitions;
02620     assert( uPartitions < BC7_MAX_REGIONS );
02621     _Analysis_assume_( uPartitions < BC7_MAX_REGIONS );
02622
02623     LDREndPntPair aOrgEndPts[BC7_MAX_REGIONS];
02624     LDREndPntPair aOptEndPts[BC7_MAX_REGIONS];
02625     size_t aOrgIdx[NUM_PIXELS_PER_BLOCK];
02626     size_t aOrgIdx2[NUM_PIXELS_PER_BLOCK];
02627     size_t aOptIdx[NUM_PIXELS_PER_BLOCK];
02628     size_t aOptIdx2[NUM_PIXELS_PER_BLOCK];
02629     float aOrgErr[BC7_MAX_REGIONS];
02630     float aOptErr[BC7_MAX_REGIONS];
02631
02632     for(register size_t p = 0; p <= uPartitions; p++)
02633     {
02634         aOrgEndPts[p].A = Quantize(aEndPts[p].A, ms_aInfo[pEP->uMode].RGBAPrecWithP);
02635         aOrgEndPts[p].B = Quantize(aEndPts[p].B, ms_aInfo[pEP->uMode].RGBAPrecWithP);
02636     }
02637
02638     AssignIndices(pEP, uShape, uIndexMode, aOrgEndPts, aOrgIdx, aOrgIdx2, aOrgErr);
02639     OptimizeEndPoints(pEP, uShape, uIndexMode, aOrgErr, aOrgEndPts, aOptEndPts);
02640     AssignIndices(pEP, uShape, uIndexMode, aOptEndPts, aOptIdx, aOptIdx2, aOptErr);
02641
02642     float fOrgTotErr = 0, fOptTotErr = 0;
02643     for(register size_t p = 0; p <= uPartitions; p++)
02644     {
02645         fOrgTotErr += aOrgErr[p];
02646         fOptTotErr += aOptErr[p];
02647     }
02648     if(fOptTotErr < fOrgTotErr)
02649     {
02650         EmitBlock(pEP, uShape, uRotation, uIndexMode, aOptEndPts, aOptIdx, aOptIdx2);
02651         return fOptTotErr;
02652     }
02653     else
02654     {
02655         EmitBlock(pEP, uShape, uRotation, uIndexMode, aOrgEndPts, aOrgIdx, aOrgIdx2);
02656         return fOrgTotErr;
02657     }
02658 }
02659
02660 _Use_decl_annotations_
02661 float D3DX_BC7::MapColors(const EncodeParams* pEP, const LDRColorA aColors[], size_t np, size_t uIndexMode, const LDREndPntPair& endPts, float fMinErr) const
02662 {
02663     assert( pEP );
02664     const uint8_t uIndexPrec = uIndexMode ? ms_aInfo[pEP->uMode].uIndexPrec2 : ms_aInfo[pEP->uMode].uIndexPrec;
02665     const uint8_t uIndexPrec2 = uIndexMode ? ms_aInfo[pEP->uMode].uIndexPrec : ms_aInfo[pEP->uMode].uIndexPrec2;
02666     LDRColorA aPalette[BC7_MAX_INDICES];
02667     float fTotalErr = 0;
02668
02669     GeneratePaletteQuantized(pEP, uIndexMode, endPts, aPalette);
02670     for(register size_t i = 0; i < np; ++i)
02671     {
02672         fTotalErr += ComputeError(aColors[i], aPalette, uIndexPrec, uIndexPrec2);
02673         if(fTotalErr > fMinErr)   // check for early exit
02674         {
02675             fTotalErr = FLT_MAX;
02676             break;
02677         }
02678     }
02679
02680     return fTotalErr;
02681 }
02682
02683 _Use_decl_annotations_
02684 float D3DX_BC7::RoughMSE(EncodeParams* pEP, size_t uShape, size_t uIndexMode)
02685 {
02686     assert( pEP );
02687     assert( uShape < BC7_MAX_SHAPES );
02688     _Analysis_assume_( uShape < BC7_MAX_SHAPES );
02689     LDREndPntPair* aEndPts = pEP->aEndPts[uShape];
02690
02691     const uint8_t uPartitions = ms_aInfo[pEP->uMode].uPartitions;
02692     assert( uPartitions < BC7_MAX_REGIONS );
02693     _Analysis_assume_( uPartitions < BC7_MAX_REGIONS );
02694
02695     const uint8_t uIndexPrec = uIndexMode ? ms_aInfo[pEP->uMode].uIndexPrec2 : ms_aInfo[pEP->uMode].uIndexPrec;
02696     const uint8_t uIndexPrec2 = uIndexMode ? ms_aInfo[pEP->uMode].uIndexPrec : ms_aInfo[pEP->uMode].uIndexPrec2;
02697     const uint8_t uNumIndices = 1 << uIndexPrec;
02698     const uint8_t uNumIndices2 = 1 << uIndexPrec2;
02699     size_t auPixIdx[NUM_PIXELS_PER_BLOCK];
02700     LDRColorA aPalette[BC7_MAX_REGIONS][BC7_MAX_INDICES];
02701
02702     for(size_t p = 0; p <= uPartitions; p++)
02703     {
02704         size_t np = 0;
02705         for(register size_t i = 0; i < NUM_PIXELS_PER_BLOCK; i++)
02706         {
02707             if (g_aPartitionTable[uPartitions][uShape][i] == p)
02708             {
02709                 auPixIdx[np++] = i;
02710             }
02711         }
02712
02713         // handle simple cases
02714         assert(np > 0);
02715         if(np == 1)
02716         {
02717             aEndPts[p].A = pEP->aLDRPixels[auPixIdx[0]];
02718             aEndPts[p].B = pEP->aLDRPixels[auPixIdx[0]];
02719             continue;
02720         }
02721         else if(np == 2)
02722         {
02723             aEndPts[p].A = pEP->aLDRPixels[auPixIdx[0]];
02724             aEndPts[p].B = pEP->aLDRPixels[auPixIdx[1]];
02725             continue;
02726         }
02727
02728         if(uIndexPrec2 == 0)
02729         {
02730             HDRColorA epA, epB;
02731             OptimizeRGBA(pEP->aHDRPixels, &epA, &epB, 4, np, auPixIdx);
02732             epA.Clamp(0.0f, 1.0f);
02733             epB.Clamp(0.0f, 1.0f);
02734             epA *= 255.0f;
02735             epB *= 255.0f;
02736             aEndPts[p].A = epA.ToLDRColorA();
02737             aEndPts[p].B = epB.ToLDRColorA();
02738         }
02739         else
02740         {
02741             uint8_t uMinAlpha = 255, uMaxAlpha = 0;
02742             for(register size_t i = 0; i < NUM_PIXELS_PER_BLOCK; ++i)
02743             {
02744                 uMinAlpha = std::min<uint8_t>(uMinAlpha, pEP->aLDRPixels[auPixIdx[i]].a);
02745                 uMaxAlpha = std::max<uint8_t>(uMaxAlpha, pEP->aLDRPixels[auPixIdx[i]].a);
02746             }
02747
02748             HDRColorA epA, epB;
02749             OptimizeRGB(pEP->aHDRPixels, &epA, &epB, 4, np, auPixIdx);
02750             epA.Clamp(0.0f, 1.0f);
02751             epB.Clamp(0.0f, 1.0f);
02752             epA *= 255.0f;
02753             epB *= 255.0f;
02754             aEndPts[p].A = epA.ToLDRColorA();
02755             aEndPts[p].B = epB.ToLDRColorA();
02756             aEndPts[p].A.a = uMinAlpha;
02757             aEndPts[p].B.a = uMaxAlpha;
02758         }
02759     }
02760
02761     if(uIndexPrec2 == 0)
02762     {
02763         for(size_t p = 0; p <= uPartitions; p++)
02764             for(register size_t i = 0; i < uNumIndices; i++)
02765                 LDRColorA::Interpolate(aEndPts[p].A, aEndPts[p].B, i, i, uIndexPrec, uIndexPrec, aPalette[p][i]);
02766     }
02767     else
02768     {
02769         for(size_t p = 0; p <= uPartitions; p++)
02770         {
02771             for(register size_t i = 0; i < uNumIndices; i++)
02772                 LDRColorA::InterpolateRGB(aEndPts[p].A, aEndPts[p].B, i, uIndexPrec, aPalette[p][i]);
02773             for(register size_t i = 0; i < uNumIndices2; i++)
02774                 LDRColorA::InterpolateA(aEndPts[p].A, aEndPts[p].B, i, uIndexPrec2, aPalette[p][i]);
02775         }
02776     }
02777
02778     float fTotalErr = 0;
02779     for(register size_t i = 0; i < NUM_PIXELS_PER_BLOCK; i++)
02780     {
02781         uint8_t uRegion = g_aPartitionTable[uPartitions][uShape][i];
02782         fTotalErr += ComputeError(pEP->aLDRPixels[i], aPalette[uRegion], uIndexPrec, uIndexPrec2);
02783     }
02784
02785     return fTotalErr;
02786 }
02787
02788 //=====================================================================================
02789 // Entry points
02790 //=====================================================================================
02791
02792 //-------------------------------------------------------------------------------------
02793 // BC6H Compression
02794 //-------------------------------------------------------------------------------------
02795 _Use_decl_annotations_
02796 void D3DXDecodeBC6HU(XMVECTOR *pColor, const uint8_t *pBC)
02797 {
02798     assert( pColor && pBC );
02799     static_assert( sizeof(D3DX_BC6H) == 16, "D3DX_BC6H should be 16 bytes" );
02800     reinterpret_cast< const D3DX_BC6H* >( pBC )->Decode(false, reinterpret_cast<HDRColorA*>(pColor));
02801 }
02802
02803 _Use_decl_annotations_
02804 void D3DXDecodeBC6HS(XMVECTOR *pColor, const uint8_t *pBC)
02805 {
02806     assert( pColor && pBC );
02807     static_assert( sizeof(D3DX_BC6H) == 16, "D3DX_BC6H should be 16 bytes" );
02808     reinterpret_cast< const D3DX_BC6H* >( pBC )->Decode(true, reinterpret_cast<HDRColorA*>(pColor));
02809 }
02810
02811 _Use_decl_annotations_
02812 void D3DXEncodeBC6HU(uint8_t *pBC, const XMVECTOR *pColor, DWORD flags)
02813 {
02814     UNREFERENCED_PARAMETER(flags);
02815     assert( pBC && pColor );
02816     static_assert( sizeof(D3DX_BC6H) == 16, "D3DX_BC6H should be 16 bytes" );
02817     reinterpret_cast< D3DX_BC6H* >( pBC )->Encode(false, reinterpret_cast<const HDRColorA*>(pColor));
02818 }
02819
02820 _Use_decl_annotations_
02821 void D3DXEncodeBC6HS(uint8_t *pBC, const XMVECTOR *pColor, DWORD flags)
02822 {
02823     UNREFERENCED_PARAMETER(flags);
02824     assert( pBC && pColor );
02825     static_assert( sizeof(D3DX_BC6H) == 16, "D3DX_BC6H should be 16 bytes" );
02826     reinterpret_cast< D3DX_BC6H* >( pBC )->Encode(true, reinterpret_cast<const HDRColorA*>(pColor));
02827 }
02828
02829
02830 //-------------------------------------------------------------------------------------
02831 // BC7 Compression
02832 //-------------------------------------------------------------------------------------
02833 _Use_decl_annotations_
02834 void D3DXDecodeBC7(XMVECTOR *pColor, const uint8_t *pBC)
02835 {
02836     assert( pColor && pBC );
02837     static_assert( sizeof(D3DX_BC7) == 16, "D3DX_BC7 should be 16 bytes" );
02838     reinterpret_cast< const D3DX_BC7* >( pBC )->Decode(reinterpret_cast<HDRColorA*>(pColor));
02839 }
02840
02841 _Use_decl_annotations_
02842 void D3DXEncodeBC7(uint8_t *pBC, const XMVECTOR *pColor, DWORD flags)
02843 {
02844     UNREFERENCED_PARAMETER(flags);
02845     assert( pBC && pColor );
02846     static_assert( sizeof(D3DX_BC7) == 16, "D3DX_BC7 should be 16 bytes" );
02847     reinterpret_cast< D3DX_BC7* >( pBC )->Encode(reinterpret_cast<const HDRColorA*>(pColor));
02848 }
02849
02850 } // namespace
Generated on Sat Nov 23 2024 16:08:11 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Sharing content source app/C++/SharePage.cpp Source File

  • Sharing content source app

SharePage.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 // SharePage.cpp
00013 // Implementation of the SharePage class
00014 //
00015
00016 #include "pch.h"
00017 #include "SharePage.h"
00018
00019 using namespace SDKSample::Common;
00020
00021 using namespace Platform;
00022 using namespace Windows::Foundation;
00023 using namespace Windows::UI::Xaml;
00024 using namespace Windows::UI::Xaml::Navigation;
00025 using namespace Windows::ApplicationModel::DataTransfer;
00026
00027 void SharePage::OnNavigatedTo(NavigationEventArgs^ e)
00028 {
00029     // Register the current page as a share source.
00030     dataRequestedToken = DataTransferManager::GetForCurrentView()->DataRequested += ref new TypedEventHandler<DataTransferManager^, DataRequestedEventArgs^>(this, &SharePage::OnDataRequested);
00031 }
00032
00033 void SharePage::OnNavigatedFrom(NavigationEventArgs^ e)
00034 {
00035     // Unregister the current page as a share source.
00036     DataTransferManager::GetForCurrentView()->DataRequested -= dataRequestedToken;
00037 }
00038
00039 // When share is invoked (by the user or programatically) the event handler we registered will be called to populate the datapackage with the
00040 // data to be shared.
00041 void SharePage::OnDataRequested(DataTransferManager^ sender, DataRequestedEventArgs^ e)
00042 {
00043     // Call the scenario specific function to populate the datapackage with the data to be shared.
00044     if (GetShareContent(e->Request))
00045     {
00046         // Out of the datapackage properties, the title is required. If the scenario completed successfully, we need
00047         // to make sure the title is valid since the sample scenario gets the title from the user.
00048         if (e->Request->Data->Properties->Title == nullptr)
00049         {
00050             e->Request->FailWithDisplayText(MainPage::MissingTitleError);
00051         }
00052     }
00053 }
00054
00055 void SharePage::ShowUIButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00056 {
00057     // If the user clicks the share button, invoke the share flow programatically.
00058     Windows::ApplicationModel::DataTransfer::DataTransferManager::ShowShareUI();
00059 }
00060
00061 // This function is implemented by each scenario to share the content specific to that scenario (text, link, image, etc.).
00062 bool SharePage::GetShareContent(DataRequest^ request)
00063 {
00064     request->FailWithDisplayText("Scenario specific class must override GetShareContent");
00065     return false;
00066 }
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File access/C++/Scenario7.xaml.cpp Source File

  • File access

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 SDKSample::FileAccess;
00020
00021 using namespace concurrency;
00022 using namespace Platform;
00023 using namespace Windows::Storage;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Controls;
00026 using namespace Windows::UI::Xaml::Navigation;
00027
00028 Scenario7::Scenario7()
00029 {
00030     InitializeComponent();
00031     rootPage = MainPage::Current;
00032     CopyFileButton->Click += ref new RoutedEventHandler(this, &Scenario7::CopyFileButton_Click);
00033 }
00034
00035 void Scenario7::CopyFileButton_Click(Object^ sender, RoutedEventArgs^ e)
00036 {
00037     rootPage->ResetScenarioOutput(OutputTextBlock);
00038     StorageFile^ file = rootPage->SampleFile;
00039     if (file != nullptr)
00040     {
00041         // Get the returned file and copy it
00042         StorageFolder^ documentsFolder = KnownFolders::DocumentsLibrary;
00043         create_task(file->CopyAsync(documentsFolder, "sample - Copy.dat", NameCollisionOption::ReplaceExisting)).then([this, file](task<StorageFile^> task)
00044         {
00045             try
00046             {
00047                 StorageFile^ sampleFileCopy = task.get();
00048                 OutputTextBlock->Text = "The file '" + file->Name + "' was copied and the new file was named '" + sampleFileCopy->Name + "'.";
00049             }
00050             catch(COMException^ ex)
00051             {
00052                 rootPage->HandleFileNotFoundException(ex);
00053             }
00054         });
00055     }
00056 }
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: LightSensor/C++/Constants.h Source File

  • LightSensor

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"Light Sensor Raw Data");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044
00045
00046 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CameraCaptureUI/C++/CapturePhoto.xaml.h Source File

  • CameraCaptureUI

CapturePhoto.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 // CapturePhoto.xaml.h
00013 // Declaration of the CapturePhoto class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "CapturePhoto.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKSample
00023 {
00024     namespace CameraCapture
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 CapturePhoto sealed
00031         {
00032         public:
00033             CapturePhoto();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void CapturePhoto_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040             void Reset_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041             void LoadPhoto(Platform::String^ filepath);
00042
00043             Windows::Foundation::Collections::IPropertySet^ appSettings;
00044         };
00045     }
00046 }
Generated on Sat Nov 23 2024 16:07:58 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

CAppWindowProvider Member List

This is the complete list of members for CAppWindowProvider, including all inherited members.
AdviseEventAdded(_In_ EVENTID eventId, _In_ SAFEARRAY *propertyIDs) | CAppWindowProvider |
AdviseEventRemoved(_In_ EVENTID eventId, _In_ SAFEARRAY *propertyIDs) | CAppWindowProvider |
CAppWindowProvider() | CAppWindowProvider |
CheckDisconnected() | CAppWindowProvider | [protected]
Disconnect() | CAppWindowProvider |
ElementProviderFromPoint(_In_ double x, _In_ double y, _Outptr_result_maybenull_ IRawElementProviderFragment **retVal) | CAppWindowProvider |
get_BoundingRectangle(_Out_ UiaRect *retVal) | CAppWindowProvider |
get_FragmentRoot(_Outptr_result_maybenull_ IRawElementProviderFragmentRoot **retVal) | CAppWindowProvider |
get_HostRawElementProvider(_Outptr_result_maybenull_ IRawElementProviderSimple **retVal) | CAppWindowProvider |
get_ProviderOptions(_Out_ ProviderOptions *retVal) | CAppWindowProvider |
GetEmbeddedFragmentRoots(_Outptr_result_maybenull_ SAFEARRAY **retVal) | CAppWindowProvider |
GetFocus(_Outptr_result_maybenull_ IRawElementProviderFragment **retVal) | CAppWindowProvider |
GetPatternProvider(_In_ PATTERNID iid, _Outptr_result_maybenull_ IUnknown **retVal) | CAppWindowProvider |
GetPropertyValue(_In_ PROPERTYID idProp, _Out_ VARIANT *retVal) | CAppWindowProvider |
GetRuntimeId(_Outptr_result_maybenull_ SAFEARRAY **retVal) | CAppWindowProvider |
Initialize(_In_ ITriColorControlInternal *pControl, _In_ IInspectable *pWindow) | CAppWindowProvider |
InspectableClass(RuntimeClass_UiaCoreWindowProvider_AppWindowProvider, BaseTrust) | CAppWindowProvider | [private]
m_control | CAppWindowProvider | [protected]
m_disconnected | CAppWindowProvider | [protected]
m_window | CAppWindowProvider | [protected]
Navigate(_In_ NavigateDirection direction, _Outptr_result_maybenull_ IRawElementProviderFragment **retVal) | CAppWindowProvider |
SetFocus() | CAppWindowProvider |
Generated on Sat Nov 23 2024 16:09:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SoundFileReader Member List

This is the complete list of members for SoundFileReader, including all inherited members.
GetSoundData() const | SoundFileReader |
GetSoundFormat() const | SoundFileReader |
m_soundData | SoundFileReader | [private]
m_soundFormat | SoundFileReader | [private]
SoundFileReader(_In_ Platform::String^soundFileName) | SoundFileReader |
Generated on Sat Nov 23 2024 16:09:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DirectX::INTColor Member List

This is the complete list of members for DirectX::INTColor, including all inherited members.
b | DirectX::INTColor |
Clamp(_In_ int iMin, _In_ int iMax) | DirectX::INTColor | [inline]
F16ToINT(_In_ const PackedVector::HALF &f, _In_ bool bSigned) | DirectX::INTColor | [inline, private, static]
g | DirectX::INTColor |
INT2F16(_In_ int input, _In_ bool bSigned) | DirectX::INTColor | [inline, private, static]
INTColor() | DirectX::INTColor | [inline]
INTColor(int nr, int ng, int nb) | DirectX::INTColor | [inline]
INTColor(const INTColor &c) | DirectX::INTColor | [inline]
operator&=(_In_ const INTColor &c) | DirectX::INTColor | [inline]
operator+=(_In_ const INTColor &c) | DirectX::INTColor | [inline]
operator-(_In_ const INTColor &c) const | DirectX::INTColor | [inline]
operator-=(_In_ const INTColor &c) | DirectX::INTColor | [inline]
operator[](_In_ uint8_t i) | DirectX::INTColor | [inline]
r | DirectX::INTColor |
Set(_In_ const HDRColorA &c, _In_ bool bSigned) | DirectX::INTColor | [inline]
SignExtend(_In_ const LDRColorA &Prec) | DirectX::INTColor | [inline]
ToF16(_Out_writes_(3) PackedVector::HALF aF16[3], _In_ bool bSigned) const | DirectX::INTColor | [inline]
Generated on Sat Nov 23 2024 16:09:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Scheduled notifications/C#,C++/App.xaml.cpp Source File

  • Scheduled notifications
  • C#,C++

App.xaml.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 //
00009 // App.xaml.cpp
00010 // Implementation of the App.xaml class.
00011 //
00012
00013 #include "pch.h"
00014 #include "App.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace Windows::UI::Xaml;
00018 using namespace Windows::UI::Xaml::Controls;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::ApplicationModel;
00021 using namespace Windows::ApplicationModel::Activation;
00022 using namespace CppSamplesUtils;
00023 using namespace ScheduledNotificationsSampleCPP;
00024 using namespace Windows::UI::Xaml::Interop;
00025
00026 App::App()
00027 {
00028     InitializeComponent();
00029     this->Suspending += ref new SuspendingEventHandler(this, &ScheduledNotificationsSampleCPP::App::OnSuspending);
00030 }
00031
00032 void App::OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs)
00033 {
00034     auto deferral = pArgs->SuspendingOperation->GetDeferral();
00035     SuspensionManager::StartSaveTask().then([deferral] () {
00036         deferral->Complete();
00037     });
00038 }
00039
00040 void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs)
00041 {
00042     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Terminated)
00043     {
00044         SuspensionManager::StartRestoreTask().then([this] () {
00045             auto rootFrame = ref new Frame();
00046             TypeName pageType = { "ScheduledNotificationsSampleCPP.MainPage", TypeKind::Custom };
00047             rootFrame->Navigate(pageType);
00048             Window::Current->Content = rootFrame;
00049             Window::Current->Activate();
00050         });
00051     }
00052     else
00053     {
00054         auto rootFrame = ref new Frame();
00055         TypeName pageType = { "ScheduledNotificationsSampleCPP.MainPage", TypeKind::Custom };
00056         rootFrame->Navigate(pageType);
00057         Window::Current->Content = rootFrame;
00058         Window::Current->Activate();
00059     }
00060 }
Generated on Sat Nov 23 2024 16:07:28 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D stereoscopic 3D/C++/Stereo3DMatrixHelper.cpp Source File

  • Direct3D stereoscopic 3D

Stereo3DMatrixHelper.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 "Stereo3DMatrixHelper.h"
00010
00011 using namespace DirectX;
00012
00013 StereoParameters CreateDefaultStereoParameters(
00014     float viewportWidthInches,
00015     float viewportHeightInches,
00016     float worldScaleInInches,
00017     float stereoExaggeration
00018     )
00019 {
00020     // The default stereo parameters produced by this method are based on two assumptions:
00021     // 1. The viewer's eyes are 24 inches from the display, and
00022     // 2. The viewer's eyes are separated by 1.25 inches (interocular distance.)
00023     const float DEFAULT_VIEWER_DISTANCE_IN_INCHES = 24.0f;
00024     const float DEFAULT_INTEROCULAR_DISTANCE_IN_INCHES = 1.25f;
00025
00026     StereoParameters parameters;
00027     parameters.viewportWidth = viewportWidthInches / worldScaleInInches;
00028     parameters.viewportHeight = viewportHeightInches / worldScaleInInches;
00029     parameters.viewerDistance = DEFAULT_VIEWER_DISTANCE_IN_INCHES / worldScaleInInches;
00030     parameters.interocularDistance = DEFAULT_INTEROCULAR_DISTANCE_IN_INCHES / worldScaleInInches * stereoExaggeration;
00031
00032     return parameters;
00033 }
00034
00035 DirectX::XMMATRIX StereoProjectionFieldOfViewRightHand(
00036     const StereoParameters& parameters,
00037     float nearZ,
00038     float farZ,
00039     bool rightChannel
00040     )
00041 {
00042     float yScale = 2.f * parameters.viewerDistance / parameters.viewportHeight;
00043     float xScale = 2.f * parameters.viewerDistance / parameters.viewportWidth;
00044
00045     float mFactor = - parameters.interocularDistance / parameters.viewportWidth;
00046
00047     if (!rightChannel)
00048     {
00049         mFactor = -mFactor;
00050     }
00051
00052     float m22 = farZ / (nearZ - farZ);
00053
00054     // Construct a stereo perspective projection matrix based on assumptions
00055     // about the viewer and specified stereo parameters. Note that compared
00056     // to a mono perspective projection matrix, there are two differences:
00057     //  - a non-zero x:z component (m20)
00058     //  - a non-zero x:w component (m30)
00059     // The values of these two factors affect both the x-offset between the
00060     // left and right eyes, as well as the depth at which they converge. The
00061     // math used to arrive at these values will often need to change depending
00062     // on the content being presented in order to ensure a comfortable viewing
00063     // experience. For example, the factors for rendering massive exterior
00064     // landscapes will be different than those used for rendering building
00065     // interiors. Because of this, developers are encouraged to experiment
00066     // with different techniques for generating these values.
00067     return XMMATRIX(
00068         xScale, 0, 0, 0,
00069         0, yScale, 0, 0,
00070         mFactor, 0, m22, -1,
00071         parameters.viewerDistance * mFactor, 0, nearZ * m22, 0
00072         );
00073 }
Generated on Sat Nov 23 2024 16:08:12 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XInput audio controller playback/C++/DirectXApp.cpp Source File

  • XInput audio controller playback

DirectXApp.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 "DirectXApp.h"
00010 #include "BasicTimer.h"
00011
00012 using namespace Windows::ApplicationModel;
00013 using namespace Windows::ApplicationModel::Core;
00014 using namespace Windows::ApplicationModel::Activation;
00015 using namespace Windows::UI::Core;
00016 using namespace Windows::System;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Graphics::Display;
00019
00020 DirectXApp::DirectXApp() :
00021     m_windowClosed(false),
00022     m_windowVisible(true)
00023 {
00024 }
00025
00026 void DirectXApp::Initialize(
00027     _In_ CoreApplicationView^ applicationView
00028     )
00029 {
00030     applicationView->Activated +=
00031         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &DirectXApp::OnActivated);
00032
00033     CoreApplication::Suspending +=
00034         ref new EventHandler<SuspendingEventArgs^>(this, &DirectXApp::OnSuspending);
00035
00036     CoreApplication::Resuming +=
00037         ref new EventHandler<Platform::Object^>(this, &DirectXApp::OnResuming);
00038
00039     m_renderer = ref new AudioController();
00040 }
00041
00042 void DirectXApp::SetWindow(
00043     _In_ CoreWindow^ window
00044     )
00045 {
00046     window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
00047
00048     window->SizeChanged +=
00049         ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &DirectXApp::OnWindowSizeChanged);
00050
00051     window->VisibilityChanged +=
00052         ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &DirectXApp::OnVisibilityChanged);
00053
00054     window->Closed +=
00055         ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &DirectXApp::OnWindowClosed);
00056
00057     DisplayProperties::LogicalDpiChanged +=
00058         ref new DisplayPropertiesEventHandler(this, &DirectXApp::OnLogicalDpiChanged);
00059
00060     m_renderer->Initialize(window, DisplayProperties::LogicalDpi);
00061 }
00062
00063 void DirectXApp::Load(
00064     _In_ Platform::String^ entryPoint
00065     )
00066 {
00067 }
00068
00069 void DirectXApp::Run()
00070 {
00071     BasicTimer^ timer = ref new BasicTimer();
00072
00073     while (!m_windowClosed)
00074     {
00075         if (m_windowVisible)
00076         {
00077             timer->Update();
00078             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
00079             m_renderer->Update(timer->Total, timer->Delta);
00080             m_renderer->Render();
00081             m_renderer->Present(); // This call is synchronized to the display frame rate.
00082         }
00083         else
00084         {
00085             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
00086         }
00087     }
00088 }
00089
00090 void DirectXApp::Uninitialize()
00091 {
00092 }
00093
00094 void DirectXApp::OnWindowSizeChanged(
00095     _In_ CoreWindow^ sender,
00096     _In_ WindowSizeChangedEventArgs^ args
00097     )
00098 {
00099     m_renderer->UpdateForWindowSizeChange();
00100 }
00101
00102 void DirectXApp::OnVisibilityChanged(
00103     _In_ CoreWindow^ sender,
00104     _In_ VisibilityChangedEventArgs^ args
00105     )
00106 {
00107     m_windowVisible = args->Visible;
00108 }
00109
00110 void DirectXApp::OnWindowClosed(
00111     _In_ CoreWindow^ sender,
00112     _In_ CoreWindowEventArgs^ args
00113     )
00114 {
00115     m_windowClosed = true;
00116 }
00117
00118 void DirectXApp::OnLogicalDpiChanged(
00119     _In_ Platform::Object^ sender
00120     )
00121 {
00122     m_renderer->SetDpi(DisplayProperties::LogicalDpi);
00123 }
00124
00125 void DirectXApp::OnActivated(
00126     _In_ CoreApplicationView^ applicationView,
00127     _In_ IActivatedEventArgs^ args
00128     )
00129 {
00130     CoreWindow::GetForCurrentThread()->Activate();
00131 }
00132
00133 void DirectXApp::OnSuspending(
00134     _In_ Platform::Object^,
00135     _In_ SuspendingEventArgs^
00136     )
00137 {
00138     m_renderer->OnSuspending();
00139 }
00140
00141 void DirectXApp::OnResuming(
00142     _In_ Platform::Object^,
00143     _In_ Platform::Object^
00144     )
00145 {
00146     m_renderer->OnResuming();
00147 }
00148
00149 IFrameworkView^ DirectXAppSource::CreateView()
00150 {
00151     return ref new DirectXApp();
00152 }
00153
00154 [Platform::MTAThread]
00155 int main(Platform::Array<Platform::String^>^)
00156 {
00157     auto directXAppSource = ref new DirectXAppSource();
00158     CoreApplication::Run(directXAppSource);
00159     return 0;
00160 }
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/HiloCommonDefinitions.h Source File

  • Hilo C++
  • Hilo

HiloCommonDefinitions.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
00009 #define HILO_PHOTO_FILE_NOT_FOUND _HRESULT_TYPEDEF_(0x80070002)
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::CryptoWinRT::sealed Member List

This is the complete list of members for SDKSample::CryptoWinRT::sealed, including all inherited members.
Default_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CryptoWinRT::sealed | [private]
Default_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CryptoWinRT::sealed | [private]
Default_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CryptoWinRT::sealed | [private]
Default_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CryptoWinRT::sealed | [private]
Default_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CryptoWinRT::sealed | [private]
Default_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CryptoWinRT::sealed | [private]
Default_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CryptoWinRT::sealed | [private]
GetNonce() | SDKSample::CryptoWinRT::sealed | [private]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::CryptoWinRT::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::CryptoWinRT::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::CryptoWinRT::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::CryptoWinRT::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::CryptoWinRT::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::CryptoWinRT::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::CryptoWinRT::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::CryptoWinRT::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::CryptoWinRT::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::CryptoWinRT::sealed | [protected, virtual]
rootPage | SDKSample::CryptoWinRT::sealed | [private]
RunSample_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CryptoWinRT::sealed | [private]
RunSample_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CryptoWinRT::sealed | [private]
RunSample_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CryptoWinRT::sealed | [private]
RunSample_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CryptoWinRT::sealed | [private]
RunSample_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CryptoWinRT::sealed | [private]
RunSample_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CryptoWinRT::sealed | [private]
RunSample_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CryptoWinRT::sealed | [private]
RunSample_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CryptoWinRT::sealed | [private]
RunSample_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CryptoWinRT::sealed | [private]
RunSample_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::CryptoWinRT::sealed | [private]
Scenario1() | SDKSample::CryptoWinRT::sealed |
Scenario10() | SDKSample::CryptoWinRT::sealed |
Scenario2() | SDKSample::CryptoWinRT::sealed |
Scenario3() | SDKSample::CryptoWinRT::sealed |
Scenario4() | SDKSample::CryptoWinRT::sealed |
Scenario5() | SDKSample::CryptoWinRT::sealed |
Scenario6() | SDKSample::CryptoWinRT::sealed |
Scenario7() | SDKSample::CryptoWinRT::sealed |
Scenario8() | SDKSample::CryptoWinRT::sealed |
Scenario9() | SDKSample::CryptoWinRT::sealed |
TestVectorNonce | SDKSample::CryptoWinRT::sealed | [private]
Generated on Sat Nov 23 2024 16:09:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D-Direct2D interop/C++/SampleOverlay.h Source File

  • Direct3D-Direct2D interop

SampleOverlay.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 "DirectXSample.h"
00011
00012 // This class is responsible for initializing and rendering the title overlay visible
00013 // at the top of the DirectX SDK samples.
00014 ref class SampleOverlay
00015 {
00016 internal:
00017     SampleOverlay();
00018
00019     void Initialize(
00020         _In_ ID2D1Device*         d2dDevice,
00021         _In_ ID2D1DeviceContext*  d2dContext,
00022         _In_ IWICImagingFactory*  wicFactory,
00023         _In_ IDWriteFactory*      dwriteFactory,
00024         _In_ Platform::String^    caption
00025         );
00026
00027     void ResetDirectXResources();
00028
00029     void UpdateForWindowSizeChange();
00030
00031     void Render();
00032
00033     float GetTitleHeightInDips();
00034
00035 private:
00036
00037     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00038     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00039     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00040     Microsoft::WRL::ComPtr<IDWriteFactory>          m_dwriteFactory;
00041     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_whiteBrush;
00042     Microsoft::WRL::ComPtr<ID2D1DrawingStateBlock>  m_stateBlock;
00043
00044     Microsoft::WRL::ComPtr<IWICImagingFactory>      m_wicFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Bitmap>             m_logoBitmap;
00046     Microsoft::WRL::ComPtr<IDWriteTextLayout>       m_textLayout;
00047
00048     UINT                                            m_idIncrement;
00049     bool                                            m_drawOverlay;
00050     Platform::String^                               m_sampleName;
00051     float                                           m_padding;
00052     float                                           m_textVerticalOffset;
00053     D2D1_SIZE_F                                     m_logoSize;
00054     float                                           m_overlayWidth;
00055 };
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::FilePicker::sealed Member List

This is the complete list of members for SDKSample::FilePicker::sealed, including all inherited members.
fileToken | SDKSample::FilePicker::sealed | [private]
OutputFileAsync(Windows::Storage::StorageFile^file) | SDKSample::FilePicker::sealed | [private]
OutputFileAsync(Windows::Storage::StorageFile^file) | SDKSample::FilePicker::sealed | [private]
OutputFileButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::FilePicker::sealed | [private]
PickAFileButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::FilePicker::sealed | [private]
PickFileButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::FilePicker::sealed | [private]
PickFilesButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::FilePicker::sealed | [private]
PickFolderButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::FilePicker::sealed | [private]
rootPage | SDKSample::FilePicker::sealed | [private]
SaveFileButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::FilePicker::sealed | [private]
SaveFileButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::FilePicker::sealed | [private]
Scenario1() | SDKSample::FilePicker::sealed |
Scenario2() | SDKSample::FilePicker::sealed |
Scenario3() | SDKSample::FilePicker::sealed |
Scenario4() | SDKSample::FilePicker::sealed |
Scenario5() | SDKSample::FilePicker::sealed |
Scenario6() | SDKSample::FilePicker::sealed |
WriteFileButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::FilePicker::sealed | [private]
Generated on Sat Nov 23 2024 16:09:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML WebView control/C++/Scenario7.xaml.h Source File

  • XAML WebView control

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 #include <agile.h>
00022
00023 namespace SDKSample
00024 {
00025     namespace WebViewControl
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 Scenario7 sealed
00032         {
00033         public:
00034             Scenario7();
00035
00036         protected:
00037             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00038         private:
00039             MainPage^ rootPage;
00040         Platform::Agile<Windows::ApplicationModel::DataTransfer::DataTransferManager> dataTransferManager;
00041         void WebView7_LoadCompleted(Platform::Object^ sender, Windows::UI::Xaml::Navigation::NavigationEventArgs^ e);
00042         void Share_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00043         void dataTransferManager_DataRequested(Windows::ApplicationModel::DataTransfer::DataTransferManager^ sender, Windows::ApplicationModel::DataTransfer::DataRequestedEventArgs^ args);
00044             Windows::Foundation::EventRegistrationToken dataRequestedToken;
00045       };
00046     }}
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playback Manager Companion/C++/StreamTypeOther.xaml.cpp Source File

  • Playback Manager Companion

StreamTypeOther.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 // StreamTypeOther.xaml.cpp
00013 // Implementation of the StreamTypeOther class
00014 //
00015
00016 #include "pch.h"
00017 #include "StreamTypeOther.xaml.h"
00018
00019 using namespace SDKSample::PlaybackManager2;
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::UI::Xaml::Media;
00025
00026 StreamTypeOther::StreamTypeOther()
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 StreamTypeOther::OnNavigatedTo(NavigationEventArgs^ e)
00037 {
00038     // Get a pointer to our main page.
00039     rootPage = MainPage::Current;
00040 }
00041
00042
00043 void StreamTypeOther::Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00044 {
00045   Playback->SetAudioCategory(AudioCategory::Other);
00046     Playback->SelectFile();
00047 }
00048
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

ViewTransform Member List

This is the complete list of members for ViewTransform, including all inherited members.
rotation | ViewTransform
scale | ViewTransform
translationX | ViewTransform
translationY | ViewTransform
Generated on Sat Nov 23 2024 16:09:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D stereoscopic 3D/C++/BasicReaderWriter.cpp Source File

  • Direct3D stereoscopic 3D

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     m_locationPath = Platform::String::Concat(m_location->Path, "\\");
00023 }
00024
00025 BasicReaderWriter::BasicReaderWriter(
00026     _In_ Windows::Storage::StorageFolder^ folder
00027     )
00028 {
00029     m_location = folder;
00030     Platform::String^ path = m_location->Path;
00031     if (path->Length() == 0)
00032     {
00033         // Applications are not permitted to access certain
00034         // folders, such as the Documents folder, using this
00035         // code path.  In such cases, the Path property for
00036         // the folder will be an empty string.
00037         throw ref new Platform::FailureException();
00038     }
00039     m_locationPath = Platform::String::Concat(path, "\\");
00040 }
00041
00042 Platform::Array<byte>^ BasicReaderWriter::ReadData(
00043     _In_ Platform::String^ filename
00044     )
00045 {
00046     CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {0};
00047     extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
00048     extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
00049     extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN;
00050     extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
00051     extendedParams.lpSecurityAttributes = nullptr;
00052     extendedParams.hTemplateFile = nullptr;
00053
00054     Wrappers::FileHandle file(
00055         CreateFile2(
00056             Platform::String::Concat(m_locationPath, filename)->Data(),
00057             GENERIC_READ,
00058             FILE_SHARE_READ,
00059             OPEN_EXISTING,
00060             &extendedParams
00061             )
00062         );
00063     if (file.Get() == INVALID_HANDLE_VALUE)
00064     {
00065         throw ref new Platform::FailureException();
00066     }
00067
00068     FILE_STANDARD_INFO fileInfo = {0};
00069     if (!GetFileInformationByHandleEx(
00070         file.Get(),
00071         FileStandardInfo,
00072         &fileInfo,
00073         sizeof(fileInfo)
00074         ))
00075     {
00076         throw ref new Platform::FailureException();
00077     }
00078
00079     if (fileInfo.EndOfFile.HighPart != 0)
00080     {
00081         throw ref new Platform::OutOfMemoryException();
00082     }
00083
00084     Platform::Array<byte>^ fileData = ref new Platform::Array<byte>(fileInfo.EndOfFile.LowPart);
00085
00086     if (!ReadFile(
00087         file.Get(),
00088         fileData->Data,
00089         fileData->Length,
00090         nullptr,
00091         nullptr
00092         ))
00093     {
00094         throw ref new Platform::FailureException();
00095     }
00096
00097     return fileData;
00098 }
00099
00100 task<Platform::Array<byte>^> BasicReaderWriter::ReadDataAsync(
00101     _In_ Platform::String^ filename
00102     )
00103 {
00104     return task<StorageFile^>(m_location->GetFileAsync(filename)).then([=](StorageFile^ file)
00105     {
00106         return FileIO::ReadBufferAsync(file);
00107     }).then([=](IBuffer^ buffer)
00108     {
00109         auto fileData = ref new Platform::Array<byte>(buffer->Length);
00110         DataReader::FromBuffer(buffer)->ReadBytes(fileData);
00111         return fileData;
00112     });
00113 }
00114
00115 uint32 BasicReaderWriter::WriteData(
00116     _In_ Platform::String^ filename,
00117     _In_ const Platform::Array<byte>^ fileData
00118     )
00119 {
00120     CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {0};
00121     extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
00122     extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
00123     extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN;
00124     extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
00125     extendedParams.lpSecurityAttributes = nullptr;
00126     extendedParams.hTemplateFile = nullptr;
00127
00128     Wrappers::FileHandle file(
00129         CreateFile2(
00130             Platform::String::Concat(m_locationPath, filename)->Data(),
00131             GENERIC_WRITE,
00132             0,
00133             CREATE_ALWAYS,
00134             &extendedParams
00135             )
00136         );
00137     if (file.Get() == INVALID_HANDLE_VALUE)
00138     {
00139         throw ref new Platform::FailureException();
00140     }
00141
00142     DWORD numBytesWritten;
00143     if (
00144         !WriteFile(
00145             file.Get(),
00146             fileData->Data,
00147             fileData->Length,
00148             &numBytesWritten,
00149             nullptr
00150             ) ||
00151         numBytesWritten != fileData->Length
00152         )
00153     {
00154         throw ref new Platform::FailureException();
00155     }
00156
00157     return numBytesWritten;
00158 }
00159
00160 task<void> BasicReaderWriter::WriteDataAsync(
00161     _In_ Platform::String^ filename,
00162     _In_ const Platform::Array<byte>^ fileData
00163     )
00164 {
00165     return task<StorageFile^>(m_location->CreateFileAsync(filename, CreationCollisionOption::ReplaceExisting)).then([=](StorageFile^ file)
00166     {
00167         FileIO::WriteBytesAsync(file, fileData);
00168     });
00169 }
Generated on Sat Nov 23 2024 16:08:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: SMS message send, receive, and SIM management/C++/Constants.cpp Source File

  • SMS message send, receive, and SIM management

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     { "Sending a text message", "SDKSample.SmsSendReceive.SendMessage" },
00020     { "Receiving a text message", "SDKSample.SmsSendReceive.ReceiveMessage" },
00021     { "Sending a message in PDU format", "SDKSample.SmsSendReceive.SendPduMessage" },
00022     { "Reading a message from SIM", "SDKSample.SmsSendReceive.ReadMessage" },
00023     { "Deleting a message from SIM", "SDKSample.SmsSendReceive.DeleteMessage" }
00024 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Toast notifications/C#,C++/CppSamplesUtils.h Source File

  • Toast notifications
  • C#,C++

CppSamplesUtils.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 <string>
00014 #include <sstream>
00015 #include <algorithm>
00016 #include <collection.h>
00017 #include <ppltasks.h>
00018
00019 namespace CppSamplesUtils
00020 {
00021     namespace Details
00022     {
00023         static Windows::Foundation::Collections::PropertySet^ sessionState = nullptr;
00024         static Platform::String^ sessionStateFileName = ref new Platform::String(L"_cppSessionState.xml");
00025
00026         concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file);
00027         concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file);
00028     }
00029
00030     class SuspensionManager
00031     {
00032     public:
00033         static Windows::Foundation::Collections::PropertySet^ SessionState()
00034         {
00035             using namespace Windows::Foundation::Collections;
00036             using namespace Details;
00037
00038             if (sessionState == nullptr)
00039             {
00040                 sessionState = ref new PropertySet();
00041             }
00042             return sessionState;
00043         }
00044
00045         static concurrency::task<void> StartRestoreTask()
00046         {
00047             using namespace Windows::Foundation;
00048             using namespace Windows::Storage;
00049             using namespace Windows::Storage::Streams;
00050             using namespace Details;
00051
00052             auto state = SessionState();
00053             state->Clear();
00054
00055             concurrency::task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFileName));
00056             return getFileTask.then([=](StorageFile^ file)
00057             {
00058                 return DeserializeSessionState(file);
00059             });
00060         }
00061
00062         static concurrency::task<void> StartSaveTask()
00063         {
00064             using namespace Windows::Foundation;
00065             using namespace Windows::Storage;
00066             using namespace Windows::Storage::Streams;
00067             using namespace Details;
00068
00069             concurrency::task<StorageFile^> createFileTask(ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFileName, CreationCollisionOption::ReplaceExisting));
00070             return createFileTask.then([=](StorageFile^ file)
00071             {
00072                 return SerializeSessionState(file);
00073             });
00074         }
00075     };
00076
00077     namespace Details
00078     {
00079         template <class T>
00080         inline Platform::String^ ToString(T value)
00081         {
00082             std::wstringstream wss;
00083             wss << value;
00084             return ref new Platform::String(wss.str().c_str());
00085         }
00086
00087         template <class T>
00088         inline T FromStringTo(Platform::String^ str)
00089         {
00090             std::wistringstream wiss(str->Data());
00091             T value = 0;
00092             wiss >> value;
00093             return value;
00094         }
00095
00096         template <class T>
00097         inline T FromHexStringTo(Platform::String^ str)
00098         {
00099             std::wistringstream wiss(str->Data());
00100             T value = 0;
00101             wiss >> std::hex >> value;
00102             return value;
00103         }
00104
00105         template <>
00106         inline Platform::Guid FromStringTo<Platform::Guid>(Platform::String^ str)
00107         {
00108             using namespace Platform;
00109
00110             if (str->Length() != 38)
00111             {
00112                 throw ref new InvalidArgumentException;
00113             }
00114             std::wstring ws(str->Data());
00115             if (ws[0] != L'{' || ws[37] != L'}' || ws[9] != L'-' || ws[14] != L'-' || ws[19] != L'-' || ws[24] != L'-')
00116             {
00117                 throw ref new InvalidArgumentException;
00118             }
00119             ws[0] = ws[37] = ws[9] = ws[14] = ws[19] =ws[24] = L' ';
00120             std::wistringstream wiss(ws);
00121             unsigned int a = 0;
00122             unsigned short b = 0;
00123             unsigned short c = 0;
00124             unsigned short d = 0;
00125             unsigned long long e = 0;
00126             static_assert(sizeof(d) == sizeof(char) * 2, "sizeof(d) == sizeof(char) * 2");
00127             static_assert(sizeof(e) == sizeof(char) * 8, "sizeof(e) == sizeof(char) * 8");
00128             wiss >> std::hex >> a >> b >> c >> d >> e;
00129             unsigned char *ad = (unsigned char*)(&d);
00130             unsigned char *ae = (unsigned char*)(&e);
00131             return Platform::Guid(a, b, c, ad[1], ad[0], ae[5], ae[4], ae[3], ae[2], ae[1], ae[0]);
00132         }
00133
00134         inline Platform::Object^ ConvertStringToObject(Windows::Foundation::PropertyType type, Platform::String^ str)
00135         {
00136             using namespace Platform;
00137             using namespace Windows::Foundation;
00138
00139             if (type == PropertyType::String)
00140             {
00141                 return PropertyValue::CreateString(str);
00142             }
00143
00144             switch (type)
00145             {
00146             case PropertyType::UInt8:
00147                 return PropertyValue::CreateUInt8((unsigned char)FromStringTo<unsigned short>(str));
00148             case PropertyType::UInt16:
00149                 return PropertyValue::CreateUInt16(FromStringTo<unsigned short>(str));
00150             case PropertyType::UInt32:
00151                 return PropertyValue::CreateUInt32(FromStringTo<unsigned int>(str));
00152             case PropertyType::UInt64:
00153                 return PropertyValue::CreateUInt64(FromStringTo<unsigned long long>(str));
00154             case PropertyType::Int16:
00155                 return PropertyValue::CreateInt16(FromStringTo<short>(str));
00156             case PropertyType::Int32:
00157                 return PropertyValue::CreateInt32(FromStringTo<int>(str));
00158             case PropertyType::Int64:
00159                 return PropertyValue::CreateInt64(FromStringTo<long long>(str));
00160             case PropertyType::Single:
00161                 return PropertyValue::CreateSingle(FromStringTo<float>(str));
00162             case PropertyType::Double:
00163                 return PropertyValue::CreateDouble(FromStringTo<double>(str));
00164             case PropertyType::Boolean:
00165                 return PropertyValue::CreateBoolean(FromStringTo<bool>(str));
00166             case PropertyType::Char16:
00167                 return PropertyValue::CreateChar16(str->Data()[0]);
00168             case PropertyType::Guid:
00169                 return PropertyValue::CreateGuid(FromStringTo<Guid>(str));
00170             default:
00171                 throw ref new Platform::InvalidCastException;
00172             }
00173         }
00174
00175         inline Platform::String^ ConvertPropertyValueToString(Windows::Foundation::IPropertyValue^ pv)
00176         {
00177             using namespace Platform;
00178             using namespace Windows::Foundation;
00179
00180             String^ valueString;
00181
00182             switch (pv->Type)
00183             {
00184             case PropertyType::String:
00185                 valueString = pv->GetString();
00186                 break;
00187
00188             case PropertyType::UInt8:
00189             case PropertyType::UInt16:
00190             case PropertyType::UInt32:
00191             case PropertyType::UInt64:
00192                 valueString = ToString(pv->GetUInt64());
00193                 break;
00194
00195             case PropertyType::Int16:
00196             case PropertyType::Int32:
00197             case PropertyType::Int64:
00198                 valueString = ToString(pv->GetInt64());
00199                 break;
00200
00201             case PropertyType::Single:
00202                 valueString = ToString(pv->GetSingle());
00203                 break;
00204
00205             case PropertyType::Double:
00206                 valueString = ToString(pv->GetDouble());
00207                 break;
00208
00209             case PropertyType::Boolean:
00210                 valueString = ToString(pv->GetBoolean());
00211                 break;
00212
00213             case PropertyType::Char16:
00214                 wchar_t buffer[2];
00215                 buffer[0] = pv->GetChar16();
00216                 buffer[1] = 0;
00217                 valueString = ref new String(buffer);
00218                 break;
00219
00220             case PropertyType::Guid:
00221                 valueString = pv->GetGuid().ToString();
00222                 break;
00223
00224             default:
00225                 throw ref new InvalidCastException;
00226             }
00227
00228             return valueString;
00229         }
00230
00231         inline Windows::Data::Xml::Dom::XmlElement^ CreateXmlElementFromObject(Windows::Data::Xml::Dom::XmlDocument^ doc, Platform::String^ name, Platform::Object^ value)
00232         {
00233             using namespace Platform;
00234             using namespace Windows::Foundation;
00235             using namespace Windows::Data::Xml::Dom;
00236
00237             XmlElement^ element = doc->CreateElement("item");
00238             element->SetAttribute("name", name);
00239
00240             IPropertyValue^ pv = (IPropertyValue^)value;
00241             element->SetAttribute("type", ToString((int)pv->Type));
00242             element->SetAttribute("value", ConvertPropertyValueToString(pv));
00243
00244             return element;
00245         }
00246
00247         inline concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file)
00248         {
00249             using namespace Windows::Data::Xml::Dom;
00250             using namespace Windows::Foundation;
00251             namespace WFC = Windows::Foundation::Collections;
00252             typedef Windows::Foundation::Collections::IKeyValuePair<Platform::String^, Platform::Object^> KVPair;
00253
00254             XmlDocument^ doc = ref new XmlDocument;
00255             doc->AppendChild(doc->CreateElement("items"));
00256             auto sessionState = SuspensionManager::SessionState();
00257
00258             std::for_each(WFC::begin(sessionState), WFC::end(sessionState), [doc](KVPair^ item)
00259             {
00260                 doc->DocumentElement->AppendChild(CreateXmlElementFromObject(doc, item->Key, item->Value));
00261             });
00262
00263             return concurrency::task<void>(doc->SaveToFileAsync(file));
00264         }
00265
00266         inline Windows::Foundation::PropertyType PropertyTypeFromString(Platform::String^ str)
00267         {
00268             int value = FromStringTo<int>(str);
00269             return (Windows::Foundation::PropertyType)value;
00270         }
00271
00272         inline concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file)
00273         {
00274             using namespace Platform;
00275             using namespace Windows::Foundation;
00276             using namespace Windows::Data::Xml::Dom;
00277             namespace WFC = Windows::Foundation::Collections;
00278
00279             concurrency::task<XmlDocument^> loadFileTask(XmlDocument::LoadFromFileAsync(file));
00280             return loadFileTask.then([=](concurrency::task<XmlDocument^> docTask)
00281             {
00282                 try
00283                 {
00284                     auto doc = docTask.get();
00285                     auto items = doc->SelectNodes("/items/item");
00286                     auto sessionState = SuspensionManager::SessionState();
00287
00288                     std::for_each(WFC::begin(items), WFC::end(items), [sessionState](IXmlNode^ node)
00289                     {
00290                         auto element = (IXmlElement^)node;
00291                         String^ name = element->GetAttribute("name");
00292                         String^ value = element->GetAttribute("value");
00293                         PropertyType type = PropertyTypeFromString(element->GetAttribute("type"));
00294
00295                         Object^ valueObject = ConvertStringToObject(type, value);
00296                         sessionState->Insert(name, valueObject);
00297                     });
00298
00299                 }
00300                 catch (Platform::Exception^)
00301                 {
00302                     // Restoring is best effort
00303                 }
00304             });
00305         }
00306     } // namespace Details
00307 } // namespace CppSamplesUtils
Generated on Sat Nov 23 2024 16:07:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX postcard app/C++/PaperFlyout.xaml.cpp Source File

  • DirectX postcard app

PaperFlyout.xaml.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 "PaperFlyout.xaml.h"
00010
00011 using namespace Postcard;
00012
00013 using namespace Platform;
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 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 PaperFlyout::PaperFlyout()
00025 {
00026     InitializeComponent();
00027 }
00028
00029 void PaperFlyout::AddButtonClicked(Object^ sender, RoutedEventArgs^ e)
00030 {
00031     AddPaperClicked();
00032 }
00033
00034 void PaperFlyout::RemoveButtonClicked(Object^ sender, RoutedEventArgs^ e)
00035 {
00036     RemovePaperClicked();
00037     Hide();
00038 }
00039
00040 void PaperFlyout::MoveButtonClicked(Object^ sender, RoutedEventArgs^ e)
00041 {
00042     MovePaperClicked();
00043     Hide();
00044 }
00045
00046 void PaperFlyout::StampButtonClicked(Object^ sender, RoutedEventArgs^ e)
00047 {
00048     StampPaperClicked();
00049     Hide();
00050 }
00051
00052 void PaperFlyout::Hide()
00053 {
00054     Popup^ parent = dynamic_cast<Popup^>(this->Parent);
00055     if (parent != nullptr)
00056     {
00057         parent->IsOpen = false;
00058     }
00059 }
Generated on Sat Nov 23 2024 16:08:15 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Credential picker/C++/ScenarioInput1.xaml.h Source File

  • Credential picker

ScenarioInput1.xaml.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 // ScenarioInput1.xaml.h
00009 // Declaration of the ScenarioInput1 class.
00010 //
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "ScenarioInput1.g.h"
00016 #include "MainPage.xaml.h"
00017
00018 namespace CredentialPickerCPP
00019 {
00020   [Windows::Foundation::Metadata::WebHostHidden]
00021     public ref class ScenarioInput1 sealed
00022     {
00023     public:
00024         ScenarioInput1();
00025
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
00030
00031     private:
00032         MainPage^ rootPage;
00033         void rootPage_OutputFrameLoaded(Object^ sender, Object^ e);
00034         void Launch_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00035         Windows::Foundation::EventRegistrationToken _frameLoadedToken;
00036         void SetError(Platform::String^ errorText);
00037         void SetResult(Windows::Security::Credentials::UI::CredentialPickerResults^ res);
00038         ~ScenarioInput1();
00039     };
00040 }
Generated on Sat Nov 23 2024 16:07:59 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::XAMLPopup::sealed Member List

This is the complete list of members for SDKSample::XAMLPopup::sealed, including all inherited members.
CloseAnimatedPopupClicked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::XAMLPopup::sealed | [private]
ClosePopupClicked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::XAMLPopup::sealed | [private]
ClosePopupClicked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::XAMLPopup::sealed | [private]
CloseSettingsPopupClicked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::XAMLPopup::sealed | [private]
DoSomething_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::XAMLPopup::sealed | [private]
nonParentPopup | SDKSample::XAMLPopup::sealed | [private]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::XAMLPopup::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::XAMLPopup::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::XAMLPopup::sealed | [protected, virtual]
OnPopupClosed(Platform::Object^sender, Platform::Object^args) | SDKSample::XAMLPopup::sealed | [private]
PopupInputContent() | SDKSample::XAMLPopup::sealed |
rootPage | SDKSample::XAMLPopup::sealed | [private]
Scenario1() | SDKSample::XAMLPopup::sealed |
Scenario2() | SDKSample::XAMLPopup::sealed |
Scenario3() | SDKSample::XAMLPopup::sealed |
ShowPopupAnimationClicked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::XAMLPopup::sealed | [private]
ShowPopupLightDismissClicked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::XAMLPopup::sealed | [private]
ShowPopupOffsetClicked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::XAMLPopup::sealed | [private]
ShowPopupSettingsClicked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::XAMLPopup::sealed | [private]
ShowPopupWithoutParentClicked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::XAMLPopup::sealed | [private]
ShowPopupWithParentClicked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::XAMLPopup::sealed | [private]
SimulateSaveClicked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::XAMLPopup::sealed | [private]
Generated on Sat Nov 23 2024 16:09:53 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Web authentication broker/C++/Scenario1.xaml.h Source File

  • Web authentication broker

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 SDKSample
00023 {
00024     namespace WebAuthentication
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 Scenario1 sealed
00031         {
00032         public:
00033             Scenario1();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void Launch_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040       };
00041     }
00042 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/ExifExtensions.h Source File

  • Hilo C++
  • Hilo

ExifExtensions.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
00009 namespace Hilo
00010 {
00011     // ExifRotations values represent the codes used by JPEG image files to indicated how an image should be rotated for display.
00012     public enum class ExifRotations
00013     {
00014         NotRotated = 1,
00015         RotatedDown = 3,
00016         RotatedLeft = 6,
00017         RotatedRight = 8
00018     };
00019
00020     // ExifExtensions is a helper class that converts image rotation angles between degrees and
00021     // Exchangeable image file format (Exif) codes that are used by JPEG images.
00022     class ExifExtensions
00023     {
00024
00025     public:
00026         static Windows::Foundation::Rect RotateClockwise(Windows::Foundation::Rect rect, Windows::Foundation::Rect bitmapSize, float64 degrees);
00027         static unsigned int ConvertExifOrientationToDegreesRotation(ExifRotations exifOrientationFlag);
00028         static ExifRotations ConvertDegreesRotationToExifOrientation(unsigned int angle);
00029
00030     };
00031 }
Generated on Sat Nov 23 2024 16:08:17 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

AutoThrottle Member List

This is the complete list of members for AutoThrottle, including all inherited members.
__pad0__ | AutoThrottle |
m_missedFrameHistory | AutoThrottle | [private]
m_targetFrameTime | AutoThrottle | [private]
Update(float frameTime) | AutoThrottle |
Update(float frameTime) | AutoThrottle |
Generated on Sat Nov 23 2024 16:09:05 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML vector-based drawing/C++/Scenario2.xaml.cpp Source File

  • XAML vector-based drawing

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 SDKSample::Drawing;
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::UI::Xaml::Controls::Primitives;
00025 using namespace Windows::UI::Xaml::Media;
00026
00027
00028
00029 Scenario2::Scenario2()
00030 {
00031     InitializeComponent();
00032   FillSelection->SelectedIndex = 0;
00033   FillSelection->SelectionChanged += ref new SelectionChangedEventHandler(this, &Scenario2::FillSelection_SelectionChanged);
00034   StrokeThicknessSelection->ValueChanged += ref new RangeBaseValueChangedEventHandler(this, &Scenario2::StrokeWidthSelection_ValueChanged);
00035 }
00036
00037 // Invoked when this page is about to be displayed in a Frame.
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
00046 // Handler for fill selection changed
00047 void SDKSample::Drawing::Scenario2::FillSelection_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e)
00048 {
00049   Scenario2Rectangle->Fill = ref new SolidColorBrush(rootPage->ConvertIndexToColor(FillSelection->SelectedIndex));
00050 }
00051
00052
00053 // Handler for stroke width slider
00054 void SDKSample::Drawing::Scenario2::StrokeWidthSelection_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e)
00055 {
00056   Scenario2Rectangle->StrokeThickness = StrokeThicknessSelection->Value;
00057 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: UI Automation core window provider/C++/DirectXBase.cpp Source File

  • UI Automation core window provider

DirectXBase.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 "DirectXBase.h"
00010
00011 using namespace Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::Graphics::Display;
00015 using namespace D2D1;
00016
00017 // Constructor.
00018 DirectXBase::DirectXBase() :
00019     m_windowSizeChangeInProgress(false),
00020     m_dpi(-1.0f)
00021 {
00022 }
00023
00024 // Initialize the DirectX resources required to run.
00025 void DirectXBase::Initialize(CoreWindow^ window, float dpi)
00026 {
00027     m_window = window;
00028
00029     CreateDeviceIndependentResources();
00030     CreateDeviceResources();
00031     SetDpi(dpi);
00032 }
00033
00034 // Recreate all device resources and set them back to the current state.
00035 void DirectXBase::HandleDeviceLost()
00036 {
00037     // Reset these member variables to ensure that SetDpi recreates all resources.
00038     float dpi = m_dpi;
00039     m_dpi = -1.0f;
00040     m_windowBounds.Width = 0;
00041     m_windowBounds.Height = 0;
00042     m_swapChain = nullptr;
00043
00044     CreateDeviceResources();
00045     SetDpi(dpi);
00046 }
00047
00048 // These are the resources required independent of the device.
00049 void DirectXBase::CreateDeviceIndependentResources()
00050 {
00051     D2D1_FACTORY_OPTIONS options;
00052     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00053
00054 #if defined(_DEBUG)
00055     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00056     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00057 #endif
00058
00059     DX::ThrowIfFailed(
00060         D2D1CreateFactory(
00061             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00062             __uuidof(ID2D1Factory1),
00063             &options,
00064             &m_d2dFactory
00065             )
00066         );
00067
00068     DX::ThrowIfFailed(
00069         DWriteCreateFactory(
00070             DWRITE_FACTORY_TYPE_SHARED,
00071             __uuidof(IDWriteFactory),
00072             &m_dwriteFactory
00073             )
00074         );
00075
00076     DX::ThrowIfFailed(
00077         CoCreateInstance(
00078             CLSID_WICImagingFactory,
00079             nullptr,
00080             CLSCTX_INPROC_SERVER,
00081             IID_PPV_ARGS(&m_wicFactory)
00082             )
00083         );
00084 }
00085
00086 // These are the resources that depend on the device.
00087 void DirectXBase::CreateDeviceResources()
00088 {
00089     // This flag adds support for surfaces with a different color channel ordering
00090     // than the API default. It is required for compatibility with Direct2D.
00091     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00092     ComPtr<IDXGIDevice> dxgiDevice;
00093
00094 #if defined(_DEBUG)
00095     // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00096     creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00097 #endif
00098
00099     // This array defines the set of DirectX hardware feature levels this app will support.
00100     // Note the ordering should be preserved.
00101     // Don't forget to declare your application's minimum required feature level in its
00102     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00103     D3D_FEATURE_LEVEL featureLevels[] =
00104     {
00105         D3D_FEATURE_LEVEL_11_1,
00106         D3D_FEATURE_LEVEL_11_0,
00107         D3D_FEATURE_LEVEL_10_1,
00108         D3D_FEATURE_LEVEL_10_0,
00109         D3D_FEATURE_LEVEL_9_3,
00110         D3D_FEATURE_LEVEL_9_2,
00111         D3D_FEATURE_LEVEL_9_1
00112     };
00113
00114     // Create the Direct3D 11 API device object and a corresponding context.
00115     ComPtr<ID3D11Device> device;
00116     ComPtr<ID3D11DeviceContext> context;
00117     DX::ThrowIfFailed(
00118         D3D11CreateDevice(
00119             nullptr,                    // Specify nullptr to use the default adapter.
00120             D3D_DRIVER_TYPE_HARDWARE,
00121             0,
00122             creationFlags,              // Set debug and Direct2D compatibility flags.
00123             featureLevels,              // List of feature levels this app can support.
00124             ARRAYSIZE(featureLevels),
00125             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Metro style apps.
00126             &device,                    // Returns the Direct3D device created.
00127             &m_featureLevel,            // Returns feature level of device created.
00128             &context                    // Returns the device immediate context.
00129             )
00130         );
00131
00132     // Get the Direct3D 11.1 API device and context interfaces.
00133     DX::ThrowIfFailed(
00134         device.As(&m_d3dDevice)
00135         );
00136
00137     DX::ThrowIfFailed(
00138         context.As(&m_d3dContext)
00139         );
00140
00141     // Get the underlying DXGI device of the Direct3D device.
00142     DX::ThrowIfFailed(
00143         m_d3dDevice.As(&dxgiDevice)
00144         );
00145
00146     // Create the Direct2D device object and a corresponding context.
00147     DX::ThrowIfFailed(
00148         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00149         );
00150
00151     DX::ThrowIfFailed(
00152         m_d2dDevice->CreateDeviceContext(
00153             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00154             &m_d2dContext
00155             )
00156         );
00157 }
00158
00159 // Helps track the DPI in the helper class.
00160 // This is called in the dpiChanged event handler in the view class.
00161 void DirectXBase::SetDpi(float dpi)
00162 {
00163     if (dpi != m_dpi)
00164     {
00165         // Save the DPI of this display in our class.
00166         m_dpi = dpi;
00167
00168         // Update Direct2D's stored DPI.
00169         m_d2dContext->SetDpi(m_dpi, m_dpi);
00170
00171         // Often a DPI change implies a window size change. In some cases Windows will issue
00172         // both a size changed event and a DPI changed event. In this case, the resulting bounds
00173         // will not change, and the window resize code will only be executed once.
00174         UpdateForWindowSizeChange();
00175     }
00176 }
00177
00178 // This routine is called in the event handler for the view SizeChanged event.
00179 void DirectXBase::UpdateForWindowSizeChange()
00180 {
00181     // Only handle window size changed if there is no pending DPI change.
00182     if (m_dpi != DisplayProperties::LogicalDpi)
00183     {
00184         return;
00185     }
00186
00187     if (m_window->Bounds.Width  != m_windowBounds.Width ||
00188         m_window->Bounds.Height != m_windowBounds.Height)
00189     {
00190         m_d2dContext->SetTarget(nullptr);
00191         m_d2dTargetBitmap = nullptr;
00192         m_d3dRenderTargetView = nullptr;
00193         m_d3dDepthStencilView = nullptr;
00194         m_windowSizeChangeInProgress = true;
00195         CreateWindowSizeDependentResources();
00196     }
00197 }
00198
00199 // Allocate all memory resources that change on a window SizeChanged event.
00200 void DirectXBase::CreateWindowSizeDependentResources()
00201 {
00202     // Store the window bounds so the next time we get a SizeChanged event we can
00203     // avoid rebuilding everything if the size is identical.
00204     m_windowBounds = m_window->Bounds;
00205
00206     if (m_swapChain != nullptr)
00207     {
00208         // If the swap chain already exists, resize it.
00209         HRESULT hr = m_swapChain->ResizeBuffers(2, 0, 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0);
00210
00211         if (hr == DXGI_ERROR_DEVICE_REMOVED)
00212         {
00213             // If the device was removed for any reason, a new device and swapchain will need to be created.
00214             HandleDeviceLost();
00215
00216             // Everything is set up now. Do not continue execution of this method.
00217             return;
00218         }
00219         else
00220         {
00221             DX::ThrowIfFailed(hr);
00222         }
00223     }
00224     else
00225     {
00226         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00227         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00228         swapChainDesc.Width = 0;                                     // Use automatic sizing.
00229         swapChainDesc.Height = 0;
00230         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;           // This is the most common swap chain format.
00231         swapChainDesc.Stereo = false;
00232         swapChainDesc.SampleDesc.Count = 1;                          // Don't use multi-sampling.
00233         swapChainDesc.SampleDesc.Quality = 0;
00234         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00235         swapChainDesc.BufferCount = 2;                               // Use double-buffering to minimize latency.
00236         swapChainDesc.Scaling = DXGI_SCALING_NONE;
00237         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Metro style apps must use this SwapEffect.
00238         swapChainDesc.Flags = 0;
00239
00240         ComPtr<IDXGIDevice1> dxgiDevice;
00241         DX::ThrowIfFailed(
00242             m_d3dDevice.As(&dxgiDevice)
00243             );
00244
00245         ComPtr<IDXGIAdapter> dxgiAdapter;
00246         DX::ThrowIfFailed(
00247             dxgiDevice->GetAdapter(&dxgiAdapter)
00248             );
00249
00250         ComPtr<IDXGIFactory2> dxgiFactory;
00251         DX::ThrowIfFailed(
00252             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00253             );
00254
00255         CoreWindow^ window = m_window.Get();
00256         DX::ThrowIfFailed(
00257             dxgiFactory->CreateSwapChainForCoreWindow(
00258                 m_d3dDevice.Get(),
00259                 reinterpret_cast<IUnknown*>(window),
00260                 &swapChainDesc,
00261                 nullptr,
00262                 &m_swapChain
00263                 )
00264             );
00265
00266         // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
00267         // ensures that the application will only render after each VSync, minimizing power consumption.
00268         DX::ThrowIfFailed(
00269             dxgiDevice->SetMaximumFrameLatency(1)
00270             );
00271     }
00272
00273     // Create a Direct3D render target view of the swap chain back buffer.
00274     ComPtr<ID3D11Texture2D> backBuffer;
00275     DX::ThrowIfFailed(
00276         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00277         );
00278
00279     DX::ThrowIfFailed(
00280         m_d3dDevice->CreateRenderTargetView(
00281             backBuffer.Get(),
00282             nullptr,
00283             &m_d3dRenderTargetView
00284             )
00285         );
00286
00287     // Cache the rendertarget dimensions in our helper class for convenient use.
00288     D3D11_TEXTURE2D_DESC backBufferDesc = {0};
00289     backBuffer->GetDesc(&backBufferDesc);
00290     m_renderTargetSize.Width  = static_cast<float>(backBufferDesc.Width);
00291     m_renderTargetSize.Height = static_cast<float>(backBufferDesc.Height);
00292
00293     // Create a depth stencil view for use with 3D rendering if needed.
00294     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00295         DXGI_FORMAT_D24_UNORM_S8_UINT,
00296         backBufferDesc.Width,
00297         backBufferDesc.Height,
00298         1,
00299         1,
00300         D3D11_BIND_DEPTH_STENCIL
00301         );
00302
00303     ComPtr<ID3D11Texture2D> depthStencil;
00304     DX::ThrowIfFailed(
00305         m_d3dDevice->CreateTexture2D(
00306             &depthStencilDesc,
00307             nullptr,
00308             &depthStencil
00309             )
00310         );
00311
00312     auto viewDesc = CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D);
00313     DX::ThrowIfFailed(
00314         m_d3dDevice->CreateDepthStencilView(
00315             depthStencil.Get(),
00316             &viewDesc,
00317             &m_d3dDepthStencilView
00318             )
00319         );
00320
00321     // Set the 3D rendering viewport to target the entire window.
00322     CD3D11_VIEWPORT viewport(
00323         0.0f,
00324         0.0f,
00325         static_cast<float>(backBufferDesc.Width),
00326         static_cast<float>(backBufferDesc.Height)
00327         );
00328
00329     m_d3dContext->RSSetViewports(1, &viewport);
00330
00331     // Create a Direct2D target bitmap associated with the
00332     // swap chain back buffer and set it as the current target.
00333     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00334         BitmapProperties1(
00335             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00336             PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00337             m_dpi,
00338             m_dpi
00339             );
00340
00341     ComPtr<IDXGISurface> dxgiBackBuffer;
00342     DX::ThrowIfFailed(
00343         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00344         );
00345
00346     DX::ThrowIfFailed(
00347         m_d2dContext->CreateBitmapFromDxgiSurface(
00348             dxgiBackBuffer.Get(),
00349             &bitmapProperties,
00350             &m_d2dTargetBitmap
00351             )
00352         );
00353
00354     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00355
00356     // Grayscale text anti-aliasing is recommended for all Metro style apps.
00357     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00358 }
00359
00360 // Method to deliver the final image to the display.
00361 void DirectXBase::Present()
00362 {
00363     // The application may optionally specify "dirty" or "scroll" rects to improve efficiency
00364     // in certain scenarios.  In this sample, however, we do not utilize those features.
00365     DXGI_PRESENT_PARAMETERS parameters = {0};
00366     parameters.DirtyRectsCount = 0;
00367     parameters.pDirtyRects = nullptr;
00368     parameters.pScrollRect = nullptr;
00369     parameters.pScrollOffset = nullptr;
00370
00371     // The first argument instructs DXGI to block until VSync, putting the application
00372     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00373     // frames that will never be displayed to the screen.
00374     HRESULT hr = m_swapChain->Present1(1, 0, &parameters);
00375
00376     // Discard the contents of the render target.
00377     // This is a valid operation only when the existing contents will be entirely
00378     // overwritten. If dirty or scroll rects are used, this call should be removed.
00379     m_d3dContext->DiscardView(m_d3dRenderTargetView.Get());
00380
00381     // Discard the contents of the depth stencil.
00382     m_d3dContext->DiscardView(m_d3dDepthStencilView.Get());
00383
00384     // If the device was removed either by a disconnect or a driver upgrade, we
00385     // must recreate all device resources.
00386     if (hr == DXGI_ERROR_DEVICE_REMOVED)
00387     {
00388         HandleDeviceLost();
00389     }
00390     else
00391     {
00392         DX::ThrowIfFailed(hr);
00393     }
00394
00395     if (m_windowSizeChangeInProgress)
00396     {
00397         // A window size change has been initiated and the app has just completed presenting
00398         // the first frame with the new size. Notify the resize manager so we can short
00399         // circuit any resize animation and prevent unnecessary delays.
00400         CoreWindowResizeManager::GetForCurrentView()->NotifyLayoutCompleted();
00401         m_windowSizeChangeInProgress = false;
00402     }
00403 }
00404
00405 void DirectXBase::ValidateDevice()
00406 {
00407     // The D3D Device is no longer valid if the default adapter changes or if
00408     // the device has been removed.
00409
00410     // First, get the information for the adapter related to the current device.
00411
00412     ComPtr<IDXGIDevice1> dxgiDevice;
00413     ComPtr<IDXGIAdapter> deviceAdapter;
00414     DXGI_ADAPTER_DESC deviceDesc;
00415     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00416     DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter));
00417     DX::ThrowIfFailed(deviceAdapter->GetDesc(&deviceDesc));
00418
00419     // Next, get the information for the default adapter.
00420
00421     ComPtr<IDXGIFactory2> dxgiFactory;
00422     ComPtr<IDXGIAdapter1> currentAdapter;
00423     DXGI_ADAPTER_DESC currentDesc;
00424     DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)));
00425     DX::ThrowIfFailed(dxgiFactory->EnumAdapters1(0, &currentAdapter));
00426     DX::ThrowIfFailed(currentAdapter->GetDesc(&currentDesc));
00427
00428     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00429     // a new D3D device must be created.
00430
00431     if ((deviceDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart) ||
00432         (deviceDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart) ||
00433         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00434     {
00435         // Release references to resources related to the old device.
00436         dxgiDevice = nullptr;
00437         deviceAdapter = nullptr;
00438
00439         // Create a new device and swap chain.
00440         HandleDeviceLost();
00441     }
00442 }
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Toast notifications/C#,C++/ScenarioOutput5.xaml.h Source File

  • Toast notifications
  • C#,C++

ScenarioOutput5.xaml.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 //
00009 // Scenario1Output.xaml.h
00010 // Declaration of the Scenario1Output class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioOutput5.g.h"
00017 #include "MainPage.xaml.h"
00018
00019 namespace ToastsSampleCPP
00020 {
00021   [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class ScenarioOutput5 sealed
00023     {
00024     public:
00025         ScenarioOutput5();
00026
00027     protected:
00028         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030
00031     private:
00032         ~ScenarioOutput5();
00033
00034     MainPage^ rootPage;
00035         void rootPage_InputFrameLoaded(Object^ sender, Object^ e);
00036         Windows::Foundation::EventRegistrationToken _frameLoadedToken;
00037     };
00038 }
Generated on Sat Nov 23 2024 16:08:24 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Device auto rotation preferences/C++/Constants.h Source File

  • Device auto rotation preferences

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"Rotation C++ sample");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041     private:
00042         static Platform::Array<Scenario>^ scenariosInner;
00043     };
00044
00045
00046 }
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Real-time communication/C#,C++/SuspensionManager.cs Source File

  • Real-time communication
  • C#,C++

SuspensionManager.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.Text;
00015 using System.Threading.Tasks;
00016 using Windows.Storage;
00017 using Windows.Storage.Streams;
00018 using System.Runtime.Serialization;
00019 using System.IO;
00020 using Windows.ApplicationModel;
00021
00022 class SuspensionManager
00023 {
00024     static private Dictionary<string, object> sessionState_ = new Dictionary<string, object>();
00025     static private List<Type> knownTypes_ = new List<Type>();
00026     private const string filename = "_sessionState.xml";
00027
00028     // Provides access to the currect session state
00029     static public Dictionary<string, object> SessionState
00030     {
00031         get { return sessionState_; }
00032     }
00033
00034     // Allows custom types to be added to the list of types that can be serialized
00035     static public List<Type> KnownTypes
00036     {
00037         get { return knownTypes_; }
00038     }
00039
00040     // Save the current session state
00041     static async public Task SaveAsync()
00042     {
00043         // Get the output stream for the SessionState file.
00044         StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
00045         using (StorageStreamTransaction transaction = await file.OpenTransactedWriteAsync())
00046         {
00047             // Serialize the Session State.
00048             DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), knownTypes_);
00049             serializer.WriteObject(transaction.Stream.AsStreamForWrite(), sessionState_);
00050             await transaction.CommitAsync();
00051         }
00052     }
00053
00054     // Restore the saved sesison state
00055     static async public Task RestoreAsync()
00056     {
00057         // Get the input stream for the SessionState file.
00058         try
00059         {
00060             StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(filename);
00061             if (file == null) return;
00062             using (IInputStream inStream = await file.OpenSequentialReadAsync())
00063             {
00064                 // Deserialize the Session State.
00065                 DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), knownTypes_);
00066                 sessionState_ = (Dictionary<string, object>)serializer.ReadObject(inStream.AsStreamForRead());
00067             }
00068         }
00069         catch (Exception)
00070         {
00071             // Restoring state is best-effort.  If it fails, the app will just come up with a new session.
00072         }
00073     }
00074 }
Generated on Sat Nov 23 2024 16:08:21 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File picker contracts/C++/FileOpenPicker_PickCachedFile.xaml.cpp Source File

  • File picker contracts

FileOpenPicker_PickCachedFile.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 // FileOpenPicker_PickCachedFile.xaml.cpp
00013 // Implementation of the FileOpenPicker_PickCachedFile class
00014 //
00015
00016 #include "pch.h"
00017 #include "FileOpenPickerPage.xaml.h"
00018 #include "FileOpenPicker_PickCachedFile.xaml.h"
00019 #include "Constants.h"
00020
00021 using namespace SDKSample::FilePickerContracts;
00022
00023 using namespace concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::Foundation;
00027 using namespace Windows::Storage;
00028 using namespace Windows::Storage::Pickers::Provider;
00029 using namespace Windows::Storage::Provider;
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
00035 FileOpenPicker_PickCachedFile::FileOpenPicker_PickCachedFile()
00036 {
00037     InitializeComponent();
00038
00039     fileID = ref new String(L"MyCachedFile");
00040     fileOpenPickerUI = FileOpenPickerPage::Current->fileOpenPickerUI;
00041
00042     AddFileButton->Click += ref new RoutedEventHandler(this, &FileOpenPicker_PickCachedFile::AddFileButton_Click);
00043     RemoveFileButton->Click += ref new RoutedEventHandler(this, &FileOpenPicker_PickCachedFile::RemoveFileButton_Click);
00044 }
00045
00046 void FileOpenPicker_PickCachedFile::UpdateButtonState(bool fileInBasket)
00047 {
00048     AddFileButton->IsEnabled = !fileInBasket;
00049     RemoveFileButton->IsEnabled = fileInBasket;
00050 }
00051
00052 void FileOpenPicker_PickCachedFile::OnNavigatedTo(NavigationEventArgs^ e)
00053 {
00054     UpdateButtonState(fileOpenPickerUI->ContainsFile(fileID));
00055     token = fileOpenPickerUI->FileRemoved += ref new TypedEventHandler<FileOpenPickerUI^, FileRemovedEventArgs^>(this, &FileOpenPicker_PickCachedFile::OnFileRemoved, CallbackContext::Same);
00056 }
00057
00058 void FileOpenPicker_PickCachedFile::OnNavigatedFrom(NavigationEventArgs^ e)
00059 {
00060     fileOpenPickerUI->FileRemoved -= token;
00061 }
00062
00063 void FileOpenPicker_PickCachedFile::OnFileRemoved(FileOpenPickerUI^ fileOPenPickerUI, FileRemovedEventArgs^ e)
00064 {
00065     // make sure that the item got removed matches the one we added.
00066     if (e->Id == fileID)
00067     {
00068         OutputTextBlock->Text = Status::FileRemoved;
00069         UpdateButtonState(false);
00070     }
00071 }
00072
00073 void FileOpenPicker_PickCachedFile::AddFileButton_Click(Object^ sender, RoutedEventArgs^ e)
00074 {
00075     create_task(ApplicationData::Current->LocalFolder->CreateFileAsync(L"CachedFile.txt", CreationCollisionOption::ReplaceExisting)).then([this](StorageFile^ file)
00076     {
00077         create_task(FileIO::WriteTextAsync(file, L"Cached file created...")).then([this, file]()
00078         {
00079             CachedFileUpdater::SetUpdateInformation(file, "CachedFile", ReadActivationMode::BeforeAccess, WriteActivationMode::NotNeeded, CachedFileOptions::RequireUpdateOnAccess);
00080
00081             bool inBasket;
00082             switch (fileOpenPickerUI->AddFile(fileID, file))
00083             {
00084             case AddFileResult::Added:
00085             case AddFileResult::AlreadyAdded:
00086                 inBasket = true;
00087                 OutputTextBlock->Text = Status::FileAdded;
00088                 break;
00089
00090             default:
00091                 inBasket = false;
00092                 OutputTextBlock->Text = Status::FileAddFailed;
00093                 break;
00094             }
00095             UpdateButtonState(inBasket);
00096         });
00097     });
00098 }
00099
00100 void FileOpenPicker_PickCachedFile::RemoveFileButton_Click(Object^ sender, RoutedEventArgs^ e)
00101 {
00102     if (fileOpenPickerUI->ContainsFile(fileID))
00103     {
00104         fileOpenPickerUI->RemoveFile(fileID);
00105         OutputTextBlock->Text = Status::FileRemoved;
00106     }
00107     UpdateButtonState(false);
00108 }
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

ShapeRecord Member List

This is the complete list of members for ShapeRecord, including all inherited members.
cursorId | ShapeRecord
next | ShapeRecord
shape | ShapeRecord
Generated on Sat Nov 23 2024 16:09:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D effects on primitives/C++/pch.h Source File

  • Direct2D effects on primitives

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 <d3d11_1.h>
00012 #include <d2d1_1.h>
00013 #include <d2d1effects.h>
00014 #include <dwrite_1.h>
00015 #include <wincodec.h>
00016 #include <agile.h>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Credential locker/C++/Scenario3.xaml.h Source File

  • Credential locker

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 SDKSample
00023 {
00024     namespace PasswordVaultCPP
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             void Go_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         void ScenarioButtonDelete_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041       };
00042     }
00043 }
Generated on Sat Nov 23 2024 16:07:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML personality animations/C++/MainPage.xaml.h Source File

  • XAML personality animations

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

MPEG1AudioFrameHeader Member List

This is the complete list of members for MPEG1AudioFrameHeader, including all inherited members.
dwBitRate | MPEG1AudioFrameHeader
dwSamplesPerSec | MPEG1AudioFrameHeader
emphasis | MPEG1AudioFrameHeader
layer | MPEG1AudioFrameHeader
mode | MPEG1AudioFrameHeader
modeExtension | MPEG1AudioFrameHeader
nBlockAlign | MPEG1AudioFrameHeader
nChannels | MPEG1AudioFrameHeader
wFlags | MPEG1AudioFrameHeader
Generated on Sat Nov 23 2024 16:09:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Compass sensor/C++/App.xaml.cpp Source File

  • Compass sensor

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media capture using capture device/C#,C++/Constants.cs Source File

  • Media capture using capture device
  • C#,C++

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 MediaCapture;
00014
00015 namespace SDKTemplate
00016 {
00017     public partial class MainPage : SDKTemplate.Common.LayoutAwarePage
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 = "MediaCapture";
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 = "Video preview, record and take pictures", ClassType = typeof(BasicCapture) },
00031             new Scenario() { Title = "Enumerate cameras and add a video effect", ClassType = typeof(AdvancedCapture) },
00032             new Scenario() { Title = "Audio Capture", ClassType = typeof(AudioCapture) }
00033
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 Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D 3D transform effect/C++/D2D3DTransformsRenderer.h Source File

  • Direct2D 3D transform effect

D2D3DTransformsRenderer.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 "DirectXBase.h"
00011
00012 // Because commands to change effect properties travel from MainPage.cpp to App.cpp to
00013 // D2D3DTransformsRenderer.cpp, we use these enums to specify which properties we are changing.
00014 enum class TransformEffect
00015 {
00016     D2D13DTransform,
00017     D2D13DPerspectiveTransform
00018 };
00019
00020 enum class TransformProperty
00021 {
00022     ScaleX,
00023     ScaleY,
00024     LocalOffsetX,
00025     LocalOffsetY,
00026     LocalOffsetZ,
00027     RotationX,
00028     RotationY,
00029     RotationZ,
00030     GlobalOffsetX,
00031     GlobalOffsetY,
00032     GlobalOffsetZ,
00033     Perspective
00034 };
00035
00036 ref class D2D3DTransformsRenderer : public DirectXBase
00037 {
00038 internal:
00039     D2D3DTransformsRenderer();
00040
00041     virtual void CreateDeviceIndependentResources() override;
00042     virtual void CreateDeviceResources() override;
00043     virtual void CreateWindowSizeDependentResources() override;
00044     virtual void Render() override;
00045
00046     void SetTransformEffect(TransformEffect transformEffect);
00047     void SetTransformProperty(TransformProperty transformProperty, float value);
00048
00049     void Render3DTransformEffect();
00050     void Render3DPerspectiveTransformEffect();
00051
00052     void UpdateForViewStateChanged(Windows::UI::ViewManagement::ApplicationViewState state);
00053
00054 private:
00055     // Helper methods to draw current transform values / properties to the screen.
00056     void Draw3DPerspectiveProperty(
00057         Platform::String^ caption,
00058         Platform::String^ value,
00059         float horizontalOffset
00060         );
00061
00062     void DrawMatrix(
00063         Platform::String^ caption,
00064         D2D1_MATRIX_4X4_F matrix,
00065         float horizontalOffset
00066         );
00067
00068     void DrawSymbol(
00069         Platform::String^ symbol,
00070         float horizontalOffset
00071         );
00072
00073     Windows::UI::ViewManagement::ApplicationViewState       m_windowState;
00074
00075     Microsoft::WRL::ComPtr<IWICFormatConverter>             m_wicFormatConverter;
00076     Microsoft::WRL::ComPtr<ID2D1Effect>                     m_bitmapSourceEffect;
00077     Microsoft::WRL::ComPtr<ID2D1Effect>                     m_3DTransformEffect;
00078     Microsoft::WRL::ComPtr<ID2D1Effect>                     m_3DPerspectiveTransformEffect;
00079
00080     TransformEffect                                         m_currentEffect;
00081     D2D1_SIZE_U                                             m_imageSize;
00082
00083     // Variables used to define matrices / set properties for the
00084     // 3DTransform and 3DPerspectiveTransform effects, respectively.
00085     float                                                   m_scaleX;
00086     float                                                   m_scaleY;
00087     float                                                   m_localOffsetX;
00088     float                                                   m_localOffsetY;
00089     float                                                   m_localOffsetZ;
00090     float                                                   m_rotationX;
00091     float                                                   m_rotationY;
00092     float                                                   m_rotationZ;
00093     float                                                   m_globalOffsetX;
00094     float                                                   m_globalOffsetY;
00095     float                                                   m_globalOffsetZ;
00096     float                                                   m_perspective;
00097
00098     // Variables used to render current matrices / properties of effects
00099     // to the screen.
00100     Microsoft::WRL::ComPtr<IDWriteTextFormat>               m_captionFormat;
00101     Microsoft::WRL::ComPtr<IDWriteTextFormat>               m_matrixValueFormat;
00102     Microsoft::WRL::ComPtr<IDWriteTextFormat>               m_propertyValueFormat;
00103     Microsoft::WRL::ComPtr<IDWriteTextFormat>               m_symbolFormat;
00104     Microsoft::WRL::ComPtr<IDWriteTextFormat>               m_snappedViewFormat;
00105     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>            m_whiteBrush;
00106     float                                                   m_captionTop;
00107     float                                                   m_captionHeight;
00108     float                                                   m_matrixTop;
00109     float                                                   m_matrixHeight;
00110     float                                                   m_matrixWidth;
00111     float                                                   m_propertyTop;
00112     float                                                   m_propertyHeight;
00113     float                                                   m_propertyWidth;
00114 };
Generated on Sat Nov 23 2024 16:08:02 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D basic image effects/C++/DirectXBase.h Source File

  • Direct2D basic image effects

DirectXBase.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 "DirectXSample.h"
00011
00012 // Helper class that initializes DirectX APIs for both 2D and 3D rendering.
00013 // Some of the code in this class may be omitted if only 2D or only 3D rendering is being used.
00014 ref class DirectXBase abstract
00015 {
00016 internal:
00017     DirectXBase();
00018
00019     virtual void Initialize(Windows::UI::Core::CoreWindow^ window, float dpi);
00020     virtual void HandleDeviceLost();
00021     virtual void CreateDeviceIndependentResources();
00022     virtual void CreateDeviceResources();
00023     virtual void SetDpi(float dpi);
00024     virtual void UpdateForWindowSizeChange();
00025     virtual void CreateWindowSizeDependentResources();
00026     virtual void Render() = 0;
00027     virtual void Present();
00028     void ValidateDevice();
00029
00030 protected private:
00031     Platform::Agile<Windows::UI::Core::CoreWindow>  m_window;
00032
00033     // DirectWrite & Windows Imaging Component Objects.
00034     Microsoft::WRL::ComPtr<IDWriteFactory1>         m_dwriteFactory;
00035     Microsoft::WRL::ComPtr<IWICImagingFactory2>     m_wicFactory;
00036
00037     // DirectX Core Objects. Required for 2D and 3D.
00038     Microsoft::WRL::ComPtr<ID3D11Device1>           m_d3dDevice;
00039     Microsoft::WRL::ComPtr<ID3D11DeviceContext1>    m_d3dContext;
00040     Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00041     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00042
00043     // Direct2D Rendering Objects. Required for 2D.
00044     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00046     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00047     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmap;
00048
00049     // Direct3D Rendering Objects. Required for 3D.
00050     Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00051
00052     // Cached renderer properties.
00053     D3D_FEATURE_LEVEL                               m_featureLevel;
00054     Windows::Foundation::Size                       m_renderTargetSize;
00055     Windows::Foundation::Rect                       m_windowBounds;
00056     float                                           m_dpi;
00057     bool                                            m_windowSizeChangeInProgress;
00058 };
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

NotificationsExtensions::TileContent::TileWideText09 Member List

This is the complete list of members for NotificationsExtensions::TileContent::TileWideText09, including all inherited members.
AddImageQuery | NotificationsExtensions::NotificationBase |
AddImageQueryNullable | NotificationsExtensions::NotificationBase |
BaseUri | NotificationsExtensions::NotificationBase |
Branding | NotificationsExtensions::TileContent::TileNotificationBase |
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
CreateNotification() | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetContent() | NotificationsExtensions::TileContent::TileWideBase | [inline, virtual]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
GetXml() | NotificationsExtensions::NotificationBase | [inline]
Images | NotificationsExtensions::NotificationBase |
Lang | NotificationsExtensions::NotificationBase |
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
NotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::NotificationBase | [inline, protected]
RequireSquareContent | NotificationsExtensions::TileContent::TileWideBase |
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) | NotificationsExtensions::NotificationBase | [inline, protected]
SquareContent | NotificationsExtensions::TileContent::TileWideBase |
StrictValidation | NotificationsExtensions::NotificationBase |
TemplateName | NotificationsExtensions::NotificationBase |
TextBodyWrap | NotificationsExtensions::TileContent::TileWideText09 |
TextFields | NotificationsExtensions::NotificationBase |
TextHeading | NotificationsExtensions::TileContent::TileWideText09 |
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileNotificationBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileNotificationBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWideBase(string templateName, int imageCount, int textCount) | NotificationsExtensions::TileContent::TileWideBase | [inline]
TileWideText09() | NotificationsExtensions::TileContent::TileWideText09 | [inline]
TileWideText09() | NotificationsExtensions::TileContent::TileWideText09 | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
ToString() | NotificationsExtensions::NotificationBase | [inline]
Generated on Sat Nov 23 2024 16:09:44 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::PropVariantClearStruct Member List

This is the complete list of members for SDKSample::PropVariantClearStruct, including all inherited members.
operator()(PROPVARIANT *pvPtr) const SDKSample::PropVariantClearStruct [inline]
Generated on Sat Nov 23 2024 16:09:49 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D-Direct2D interop/C++/BasicReaderWriter.cpp Source File

  • Direct3D-Direct2D interop

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     m_locationPath = Platform::String::Concat(m_location->Path, "\\");
00023 }
00024
00025 BasicReaderWriter::BasicReaderWriter(
00026     _In_ Windows::Storage::StorageFolder^ folder
00027     )
00028 {
00029     m_location = folder;
00030     Platform::String^ path = m_location->Path;
00031     if (path->Length() == 0)
00032     {
00033         // Applications are not permitted to access certain
00034         // folders, such as the Documents folder, using this
00035         // code path.  In such cases, the Path property for
00036         // the folder will be an empty string.
00037         throw ref new Platform::FailureException();
00038     }
00039     m_locationPath = Platform::String::Concat(path, "\\");
00040 }
00041
00042 Platform::Array<byte>^ BasicReaderWriter::ReadData(
00043     _In_ Platform::String^ filename
00044     )
00045 {
00046     CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {0};
00047     extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
00048     extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
00049     extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN;
00050     extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
00051     extendedParams.lpSecurityAttributes = nullptr;
00052     extendedParams.hTemplateFile = nullptr;
00053
00054     Wrappers::FileHandle file(
00055         CreateFile2(
00056             Platform::String::Concat(m_locationPath, filename)->Data(),
00057             GENERIC_READ,
00058             FILE_SHARE_READ,
00059             OPEN_EXISTING,
00060             &extendedParams
00061             )
00062         );
00063     if (file.Get() == INVALID_HANDLE_VALUE)
00064     {
00065         throw ref new Platform::FailureException();
00066     }
00067
00068     FILE_STANDARD_INFO fileInfo = {0};
00069     if (!GetFileInformationByHandleEx(
00070         file.Get(),
00071         FileStandardInfo,
00072         &fileInfo,
00073         sizeof(fileInfo)
00074         ))
00075     {
00076         throw ref new Platform::FailureException();
00077     }
00078
00079     if (fileInfo.EndOfFile.HighPart != 0)
00080     {
00081         throw ref new Platform::OutOfMemoryException();
00082     }
00083
00084     Platform::Array<byte>^ fileData = ref new Platform::Array<byte>(fileInfo.EndOfFile.LowPart);
00085
00086     if (!ReadFile(
00087         file.Get(),
00088         fileData->Data,
00089         fileData->Length,
00090         nullptr,
00091         nullptr
00092         ))
00093     {
00094         throw ref new Platform::FailureException();
00095     }
00096
00097     return fileData;
00098 }
00099
00100 task<Platform::Array<byte>^> BasicReaderWriter::ReadDataAsync(
00101     _In_ Platform::String^ filename
00102     )
00103 {
00104     return task<StorageFile^>(m_location->GetFileAsync(filename)).then([=](StorageFile^ file)
00105     {
00106         return FileIO::ReadBufferAsync(file);
00107     }).then([=](IBuffer^ buffer)
00108     {
00109         auto fileData = ref new Platform::Array<byte>(buffer->Length);
00110         DataReader::FromBuffer(buffer)->ReadBytes(fileData);
00111         return fileData;
00112     });
00113 }
00114
00115 uint32 BasicReaderWriter::WriteData(
00116     _In_ Platform::String^ filename,
00117     _In_ const Platform::Array<byte>^ fileData
00118     )
00119 {
00120     CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {0};
00121     extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
00122     extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
00123     extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN;
00124     extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
00125     extendedParams.lpSecurityAttributes = nullptr;
00126     extendedParams.hTemplateFile = nullptr;
00127
00128     Wrappers::FileHandle file(
00129         CreateFile2(
00130             Platform::String::Concat(m_locationPath, filename)->Data(),
00131             GENERIC_WRITE,
00132             0,
00133             CREATE_ALWAYS,
00134             &extendedParams
00135             )
00136         );
00137     if (file.Get() == INVALID_HANDLE_VALUE)
00138     {
00139         throw ref new Platform::FailureException();
00140     }
00141
00142     DWORD numBytesWritten;
00143     if (
00144         !WriteFile(
00145             file.Get(),
00146             fileData->Data,
00147             fileData->Length,
00148             &numBytesWritten,
00149             nullptr
00150             ) ||
00151         numBytesWritten != fileData->Length
00152         )
00153     {
00154         throw ref new Platform::FailureException();
00155     }
00156
00157     return numBytesWritten;
00158 }
00159
00160 task<void> BasicReaderWriter::WriteDataAsync(
00161     _In_ Platform::String^ filename,
00162     _In_ const Platform::Array<byte>^ fileData
00163     )
00164 {
00165     return task<StorageFile^>(m_location->CreateFileAsync(filename, CreationCollisionOption::ReplaceExisting)).then([=](StorageFile^ file)
00166     {
00167         FileIO::WriteBytesAsync(file, fileData);
00168     });
00169 }
Generated on Sat Nov 23 2024 16:08:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite inline object/C++/DirectXBase.h Source File

  • DirectWrite inline object

DirectXBase.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 "DirectXSample.h"
00011
00012 // Helper class that initializes DirectX APIs for both 2D and 3D rendering.
00013 // Some of the code in this class may be omitted if only 2D or only 3D rendering is being used.
00014 ref class DirectXBase abstract
00015 {
00016 internal:
00017     DirectXBase();
00018
00019     virtual void Initialize(Windows::UI::Core::CoreWindow^ window, float dpi);
00020     virtual void HandleDeviceLost();
00021     virtual void CreateDeviceIndependentResources();
00022     virtual void CreateDeviceResources();
00023     virtual void SetDpi(float dpi);
00024     virtual void UpdateForWindowSizeChange();
00025     virtual void CreateWindowSizeDependentResources();
00026     virtual void Render() = 0;
00027     virtual void Present();
00028     void ValidateDevice();
00029
00030 protected private:
00031     Platform::Agile<Windows::UI::Core::CoreWindow>  m_window;
00032
00033     // DirectWrite & Windows Imaging Component Objects.
00034     Microsoft::WRL::ComPtr<IDWriteFactory1>         m_dwriteFactory;
00035     Microsoft::WRL::ComPtr<IWICImagingFactory2>     m_wicFactory;
00036
00037     // DirectX Core Objects. Required for 2D and 3D.
00038     Microsoft::WRL::ComPtr<ID3D11Device1>           m_d3dDevice;
00039     Microsoft::WRL::ComPtr<ID3D11DeviceContext1>    m_d3dContext;
00040     Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00041     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00042
00043     // Direct2D Rendering Objects. Required for 2D.
00044     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00046     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00047     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmap;
00048
00049     // Direct3D Rendering Objects. Required for 3D.
00050     Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00051
00052     // Cached renderer properties.
00053     D3D_FEATURE_LEVEL                               m_featureLevel;
00054     Windows::Foundation::Size                       m_renderTargetSize;
00055     Windows::Foundation::Rect                       m_windowBounds;
00056     float                                           m_dpi;
00057     bool                                            m_windowSizeChangeInProgress;
00058 };
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/Level3.h Source File

  • XAML DirectX 3D shooting game

Level3.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 // Level3:
00011 // This class defines the third level of the game.  In this level each of the
00012 // nine targets is moving along closed paths and can be hit
00013 // in any order.
00014
00015 #include "Level.h"
00016
00017 ref class Level3: public Level
00018 {
00019 internal:
00020     Level3();
00021     virtual void Initialize(std::vector<GameObject^> objects) override;
00022 };
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML personality animations/C++/Constants.cpp Source File

  • XAML personality animations

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully qualified name for the class that implements the scenario" }
00021     { "PopIn animation", "SDKSample.PersonalityAnimations.Scenario1" },
00022     { "Content transition animation", "SDKSample.PersonalityAnimations.Scenario2" },
00023     { "Transitions between pages", "SDKSample.PersonalityAnimations.Scenario3" }
00024 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: ControlChannelTrigger StreamSocket/C++/Background/Background.h Source File

  • ControlChannelTrigger StreamSocket
  • Background

Background.h

Go to the documentation of this file.
00001 #include "pch.h"
00002 using namespace Platform;
00003 using namespace Windows::ApplicationModel::Background;
00004
00005 namespace Background
00006 {
00007     [Windows::Foundation::Metadata::WebHostHidden]
00008     public ref class NetworkChangeTask sealed :IBackgroundTask
00009     {
00010     public:
00011         virtual void Run(IBackgroundTaskInstance^ taskInstance);
00012     };
00013
00014     [Windows::Foundation::Metadata::WebHostHidden]
00015     public ref class KATask sealed : IBackgroundTask
00016     {
00017     public:
00018         virtual void Run(IBackgroundTaskInstance^ taskInstance);
00019     };
00020
00021     [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class PushNotifyTask sealed : IBackgroundTask
00023     {
00024     public:
00025         virtual void Run(IBackgroundTaskInstance^ taskInstance);
00026         void InvokeSimpleToast(String^ msgReceived);
00027     };
00028 }
Generated on Sat Nov 23 2024 16:07:59 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Device enumeration/C++/common/LayoutAwarePage.cpp Source File

  • Device enumeration
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:31 for Win8-Examples by doxygen 1.7.1


Win8-Examples: User domain name/C++/GetPrincipalName.xaml.cpp Source File

  • User domain name

GetPrincipalName.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 // GetPrincipalName.xaml.cpp
00013 // Implementation of the GetPrincipalName class
00014 //
00015
00016 #include "pch.h"
00017 #include "GetPrincipalName.xaml.h"
00018 #include <ppltasks.h>
00019
00020 using namespace Windows::System::UserProfile;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024 using namespace Platform;
00025 using namespace SDKSample::UserDomainName;
00026 using namespace concurrency;
00027
00028 GetPrincipalName::GetPrincipalName()
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 GetPrincipalName::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 SDKSample::UserDomainName::GetPrincipalName::GetPrincipalName_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00046 {
00047     // The user or domain administrator may disable access to personal information by apps
00048     if (UserInformation::NameAccessAllowed)
00049     {
00050         PrincipalResultText->Text = "Getting principal name.";
00051         create_task(UserInformation::GetPrincipalNameAsync()).then([this](String^ principalName)
00052         {
00053             // an empty string may be returned in any of the following circumstances:
00054             // The information cannot be retrieved from the directory
00055             // The calling user is not a member of a domain
00056             // The user or administrator has disabled the privacy setting
00057             if (principalName->IsEmpty())
00058             {
00059                 PrincipalResultText->Text = "No principal name returned for the current user.";
00060             }
00061             else
00062             {
00063                 PrincipalResultText->Text = principalName;
00064             }
00065         });
00066     }
00067     else
00068     {
00069         PrincipalResultText->Text = "Access to user information is disabled by the user or administrator";
00070     }
00071 }
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Accelerometer sensor/C++/common/LayoutAwarePage.h Source File

  • Accelerometer sensor
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:34 for Win8-Examples by doxygen 1.7.1


Win8-Examples: UI contrast and settings/C++/cppsamplesutils.h Source File

  • UI contrast and settings

cppsamplesutils.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 <string>
00014 #include <sstream>
00015 #include <algorithm>
00016 #include <collection.h>
00017 #include <ppltasks.h>
00018
00019 namespace CppSamplesUtils
00020 {
00021     namespace Details
00022     {
00023         static Windows::Foundation::Collections::PropertySet^ sessionState = nullptr;
00024         static Platform::String^ sessionStateFileName = ref new Platform::String(L"_cppSessionState.xml");
00025
00026         concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file);
00027         concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file);
00028     }
00029
00030     class SuspensionManager
00031     {
00032     public:
00033         static Windows::Foundation::Collections::PropertySet^ SessionState()
00034         {
00035             using namespace Windows::Foundation::Collections;
00036             using namespace Details;
00037
00038             if (sessionState == nullptr)
00039             {
00040                 sessionState = ref new PropertySet();
00041             }
00042             return sessionState;
00043         }
00044
00045         static concurrency::task<void> StartRestoreTask()
00046         {
00047             using namespace Windows::Foundation;
00048             using namespace Windows::Storage;
00049             using namespace Windows::Storage::Streams;
00050             using namespace Details;
00051
00052             auto state = SessionState();
00053             state->Clear();
00054
00055             concurrency::task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFileName));
00056             return getFileTask.then([=](StorageFile^ file)
00057             {
00058                 return DeserializeSessionState(file);
00059             });
00060         }
00061
00062         static concurrency::task<void> StartSaveTask()
00063         {
00064             using namespace Windows::Foundation;
00065             using namespace Windows::Storage;
00066             using namespace Windows::Storage::Streams;
00067             using namespace Details;
00068
00069             concurrency::task<StorageFile^> createFileTask(ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFileName, CreationCollisionOption::ReplaceExisting));
00070             return createFileTask.then([=](StorageFile^ file)
00071             {
00072                 return SerializeSessionState(file);
00073             });
00074         }
00075     };
00076
00077     namespace Details
00078     {
00079         template <class T>
00080         inline Platform::String^ ToString(T value)
00081         {
00082             std::wstringstream wss;
00083             wss << value;
00084             return ref new Platform::String(wss.str().c_str());
00085         }
00086
00087         template <class T>
00088         inline T FromStringTo(Platform::String^ str)
00089         {
00090             std::wistringstream wiss(str->Data());
00091             T value = 0;
00092             wiss >> value;
00093             return value;
00094         }
00095
00096         template <class T>
00097         inline T FromHexStringTo(Platform::String^ str)
00098         {
00099             std::wistringstream wiss(str->Data());
00100             T value = 0;
00101             wiss >> std::hex >> value;
00102             return value;
00103         }
00104
00105         template <>
00106         inline Platform::Guid FromStringTo<Platform::Guid>(Platform::String^ str)
00107         {
00108             using namespace Platform;
00109
00110             if (str->Length() != 38)
00111             {
00112                 throw ref new InvalidArgumentException;
00113             }
00114             std::wstring ws(str->Data());
00115             if (ws[0] != L'{' || ws[37] != L'}' || ws[9] != L'-' || ws[14] != L'-' || ws[19] != L'-' || ws[24] != L'-')
00116             {
00117                 throw ref new InvalidArgumentException;
00118             }
00119             ws[0] = ws[37] = ws[9] = ws[14] = ws[19] =ws[24] = L' ';
00120             std::wistringstream wiss(ws);
00121             unsigned int a = 0;
00122             unsigned short b = 0;
00123             unsigned short c = 0;
00124             unsigned short d = 0;
00125             unsigned long long e = 0;
00126             static_assert(sizeof(d) == sizeof(char) * 2, "sizeof(d) == sizeof(char) * 2");
00127             static_assert(sizeof(e) == sizeof(char) * 8, "sizeof(e) == sizeof(char) * 8");
00128             wiss >> std::hex >> a >> b >> c >> d >> e;
00129             unsigned char *ad = (unsigned char*)(&d);
00130             unsigned char *ae = (unsigned char*)(&e);
00131             return Platform::Guid(a, b, c, ad[1], ad[0], ae[5], ae[4], ae[3], ae[2], ae[1], ae[0]);
00132         }
00133
00134         inline Platform::Object^ ConvertStringToObject(Windows::Foundation::PropertyType type, Platform::String^ str)
00135         {
00136             using namespace Platform;
00137             using namespace Windows::Foundation;
00138
00139             if (type == PropertyType::String)
00140             {
00141                 return PropertyValue::CreateString(str);
00142             }
00143
00144             switch (type)
00145             {
00146             case PropertyType::UInt8:
00147                 return PropertyValue::CreateUInt8((unsigned char)FromStringTo<unsigned short>(str));
00148             case PropertyType::UInt16:
00149                 return PropertyValue::CreateUInt16(FromStringTo<unsigned short>(str));
00150             case PropertyType::UInt32:
00151                 return PropertyValue::CreateUInt32(FromStringTo<unsigned int>(str));
00152             case PropertyType::UInt64:
00153                 return PropertyValue::CreateUInt64(FromStringTo<unsigned long long>(str));
00154             case PropertyType::Int16:
00155                 return PropertyValue::CreateInt16(FromStringTo<short>(str));
00156             case PropertyType::Int32:
00157                 return PropertyValue::CreateInt32(FromStringTo<int>(str));
00158             case PropertyType::Int64:
00159                 return PropertyValue::CreateInt64(FromStringTo<long long>(str));
00160             case PropertyType::Single:
00161                 return PropertyValue::CreateSingle(FromStringTo<float>(str));
00162             case PropertyType::Double:
00163                 return PropertyValue::CreateDouble(FromStringTo<double>(str));
00164             case PropertyType::Boolean:
00165                 return PropertyValue::CreateBoolean(FromStringTo<bool>(str));
00166             case PropertyType::Char16:
00167                 return PropertyValue::CreateChar16(str->Data()[0]);
00168             case PropertyType::Guid:
00169                 return PropertyValue::CreateGuid(FromStringTo<Guid>(str));
00170             default:
00171                 throw ref new Platform::InvalidCastException;
00172             }
00173         }
00174
00175         inline Platform::String^ ConvertPropertyValueToString(Windows::Foundation::IPropertyValue^ pv)
00176         {
00177             using namespace Platform;
00178             using namespace Windows::Foundation;
00179
00180             String^ valueString;
00181
00182             switch (pv->Type)
00183             {
00184             case PropertyType::String:
00185                 valueString = pv->GetString();
00186                 break;
00187
00188             case PropertyType::UInt8:
00189             case PropertyType::UInt16:
00190             case PropertyType::UInt32:
00191             case PropertyType::UInt64:
00192                 valueString = ToString(pv->GetUInt64());
00193                 break;
00194
00195             case PropertyType::Int16:
00196             case PropertyType::Int32:
00197             case PropertyType::Int64:
00198                 valueString = ToString(pv->GetInt64());
00199                 break;
00200
00201             case PropertyType::Single:
00202                 valueString = ToString(pv->GetSingle());
00203                 break;
00204
00205             case PropertyType::Double:
00206                 valueString = ToString(pv->GetDouble());
00207                 break;
00208
00209             case PropertyType::Boolean:
00210                 valueString = ToString(pv->GetBoolean());
00211                 break;
00212
00213             case PropertyType::Char16:
00214                 wchar_t buffer[2];
00215                 buffer[0] = pv->GetChar16();
00216                 buffer[1] = 0;
00217                 valueString = ref new String(buffer);
00218                 break;
00219
00220             case PropertyType::Guid:
00221                 valueString = pv->GetGuid().ToString();
00222                 break;
00223
00224             default:
00225                 throw ref new InvalidCastException;
00226             }
00227
00228             return valueString;
00229         }
00230
00231         inline Windows::Data::Xml::Dom::XmlElement^ CreateXmlElementFromObject(Windows::Data::Xml::Dom::XmlDocument^ doc, Platform::String^ name, Platform::Object^ value)
00232         {
00233             using namespace Platform;
00234             using namespace Windows::Foundation;
00235             using namespace Windows::Data::Xml::Dom;
00236
00237             XmlElement^ element = doc->CreateElement("item");
00238             element->SetAttribute("name", name);
00239
00240             IPropertyValue^ pv = (IPropertyValue^)value;
00241             element->SetAttribute("type", ToString((int)pv->Type));
00242             element->SetAttribute("value", ConvertPropertyValueToString(pv));
00243
00244             return element;
00245         }
00246
00247         inline concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file)
00248         {
00249             using namespace Windows::Data::Xml::Dom;
00250             using namespace Windows::Foundation;
00251             namespace WFC = Windows::Foundation::Collections;
00252             typedef Windows::Foundation::Collections::IKeyValuePair<Platform::String^, Platform::Object^> KVPair;
00253
00254             XmlDocument^ doc = ref new XmlDocument;
00255             doc->AppendChild(doc->CreateElement("items"));
00256             auto sessionState = SuspensionManager::SessionState();
00257
00258             std::for_each(WFC::begin(sessionState), WFC::end(sessionState), [doc](KVPair^ item)
00259             {
00260                 doc->DocumentElement->AppendChild(CreateXmlElementFromObject(doc, item->Key, item->Value));
00261             });
00262
00263             return concurrency::task<void>(doc->SaveToFileAsync(file));
00264         }
00265
00266         inline Windows::Foundation::PropertyType PropertyTypeFromString(Platform::String^ str)
00267         {
00268             int value = FromStringTo<int>(str);
00269             return (Windows::Foundation::PropertyType)value;
00270         }
00271
00272         inline concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file)
00273         {
00274             using namespace Platform;
00275             using namespace Windows::Foundation;
00276             using namespace Windows::Data::Xml::Dom;
00277             namespace WFC = Windows::Foundation::Collections;
00278
00279             concurrency::task<XmlDocument^> loadFileTask(XmlDocument::LoadFromFileAsync(file));
00280             return loadFileTask.then([=](concurrency::task<XmlDocument^> docTask)
00281             {
00282                 try
00283                 {
00284                     auto doc = docTask.get();
00285                     auto items = doc->SelectNodes("/items/item");
00286                     auto sessionState = SuspensionManager::SessionState();
00287
00288                     std::for_each(WFC::begin(items), WFC::end(items), [sessionState](IXmlNode^ node)
00289                     {
00290                         auto element = (IXmlElement^)node;
00291                         String^ name = element->GetAttribute("name");
00292                         String^ value = element->GetAttribute("value");
00293                         PropertyType type = PropertyTypeFromString(element->GetAttribute("type"));
00294
00295                         Object^ valueObject = ConvertStringToObject(type, value);
00296                         sessionState->Insert(name, valueObject);
00297                     });
00298
00299                 }
00300                 catch (Platform::Exception^)
00301                 {
00302                     // Restoring is best effort
00303                 }
00304             });
00305         }
00306     } // namespace Details
00307 } // namespace CppSamplesUtils
Generated on Sat Nov 23 2024 16:07:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D sprite/C++/DDSTextureLoader.h Source File

  • Direct3D sprite

DDSTextureLoader.h

Go to the documentation of this file.
00001 //--------------------------------------------------------------------------------------
00002 // File: DDSTextureLoader.h
00003 //
00004 // Function for loading a DDS texture and creating a Direct3D 11 runtime resource for it
00005 //
00006 // Note this function is 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
00018 #pragma once
00019
00020 void CreateDDSTextureFromMemory(
00021     _In_ ID3D11Device* d3dDevice,
00022     _In_reads_bytes_(ddsDataSize) const byte* ddsData,
00023     _In_ size_t ddsDataSize,
00024     _Out_opt_ ID3D11Resource** texture,
00025     _Out_opt_ ID3D11ShaderResourceView** textureView,
00026     _In_ size_t maxsize = 0
00027     );
Generated on Sat Nov 23 2024 16:08:11 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DirectX::ScratchImage Member List

This is the complete list of members for DirectX::ScratchImage, including all inherited members.
_image | DirectX::ScratchImage | [private]
_memory | DirectX::ScratchImage | [private]
_metadata | DirectX::ScratchImage | [private]
_nimages | DirectX::ScratchImage | [private]
_size | DirectX::ScratchImage | [private]
GetImage(_In_ size_t mip, _In_ size_t item, _In_ size_t slice) const | DirectX::ScratchImage |
GetImageCount() const | DirectX::ScratchImage | [inline]
GetImages() const | DirectX::ScratchImage | [inline]
GetMetadata() const | DirectX::ScratchImage | [inline]
GetPixels() const | DirectX::ScratchImage | [inline]
GetPixelsSize() const | DirectX::ScratchImage | [inline]
Initialize(_In_ const TexMetadata &mdata) | DirectX::ScratchImage |
Initialize1D(_In_ DXGI_FORMAT fmt, _In_ size_t length, _In_ size_t arraySize, _In_ size_t mipLevels) | DirectX::ScratchImage |
Initialize2D(_In_ DXGI_FORMAT fmt, _In_ size_t width, _In_ size_t height, _In_ size_t arraySize, _In_ size_t mipLevels) | DirectX::ScratchImage |
Initialize3D(_In_ DXGI_FORMAT fmt, _In_ size_t width, _In_ size_t height, _In_ size_t depth, _In_ size_t mipLevels) | DirectX::ScratchImage |
Initialize3DFromImages(_In_reads_(depth) const Image *images, _In_ size_t depth) | DirectX::ScratchImage |
InitializeArrayFromImages(_In_reads_(nImages) const Image *images, _In_ size_t nImages, _In_ bool allow1D=false) | DirectX::ScratchImage |
InitializeCube(_In_ DXGI_FORMAT fmt, _In_ size_t width, _In_ size_t height, _In_ size_t nCubes, _In_ size_t mipLevels) | DirectX::ScratchImage |
InitializeCubeFromImages(_In_reads_(nImages) const Image *images, _In_ size_t nImages) | DirectX::ScratchImage |
InitializeFromImage(_In_ const Image &srcImage, _In_ bool allow1D=false) | DirectX::ScratchImage |
operator=(const ScratchImage &) | DirectX::ScratchImage | [private]
Release() | DirectX::ScratchImage |
ScratchImage() | DirectX::ScratchImage | [inline]
ScratchImage(const ScratchImage &) | DirectX::ScratchImage | [private]
~ScratchImage() | DirectX::ScratchImage | [inline]
Generated on Sat Nov 23 2024 16:09:38 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

CAutoDXDevLockBase< DevManager, DevInterface > Member List

This is the complete list of members for CAutoDXDevLockBase< DevManager, DevInterface >, including all inherited members.
CAutoDXDevLockBase(_In_ Microsoft::WRL::ComPtr< DevManager > spDevManager) | CAutoDXDevLockBase< DevManager, DevInterface > | [inline]
LockDevice(_Out_ Microsoft::WRL::ComPtr< DevInterface > &spDev)=0 | CAutoDXDevLockBase< DevManager, DevInterface > | [pure virtual]
m_hDev | CAutoDXDevLockBase< DevManager, DevInterface > | [protected]
m_locked | CAutoDXDevLockBase< DevManager, DevInterface > | [protected]
m_spDevManager | CAutoDXDevLockBase< DevManager, DevInterface > | [protected]
~CAutoDXDevLockBase() | CAutoDXDevLockBase< DevManager, DevInterface > | [inline]
Generated on Sat Nov 23 2024 16:09:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

MPEG1PacketHeader Member List

This is the complete list of members for MPEG1PacketHeader, including all inherited members.
bHasPTS | MPEG1PacketHeader
cbPacketSize | MPEG1PacketHeader
cbPayload | MPEG1PacketHeader
number | MPEG1PacketHeader
PTS | MPEG1PacketHeader
stream_id | MPEG1PacketHeader
type | MPEG1PacketHeader
Generated on Sat Nov 23 2024 16:09:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite custom text renderer/C++/DWriteCustomTextRenderer.h Source File

  • DirectWrite custom text renderer

DWriteCustomTextRenderer.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 "DirectXBase.h"
00011 #include "SampleOverlay.h"
00012 #include "CustomTextRenderer.h"
00013
00014 ref class DWriteCustomTextRenderer : public DirectXBase, public Windows::ApplicationModel::Core::IFrameworkView
00015 {
00016 internal:
00017     DWriteCustomTextRenderer();
00018
00019     // DirectXBase Methods
00020     virtual void CreateDeviceIndependentResources() override;
00021     virtual void CreateDeviceResources() override;
00022     virtual void CreateWindowSizeDependentResources() override;
00023     virtual void Render() override;
00024
00025 public:
00026     // IFrameworkView Methods
00027     virtual void Initialize(_In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00028     virtual void SetWindow(_In_ Windows::UI::Core::CoreWindow^ window);
00029     virtual void Load(_In_ Platform::String^ entryPoint);
00030     virtual void Run();
00031     virtual void Uninitialize();
00032
00033 private:
00034     // Event Handlers
00035     void OnWindowSizeChanged(
00036         _In_ Windows::UI::Core::CoreWindow^ sender,
00037         _In_ Windows::UI::Core::WindowSizeChangedEventArgs^ args
00038         );
00039
00040     void OnLogicalDpiChanged(
00041         _In_ Platform::Object^ sender
00042         );
00043
00044     void OnDisplayContentsInvalidated(
00045         _In_ Platform::Object^ sender
00046         );
00047
00048     void OnActivated(
00049         _In_ Windows::ApplicationModel::Core::CoreApplicationView^ applicationView,
00050         _In_ Windows::ApplicationModel::Activation::IActivatedEventArgs^ args
00051         );
00052
00053     void OnSuspending(
00054         _In_ Platform::Object^ sender,
00055         _In_ Windows::ApplicationModel::SuspendingEventArgs^ args
00056         );
00057
00058     void OnResuming(
00059         _In_ Platform::Object^ sender,
00060         _In_ Platform::Object^ args
00061         );
00062
00063     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>                    m_blackBrush;
00064     Microsoft::WRL::ComPtr<IDWriteTextFormat>                       m_textFormat;
00065     Microsoft::WRL::ComPtr<IDWriteTypography>                       m_textTypography;
00066     Microsoft::WRL::ComPtr<IDWriteTextLayout>                       m_textLayout;
00067     Microsoft::WRL::ComPtr<IWICBitmapDecoder>                       m_wicBitmapDecoder;
00068     Microsoft::WRL::ComPtr<IWICBitmapFrameDecode>                   m_wicBitmapFrame;
00069     Microsoft::WRL::ComPtr<IWICFormatConverter>                     m_wicFormatConverter;
00070     Microsoft::WRL::ComPtr<ID2D1Bitmap>                             m_logoBitmap;
00071     Microsoft::WRL::ComPtr<ID2D1BitmapBrush>                        m_bitmapBrush;
00072     Microsoft::WRL::ComPtr<CustomTextRenderer>                      m_textRenderer;
00073     SampleOverlay^                                                  m_sampleOverlay;
00074 };
00075
00076 ref class DirectXAppSource : Windows::ApplicationModel::Core::IFrameworkViewSource
00077 {
00078 public:
00079     virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00080 };
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Snap/C++/MainPage.xaml.h Source File

  • Snap

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/ScenarioOutput1.xaml.cpp Source File

  • Media extensions

ScenarioOutput1.xaml.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 //
00009 // Scenario1Output.xaml.cpp
00010 // Implementation of the Scenario1Output class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioOutput1.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace MediaExtensionsCPP;
00018
00019 using namespace Platform;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Graphics::Display;
00023 using namespace Windows::UI::ViewManagement;
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 ScenarioOutput1::ScenarioOutput1()
00033 {
00034     InitializeComponent();
00035 }
00036
00037 ScenarioOutput1::~ScenarioOutput1()
00038 {
00039 }
00040
00041 #pragma region Template-Related Code - Do not remove
00042 void ScenarioOutput1::OnNavigatedTo(NavigationEventArgs^ e)
00043 {
00044     // Get a pointer to our main page.
00045     rootPage = dynamic_cast<MainPage^>(e->Parameter);
00046
00047     _mediaFailedToken = Video->MediaFailed += ref new ExceptionRoutedEventHandler(rootPage, &MediaExtensionsCPP::MainPage::VideoOnError);
00048 }
00049
00050 void ScenarioOutput1::OnNavigatedFrom(NavigationEventArgs^ e)
00051 {
00052     Video->MediaFailed -= _mediaFailedToken;
00053     Video->Source = nullptr;
00054 }
00055 #pragma endregion
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D geometry realization/C++/SampleOverlay.h Source File

  • Direct2D geometry realization

SampleOverlay.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 "DirectXSample.h"
00011
00012 // This class is responsible for initializing and rendering the title overlay visible
00013 // at the top of the DirectX SDK samples.
00014 ref class SampleOverlay
00015 {
00016 internal:
00017     SampleOverlay();
00018
00019     void Initialize(
00020         _In_ ID2D1Device*         d2dDevice,
00021         _In_ ID2D1DeviceContext*  d2dContext,
00022         _In_ IWICImagingFactory*  wicFactory,
00023         _In_ IDWriteFactory*      dwriteFactory,
00024         _In_ Platform::String^    caption
00025         );
00026
00027     void ResetDirectXResources();
00028
00029     void UpdateForWindowSizeChange();
00030
00031     void Render();
00032
00033     float GetTitleHeightInDips();
00034
00035 private:
00036
00037     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00038     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00039     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00040     Microsoft::WRL::ComPtr<IDWriteFactory>          m_dwriteFactory;
00041     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_whiteBrush;
00042     Microsoft::WRL::ComPtr<ID2D1DrawingStateBlock>  m_stateBlock;
00043
00044     Microsoft::WRL::ComPtr<IWICImagingFactory>      m_wicFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Bitmap>             m_logoBitmap;
00046     Microsoft::WRL::ComPtr<IDWriteTextLayout>       m_textLayout;
00047
00048     UINT                                            m_idIncrement;
00049     bool                                            m_drawOverlay;
00050     Platform::String^                               m_sampleName;
00051     float                                           m_padding;
00052     float                                           m_textVerticalOffset;
00053     D2D1_SIZE_F                                     m_logoSize;
00054     float                                           m_overlayWidth;
00055 };
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Date and time formatting/C++/Constants.cpp Source File

  • Date and time formatting

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
00021     { "Format date and time using long and short", "SDKSample.DateTimeFormatting.LongAndShortFormats" },
00022     { "Format using a string template", "SDKSample.DateTimeFormatting.StringTemplate" },
00023     { "Format using a parametrized template", "SDKSample.DateTimeFormatting.ParametrizedTemplate" },
00024     { "Override the current user's settings", "SDKSample.DateTimeFormatting.OverrideSettings" }
00025 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D custom image effects/C++/VertexShader/DirectXBase.h Source File

  • Direct2D custom image effects
  • VertexShader

DirectXBase.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 "DirectXSample.h"
00011
00012 // Helper class that initializes DirectX APIs for both 2D and 3D rendering.
00013 // Some of the code in this class may be omitted if only 2D or only 3D rendering is being used.
00014 ref class DirectXBase abstract
00015 {
00016 internal:
00017     DirectXBase();
00018
00019     virtual void Initialize(Windows::UI::Core::CoreWindow^ window, float dpi);
00020     virtual void HandleDeviceLost();
00021     virtual void CreateDeviceIndependentResources();
00022     virtual void CreateDeviceResources();
00023     virtual void SetDpi(float dpi);
00024     virtual void UpdateForWindowSizeChange();
00025     virtual void CreateWindowSizeDependentResources();
00026     virtual void Render() = 0;
00027     virtual void Present();
00028     void ValidateDevice();
00029
00030 protected private:
00031     Platform::Agile<Windows::UI::Core::CoreWindow>  m_window;
00032
00033     // DirectWrite & Windows Imaging Component Objects.
00034     Microsoft::WRL::ComPtr<IDWriteFactory1>         m_dwriteFactory;
00035     Microsoft::WRL::ComPtr<IWICImagingFactory2>     m_wicFactory;
00036
00037     // DirectX Core Objects. Required for 2D and 3D.
00038     Microsoft::WRL::ComPtr<ID3D11Device1>           m_d3dDevice;
00039     Microsoft::WRL::ComPtr<ID3D11DeviceContext1>    m_d3dContext;
00040     Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00041     Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00042
00043     // Direct2D Rendering Objects. Required for 2D.
00044     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00046     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00047     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmap;
00048
00049     // Direct3D Rendering Objects. Required for 3D.
00050     Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00051
00052     // Cached renderer properties.
00053     D3D_FEATURE_LEVEL                               m_featureLevel;
00054     Windows::Foundation::Size                       m_renderTargetSize;
00055     Windows::Foundation::Rect                       m_windowBounds;
00056     float                                           m_dpi;
00057     bool                                            m_windowSizeChangeInProgress;
00058 };
Generated on Sat Nov 23 2024 16:08:03 for Win8-Examples by doxygen 1.7.1


Win8-Examples: EAS policies for mail clients/C++/App.xaml.cpp Source File

  • EAS policies for mail clients

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Geolocation/C++/Constants.cpp Source File

  • Geolocation

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     { "Track position", "SDKSample.GeolocationCPP.Scenario1" },
00020     { "Get position", "SDKSample.GeolocationCPP.Scenario2" },
00021     { "Get position in background task", "SDKSample.GeolocationCPP.Scenario3" }
00022 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DXGI offer and reclaim resources/C++/BasicShapes.cpp Source File

  • DXGI offer and reclaim resources

BasicShapes.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 #pragma once
00009
00010 #include "pch.h"
00011 #include "BasicShapes.h"
00012 #include "DirectXSample.h"
00013 #include <memory>
00014
00015 BasicShapes::BasicShapes(ID3D11Device *d3dDevice) : m_d3dDevice(d3dDevice)
00016 {
00017 }
00018
00019 void BasicShapes::CreateVertexBuffer(
00020     _In_ unsigned int numVertices,
00021     _In_ BasicVertex *vertexData,
00022     _Out_ ID3D11Buffer **vertexBuffer
00023     )
00024 {
00025     *vertexBuffer = nullptr;
00026     Microsoft::WRL::ComPtr<ID3D11Buffer> vertexBufferInternal;
00027
00028     D3D11_BUFFER_DESC VertexBufferDesc;
00029     VertexBufferDesc.ByteWidth = sizeof(BasicVertex) * numVertices;
00030     VertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
00031     VertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
00032     VertexBufferDesc.CPUAccessFlags = 0;
00033     VertexBufferDesc.MiscFlags = 0;
00034     VertexBufferDesc.StructureByteStride = 0;
00035
00036     D3D11_SUBRESOURCE_DATA VertexBufferData;
00037     VertexBufferData.pSysMem = vertexData;
00038     VertexBufferData.SysMemPitch = 0;
00039     VertexBufferData.SysMemSlicePitch = 0;
00040
00041     DX::ThrowIfFailed(
00042         m_d3dDevice->CreateBuffer(
00043             &VertexBufferDesc,
00044             &VertexBufferData,
00045             &vertexBufferInternal
00046             )
00047         );
00048
00049
00050     *vertexBuffer = vertexBufferInternal.Detach();
00051 }
00052
00053 void BasicShapes::CreateIndexBuffer(
00054     _In_ unsigned int numIndices,
00055     _In_ unsigned short *indexData,
00056     _Out_ ID3D11Buffer **indexBuffer
00057     )
00058 {
00059     *indexBuffer = nullptr;
00060     Microsoft::WRL::ComPtr<ID3D11Buffer> indexBufferInternal;
00061
00062     D3D11_BUFFER_DESC IndexBufferDesc;
00063     IndexBufferDesc.ByteWidth = sizeof(unsigned short) * numIndices;
00064     IndexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
00065     IndexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
00066     IndexBufferDesc.CPUAccessFlags = 0;
00067     IndexBufferDesc.MiscFlags = 0;
00068     IndexBufferDesc.StructureByteStride = 0;
00069
00070     D3D11_SUBRESOURCE_DATA IndexBufferData;
00071     IndexBufferData.pSysMem = indexData;
00072     IndexBufferData.SysMemPitch = 0;
00073     IndexBufferData.SysMemSlicePitch = 0;
00074
00075     DX::ThrowIfFailed(
00076         m_d3dDevice->CreateBuffer(
00077             &IndexBufferDesc,
00078             &IndexBufferData,
00079             &indexBufferInternal
00080             )
00081         );
00082
00083     *indexBuffer = indexBufferInternal.Detach();
00084 }
00085
00086 void BasicShapes::CreateTangentVertexBuffer(
00087     _In_ unsigned int numVertices,
00088     _In_ TangentVertex *vertexData,
00089     _Out_ ID3D11Buffer **vertexBuffer
00090     )
00091 {
00092     *vertexBuffer = nullptr;
00093     Microsoft::WRL::ComPtr<ID3D11Buffer> vertexBufferInternal;
00094
00095     D3D11_BUFFER_DESC VertexBufferDesc;
00096     VertexBufferDesc.ByteWidth = sizeof(TangentVertex) * numVertices;
00097     VertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
00098     VertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
00099     VertexBufferDesc.CPUAccessFlags = 0;
00100     VertexBufferDesc.MiscFlags = 0;
00101     VertexBufferDesc.StructureByteStride = 0;
00102
00103     D3D11_SUBRESOURCE_DATA VertexBufferData;
00104     VertexBufferData.pSysMem = vertexData;
00105     VertexBufferData.SysMemPitch = 0;
00106     VertexBufferData.SysMemSlicePitch = 0;
00107
00108     DX::ThrowIfFailed(
00109         m_d3dDevice->CreateBuffer(
00110             &VertexBufferDesc,
00111             &VertexBufferData,
00112             &vertexBufferInternal
00113             )
00114         );
00115
00116
00117     *vertexBuffer = vertexBufferInternal.Detach();
00118 }
00119
00120 void BasicShapes::CreateCube(
00121     _Out_ ID3D11Buffer **vertexBuffer,
00122     _Out_ ID3D11Buffer **indexBuffer,
00123     _Out_opt_ unsigned int *vertexCount,
00124     _Out_opt_ unsigned int *indexCount
00125     )
00126 {
00127     BasicVertex cubeVertices[] =
00128     {
00129         { float3(-0.5f, 0.5f, -0.5f), float3(0.0f, 1.0f, 0.0f), float2(0.0f, 0.0f) }, // +Y (top face)
00130         { float3( 0.5f, 0.5f, -0.5f), float3(0.0f, 1.0f, 0.0f), float2(1.0f, 0.0f) },
00131         { float3( 0.5f, 0.5f,  0.5f), float3(0.0f, 1.0f, 0.0f), float2(1.0f, 1.0f) },
00132         { float3(-0.5f, 0.5f,  0.5f), float3(0.0f, 1.0f, 0.0f), float2(0.0f, 1.0f) },
00133
00134         { float3(-0.5f, -0.5f,  0.5f), float3(0.0f, -1.0f, 0.0f), float2(0.0f, 0.0f) }, // -Y (bottom face)
00135         { float3( 0.5f, -0.5f,  0.5f), float3(0.0f, -1.0f, 0.0f), float2(1.0f, 0.0f) },
00136         { float3 (0.5f, -0.5f, -0.5f), float3(0.0f, -1.0f, 0.0f), float2(1.0f, 1.0f) },
00137         { float3(-0.5f, -0.5f, -0.5f), float3(0.0f, -1.0f, 0.0f), float2(0.0f, 1.0f) },
00138
00139         { float3(0.5f,  0.5f,  0.5f), float3(1.0f, 0.0f, 0.0f), float2(0.0f, 0.0f) }, // +X (right face)
00140         { float3(0.5f,  0.5f, -0.5f), float3(1.0f, 0.0f, 0.0f), float2(1.0f, 0.0f) },
00141         { float3(0.5f, -0.5f, -0.5f), float3(1.0f, 0.0f, 0.0f), float2(1.0f, 1.0f) },
00142         { float3(0.5f, -0.5f,  0.5f), float3(1.0f, 0.0f, 0.0f), float2(0.0f, 1.0f) },
00143
00144         { float3(-0.5f,  0.5f, -0.5f), float3(-1.0f, 0.0f, 0.0f), float2(0.0f, 0.0f) }, // -X (left face)
00145         { float3(-0.5f,  0.5f,  0.5f), float3(-1.0f, 0.0f, 0.0f), float2(1.0f, 0.0f) },
00146         { float3(-0.5f, -0.5f,  0.5f), float3(-1.0f, 0.0f, 0.0f), float2(1.0f, 1.0f) },
00147         { float3(-0.5f, -0.5f, -0.5f), float3(-1.0f, 0.0f, 0.0f), float2(0.0f, 1.0f) },
00148
00149         { float3(-0.5f,  0.5f, 0.5f), float3(0.0f, 0.0f, 1.0f), float2(0.0f, 0.0f) }, // +Z (front face)
00150         { float3( 0.5f,  0.5f, 0.5f), float3(0.0f, 0.0f, 1.0f), float2(1.0f, 0.0f) },
00151         { float3( 0.5f, -0.5f, 0.5f), float3(0.0f, 0.0f, 1.0f), float2(1.0f, 1.0f) },
00152         { float3(-0.5f, -0.5f, 0.5f), float3(0.0f, 0.0f, 1.0f), float2(0.0f, 1.0f) },
00153
00154         { float3( 0.5f,  0.5f, -0.5f), float3(0.0f, 0.0f, -1.0f), float2(0.0f, 0.0f) }, // -Z (back face)
00155         { float3(-0.5f,  0.5f, -0.5f), float3(0.0f, 0.0f, -1.0f), float2(1.0f, 0.0f) },
00156         { float3(-0.5f, -0.5f, -0.5f), float3(0.0f, 0.0f, -1.0f), float2(1.0f, 1.0f) },
00157         { float3( 0.5f, -0.5f, -0.5f), float3(0.0f, 0.0f, -1.0f), float2(0.0f, 1.0f) },
00158     };
00159
00160     unsigned short cubeIndices[] =
00161     {
00162         0, 1, 2,
00163         0, 2, 3,
00164
00165         4, 5, 6,
00166         4, 6, 7,
00167
00168         8, 9, 10,
00169         8, 10, 11,
00170
00171         12, 13, 14,
00172         12, 14, 15,
00173
00174         16, 17, 18,
00175         16, 18, 19,
00176
00177         20, 21, 22,
00178         20, 22, 23
00179     };
00180
00181     CreateVertexBuffer(
00182         ARRAYSIZE(cubeVertices),
00183         cubeVertices,
00184         vertexBuffer
00185         );
00186     if (vertexCount != nullptr)
00187     {
00188         *vertexCount = ARRAYSIZE(cubeVertices);
00189     }
00190
00191     CreateIndexBuffer(
00192         ARRAYSIZE(cubeIndices),
00193         cubeIndices,
00194         indexBuffer
00195         );
00196     if (indexCount != nullptr)
00197     {
00198         *indexCount = ARRAYSIZE(cubeIndices);
00199     }
00200 }
00201
00202 void BasicShapes::CreateBox(
00203     float3 r,
00204     _Out_ ID3D11Buffer **vertexBuffer,
00205     _Out_ ID3D11Buffer **indexBuffer,
00206     _Out_opt_ unsigned int *vertexCount,
00207     _Out_opt_ unsigned int *indexCount
00208     )
00209 {
00210     BasicVertex boxVertices[] =
00211     {
00212         // FLOOR
00213         {float3(-r.x, -r.y,  r.z), float3(0.0f, 1.0f, 0.0f), float2(0.0f, 0.0f)},
00214         {float3( r.x, -r.y,  r.z), float3(0.0f, 1.0f, 0.0f), float2(1.0f, 0.0f)},
00215         {float3(-r.x, -r.y, -r.z), float3(0.0f, 1.0f, 0.0f), float2(0.0f, 1.5f)},
00216         {float3( r.x, -r.y, -r.z), float3(0.0f, 1.0f, 0.0f), float2(1.0f, 1.5f)},
00217         // WALL
00218         {float3(-r.x,  r.y, r.z), float3(0.0f, 0.0f, -1.0f), float2(0.0f, 0.0f)},
00219         {float3( r.x,  r.y, r.z), float3(0.0f, 0.0f, -1.0f), float2(2.0f, 0.0f)},
00220         {float3(-r.x, -r.y, r.z), float3(0.0f, 0.0f, -1.0f), float2(0.0f, 1.5f)},
00221         {float3( r.x, -r.y, r.z), float3(0.0f, 0.0f, -1.0f), float2(2.0f, 1.5f)},
00222         // WALL
00223         {float3(r.x,  r.y,  r.z), float3(-1.0f, 0.0f, 0.0f), float2(0.0f, 0.0f)},
00224         {float3(r.x,  r.y, -r.z), float3(-1.0f, 0.0f, 0.0f), float2(r.y,  0.0f)},
00225         {float3(r.x, -r.y,  r.z), float3(-1.0f, 0.0f, 0.0f), float2(0.0f, 1.5f)},
00226         {float3(r.x, -r.y, -r.z), float3(-1.0f, 0.0f, 0.0f), float2(r.y,  1.5f)},
00227         // WALL
00228         {float3( r.x,  r.y, -r.z), float3(0.0f, 0.0f, 1.0f), float2(0.0f, 0.0f)},
00229         {float3(-r.x,  r.y, -r.z), float3(0.0f, 0.0f, 1.0f), float2(2.0f, 0.0f)},
00230         {float3( r.x, -r.y, -r.z), float3(0.0f, 0.0f, 1.0f), float2(0.0f, 1.5f)},
00231         {float3(-r.x, -r.y, -r.z), float3(0.0f, 0.0f, 1.0f), float2(2.0f, 1.5f)},
00232         // WALL
00233         {float3(-r.x,  r.y, -r.z), float3(1.0f, 0.0f, 0.0f), float2(0.0f, 0.0f)},
00234         {float3(-r.x,  r.y,  r.z), float3(1.0f, 0.0f, 0.0f), float2(r.y,  0.0f)},
00235         {float3(-r.x, -r.y, -r.z), float3(1.0f, 0.0f, 0.0f), float2(0.0f, 1.5f)},
00236         {float3(-r.x, -r.y,  r.z), float3(1.0f, 0.0f, 0.0f), float2(r.y,  1.5f)},
00237         // CEILING
00238         {float3(-r.x, r.y, -r.z), float3(0.0f, -1.0f, 0.0f), float2(-0.15f, 0.0f)},
00239         {float3( r.x, r.y, -r.z), float3(0.0f, -1.0f, 0.0f), float2( 1.25f, 0.0f)},
00240         {float3(-r.x, r.y,  r.z), float3(0.0f, -1.0f, 0.0f), float2(-0.15f, 2.1f)},
00241         {float3( r.x, r.y,  r.z), float3(0.0f, -1.0f, 0.0f), float2( 1.25f, 2.1f)},
00242     };
00243
00244     unsigned short boxIndices[] =
00245     {
00246         0, 2, 1,
00247         1, 2, 3,
00248
00249         4, 6, 5,
00250         5, 6, 7,
00251
00252         8, 10, 9,
00253         9, 10, 11,
00254
00255         12, 14, 13,
00256         13, 14, 15,
00257
00258         16, 18, 17,
00259         17, 18, 19,
00260
00261         20, 22, 21,
00262         21, 22, 23,
00263     };
00264
00265     CreateVertexBuffer(
00266         ARRAYSIZE(boxVertices),
00267         boxVertices,
00268         vertexBuffer
00269         );
00270     if (vertexCount != nullptr)
00271     {
00272         *vertexCount = ARRAYSIZE(boxVertices);
00273     }
00274
00275     CreateIndexBuffer(
00276         ARRAYSIZE(boxIndices),
00277         boxIndices,
00278         indexBuffer
00279         );
00280     if (indexCount != nullptr)
00281     {
00282         *indexCount = ARRAYSIZE(boxIndices);
00283     }
00284 }
00285
00286 void BasicShapes::CreateSphere(
00287     _Out_ ID3D11Buffer **vertexBuffer,
00288     _Out_ ID3D11Buffer **indexBuffer,
00289     _Out_opt_ unsigned int *vertexCount,
00290     _Out_opt_ unsigned int *indexCount
00291     )
00292 {
00293     const int numSegments = 64;
00294     const int numSlices = numSegments / 2;
00295
00296     const int numVertices = (numSlices + 1) * (numSegments + 1);
00297     std::unique_ptr<BasicVertex[]> sphereVertices(new BasicVertex[numVertices]);
00298
00299     for (int slice = 0; slice <= numSlices; slice++)
00300     {
00301         float v = (float)slice/(float)numSlices;
00302         float inclination = v * PI_F;
00303         float y = cos(inclination);
00304         float r = sin(inclination);
00305         for (int segment = 0; segment <= numSegments; segment++)
00306         {
00307             float u = (float)segment/(float)numSegments;
00308             float azimuth = u * PI_F * 2.0f;
00309             int index = slice * (numSegments+1) + segment;
00310             sphereVertices[index].pos = float3(r * sin(azimuth), y, r * cos(azimuth));
00311             sphereVertices[index].norm = sphereVertices[index].pos;
00312             sphereVertices[index].tex = float2(u, v);
00313         }
00314     }
00315
00316     const int numIndices = numSlices * (numSegments-2) * 6;
00317     std::unique_ptr<unsigned short[]> sphereIndices(new unsigned short[numIndices]);
00318
00319     unsigned int index = 0;
00320     for (int slice = 0; slice < numSlices; slice++)
00321     {
00322         unsigned short sliceBase0 = (unsigned short)((slice)*(numSegments+1));
00323         unsigned short sliceBase1 = (unsigned short)((slice+1)*(numSegments+1));
00324         for (int segment = 0; segment < numSegments; segment++)
00325         {
00326             if (slice > 0)
00327             {
00328                 sphereIndices[index++] = sliceBase0 + segment;
00329                 sphereIndices[index++] = sliceBase0 + segment + 1;
00330                 sphereIndices[index++] = sliceBase1 + segment + 1;
00331             }
00332             if (slice < numSlices-1)
00333             {
00334                 sphereIndices[index++] = sliceBase0 + segment;
00335                 sphereIndices[index++] = sliceBase1 + segment + 1;
00336                 sphereIndices[index++] = sliceBase1 + segment;
00337             }
00338         }
00339     }
00340
00341     CreateVertexBuffer(
00342         numVertices,
00343         sphereVertices.get(),
00344         vertexBuffer
00345         );
00346     if (vertexCount != nullptr)
00347     {
00348         *vertexCount = numVertices;
00349     }
00350
00351     CreateIndexBuffer(
00352         numIndices,
00353         sphereIndices.get(),
00354         indexBuffer
00355         );
00356     if (indexCount != nullptr)
00357     {
00358         *indexCount = numIndices;
00359     }
00360 }
00361 void BasicShapes::CreateTangentSphere(
00362     _Out_ ID3D11Buffer **vertexBuffer,
00363     _Out_ ID3D11Buffer **indexBuffer,
00364     _Out_opt_ unsigned int *vertexCount,
00365     _Out_opt_ unsigned int *indexCount
00366     )
00367 {
00368     const int numSegments = 64;
00369     const int numSlices = numSegments / 2;
00370
00371     const int numVertices = (numSlices + 1) * (numSegments + 1);
00372     std::unique_ptr<TangentVertex[]> sphereVertices(new TangentVertex[numVertices]);
00373
00374     for (int slice = 0; slice <= numSlices; slice++)
00375     {
00376         float v = (float)slice/(float)numSlices;
00377         float inclination = v * PI_F;
00378         float y = cos(inclination);
00379         float r = sin(inclination);
00380         for (int segment = 0; segment <= numSegments; segment++)
00381         {
00382             float u = (float)segment/(float)numSegments;
00383             float azimuth = u * PI_F * 2.0f;
00384             int index = slice * (numSegments+1) + segment;
00385             sphereVertices[index].pos = float3(r*sin(azimuth), y, r*cos(azimuth));
00386             sphereVertices[index].tex = float2(u, v);
00387             sphereVertices[index].uTan = float3(cos(azimuth), 0, -sin(azimuth));
00388             sphereVertices[index].vTan = float3(cos(inclination)*sin(azimuth), -sin(inclination), cos(inclination)*cos(azimuth));
00389
00390         }
00391     }
00392
00393     const int numIndices = numSlices * (numSegments-2) * 6;
00394     std::unique_ptr<unsigned short[]> sphereIndices(new unsigned short[numIndices]);
00395
00396     unsigned int index = 0;
00397     for (int slice = 0; slice < numSlices; slice++)
00398     {
00399         unsigned short sliceBase0 = (unsigned short)((slice)*(numSegments+1));
00400         unsigned short sliceBase1 = (unsigned short)((slice+1)*(numSegments+1));
00401         for (int segment = 0; segment < numSegments; segment++)
00402         {
00403             if (slice > 0)
00404             {
00405                 sphereIndices[index++] = sliceBase0 + segment;
00406                 sphereIndices[index++] = sliceBase0 + segment + 1;
00407                 sphereIndices[index++] = sliceBase1 + segment + 1;
00408             }
00409             if (slice < numSlices-1)
00410             {
00411                 sphereIndices[index++] = sliceBase0 + segment;
00412                 sphereIndices[index++] = sliceBase1 + segment + 1;
00413                 sphereIndices[index++] = sliceBase1 + segment;
00414             }
00415         }
00416     }
00417
00418     CreateTangentVertexBuffer(
00419         numVertices,
00420         sphereVertices.get(),
00421         vertexBuffer
00422         );
00423     if (vertexCount != nullptr)
00424     {
00425         *vertexCount = numVertices;
00426     }
00427
00428     CreateIndexBuffer(
00429         numIndices,
00430         sphereIndices.get(),
00431         indexBuffer
00432         );
00433     if (indexCount != nullptr)
00434     {
00435         *indexCount = numIndices;
00436     }
00437 }
00438
00439 void BasicShapes::CreateReferenceAxis(
00440     _Out_ ID3D11Buffer **vertexBuffer,
00441     _Out_ ID3D11Buffer **indexBuffer,
00442     _Out_opt_ unsigned int *vertexCount,
00443     _Out_opt_ unsigned int *indexCount
00444     )
00445 {
00446     BasicVertex axisVertices[] =
00447     {
00448         { float3( 0.500f, 0.000f, 0.000f), float3( 0.125f, 0.500f, 0.500f), float2(0.250f, 0.250f) },
00449         { float3( 0.000f, 0.125f, 0.000f), float3( 0.125f, 0.500f, 0.500f), float2(0.250f, 0.250f) },
00450         { float3( 0.000f, 0.000f, 0.125f), float3( 0.125f, 0.500f, 0.500f), float2(0.250f, 0.250f) },
00451         { float3( 0.500f, 0.000f, 0.000f), float3( 0.125f,-0.500f, 0.500f), float2(0.250f, 0.250f) },
00452         { float3( 0.000f, 0.000f, 0.125f), float3( 0.125f,-0.500f, 0.500f), float2(0.250f, 0.250f) },
00453         { float3( 0.000f,-0.125f, 0.000f), float3( 0.125f,-0.500f, 0.500f), float2(0.250f, 0.250f) },
00454         { float3( 0.500f, 0.000f, 0.000f), float3( 0.125f,-0.500f,-0.500f), float2(0.250f, 0.250f) },
00455         { float3( 0.000f,-0.125f, 0.000f), float3( 0.125f,-0.500f,-0.500f), float2(0.250f, 0.250f) },
00456         { float3( 0.000f, 0.000f,-0.125f), float3( 0.125f,-0.500f,-0.500f), float2(0.250f, 0.250f) },
00457         { float3( 0.500f, 0.000f, 0.000f), float3( 0.125f, 0.500f,-0.500f), float2(0.250f, 0.250f) },
00458         { float3( 0.000f, 0.000f,-0.125f), float3( 0.125f, 0.500f,-0.500f), float2(0.250f, 0.250f) },
00459         { float3( 0.000f, 0.125f, 0.000f), float3( 0.125f, 0.500f,-0.500f), float2(0.250f, 0.250f) },
00460         { float3( 0.000f, 0.125f, 0.000f), float3(-0.125f, 0.000f, 0.000f), float2(0.250f, 0.250f) },
00461         { float3( 0.000f, 0.000f,-0.125f), float3(-0.125f, 0.000f, 0.000f), float2(0.250f, 0.250f) },
00462         { float3( 0.000f,-0.125f, 0.000f), float3(-0.125f, 0.000f, 0.000f), float2(0.250f, 0.250f) },
00463         { float3( 0.000f, 0.000f, 0.125f), float3(-0.125f, 0.000f, 0.000f), float2(0.250f, 0.250f) },
00464         { float3(-0.500f, 0.000f, 0.000f), float3(-0.125f, 0.500f, 0.500f), float2(0.250f, 0.500f) },
00465         { float3( 0.000f, 0.000f, 0.125f), float3(-0.125f, 0.500f, 0.500f), float2(0.250f, 0.500f) },
00466         { float3( 0.000f, 0.125f, 0.000f), float3(-0.125f, 0.500f, 0.500f), float2(0.250f, 0.500f) },
00467         { float3(-0.500f, 0.000f, 0.000f), float3(-0.125f, 0.500f,-0.500f), float2(0.250f, 0.500f) },
00468         { float3( 0.000f, 0.125f, 0.000f), float3(-0.125f, 0.500f,-0.500f), float2(0.250f, 0.500f) },
00469         { float3( 0.000f, 0.000f,-0.125f), float3(-0.125f, 0.500f,-0.500f), float2(0.250f, 0.500f) },
00470         { float3(-0.500f, 0.000f, 0.000f), float3(-0.125f,-0.500f,-0.500f), float2(0.250f, 0.500f) },
00471         { float3( 0.000f, 0.000f,-0.125f), float3(-0.125f,-0.500f,-0.500f), float2(0.250f, 0.500f) },
00472         { float3( 0.000f,-0.125f, 0.000f), float3(-0.125f,-0.500f,-0.500f), float2(0.250f, 0.500f) },
00473         { float3(-0.500f, 0.000f, 0.000f), float3(-0.125f,-0.500f, 0.500f), float2(0.250f, 0.500f) },
00474         { float3( 0.000f,-0.125f, 0.000f), float3(-0.125f,-0.500f, 0.500f), float2(0.250f, 0.500f) },
00475         { float3( 0.000f, 0.000f, 0.125f), float3(-0.125f,-0.500f, 0.500f), float2(0.250f, 0.500f) },
00476         { float3( 0.000f, 0.000f, 0.125f), float3( 0.125f, 0.000f, 0.000f), float2(0.250f, 0.500f) },
00477         { float3( 0.000f,-0.125f, 0.000f), float3( 0.125f, 0.000f, 0.000f), float2(0.250f, 0.500f) },
00478         { float3( 0.000f, 0.000f,-0.125f), float3( 0.125f, 0.000f, 0.000f), float2(0.250f, 0.500f) },
00479         { float3( 0.000f, 0.125f, 0.000f), float3( 0.125f, 0.000f, 0.000f), float2(0.250f, 0.500f) },
00480         { float3( 0.000f, 0.500f, 0.000f), float3( 0.500f, 0.125f, 0.500f), float2(0.500f, 0.250f) },
00481         { float3( 0.000f, 0.000f, 0.125f), float3( 0.500f, 0.125f, 0.500f), float2(0.500f, 0.250f) },
00482         { float3( 0.125f, 0.000f, 0.000f), float3( 0.500f, 0.125f, 0.500f), float2(0.500f, 0.250f) },
00483         { float3( 0.000f, 0.500f, 0.000f), float3( 0.500f, 0.125f,-0.500f), float2(0.500f, 0.250f) },
00484         { float3( 0.125f, 0.000f, 0.000f), float3( 0.500f, 0.125f,-0.500f), float2(0.500f, 0.250f) },
00485         { float3( 0.000f, 0.000f,-0.125f), float3( 0.500f, 0.125f,-0.500f), float2(0.500f, 0.250f) },
00486         { float3( 0.000f, 0.500f, 0.000f), float3(-0.500f, 0.125f,-0.500f), float2(0.500f, 0.250f) },
00487         { float3( 0.000f, 0.000f,-0.125f), float3(-0.500f, 0.125f,-0.500f), float2(0.500f, 0.250f) },
00488         { float3(-0.125f, 0.000f, 0.000f), float3(-0.500f, 0.125f,-0.500f), float2(0.500f, 0.250f) },
00489         { float3( 0.000f, 0.500f, 0.000f), float3(-0.500f, 0.125f, 0.500f), float2(0.500f, 0.250f) },
00490         { float3(-0.125f, 0.000f, 0.000f), float3(-0.500f, 0.125f, 0.500f), float2(0.500f, 0.250f) },
00491         { float3( 0.000f, 0.000f, 0.125f), float3(-0.500f, 0.125f, 0.500f), float2(0.500f, 0.250f) },
00492         { float3( 0.125f, 0.000f, 0.000f), float3( 0.000f,-0.125f, 0.000f), float2(0.500f, 0.250f) },
00493         { float3( 0.000f, 0.000f, 0.125f), float3( 0.000f,-0.125f, 0.000f), float2(0.500f, 0.250f) },
00494         { float3(-0.125f, 0.000f, 0.000f), float3( 0.000f,-0.125f, 0.000f), float2(0.500f, 0.250f) },
00495         { float3( 0.000f, 0.000f,-0.125f), float3( 0.000f,-0.125f, 0.000f), float2(0.500f, 0.250f) },
00496         { float3( 0.000f,-0.500f, 0.000f), float3( 0.500f,-0.125f, 0.500f), float2(0.500f, 0.500f) },
00497         { float3( 0.125f, 0.000f, 0.000f), float3( 0.500f,-0.125f, 0.500f), float2(0.500f, 0.500f) },
00498         { float3( 0.000f, 0.000f, 0.125f), float3( 0.500f,-0.125f, 0.500f), float2(0.500f, 0.500f) },
00499         { float3( 0.000f,-0.500f, 0.000f), float3(-0.500f,-0.125f, 0.500f), float2(0.500f, 0.500f) },
00500         { float3( 0.000f, 0.000f, 0.125f), float3(-0.500f,-0.125f, 0.500f), float2(0.500f, 0.500f) },
00501         { float3(-0.125f, 0.000f, 0.000f), float3(-0.500f,-0.125f, 0.500f), float2(0.500f, 0.500f) },
00502         { float3( 0.000f,-0.500f, 0.000f), float3(-0.500f,-0.125f,-0.500f), float2(0.500f, 0.500f) },
00503         { float3(-0.125f, 0.000f, 0.000f), float3(-0.500f,-0.125f,-0.500f), float2(0.500f, 0.500f) },
00504         { float3( 0.000f, 0.000f,-0.125f), float3(-0.500f,-0.125f,-0.500f), float2(0.500f, 0.500f) },
00505         { float3( 0.000f,-0.500f, 0.000f), float3( 0.500f,-0.125f,-0.500f), float2(0.500f, 0.500f) },
00506         { float3( 0.000f, 0.000f,-0.125f), float3( 0.500f,-0.125f,-0.500f), float2(0.500f, 0.500f) },
00507         { float3( 0.125f, 0.000f, 0.000f), float3( 0.500f,-0.125f,-0.500f), float2(0.500f, 0.500f) },
00508         { float3( 0.000f, 0.000f,-0.125f), float3( 0.000f, 0.125f, 0.000f), float2(0.500f, 0.500f) },
00509         { float3(-0.125f, 0.000f, 0.000f), float3( 0.000f, 0.125f, 0.000f), float2(0.500f, 0.500f) },
00510         { float3( 0.000f, 0.000f, 0.125f), float3( 0.000f, 0.125f, 0.000f), float2(0.500f, 0.500f) },
00511         { float3( 0.125f, 0.000f, 0.000f), float3( 0.000f, 0.125f, 0.000f), float2(0.500f, 0.500f) },
00512         { float3( 0.000f, 0.000f, 0.500f), float3( 0.500f, 0.500f, 0.125f), float2(0.750f, 0.250f) },
00513         { float3( 0.125f, 0.000f, 0.000f), float3( 0.500f, 0.500f, 0.125f), float2(0.750f, 0.250f) },
00514         { float3( 0.000f, 0.125f, 0.000f), float3( 0.500f, 0.500f, 0.125f), float2(0.750f, 0.250f) },
00515         { float3( 0.000f, 0.000f, 0.500f), float3(-0.500f, 0.500f, 0.125f), float2(0.750f, 0.250f) },
00516         { float3( 0.000f, 0.125f, 0.000f), float3(-0.500f, 0.500f, 0.125f), float2(0.750f, 0.250f) },
00517         { float3(-0.125f, 0.000f, 0.000f), float3(-0.500f, 0.500f, 0.125f), float2(0.750f, 0.250f) },
00518         { float3( 0.000f, 0.000f, 0.500f), float3(-0.500f,-0.500f, 0.125f), float2(0.750f, 0.250f) },
00519         { float3(-0.125f, 0.000f, 0.000f), float3(-0.500f,-0.500f, 0.125f), float2(0.750f, 0.250f) },
00520         { float3( 0.000f,-0.125f, 0.000f), float3(-0.500f,-0.500f, 0.125f), float2(0.750f, 0.250f) },
00521         { float3( 0.000f, 0.000f, 0.500f), float3( 0.500f,-0.500f, 0.125f), float2(0.750f, 0.250f) },
00522         { float3( 0.000f,-0.125f, 0.000f), float3( 0.500f,-0.500f, 0.125f), float2(0.750f, 0.250f) },
00523         { float3( 0.125f, 0.000f, 0.000f), float3( 0.500f,-0.500f, 0.125f), float2(0.750f, 0.250f) },
00524         { float3( 0.125f, 0.000f, 0.000f), float3( 0.000f, 0.000f,-0.125f), float2(0.750f, 0.250f) },
00525         { float3( 0.000f,-0.125f, 0.000f), float3( 0.000f, 0.000f,-0.125f), float2(0.750f, 0.250f) },
00526         { float3(-0.125f, 0.000f, 0.000f), float3( 0.000f, 0.000f,-0.125f), float2(0.750f, 0.250f) },
00527         { float3( 0.000f, 0.125f, 0.000f), float3( 0.000f, 0.000f,-0.125f), float2(0.750f, 0.250f) },
00528         { float3( 0.000f, 0.000f,-0.500f), float3( 0.500f, 0.500f,-0.125f), float2(0.750f, 0.500f) },
00529         { float3( 0.000f, 0.125f, 0.000f), float3( 0.500f, 0.500f,-0.125f), float2(0.750f, 0.500f) },
00530         { float3( 0.125f, 0.000f, 0.000f), float3( 0.500f, 0.500f,-0.125f), float2(0.750f, 0.500f) },
00531         { float3( 0.000f, 0.000f,-0.500f), float3( 0.500f,-0.500f,-0.125f), float2(0.750f, 0.500f) },
00532         { float3( 0.125f, 0.000f, 0.000f), float3( 0.500f,-0.500f,-0.125f), float2(0.750f, 0.500f) },
00533         { float3( 0.000f,-0.125f, 0.000f), float3( 0.500f,-0.500f,-0.125f), float2(0.750f, 0.500f) },
00534         { float3( 0.000f, 0.000f,-0.500f), float3(-0.500f,-0.500f,-0.125f), float2(0.750f, 0.500f) },
00535         { float3( 0.000f,-0.125f, 0.000f), float3(-0.500f,-0.500f,-0.125f), float2(0.750f, 0.500f) },
00536         { float3(-0.125f, 0.000f, 0.000f), float3(-0.500f,-0.500f,-0.125f), float2(0.750f, 0.500f) },
00537         { float3( 0.000f, 0.000f,-0.500f), float3(-0.500f, 0.500f,-0.125f), float2(0.750f, 0.500f) },
00538         { float3(-0.125f, 0.000f, 0.000f), float3(-0.500f, 0.500f,-0.125f), float2(0.750f, 0.500f) },
00539         { float3( 0.000f, 0.125f, 0.000f), float3(-0.500f, 0.500f,-0.125f), float2(0.750f, 0.500f) },
00540         { float3( 0.000f, 0.125f, 0.000f), float3( 0.000f, 0.000f, 0.125f), float2(0.750f, 0.500f) },
00541         { float3(-0.125f, 0.000f, 0.000f), float3( 0.000f, 0.000f, 0.125f), float2(0.750f, 0.500f) },
00542         { float3( 0.000f,-0.125f, 0.000f), float3( 0.000f, 0.000f, 0.125f), float2(0.750f, 0.500f) },
00543         { float3( 0.125f, 0.000f, 0.000f), float3( 0.000f, 0.000f, 0.125f), float2(0.750f, 0.500f) },
00544     };
00545
00546     unsigned short axisIndices[] =
00547     {
00548          0,  2,  1,
00549          3,  5,  4,
00550          6,  8,  7,
00551          9, 11, 10,
00552         12, 14, 13,
00553         12, 15, 14,
00554         16, 18, 17,
00555         19, 21, 20,
00556         22, 24, 23,
00557         25, 27, 26,
00558         28, 30, 29,
00559         28, 31, 30,
00560         32, 34, 33,
00561         35, 37, 36,
00562         38, 40, 39,
00563         41, 43, 42,
00564         44, 46, 45,
00565         44, 47, 46,
00566         48, 50, 49,
00567         51, 53, 52,
00568         54, 56, 55,
00569         57, 59, 58,
00570         60, 62, 61,
00571         60, 63, 62,
00572         64, 66, 65,
00573         67, 69, 68,
00574         70, 72, 71,
00575         73, 75, 74,
00576         76, 78, 77,
00577         76, 79, 78,
00578         80, 82, 81,
00579         83, 85, 84,
00580         86, 88, 87,
00581         89, 91, 90,
00582         92, 94, 93,
00583         92, 95, 94,
00584     };
00585
00586     CreateVertexBuffer(
00587         ARRAYSIZE(axisVertices),
00588         axisVertices,
00589         vertexBuffer
00590         );
00591     if (vertexCount != nullptr)
00592     {
00593         *vertexCount = ARRAYSIZE(axisVertices);
00594     }
00595
00596     CreateIndexBuffer(
00597         ARRAYSIZE(axisIndices),
00598         axisIndices,
00599         indexBuffer
00600         );
00601     if (indexCount != nullptr)
00602     {
00603         *indexCount = ARRAYSIZE(axisIndices);
00604     }
00605 }
Generated on Sat Nov 23 2024 16:08:10 for Win8-Examples by doxygen 1.7.1


Win8-Examples: HttpClient/C++/HttpRequest.h Source File

  • HttpClient

HttpRequest.h

Go to the documentation of this file.
00001 //-----------------------------------------------------------------------
00002 //
00003 //  Copyright (C) Microsoft Corporation.  All rights reserved.
00004 //
00005 //
00006 // THIS CODE AND INFORMATION ARE PROVIDED AS-IS WITHOUT WARRANTY OF ANY
00007 // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
00008 // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00009 // PARTICULAR PURPOSE.
00010 //-----------------------------------------------------------------------
00011 #pragma once
00012 #include "pch.h"
00013
00014 inline void CheckHResult(HRESULT hResult)
00015 {
00016     if (hResult == E_ABORT)
00017     {
00018         concurrency::cancel_current_task();
00019     }
00020     else if (FAILED(hResult))
00021     {
00022         throw Platform::Exception::CreateException(hResult);
00023     }
00024 }
00025
00026 namespace Web
00027 {
00028
00029 namespace Details
00030 {
00031
00032 // Implementation of IXMLHTTPRequest2Callback used when partial buffers are needed from the response.
00033 // When only the complete response is needed, use HttpRequestStringCallback instead.
00034 class HttpRequestBuffersCallback
00035     : public Microsoft::WRL::RuntimeClass<
00036         Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::ClassicCom>,
00037         IXMLHTTPRequest2Callback,
00038         Microsoft::WRL::FtmBase>
00039 {
00040 public:
00041     HttpRequestBuffersCallback(IXMLHTTPRequest2* httpRequest,
00042         concurrency::cancellation_token ct = concurrency::cancellation_token::none()) :
00043         request(httpRequest), cancellationToken(ct), responseReceived(false), dataHResult(S_OK), statusCode(200)
00044     {
00045         // Register a callback function that aborts the HTTP operation when
00046         // the cancellation token is canceled.
00047         if (cancellationToken != concurrency::cancellation_token::none())
00048         {
00049             registrationToken = cancellationToken.register_callback([this]()
00050             {
00051                 if (request != nullptr)
00052                 {
00053                     request->Abort();
00054                 }
00055             });
00056         }
00057
00058         dataEvent = concurrency::task_completion_event<void>();
00059     }
00060
00061     // Called when the HTTP request is being redirected to a new URL.
00062     IFACEMETHODIMP OnRedirect(IXMLHTTPRequest2*, PCWSTR)
00063     {
00064         return S_OK;
00065     }
00066
00067     // Called when HTTP headers have been received and processed.
00068     IFACEMETHODIMP OnHeadersAvailable(IXMLHTTPRequest2*, DWORD statusCode, PCWSTR reasonPhrase)
00069     {
00070         HRESULT hr = S_OK;
00071
00072         // We must not propagate exceptions back to IXHR2.
00073         try
00074         {
00075             this->statusCode = statusCode;
00076             this->reasonPhrase = reasonPhrase;
00077
00078             concurrency::critical_section::scoped_lock lock(dataEventLock);
00079             dataEvent.set();
00080         }
00081         catch (std::bad_alloc&)
00082         {
00083             hr = E_OUTOFMEMORY;
00084         }
00085         return hr;
00086     }
00087
00088     // Called when a portion of the entity body has been received.
00089     IFACEMETHODIMP OnDataAvailable(IXMLHTTPRequest2*, ISequentialStream* stream)
00090     {
00091         HRESULT hr = S_OK;
00092
00093         // We must not propagate exceptions back to IXHR2.
00094         try
00095         {
00096             // Store a reference on the stream so it can be accessed by the task.
00097             dataStream = stream;
00098
00099             // The work must be done as fast as possible, and must not block this thread,
00100             // for example, waiting on another event object.  Here we simply set an event
00101             // that can be processed by another thread.
00102             concurrency::critical_section::scoped_lock lock(dataEventLock);
00103             dataEvent.set();
00104         }
00105         catch (std::bad_alloc&)
00106         {
00107             hr = E_OUTOFMEMORY;
00108         }
00109         return hr;
00110     }
00111
00112     // Called when the entire entity response has been received.
00113     IFACEMETHODIMP OnResponseReceived(IXMLHTTPRequest2* xhr, ISequentialStream* responseStream)
00114     {
00115         responseReceived = true;
00116         return OnDataAvailable(xhr, responseStream);
00117     }
00118
00119     // Called when an error occurs during the HTTP request.
00120     IFACEMETHODIMP OnError(IXMLHTTPRequest2*, HRESULT hrError)
00121     {
00122         HRESULT hr = S_OK;
00123
00124         // We must not propagate exceptions back to IXHR2.
00125         try
00126         {
00127             concurrency::critical_section::scoped_lock lock(dataEventLock);
00128             dataHResult = hrError;
00129             dataEvent.set();
00130         }
00131         catch (std::bad_alloc&)
00132         {
00133             hr = E_OUTOFMEMORY;
00134         }
00135
00136         return hr;
00137     }
00138
00139     // Create a task that completes when data is available, in an exception-safe way.
00140     concurrency::task<void> CreateDataTask();
00141
00142     HRESULT GetError() const
00143     {
00144         return dataHResult;
00145     }
00146
00147     int GetStatusCode() const
00148     {
00149         return statusCode;
00150     }
00151
00152     std::wstring const& GetReasonPhrase() const
00153     {
00154         return reasonPhrase;
00155     }
00156
00157     bool IsResponseReceived() const
00158     {
00159         return responseReceived;
00160     }
00161
00162     // Copy bytes from the sequential stream into the buffer provided until
00163     // we reach the end of one or the other.
00164     unsigned int ReadData(
00165         _Out_writes_(outputBufferSize) byte* outputBuffer,
00166         unsigned int outputBufferSize);
00167
00168 private:
00169     ~HttpRequestBuffersCallback()
00170     {
00171         // Unregister the callback.
00172         if (cancellationToken != concurrency::cancellation_token::none())
00173         {
00174             cancellationToken.deregister_callback(registrationToken);
00175         }
00176     }
00177
00178     // Signals that the download operation was canceled.
00179     concurrency::cancellation_token cancellationToken;
00180
00181     // Used to unregister the cancellation token callback.
00182     concurrency::cancellation_token_registration registrationToken;
00183
00184     // The IXMLHTTPRequest2 that processes the HTTP request.
00185     Microsoft::WRL::ComPtr<IXMLHTTPRequest2> request;
00186
00187     // Task completion event that is set when data is available or error is triggered.
00188     concurrency::task_completion_event<void> dataEvent;
00189     concurrency::critical_section dataEventLock;
00190
00191     // We cannot store the error obtained from IXHR2 in the dataEvent since any value there is first-writer-wins,
00192     // whereas we want a subsequent error to override an initial success.
00193     HRESULT dataHResult;
00194
00195     // Referenced pointer to the data stream.
00196     Microsoft::WRL::ComPtr<ISequentialStream> dataStream;
00197
00198     // HTTP status code and reason returned by the server.
00199     int statusCode;
00200     std::wstring reasonPhrase;
00201
00202     // Whether the response has been completely received.
00203     bool responseReceived;
00204 };
00205
00206 };
00207
00208 // Utility class for performing asynchronous HTTP requests.
00209 // This class only supports one outstanding request at a time.
00210 class HttpRequest
00211 {
00212 public:
00213     HttpRequest();
00214
00215     int GetStatusCode() const
00216     {
00217         return statusCode;
00218     }
00219
00220     std::wstring const& GetReasonPhrase() const
00221     {
00222         return reasonPhrase;
00223     }
00224
00225     // Whether the response has been completely received, if using ReadAsync().
00226     bool IsResponseComplete() const
00227     {
00228         return responseComplete;
00229     }
00230
00231     // Start an HTTP GET on the specified URI.  The returned task completes once the entire response
00232     // has been received, and the task produces the HTTP response text.  The status code and reason
00233     // can be read with GetStatusCode() and GetReasonPhrase().
00234     concurrency::task<std::wstring> GetAsync(
00235         Windows::Foundation::Uri^ uri,
00236         concurrency::cancellation_token cancellationToken = concurrency::cancellation_token::none());
00237
00238     // Start an HTTP POST on the specified URI, using a string body.  The returned task produces the
00239     // HTTP response text.  The status code and reason can be read with GetStatusCode() and GetReasonPhrase().
00240     concurrency::task<std::wstring> PostAsync(
00241         Windows::Foundation::Uri^ uri,
00242         PCWSTR contentType,
00243         IStream* postStream,
00244         uint64 postStreamSizeToSend,
00245         concurrency::cancellation_token cancellationToken = concurrency::cancellation_token::none());
00246
00247     // Start an HTTP POST on the specified URI, using a stream body.  The returned task produces the
00248     // HTTP response text.  The status code and reason can be read with GetStatusCode() and GetReasonPhrase().
00249     concurrency::task<std::wstring> PostAsync(
00250         Windows::Foundation::Uri^ uri,
00251         const std::wstring& str,
00252         concurrency::cancellation_token cancellationToken = concurrency::cancellation_token::none());
00253
00254     // Send a request but don't return the response.  Instead, let the caller read it with ReadAsync().
00255     concurrency::task<void> SendAsync(
00256         const std::wstring& httpMethod,
00257         Windows::Foundation::Uri^ uri,
00258         concurrency::cancellation_token cancellationToken = concurrency::cancellation_token::none());
00259
00260     // Read a chunk of data from the HTTP response, up to a specified length or until we reach the end
00261     // of the response, and store the value in the provided buffer.  This is useful for large content,
00262     // enabling the streaming of the result.
00263     concurrency::task<void> ReadAsync(
00264         Windows::Storage::Streams::IBuffer^ readBuffer,
00265         unsigned int offsetInBuffer,
00266         unsigned int requestedBytesToRead);
00267
00268     static void CreateMemoryStream(IStream **stream);
00269
00270 private:
00271     // Start a download of the specified URI using the specified method.  The returned task produces the
00272     // HTTP response text.  The status code and reason can be read with GetStatusCode() and GetReasonPhrase().
00273     concurrency::task<std::wstring> DownloadAsync(
00274         PCWSTR httpMethod,
00275         PCWSTR uri,
00276         concurrency::cancellation_token cancellationToken,
00277         PCWSTR contentType,
00278         IStream* postStream,
00279         uint64 postStreamBytesToSend);
00280
00281     // Referenced pointer to the callback, if using SendAsync/ReadAsync.
00282     Microsoft::WRL::ComPtr<Details::HttpRequestBuffersCallback> buffersCallback;
00283
00284     int statusCode;
00285     std::wstring reasonPhrase;
00286
00287     // Whether the response has been completely received, if using ReadAsync().
00288     bool responseComplete;
00289 };
00290
00291 };
Generated on Sat Nov 23 2024 16:07:58 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX postcard app/C++/ExtrudedTextRenderer.cpp Source File

  • DirectX postcard app

ExtrudedTextRenderer.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 "ExtrudedTextRenderer.h"
00010
00011 using namespace Microsoft::WRL;
00012 using namespace Platform;
00013 using namespace Windows::Foundation;
00014
00015 ExtrudedTextRenderer::ExtrudedTextRenderer() :
00016     m_zoom(1.0f)
00017 {
00018 }
00019
00020 void ExtrudedTextRenderer::CreateDeviceIndependentResources(
00021     ComPtr<ID2D1Factory1> d2dFactory,
00022     ComPtr<IDWriteFactory1> dwriteFactory
00023     )
00024 {
00025     // Save the shared factories.
00026     m_d2dFactory = d2dFactory;
00027     m_dwriteFactory = dwriteFactory;
00028 }
00029
00030 void ExtrudedTextRenderer::CreateDeviceResources(
00031     ComPtr<ID3D11Device1> d3dDevice,
00032     ComPtr<ID3D11DeviceContext1> d3dContext
00033     )
00034 {
00035     // Save the shared Direct3D resources.
00036     m_d3dDevice = d3dDevice;
00037     m_d3dContext = d3dContext;
00038
00039     BasicLoader^ loader = ref new BasicLoader(m_d3dDevice.Get());
00040
00041     loader->LoadShader(
00042         L"SimpleVertexShader.cso",
00043         nullptr,
00044         0,
00045         &m_vertexShader,
00046         &m_inputLayout
00047         );
00048
00049     // create the constant buffer for updating model and camera data
00050     CD3D11_BUFFER_DESC constantBufferDesc(sizeof(ConstantBuffer), D3D11_BIND_CONSTANT_BUFFER);
00051     DX::ThrowIfFailed(
00052         m_d3dDevice->CreateBuffer(
00053             &constantBufferDesc,
00054             nullptr,             // leave the buffer uninitialized
00055             &m_constantBuffer
00056             )
00057         );
00058
00059     loader->LoadShader(
00060         L"SimplePixelShader.cso",
00061         &m_pixelShader
00062         );
00063
00064     m_camera = ref new BasicCamera();
00065 }
00066
00067 void ExtrudedTextRenderer::CreateWindowSizeDependentResources(
00068     float dpi,
00069     ComPtr<ID3D11RenderTargetView> renderTargetView,
00070     ComPtr<ID3D11DepthStencilView> depthStencilView,
00071     Size renderTargetSize
00072     )
00073 {
00074     // Save the shared resources.
00075     m_dpi = dpi;
00076     m_d3dRenderTargetView = renderTargetView;
00077     m_d3dDepthStencilView = depthStencilView;
00078     m_renderTargetSize = renderTargetSize;
00079
00080     // update the 3D projection matrix
00081     m_camera->SetProjectionParameters(
00082         70.0f,                                                // use a 70-degree vertical field of view
00083         m_renderTargetSize.Width / m_renderTargetSize.Height, // specify the aspect ratio of the window
00084         0.01f,                                                // specify the nearest Z-distance at which to draw vertices
00085         10000.0f                                              // specify the farthest Z-distance at which to draw vertices
00086         );
00087
00088     // save the new projection matrix to the constant buffer data struct
00089     m_camera->GetProjectionMatrix(&m_constantBufferData.projection);
00090 }
00091
00092 void ExtrudedTextRenderer::DrawExtrudedText()
00093 {
00094     if (m_characters != nullptr && m_characters->Length() > 0)
00095     {
00096         // Get the outline of the current text as a geometry.
00097         ComPtr<ID2D1Geometry> textOutlineGeometry;
00098         GenerateTextOutline(&textOutlineGeometry);
00099
00100         // Extrude the geometry into a vector of SimpleVertex.
00101         std::vector<SimpleVertex> vertices;
00102         Extruder::ExtrudeGeometry(
00103             textOutlineGeometry.Get(),
00104             24.0f, // height
00105             &vertices
00106             );
00107
00108         m_indexCount = vertices.size();
00109
00110         // Convert the vector of SimpleVertex into an array of BasicVertex.
00111         std::unique_ptr<BasicVertex[]> basicVertices(new BasicVertex[m_indexCount]);
00112         for (unsigned int i = 0; i < m_indexCount; i++)
00113         {
00114             SimpleVertex v = vertices[i];
00115             basicVertices[i].pos = v.Pos;
00116             basicVertices[i].norm = v.Norm;
00117             // basicVertices[i].tex is not used
00118         }
00119
00120         // Build the index buffer. It's reversed so that handedness is correct.
00121         std::unique_ptr<unsigned short[]> indices(new unsigned short[m_indexCount]);
00122         for (unsigned int i = 0; i < m_indexCount; i++)
00123         {
00124             indices[i] = m_indexCount - i - 1;
00125         }
00126
00127         CreateBuffers(
00128             m_indexCount,
00129             m_indexCount,
00130             basicVertices.get(),
00131             indices.get(),
00132             &m_vertexBuffer,
00133             &m_indexBuffer
00134             );
00135
00136         uint stride = sizeof(BasicVertex);
00137         uint offset = 0;
00138
00139         // Bind the render targets.
00140         m_d3dContext->OMSetRenderTargets(
00141             1,
00142             m_d3dRenderTargetView.GetAddressOf(),
00143             m_d3dDepthStencilView.Get()
00144             );
00145
00146         m_d3dContext->ClearDepthStencilView(
00147             m_d3dDepthStencilView.Get(),
00148             D3D11_CLEAR_DEPTH,
00149             1.0f,
00150             0
00151             );
00152
00153         m_d3dContext->IASetInputLayout(m_inputLayout.Get());
00154
00155         // Set the vertex buffer.
00156         m_d3dContext->IASetVertexBuffers(
00157             0,                              // starting at the first vertex buffer slot
00158             1,                              // set one vertex buffer binding
00159             m_vertexBuffer.GetAddressOf(),
00160             &stride,                        // specify the size in bytes of a single vertex
00161             &offset                         // specify the base vertex in the buffer
00162             );
00163
00164         // Set the index buffer.
00165         m_d3dContext->IASetIndexBuffer(
00166             m_indexBuffer.Get(),
00167             DXGI_FORMAT_R16_UINT,   // unsigned short index format
00168             0                       // specify the base index in the buffer
00169             );
00170
00171         // Specify the way the vertex and index buffers define geometry.
00172         m_d3dContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
00173
00174         // Set the vertex shader stage state.
00175         m_d3dContext->VSSetShader(
00176             m_vertexShader.Get(),
00177             nullptr,                // don't use shader linkage
00178             0                       // don't use shader linkage
00179             );
00180
00181         // Set the constant buffer.
00182         m_d3dContext->VSSetConstantBuffers(
00183             0,                              // starting at the first constant buffer slot
00184             1,                              // set one constant buffer binding
00185             m_constantBuffer.GetAddressOf()
00186             );
00187
00188         // Create a viewport descriptor of the full window size. The
00189         // panning position is used to offset the rendering.
00190         CD3D11_VIEWPORT viewport(
00191             m_panPosition.X,
00192             m_panPosition.Y,
00193             m_renderTargetSize.Width,
00194             m_renderTargetSize.Height
00195             );
00196
00197         // Set the current viewport using the descriptor.
00198         m_d3dContext->RSSetViewports(1, &viewport);
00199
00200         // Set the pixel shader stage state.
00201         m_d3dContext->PSSetShader(
00202             m_pixelShader.Get(),
00203             nullptr,                // don't use shader linkage
00204             0                       // don't use shader linkage
00205             );
00206
00207         // Draw the vertices.
00208         m_d3dContext->DrawIndexed(
00209             m_indexCount,   // draw all created vertices
00210             0,              // starting with the first vertex
00211             0               // and the first index
00212             );
00213     }
00214 }
00215
00216 void ExtrudedTextRenderer::SetExtrudedText(String^ text)
00217 {
00218     m_characters = text;
00219     UpdateTextGeometry();
00220     UpdateModelAndCamera();
00221 }
00222
00223 void ExtrudedTextRenderer::Reset()
00224 {
00225     m_characters = nullptr;
00226     m_panPosition = Point(0.0f, 0.0f);
00227     m_zoom = 1.0f;
00228 }
00229
00230 void ExtrudedTextRenderer::ReleaseBufferResources()
00231 {
00232     m_d3dRenderTargetView = nullptr;
00233     m_d3dDepthStencilView = nullptr;
00234 }
00235
00236 void ExtrudedTextRenderer::OnManipulationDelta(
00237     Point position,
00238     Point positionDelta,
00239     float zoomDelta,
00240     float rotation
00241     )
00242 {
00243     // Update the transformation variables to reflect how the user is manipulating the text.
00244     m_panPosition.X += positionDelta.X;
00245     m_panPosition.Y += positionDelta.Y;
00246
00247     m_zoom *= zoomDelta;
00248     m_zoom = Clamp(m_zoom, 0.75, 2.0);
00249
00250     UpdateModelAndCamera();
00251 }
00252
00253 void ExtrudedTextRenderer::UpdateModelAndCamera()
00254 {
00255     // Update the model based on the current zoom level.
00256     float4x4 model = identity();
00257     model = mul(model, scale(m_zoom, m_zoom, m_zoom));
00258
00259     m_constantBufferData.model = model;
00260
00261     // Update the view matrix based on the camera position.
00262     // For this sample, the camera position is fixed.
00263     m_camera->SetViewParameters(
00264         float3(0, -20, -500.0f),
00265         float3(0, -20.0f, 0),
00266         float3(0, -1, 0)
00267         );
00268
00269     m_camera->GetViewMatrix(&m_constantBufferData.view);
00270
00271     // Update the constant buffer with the new data.
00272     m_d3dContext->UpdateSubresource(
00273         m_constantBuffer.Get(),
00274         0,
00275         nullptr,
00276         &m_constantBufferData,
00277         0,
00278         0
00279         );
00280 }
00281
00282 // Generates a layout object and a geometric outline
00283 // corresponding to the current text string and stores the
00284 // results in m_pTextLayout and m_pTextGeometry.
00285 void ExtrudedTextRenderer::UpdateTextGeometry()
00286 {
00287     if (m_characters != nullptr && m_characters->Length() > 0)
00288     {
00289         const float fontSize = 72.0f;
00290
00291         ComPtr<IDWriteTextFormat> textFormat;
00292         DX::ThrowIfFailed(
00293             m_dwriteFactory->CreateTextFormat(
00294                 L"Gabriola",
00295                 nullptr,
00296                 DWRITE_FONT_WEIGHT_EXTRA_BOLD,
00297                 DWRITE_FONT_STYLE_NORMAL,
00298                 DWRITE_FONT_STRETCH_NORMAL,
00299                 fontSize,
00300                 L"en-us",
00301                 &textFormat
00302                 )
00303             );
00304
00305         DX::ThrowIfFailed(
00306             m_dwriteFactory->CreateTextLayout(
00307                 m_characters->Data(),
00308                 m_characters->Length(),
00309                 textFormat.Get(),
00310                 0.0f,           // lineWidth (ignored because of NO_WRAP)
00311                 fontSize,       // lineHeight
00312                 &m_textLayout
00313                 )
00314             );
00315
00316         DX::ThrowIfFailed(
00317             m_textLayout->SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP)
00318             );
00319
00320         ComPtr<IDWriteTypography> typography;
00321         DX::ThrowIfFailed(
00322             m_dwriteFactory->CreateTypography(&typography)
00323             );
00324
00325         DWRITE_FONT_FEATURE fontFeature =
00326         {
00327             DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_7,
00328             1
00329         };
00330
00331         DX::ThrowIfFailed(
00332             typography->AddFontFeature(fontFeature)
00333             );
00334
00335         DWRITE_TEXT_RANGE textRange = {0, m_characters->Length()};
00336
00337         DX::ThrowIfFailed(
00338             m_textLayout->SetTypography(typography.Get(), textRange)
00339             );
00340
00341         // Create a custom text renderer, then pass the text through it via
00342         // the Draw method in order to compute the text's outline.
00343         ComPtr<OutlineRenderer> renderer;
00344         OutlineRenderer::CreateOutlineRenderer(m_d2dFactory.Get(), &renderer);
00345
00346         DX::ThrowIfFailed(
00347             m_textLayout->Draw(
00348                 nullptr,    // clientDrawingContext
00349                 renderer.Get(),
00350                 0.0f,       // originX
00351                 0.0f        // originY
00352                 )
00353             );
00354
00355         // Retrieve the ID2D1Geometry representing the text's outline.
00356         renderer->GetGeometry(&m_textGeometry);
00357     }
00358 }
00359
00360 // Returns a version of the text geometry that is horizontally
00361 // centered and vertically positioned so (0, 0) is on the baseline.
00362 void ExtrudedTextRenderer::GenerateTextOutline(ID2D1Geometry** ppGeometry)
00363 {
00364     DWRITE_LINE_METRICS lineMetrics;
00365     DWRITE_TEXT_METRICS textMetrics;
00366     UINT actualNumLines;
00367
00368     //
00369     // We're assuming here that the text doesn't wrap and doesn't contain
00370     // newlines.
00371     //
00372     DX::ThrowIfFailed(
00373         m_textLayout->GetLineMetrics(
00374             &lineMetrics,
00375             1,                  // maxLineCount
00376             &actualNumLines     // ignored
00377             )
00378         );
00379
00380     DX::ThrowIfFailed(
00381         m_textLayout->GetMetrics(&textMetrics)
00382         );
00383
00384     float offsetY = -lineMetrics.baseline;
00385     float offsetX = -textMetrics.widthIncludingTrailingWhitespace / 2;
00386
00387     ComPtr<ID2D1TransformedGeometry> pTransformedGeometry;
00388     DX::ThrowIfFailed(
00389         m_d2dFactory->CreateTransformedGeometry(
00390             m_textGeometry.Get(),
00391             D2D1::Matrix3x2F::Translation(offsetX, offsetY),
00392             &pTransformedGeometry
00393             )
00394         );
00395
00396     // Transfer reference.
00397     *ppGeometry = pTransformedGeometry.Get();
00398     (*ppGeometry)->AddRef();
00399 }
00400
00401 void ExtrudedTextRenderer::CreateBuffers(
00402     uint32 numVertices,
00403     uint32 numIndices,
00404     BasicVertex* vertexData,
00405     unsigned short* indexData,
00406     ID3D11Buffer** vertexBuffer,
00407     ID3D11Buffer** indexBuffer
00408     )
00409 {
00410     *vertexBuffer = nullptr;
00411     *indexBuffer = nullptr;
00412     ComPtr<ID3D11Buffer> vertexBufferInternal;
00413     ComPtr<ID3D11Buffer> indexBufferInternal;
00414
00415     D3D11_BUFFER_DESC VertexBufferDesc;
00416     VertexBufferDesc.ByteWidth = sizeof(BasicVertex) * numVertices;
00417     VertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
00418     VertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
00419     VertexBufferDesc.CPUAccessFlags = 0;
00420     VertexBufferDesc.MiscFlags = 0;
00421     VertexBufferDesc.StructureByteStride = 0;
00422
00423     D3D11_SUBRESOURCE_DATA VertexBufferData;
00424     VertexBufferData.pSysMem = vertexData;
00425     VertexBufferData.SysMemPitch = 0;
00426     VertexBufferData.SysMemSlicePitch = 0;
00427
00428     DX::ThrowIfFailed(
00429         m_d3dDevice->CreateBuffer(
00430             &VertexBufferDesc,
00431             &VertexBufferData,
00432             &vertexBufferInternal
00433             )
00434         );
00435
00436     D3D11_BUFFER_DESC IndexBufferDesc;
00437     IndexBufferDesc.ByteWidth = sizeof(unsigned short) * numIndices;
00438     IndexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
00439     IndexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
00440     IndexBufferDesc.CPUAccessFlags = 0;
00441     IndexBufferDesc.MiscFlags = 0;
00442     IndexBufferDesc.StructureByteStride = 0;
00443
00444     D3D11_SUBRESOURCE_DATA IndexBufferData;
00445     IndexBufferData.pSysMem = indexData;
00446     IndexBufferData.SysMemPitch = 0;
00447     IndexBufferData.SysMemSlicePitch = 0;
00448
00449     DX::ThrowIfFailed(
00450         m_d3dDevice->CreateBuffer(
00451             &IndexBufferDesc,
00452             &IndexBufferData,
00453             &indexBufferInternal
00454             )
00455         );
00456
00457     *vertexBuffer = vertexBufferInternal.Detach();
00458     *indexBuffer = indexBufferInternal.Detach();
00459 }
Generated on Sat Nov 23 2024 16:08:15 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Network information/C++/MainPage.xaml.h Source File

  • Network information

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:46 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application resources and localization/C++/Scenario4.xaml.cpp Source File

  • Application resources and localization

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::ApplicationResources;
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 using namespace Windows::ApplicationModel::Resources::Core;
00026
00027 Scenario4::Scenario4()
00028 {
00029     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 void Scenario4::OnNavigatedTo(NavigationEventArgs^ e)
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     rootPage = MainPage::Current;
00042   Scenario4TextBlock->Text = "";
00043 }
Generated on Sat Nov 23 2024 16:07:55 for Win8-Examples by doxygen 1.7.1


Win8-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
BBitMask | DDS_PIXELFORMAT
flags | DDS_PIXELFORMAT
fourCC | DDS_PIXELFORMAT
GBitMask | DDS_PIXELFORMAT
RBitMask | DDS_PIXELFORMAT
RGBBitCount | DDS_PIXELFORMAT
size | DDS_PIXELFORMAT
Generated on Sat Nov 23 2024 16:09:11 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Custom driver access/C++/app_cpp/common/LayoutAwarePage.cpp Source File

  • Custom driver access
  • app_cpp
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:31 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Print/C++/ScenarioOutput2.xaml.cpp Source File

  • Print

ScenarioOutput2.xaml.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 //
00009 // Scenario2Output.xaml.cpp
00010 // Implementation of the Scenario2Output class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioOutput2.xaml.h"
00015
00016 using namespace PrintSample;
00017
00018 ScenarioOutput2::ScenarioOutput2()
00019 {
00020     InitializeComponent();
00021 }
00022
00023 ScenarioOutput2::~ScenarioOutput2()
00024 {
00025 }
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: AtomPub/C++/App.xaml.cpp Source File

  • AtomPub

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectWrite custom text renderer/C++/SampleOverlay.h Source File

  • DirectWrite custom text renderer

SampleOverlay.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 "DirectXSample.h"
00011
00012 // This class is responsible for initializing and rendering the title overlay visible
00013 // at the top of the DirectX SDK samples.
00014 ref class SampleOverlay
00015 {
00016 internal:
00017     SampleOverlay();
00018
00019     void Initialize(
00020         _In_ ID2D1Device*         d2dDevice,
00021         _In_ ID2D1DeviceContext*  d2dContext,
00022         _In_ IWICImagingFactory*  wicFactory,
00023         _In_ IDWriteFactory*      dwriteFactory,
00024         _In_ Platform::String^    caption
00025         );
00026
00027     void ResetDirectXResources();
00028
00029     void UpdateForWindowSizeChange();
00030
00031     void Render();
00032
00033     float GetTitleHeightInDips();
00034
00035 private:
00036
00037     Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
00038     Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
00039     Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
00040     Microsoft::WRL::ComPtr<IDWriteFactory>          m_dwriteFactory;
00041     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_whiteBrush;
00042     Microsoft::WRL::ComPtr<ID2D1DrawingStateBlock>  m_stateBlock;
00043
00044     Microsoft::WRL::ComPtr<IWICImagingFactory>      m_wicFactory;
00045     Microsoft::WRL::ComPtr<ID2D1Bitmap>             m_logoBitmap;
00046     Microsoft::WRL::ComPtr<IDWriteTextLayout>       m_textLayout;
00047
00048     UINT                                            m_idIncrement;
00049     bool                                            m_drawOverlay;
00050     Platform::String^                               m_sampleName;
00051     float                                           m_padding;
00052     float                                           m_textVerticalOffset;
00053     D2D1_SIZE_F                                     m_logoSize;
00054     float                                           m_overlayWidth;
00055 };
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX postcard app/C++/PointSnapper.cpp Source File

  • DirectX postcard app

PointSnapper.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 "PointSnapper.h"
00010
00011 using namespace Microsoft::WRL;
00012
00013 // Utility class for snapping points and vertices to grid points.
00014 // This is useful when preparing and consuming tessellation data.
00015 // Grid-points are spaced at 1/16 intervals and aligned on integer
00016 // boundaries.
00017 void PointSnapper::SnapGeometry(ID2D1Geometry* pGeometry, ID2D1Geometry** ppGeometry)
00018 {
00019     ComPtr<ID2D1Factory> pFactory;
00020     pGeometry->GetFactory(&pFactory);
00021
00022     ComPtr<ID2D1PathGeometry> pPathGeometry;
00023     DX::ThrowIfFailed(
00024         pFactory->CreatePathGeometry(&pPathGeometry)
00025         );
00026
00027     ComPtr<ID2D1GeometrySink> pSink;
00028     DX::ThrowIfFailed(
00029         pPathGeometry->Open(&pSink)
00030         );
00031
00032     ComPtr<PointSnappingSink> snapper;
00033     PointSnappingSink::CreatePointSnappingSink(
00034         pSink.Get(),
00035         &snapper
00036         );
00037
00038     DX::ThrowIfFailed(
00039         pGeometry->Simplify(
00040             D2D1_GEOMETRY_SIMPLIFICATION_OPTION_LINES,
00041             nullptr, // world transform
00042             snapper.Get()
00043             )
00044         );
00045
00046     DX::ThrowIfFailed(
00047         snapper->Close()
00048         );
00049
00050     *ppGeometry = pPathGeometry.Get();
00051     (*ppGeometry)->AddRef();
00052 }
00053
00054 float PointSnapper::SnapCoordinate(float x)
00055 {
00056     return floorf((16.0f * x) + 0.5f) / 16.0f;
00057 }
00058
00059 D2D1_POINT_2F PointSnapper::SnapPoint(D2D1_POINT_2F pt)
00060 {
00061     return D2D1::Point2F(
00062         SnapCoordinate(pt.x),
00063         SnapCoordinate(pt.y)
00064         );
00065 }
00066
00067 float2 PointSnapper::SnapPoint(float2 pt)
00068 {
00069     return float2(
00070         SnapCoordinate(pt.x),
00071         SnapCoordinate(pt.y)
00072         );
00073 }
00074
00075 // Internal sink used to implement SnapGeometry.
00076 // Note: This class makes certain assumptions about its usage
00077 // (e.g. no Beziers), which is why it's a private class.
00078 void PointSnapper::PointSnappingSink::CreatePointSnappingSink(
00079     _In_ ID2D1SimplifiedGeometrySink* pSink,
00080     _Outptr_ PointSnapper::PointSnappingSink** ppPointSnappingSink
00081     )
00082 {
00083     *ppPointSnappingSink = new PointSnappingSink(pSink);
00084     (*ppPointSnappingSink)->AddRef();
00085 }
00086
00087 PointSnapper::PointSnappingSink::PointSnappingSink(_In_ ID2D1SimplifiedGeometrySink* pSink) :
00088     m_pSinkNoRef(pSink),
00089     m_ref(0)
00090 {
00091 }
00092
00093 void PointSnapper::PointSnappingSink::AddBeziers(const D2D1_BEZIER_SEGMENT* /*beziers*/, UINT /*beziersCount*/)
00094 {
00095     //
00096     // Users should be sure to flatten their geometries prior to passing
00097     // through a PointSnappingSink. It makes little sense snapping
00098     // the control points of a Bezier, as the vertices from the
00099     // flattened Bezier will almost certainly not be snapped.
00100     //
00101 }
00102
00103 void PointSnapper::PointSnappingSink::AddLines(const D2D1_POINT_2F* points, UINT pointsCount)
00104 {
00105     for (UINT i = 0; i < pointsCount; ++i)
00106     {
00107         D2D1_POINT_2F pt = SnapPoint(points[i]);
00108         m_pSinkNoRef->AddLines(&pt, 1);
00109     }
00110 }
00111
00112 void PointSnapper::PointSnappingSink::BeginFigure(D2D1_POINT_2F startPoint, D2D1_FIGURE_BEGIN figureBegin)
00113 {
00114     D2D1_POINT_2F pt = SnapPoint(startPoint);
00115     m_pSinkNoRef->BeginFigure(pt, figureBegin);
00116 }
00117
00118 void PointSnapper::PointSnappingSink::EndFigure(D2D1_FIGURE_END figureEnd)
00119 {
00120     m_pSinkNoRef->EndFigure(figureEnd);
00121 }
00122
00123 void PointSnapper::PointSnappingSink::SetFillMode(D2D1_FILL_MODE fillMode)
00124 {
00125     m_pSinkNoRef->SetFillMode(fillMode);
00126 }
00127
00128 void PointSnapper::PointSnappingSink::SetSegmentFlags(D2D1_PATH_SEGMENT vertexFlags)
00129 {
00130     m_pSinkNoRef->SetSegmentFlags(vertexFlags);
00131 }
00132
00133 HRESULT PointSnapper::PointSnappingSink::Close()
00134 {
00135     return m_pSinkNoRef->Close();
00136 }
00137
00138 //
00139 // IUnknown methods
00140 //
00141 // These use a basic, non-thread-safe implementation of the
00142 // standard reference-counting logic.
00143 //
00144 HRESULT PointSnapper::PointSnappingSink::QueryInterface(REFIID riid, _Outptr_ void** object)
00145 {
00146     *object = nullptr;
00147     return E_NOTIMPL;
00148 }
00149
00150 ULONG PointSnapper::PointSnappingSink::AddRef()
00151 {
00152     m_ref++;
00153     return m_ref;
00154 }
00155
00156 ULONG PointSnapper::PointSnappingSink::Release()
00157 {
00158     m_ref--;
00159
00160     if (m_ref == 0)
00161     {
00162         delete this;
00163         return 0;
00164     }
00165
00166     return m_ref;
00167 }
Generated on Sat Nov 23 2024 16:08:15 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

MarbleMaze Member List

This is the complete list of members for MarbleMaze, including all inherited members.
__pad0__ | MarbleMaze |
AddTouch(int id, Windows::Foundation::Point point) | MarbleMaze |
Checkpoints typedef | MarbleMaze | [private]
CreateDeviceResources() override | MarbleMaze | [virtual]
CreateWindowSizeDependentResources() override | MarbleMaze | [virtual]
ExtractTrianglesFromMesh(SDKMesh &mesh, const char *meshName, std::vector< Triangle > &triangles) | MarbleMaze | [private]
HandleDeviceLost() override | MarbleMaze | [virtual]
Initialize(Windows::UI::Core::CoreWindow^window, float dpi) override | MarbleMaze | [virtual]
KeyDown(Windows::System::VirtualKey key) | MarbleMaze |
KeyUp(Windows::System::VirtualKey key) | MarbleMaze |
LoadDeferredResources(bool delay, bool deviceOnly) | MarbleMaze |
LoadState() | MarbleMaze | [private]
m_accelerometer | MarbleMaze | [private]
m_audio | MarbleMaze | [private]
m_blendState | MarbleMaze | [private]
m_camera | MarbleMaze | [private]
m_checkpoints | MarbleMaze | [private]
m_checkpointText | MarbleMaze | [private]
m_collision | MarbleMaze | [private]
m_constantBuffer | MarbleMaze | [private]
m_currentCheckpoint | MarbleMaze | [private]
m_deferredResourcesReady | MarbleMaze | [private]
m_gameState | MarbleMaze | [private]
m_highScoreButton | MarbleMaze | [private]
m_highScoreTable | MarbleMaze | [private]
m_homeKeyActive | MarbleMaze | [private]
m_homeKeyPressed | MarbleMaze | [private]
m_inGameStopwatchTimer | MarbleMaze | [private]
m_inputLayout | MarbleMaze | [private]
m_lightStrength | MarbleMaze | [private]
m_loadScreen | MarbleMaze | [private]
m_marbleConstantBufferData | MarbleMaze | [private]
m_marbleMesh | MarbleMaze | [private]
m_mazeConstantBufferData | MarbleMaze | [private]
m_mazeMesh | MarbleMaze | [private]
m_newHighScore | MarbleMaze | [private]
m_pausedText | MarbleMaze | [private]
m_pauseKeyActive | MarbleMaze | [private]
m_pauseKeyPressed | MarbleMaze | [private]
m_persistentState | MarbleMaze | [private]
m_physics | MarbleMaze | [private]
m_pixelShader | MarbleMaze | [private]
m_pointQueue | MarbleMaze | [private]
m_preGameCountdownTimer | MarbleMaze | [private]
m_resetCamera | MarbleMaze | [private]
m_resetMarbleRotation | MarbleMaze | [private]
m_resultsText | MarbleMaze | [private]
m_sampleOverlay | MarbleMaze | [private]
m_sampler | MarbleMaze | [private]
m_startGameButton | MarbleMaze | [private]
m_targetLightStrength | MarbleMaze | [private]
m_touches | MarbleMaze | [private]
m_vertexShader | MarbleMaze | [private]
m_vertexStride | MarbleMaze | [private]
m_viewState | MarbleMaze | [private]
m_windowActive | MarbleMaze | [private]
OnFocusChange(bool active) | MarbleMaze |
OnResuming() | MarbleMaze |
OnSuspending() | MarbleMaze |
OnViewChange(Windows::UI::ViewManagement::ApplicationViewState state) | MarbleMaze |
PointQueue typedef | MarbleMaze | [private]
RemoveTouch(int id) | MarbleMaze |
Render() override | MarbleMaze | [virtual]
ResetCheckpoints() | MarbleMaze | [private]
SaveState() | MarbleMaze | [private]
SetGameState(GameState nextState) | MarbleMaze | [private]
TouchMap typedef | MarbleMaze | [private]
Update(float timeTotal, float timeDelta) | MarbleMaze |
UpdateCheckpoints() | MarbleMaze | [private]
UpdateTouch(int id, Windows::Foundation::Point point) | MarbleMaze |
Generated on Sat Nov 23 2024 16:09:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows account authorization/C++/App.xaml.h Source File

  • Windows account authorization

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::ProvisioningAgent::sealed Member List

This is the complete list of members for SDKSample::ProvisioningAgent::sealed, including all inherited members.
MediaType_SelectionChanged(Object^sender, SelectionChangedEventArgs^e) | SDKSample::ProvisioningAgent::sealed | [private]
MediaType_SelectionChanged(Object^sender, SelectionChangedEventArgs^e) | SDKSample::ProvisioningAgent::sealed | [private]
NetworkCostCategory_SelectionChanged(Object^sender, SelectionChangedEventArgs^e) | SDKSample::ProvisioningAgent::sealed | [private]
networkCostType | SDKSample::ProvisioningAgent::sealed | [private]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::ProvisioningAgent::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::ProvisioningAgent::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::ProvisioningAgent::sealed | [protected, virtual]
ParseErrorCode(String^errorCode) | SDKSample::ProvisioningAgent::sealed |
ParseResultXML(String^resultsXml) | SDKSample::ProvisioningAgent::sealed |
PrintExceptionCode(Exception^error) | SDKSample::ProvisioningAgent::sealed |
profileMediaType | SDKSample::ProvisioningAgent::sealed | [private]
ProvisionMno() | SDKSample::ProvisioningAgent::sealed |
ProvisionMno_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::ProvisioningAgent::sealed | [private]
rootPage | SDKSample::ProvisioningAgent::sealed | [private]
UpdateCost() | SDKSample::ProvisioningAgent::sealed |
UpdateCost_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::ProvisioningAgent::sealed | [private]
UpdateUsage() | SDKSample::ProvisioningAgent::sealed |
UpdateUsage_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::ProvisioningAgent::sealed | [private]
util | SDKSample::ProvisioningAgent::sealed | [private]
Util() | SDKSample::ProvisioningAgent::sealed |
Generated on Sat Nov 23 2024 16:09:52 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Store device app for camera/C#,C++/Wrapper/pch.h Source File

  • Windows Store device app for camera
  • C#,C++
  • Wrapper

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
00009 // pch.h : include file for standard system include files, or project specific
00010 // include files that are used frequently, but are changed infrequently
00011
00012 #pragma once
00013
00014 #include <winstring.h>
00015 #include <wrl\client.h>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DXGI offer and reclaim resources/C++/BasicLoader.cpp Source File

  • DXGI offer and reclaim resources

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 Sat Nov 23 2024 16:08:07 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/Cylinder.cpp Source File

  • XAML DirectX 3D shooting game

Cylinder.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 "Cylinder.h"
00010
00011 using namespace DirectX;
00012
00013 //----------------------------------------------------------------------
00014
00015 Cylinder::Cylinder()
00016 {
00017     Initialize(XMFLOAT3(0.0f, 0.0f, 0.0f), 1.0f, XMFLOAT3(0.0f, 0.0f, 1.0f));
00018 }
00019
00020 //----------------------------------------------------------------------
00021
00022 Cylinder::Cylinder(
00023     XMFLOAT3 position,
00024     float radius,
00025     XMFLOAT3 direction
00026     )
00027 {
00028     Initialize(position, radius, direction);
00029 }
00030
00031 //----------------------------------------------------------------------
00032
00033 void Cylinder::Initialize(
00034     XMFLOAT3 position,
00035     float radius,
00036     XMFLOAT3 direction
00037     )
00038 {
00039     m_position = position;
00040     m_radius = radius;
00041     m_length = XMVectorGetX(XMVector3Length(XMLoadFloat3(&direction)));
00042     XMStoreFloat3(&m_axis, XMVector3Normalize(XMLoadFloat3(&direction)));
00043
00044     XMVECTOR up = XMVectorSet(0.0f, 0.0f, 1.0f, 1.0f);
00045     float angle1 = XMVectorGetX(
00046         XMVector3AngleBetweenVectors(up, XMLoadFloat3(&m_axis))
00047         );
00048
00049     XMMATRIX mat1 = XMMatrixIdentity();
00050
00051     if ((angle1 * angle1) > 0.025)
00052     {
00053         XMVECTOR axis1 = XMVector3Cross(up, XMLoadFloat3(&m_axis));
00054
00055         mat1 = XMMatrixRotationAxis(axis1, angle1);
00056     }
00057     XMStoreFloat4x4(&m_rotationMatrix, mat1);
00058
00059     XMStoreFloat4x4(
00060         &m_modelMatrix,
00061         XMMatrixScaling(m_radius, m_radius, m_length) *
00062         mat1 *
00063         XMMatrixTranslation(m_position.x, m_position.y, m_position.z)
00064         );
00065 }
00066
00067 //--------------------------------------------------------------------------------
00068
00069 void Cylinder::UpdatePosition()
00070 {
00071     XMStoreFloat4x4(
00072         &m_modelMatrix,
00073         XMMatrixScaling(m_radius, m_radius, m_length) *
00074         XMLoadFloat4x4(&m_rotationMatrix) *
00075         XMMatrixTranslation(m_position.x, m_position.y, m_position.z)
00076         );
00077 }
00078
00079 //--------------------------------------------------------------------------------
00080
00081 bool Cylinder::IsTouching(
00082     XMFLOAT3 point,
00083     float radius,
00084     _Out_ XMFLOAT3 *contact,
00085     _Out_ XMFLOAT3 *normal
00086     )
00087 {
00088     XMVECTOR p0;
00089     XMVECTOR axis;
00090     XMVECTOR p1;
00091     XMVECTOR px;
00092
00093     // Determine if a point is within radius distance of the cylinder and
00094     // return the point of contact (projection of the point onto the cylinder).
00095
00096     p0 = XMLoadFloat3(&m_position);
00097     axis = XMLoadFloat3(&m_axis);
00098     p1 = p0 + axis * m_length;
00099     px = XMLoadFloat3(&point);
00100
00101     float dist = XMVectorGetX(
00102         XMVector3LinePointDistance(p0, p1, px)
00103         );
00104
00105     // Projection of the point onto the Vector.
00106     float dist2 = XMVectorGetX(
00107         XMVector3Dot(px - p0, axis)
00108         );
00109
00110     XMVECTOR ptOnVector =  p0 + dist2 * axis;
00111
00112     XMVECTOR normalVector = XMVector3Normalize(px - ptOnVector);
00113
00114     XMStoreFloat3(normal, normalVector);
00115     XMStoreFloat3(contact, ptOnVector + normalVector * m_radius);
00116
00117     if (dist < 0.0f)
00118     {
00119         dist *= -1.0f;
00120     }
00121
00122     if (dist < (radius + m_radius))
00123     {
00124         if (dist2 >= 0.0f && dist2 <= m_length)
00125         {
00126             return true;
00127         }
00128         else
00129         {
00130             return false;
00131         }
00132     }
00133     return false;
00134 }
00135
00136 //--------------------------------------------------------------------------------
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Bluetooth call control/C++/PhoneCall.xaml.cpp Source File

  • Bluetooth call control

PhoneCall.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 // PhoneCall.xaml.cpp
00013 // Implementation of the PhoneCall class
00014 //
00015
00016 #include "pch.h"
00017 #include "PhoneCall.xaml.h"
00018 #include "ppltasks.h"
00019
00020 using namespace SDKSample::CallControl;
00021
00022 using namespace Windows::UI;
00023 using namespace Windows::UI::Xaml;
00024 using namespace Windows::UI::Xaml::Controls;
00025 using namespace Windows::UI::Xaml::Data;
00026 using namespace Windows::UI::Xaml::Navigation;
00027 using namespace Windows::UI::Xaml::Media;
00028 using namespace Windows::System;
00029 using namespace Windows::Foundation;
00030 using namespace Windows::Media;
00031 using namespace Windows::Storage;
00032 using namespace Windows::Storage::Streams;
00033 using namespace Platform;
00034 using namespace Concurrency;
00035
00036 PhoneCall::PhoneCall()
00037 {
00038     InitializeComponent();
00039     _dispatcher = Window::Current->Dispatcher;
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 void PhoneCall::OnNavigatedTo(NavigationEventArgs^ e)
00048 {
00049     // Get a pointer to our main page.
00050     rootPage = MainPage::Current;
00051 }
00052
00053
00054 void PhoneCall::ButtonInitialize_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00055 {
00056     Button^ b = safe_cast<Button^>(sender);
00057     if (b != nullptr)
00058     {
00059         rootPage->NotifyUser("You clicked the " + b->Name + " button", NotifyType::StatusMessage);
00060     }
00061     try
00062     {
00063         CallControls = Windows::Media::Devices::CallControl::GetDefault();
00064         if (CallControls == nullptr)
00065         {
00066             CallControlError("Call Controls Initialization Failed.\tEnsure you have a bluetooth device and press the initialize the call control button.");
00067         }
00068         else
00069         {
00070             CallControls->AnswerRequested += ref new Devices::CallControlEventHandler(this, &PhoneCall::CallControls_AnswerRequested);
00071             CallControls->HangUpRequested += ref new Devices::CallControlEventHandler(this, &PhoneCall::CallControls_HangUpRequested);
00072             CallControls->AudioTransferRequested += ref new Devices::CallControlEventHandler(this, &PhoneCall::CallControls_AudioTransferRequested);
00073             CallControls->RedialRequested += ref new Devices::RedialRequestedEventHandler(this, &PhoneCall::CallControls_RedialRequested);
00074             CallControls->DialRequested += ref new Devices::DialRequestedEventHandler(this, &PhoneCall::CallControls_DialRequested);
00075             enableIncomingCallButton();
00076             disableInitializeButton();
00077
00078             CallControlStatus("Call Controls Initialized");
00079         }
00080     }
00081     catch (Exception^ Exception)
00082     {
00083         if (Exception->Message == "Element not found.\r\n")
00084         {
00085             CallControlError("Call Controls Initialization Failed.\tEnsure you have a bluetooth device and press the initialize the call control button.");
00086         }
00087         else
00088         {
00089             CallControlError(Exception->Message);
00090         }
00091     }
00092 }
00093
00094
00095 void PhoneCall::ButtonRing_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00096 {
00097     if (CallToken == 0 && CallControls != nullptr)
00098     {
00099         CallToken = CallControls->IndicateNewIncomingCall(true, "5555555555");
00100         CallControlStatus("Call Token: " + CallToken.ToString());
00101         disableIncomingCallButton();
00102     }
00103 }
00104
00105
00106 void PhoneCall::CallControlError(String^ ErrorText)
00107 {
00108   rootPage->NotifyUser(ErrorText, NotifyType::ErrorMessage);
00109 }
00110
00111 void PhoneCall::CallControlStatus(String^ StatusText)
00112 {
00113   rootPage->NotifyUser(StatusText, NotifyType::StatusMessage);
00114 }
00115
00116
00117 void PhoneCall::CallControls_AnswerRequested(Devices::CallControl^ sender)
00118 {
00119     if (CallToken != 0 && CallControls != nullptr)
00120     {
00121         _dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([=]()
00122         {
00123       CallControls->IndicateActiveCall(CallToken);
00124             SetAudioSource();
00125             PlayAudio();
00126             CallControlStatus("Answer requested: " + CallToken.ToString());
00127             enableHangUpButton();
00128         }
00129         , CallbackContext::Any));
00130     }
00131 }
00132
00133 void PhoneCall::ButtonHangUp_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00134 {
00135
00136     if (CallToken != 0 && CallControls != nullptr)
00137     {
00138         _dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([=]()
00139         {
00140             CallControls->EndCall(CallToken);
00141             CallToken = 0;
00142             PauseAudio();
00143             CallControlStatus("Hangup requested");
00144             disableHangUpButton();
00145         }
00146         , CallbackContext::Any));
00147
00148     enableIncomingCallButton();
00149     }
00150
00151 }
00152
00153 void PhoneCall::CallControls_HangUpRequested(Devices::CallControl^ sender)
00154 {
00155     if (CallToken != 0 && CallControls != nullptr)
00156     {
00157         _dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([=]()
00158         {
00159             CallControls->EndCall(CallToken);
00160             CallToken = 0;
00161             PauseAudio();
00162             CallControlStatus("Hangup requested");
00163             disableHangUpButton();
00164         }
00165         , CallbackContext::Any));
00166
00167         enableIncomingCallButton();
00168     }
00169 }
00170
00171 void PhoneCall::CallControls_AudioTransferRequested(Devices::CallControl^ sender)
00172 {
00173     CallControlStatus("Audio Transfer requested");
00174 }
00175
00176 void PhoneCall::CallControls_RedialRequested(Devices::CallControl^ sender, Devices::RedialRequestedEventArgs^ e)
00177 {
00178     if (CallToken != 0)
00179     {
00180         // Already in a call.
00181         CallControlStatus("Already in a call");
00182         return;
00183     }
00184     else
00185     {
00186         e->Handled();
00187         CallControlStatus("Redial requested");
00188     }
00189 }
00190
00191 void PhoneCall::enableIncomingCallButton() {
00192   _dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([=]()
00193   {
00194     ButtonRing->IsEnabled = true;
00195   }
00196   , CallbackContext::Any));
00197 }
00198
00199 void PhoneCall::disableIncomingCallButton() {
00200   _dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([=]()
00201   {
00202     ButtonRing->IsEnabled = false;
00203   }
00204   , CallbackContext::Any));
00205 }
00206
00207 void PhoneCall::enableInitializeButton() {
00208   _dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([=]()
00209   {
00210     ButtonInitialize->IsEnabled = true;
00211   }
00212   , CallbackContext::Any));
00213 }
00214
00215 void PhoneCall::disableInitializeButton() {
00216   _dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([=]()
00217   {
00218     ButtonInitialize->IsEnabled = false;
00219   }
00220   , CallbackContext::Any));
00221 }
00222
00223 void PhoneCall::enableHangUpButton() {
00224   _dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([=]()
00225   {
00226     ButtonHangUp->IsEnabled = true;
00227   }
00228   , CallbackContext::Any));
00229 }
00230
00231 void PhoneCall::disableHangUpButton() {
00232   _dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([=]()
00233   {
00234     ButtonHangUp->IsEnabled = false;
00235   }
00236   , CallbackContext::Any));
00237 }
00238
00239 void PhoneCall::CallControls_DialRequested(Devices::CallControl^ sender, Devices::DialRequestedEventArgs^ e)
00240 {
00241     if (CallToken != 0)
00242     {
00243         // Already in a call.
00244         CallControlStatus("Already in a call");
00245     }
00246 }
00247
00248 void PhoneCall::SetAudioSource()
00249 {
00250     MediaElement^ player = OutputMediaElement;
00251     create_task(Windows::ApplicationModel::Package::Current->InstalledLocation->GetFileAsync("folk_rock.mp3")).then([player](StorageFile^ file)
00252     {
00253             create_task(file->OpenAsync(FileAccessMode::Read)).then([file, player](IRandomAccessStream^ stream)
00254             {
00255                     player->SetSource(stream, file->ContentType);
00256             });
00257     });
00258 }
00259
00260 void PhoneCall::PlayAudio()
00261 {
00262     OutputMediaElement->Play();
00263 }
00264
00265 void PhoneCall::StopAudio()
00266 {
00267     OutputMediaElement->Stop();
00268 }
00269
00270 void PhoneCall::PauseAudio()
00271 {
00272     OutputMediaElement->Pause();
00273 }
00274
00275
Generated on Sat Nov 23 2024 16:07:58 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Bing Maps Trip Optimizer/C++,JavaScript/cpp/pch.h Source File

  • Bing Maps Trip Optimizer
  • C++,JavaScript
  • cpp

pch.h

Go to the documentation of this file.
00001 ﻿// pch.h : include file for standard system include files, or project specific
00002 // include files that are used frequently, but are changed infrequently
00003
00004 #pragma once
00005
00006 // TODO: reference additional headers your program requires here
00007 #include <collection.h>
00008 #include <concurrent_vector.h>
00009 #include <list>
00010 #include <msxml6.h>
00011 #include <ppltasks.h>
00012 #include <sstream>
00013 #include <strsafe.h>
00014 #include <wrl.h>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Display orientation/C++/common/suspensionmanager.cpp Source File

  • Display orientation
  • common

suspensionmanager.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 // SuspensionManager.cpp
00013 // Implementation of the SuspensionManager class
00014 //
00015
00016 #include "pch.h"
00017 #include "SuspensionManager.h"
00018
00019 #include <collection.h>
00020 #include <algorithm>
00021
00022 using namespace SDKSample::Common;
00023
00024 using namespace Concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::FileProperties;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Xaml;
00033 using namespace Windows::UI::Xaml::Controls;
00034 using namespace Windows::UI::Xaml::Interop;
00035
00036 namespace
00037 {
00038     Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
00039     String^ sessionStateFilename = "_sessionState.dat";
00040
00041     // Forward declarations for object object read / write support
00042     void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
00043     Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
00044 }
00045
00046 /// <summary>
00047 /// Provides access to global session state for the current session.  This state is serialized by
00048 /// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
00049 /// one of the following: boxed values including integers, floating-point singles and doubles,
00050 /// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
00051 /// subject to the same constraints.  Session state should be as compact as possible.
00052 /// </summary>
00053 IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
00054 {
00055     return _sessionState;
00056 }
00057
00058 /// <summary>
00059 /// Wrap a WeakReference as a reference object for use in a collection.
00060 /// </summary>
00061 private ref class WeakFrame sealed
00062 {
00063 private:
00064     WeakReference _frameReference;
00065
00066 internal:
00067     WeakFrame(Frame^ frame) { _frameReference = frame; }
00068     property Frame^ ResolvedFrame
00069     {
00070         Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
00071     };
00072 };
00073
00074 namespace
00075 {
00076     std::vector<WeakFrame^> _registeredFrames;
00077     DependencyProperty^ FrameSessionStateKeyProperty =
00078         DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
00079         TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
00080     DependencyProperty^ FrameSessionStateProperty =
00081         DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
00082         TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
00083 }
00084
00085 /// <summary>
00086 /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00087 /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00088 /// immediately after creation if they will participate in session state management.  Upon
00089 /// registration if state has already been restored for the specified key
00090 /// the navigation history will immediately be restored.  Subsequent invocations of
00091 /// <see cref="RestoreAsync(String)"/> will also restore navigation history.
00092 /// </summary>
00093 /// <param name="frame">An instance whose navigation history should be managed by
00094 /// <see cref="SuspensionManager"/></param>
00095 /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00096 /// store navigation-related information.</param>
00097 void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
00098 {
00099     if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
00100     {
00101         throw ref new FailureException("Frames can only be registered to one session state key");
00102     }
00103
00104     if (frame->GetValue(FrameSessionStateProperty) != nullptr)
00105     {
00106         throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
00107     }
00108
00109     // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00110     // navigation state should be managed
00111     frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00112     _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
00113
00114     // Check to see if navigation state can be restored
00115     RestoreFrameNavigationState(frame);
00116 }
00117
00118 /// <summary>
00119 /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00120 /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00121 /// removed.
00122 /// </summary>
00123 /// <param name="frame">An instance whose navigation history should no longer be
00124 /// managed.</param>
00125 void SuspensionManager::UnregisterFrame(Frame^ frame)
00126 {
00127     // Remove session state and remove the frame from the list of frames whose navigation
00128     // state will be saved (along with any weak references that are no longer reachable)
00129     auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00130     if (SessionState->HasKey(key)) SessionState->Remove(key);
00131     _registeredFrames.erase(
00132         std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
00133         {
00134             auto testFrame = e->ResolvedFrame;
00135             return testFrame == nullptr || testFrame == frame;
00136         }),
00137         _registeredFrames.end()
00138     );
00139 }
00140
00141 /// <summary>
00142 /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00143 /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00144 /// their session state saved and restored automatically as a part of the global
00145 /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00146 /// that can still be useful when restoring pages that have been discarded from the
00147 /// navigation cache.
00148 /// </summary>
00149 /// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
00150 /// page-specific state instead of working with frame session state directly.</remarks>
00151 /// <param name="frame">The instance for which session state is desired.</param>
00152 /// <returns>A collection of state subject to the same serialization mechanism as
00153 /// <see cref="SessionState"/>.</returns>
00154 IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
00155 {
00156     auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
00157
00158     if (frameState == nullptr)
00159     {
00160         auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
00161         if (frameSessionKey != nullptr)
00162         {
00163             // Registered frames reflect the corresponding session state
00164             if (!_sessionState->HasKey(frameSessionKey))
00165             {
00166                 _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
00167             }
00168             frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
00169         }
00170         else
00171         {
00172             // Frames that aren't registered have transient state
00173             frameState = ref new Map<String^, Object^>();
00174         }
00175         frame->SetValue(FrameSessionStateProperty, frameState);
00176     }
00177     return frameState;
00178 }
00179
00180 void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
00181 {
00182     auto frameState = SessionStateForFrame(frame);
00183     if (frameState->HasKey("Navigation"))
00184     {
00185         frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
00186     }
00187 }
00188
00189 void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
00190 {
00191     auto frameState = SessionStateForFrame(frame);
00192     frameState->Insert("Navigation", frame->GetNavigationState());
00193 }
00194
00195 /// <summary>
00196 /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00197 /// registered with <see cref="RegisterFrame"/> will also preserve their current
00198 /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00199 /// to save its state.
00200 /// </summary>
00201 /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00202 task<void> SuspensionManager::SaveAsync(void)
00203 {
00204     // Save the navigation state for all registered frames
00205     for (auto&& weakFrame : _registeredFrames)
00206     {
00207         auto frame = weakFrame->ResolvedFrame;
00208         if (frame != nullptr) SaveFrameNavigationState(frame);
00209     }
00210
00211     // Serialize the session state synchronously to avoid asynchronous access to shared
00212     // state
00213     auto sessionData = ref new InMemoryRandomAccessStream();
00214     auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
00215     WriteObject(sessionDataWriter, _sessionState);
00216
00217     // Once session state has been captured synchronously, begin the asynchronous process
00218     // of writing the result to disk
00219     return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
00220     {
00221         return sessionDataWriter->FlushAsync();
00222     }).then([=](bool flushSucceeded)
00223     {
00224         (void)flushSucceeded; // Unused parameter
00225         return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
00226             CreationCollisionOption::ReplaceExisting);
00227     }).then([=](StorageFile^ createdFile)
00228     {
00229         return createdFile->OpenAsync(FileAccessMode::ReadWrite);
00230     }).then([=](IRandomAccessStream^ newStream)
00231     {
00232         return RandomAccessStream::CopyAndCloseAsync(
00233             sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
00234     }).then([=](UINT64 copiedBytes)
00235     {
00236         (void)copiedBytes; // Unused parameter
00237         return;
00238     });
00239 }
00240
00241 /// <summary>
00242 /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00243 /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00244 /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00245 /// state.
00246 /// </summary>
00247 /// <param name="version">A version identifer compared to the session state to prevent
00248 /// incompatible versions of session state from reaching app code.  Saved state with a
00249 /// different version will be ignored, resulting in an empty <see cref="SessionState"/>
00250 /// dictionary.</param>
00251 /// <returns>An asynchronous task that reflects when session state has been read.  The
00252 /// content of <see cref="SessionState"/> should not be relied upon until this task
00253 /// completes.</returns>
00254 task<void> SuspensionManager::RestoreAsync(void)
00255 {
00256     _sessionState->Clear();
00257
00258     task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
00259     return getFileTask.then([=](StorageFile^ stateFile)
00260     {
00261         task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
00262         return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
00263         {
00264             auto size = unsigned int(stateFileProperties->Size);
00265             if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
00266             task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
00267             return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
00268             {
00269                 auto stateReader = ref new DataReader(stateFileStream);
00270                 return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
00271                 {
00272                     (void)bytesRead; // Unused parameter
00273                     // Deserialize the Session State
00274                     Object^ content = ReadObject(stateReader);
00275                     _sessionState = (Map<String^, Object^>^)content;
00276
00277                     // Restore any registered frames to their saved state
00278                     for (auto&& weakFrame : _registeredFrames)
00279                     {
00280                         auto frame = weakFrame->ResolvedFrame;
00281                         if (frame != nullptr)
00282                         {
00283                             frame->ClearValue(FrameSessionStateProperty);
00284                             RestoreFrameNavigationState(frame);
00285                         }
00286                     }
00287                 }, task_continuation_context::use_current());
00288             });
00289         });
00290     });
00291 }
00292
00293 #pragma region Object serialization for a known set of types
00294
00295 namespace
00296 {
00297     // Codes used for identifying serialized types
00298     enum StreamTypes {
00299         NullPtrType = 0,
00300
00301         // Supported IPropertyValue types
00302         UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
00303         SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
00304
00305         // Additional supported types
00306         StringToObjectMapType,
00307
00308         // Marker values used to ensure stream integrity
00309         MapEndMarker
00310     };
00311
00312     void WriteString(DataWriter^ writer, String^ string)
00313     {
00314         writer->WriteByte(StringType);
00315         writer->WriteUInt32(writer->MeasureString(string));
00316         writer->WriteString(string);
00317     }
00318
00319     void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
00320     {
00321         switch (propertyValue->Type)
00322         {
00323         case PropertyType::UInt8:
00324             writer->WriteByte(UInt8Type);
00325             writer->WriteByte(propertyValue->GetUInt8());
00326             return;
00327         case PropertyType::UInt16:
00328             writer->WriteByte(UInt16Type);
00329             writer->WriteUInt16(propertyValue->GetUInt16());
00330             return;
00331         case PropertyType::UInt32:
00332             writer->WriteByte(UInt32Type);
00333             writer->WriteUInt32(propertyValue->GetUInt32());
00334             return;
00335         case PropertyType::UInt64:
00336             writer->WriteByte(UInt64Type);
00337             writer->WriteUInt64(propertyValue->GetUInt64());
00338             return;
00339         case PropertyType::Int16:
00340             writer->WriteByte(Int16Type);
00341             writer->WriteUInt16(propertyValue->GetInt16());
00342             return;
00343         case PropertyType::Int32:
00344             writer->WriteByte(Int32Type);
00345             writer->WriteUInt32(propertyValue->GetInt32());
00346             return;
00347         case PropertyType::Int64:
00348             writer->WriteByte(Int64Type);
00349             writer->WriteUInt64(propertyValue->GetInt64());
00350             return;
00351         case PropertyType::Single:
00352             writer->WriteByte(SingleType);
00353             writer->WriteSingle(propertyValue->GetSingle());
00354             return;
00355         case PropertyType::Double:
00356             writer->WriteByte(DoubleType);
00357             writer->WriteDouble(propertyValue->GetDouble());
00358             return;
00359         case PropertyType::Boolean:
00360             writer->WriteByte(BooleanType);
00361             writer->WriteBoolean(propertyValue->GetBoolean());
00362             return;
00363         case PropertyType::Char16:
00364             writer->WriteByte(Char16Type);
00365             writer->WriteUInt16(propertyValue->GetChar16());
00366             return;
00367         case PropertyType::Guid:
00368             writer->WriteByte(GuidType);
00369             writer->WriteGuid(propertyValue->GetGuid());
00370             return;
00371         case PropertyType::String:
00372             WriteString(writer, propertyValue->GetString());
00373             return;
00374         default:
00375             throw ref new InvalidArgumentException("Unsupported property type");
00376         }
00377     }
00378
00379     void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
00380     {
00381         writer->WriteByte(StringToObjectMapType);
00382         writer->WriteUInt32(map->Size);
00383         for (auto&& pair : map)
00384         {
00385             WriteObject(writer, pair->Key);
00386             WriteObject(writer, pair->Value);
00387         }
00388         writer->WriteByte(MapEndMarker);
00389     }
00390
00391     void WriteObject(DataWriter^ writer, Object^ object)
00392     {
00393         if (object == nullptr)
00394         {
00395             writer->WriteByte(NullPtrType);
00396             return;
00397         }
00398
00399         auto propertyObject = dynamic_cast<IPropertyValue^>(object);
00400         if (propertyObject != nullptr)
00401         {
00402             WriteProperty(writer, propertyObject);
00403             return;
00404         }
00405
00406         auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
00407         if (mapObject != nullptr)
00408         {
00409             WriteStringToObjectMap(writer, mapObject);
00410             return;
00411         }
00412
00413         throw ref new InvalidArgumentException("Unsupported data type");
00414     }
00415
00416     String^ ReadString(DataReader^ reader)
00417     {
00418         int length = reader->ReadUInt32();
00419         String^ string = reader->ReadString(length);
00420         return string;
00421     }
00422
00423     IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
00424     {
00425         auto map = ref new Map<String^, Object^>();
00426         auto size = reader->ReadUInt32();
00427         for (unsigned int index = 0; index < size; index++)
00428         {
00429             auto key = safe_cast<String^>(ReadObject(reader));
00430             auto value = ReadObject(reader);
00431             map->Insert(key, value);
00432         }
00433         if (reader->ReadByte() != MapEndMarker)
00434         {
00435             throw ref new InvalidArgumentException("Invalid stream");
00436         }
00437         return map;
00438     }
00439
00440     Object^ ReadObject(DataReader^ reader)
00441     {
00442         auto type = reader->ReadByte();
00443         switch (type)
00444         {
00445         case NullPtrType:
00446             return nullptr;
00447         case UInt8Type:
00448             return reader->ReadByte();
00449         case UInt16Type:
00450             return reader->ReadUInt16();
00451         case UInt32Type:
00452             return reader->ReadUInt32();
00453         case UInt64Type:
00454             return reader->ReadUInt64();
00455         case Int16Type:
00456             return reader->ReadInt16();
00457         case Int32Type:
00458             return reader->ReadInt32();
00459         case Int64Type:
00460             return reader->ReadInt64();
00461         case SingleType:
00462             return reader->ReadSingle();
00463         case DoubleType:
00464             return reader->ReadDouble();
00465         case BooleanType:
00466             return reader->ReadBoolean();
00467         case Char16Type:
00468             return (char16_t)reader->ReadUInt16();
00469         case GuidType:
00470             return reader->ReadGuid();
00471         case StringType:
00472             return ReadString(reader);
00473         case StringToObjectMapType:
00474             return ReadStringToObjectMap(reader);
00475         default:
00476             throw ref new InvalidArgumentException("Unsupported property type");
00477         }
00478     }
00479 }
00480
00481 #pragma endregion
Generated on Sat Nov 23 2024 16:07:36 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Raw notifications/C++/MainAppSample/CppSamplesUtils.h Source File

  • Raw notifications
  • MainAppSample

CppSamplesUtils.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 <string>
00014 #include <sstream>
00015 #include <algorithm>
00016 #include <collection.h>
00017 #include <ppltasks.h>
00018
00019 namespace CppSamplesUtils
00020 {
00021     namespace Details
00022     {
00023         static Windows::Foundation::Collections::PropertySet^ sessionState = nullptr;
00024         static Platform::String^ sessionStateFileName = ref new Platform::String(L"_cppSessionState.xml");
00025
00026         concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file);
00027         concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file);
00028     }
00029
00030     class SuspensionManager
00031     {
00032     public:
00033         static Windows::Foundation::Collections::PropertySet^ SessionState()
00034         {
00035             using namespace Windows::Foundation::Collections;
00036             using namespace Details;
00037
00038             if (sessionState == nullptr)
00039             {
00040                 sessionState = ref new PropertySet();
00041             }
00042             return sessionState;
00043         }
00044
00045         static concurrency::task<void> StartRestoreTask()
00046         {
00047             using namespace Windows::Foundation;
00048             using namespace Windows::Storage;
00049             using namespace Windows::Storage::Streams;
00050             using namespace Details;
00051
00052             auto state = SessionState();
00053             state->Clear();
00054
00055             concurrency::task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFileName));
00056             return getFileTask.then([=](StorageFile^ file)
00057             {
00058                 return DeserializeSessionState(file);
00059             });
00060         }
00061
00062         static concurrency::task<void> StartSaveTask()
00063         {
00064             using namespace Windows::Foundation;
00065             using namespace Windows::Storage;
00066             using namespace Windows::Storage::Streams;
00067             using namespace Details;
00068
00069             concurrency::task<StorageFile^> createFileTask(ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFileName, CreationCollisionOption::ReplaceExisting));
00070             return createFileTask.then([=](StorageFile^ file)
00071             {
00072                 return SerializeSessionState(file);
00073             });
00074         }
00075     };
00076
00077     namespace Details
00078     {
00079         template <class T>
00080         inline Platform::String^ ToString(T value)
00081         {
00082             std::wstringstream wss;
00083             wss << value;
00084             return ref new Platform::String(wss.str().c_str());
00085         }
00086
00087         template <class T>
00088         inline T FromStringTo(Platform::String^ str)
00089         {
00090             std::wistringstream wiss(str->Data());
00091             T value = 0;
00092             wiss >> value;
00093             return value;
00094         }
00095
00096         template <class T>
00097         inline T FromHexStringTo(Platform::String^ str)
00098         {
00099             std::wistringstream wiss(str->Data());
00100             T value = 0;
00101             wiss >> std::hex >> value;
00102             return value;
00103         }
00104
00105         template <>
00106         inline Platform::Guid FromStringTo<Platform::Guid>(Platform::String^ str)
00107         {
00108             using namespace Platform;
00109
00110             if (str->Length() != 38)
00111             {
00112                 throw ref new InvalidArgumentException;
00113             }
00114             std::wstring ws(str->Data());
00115             if (ws[0] != L'{' || ws[37] != L'}' || ws[9] != L'-' || ws[14] != L'-' || ws[19] != L'-' || ws[24] != L'-')
00116             {
00117                 throw ref new InvalidArgumentException;
00118             }
00119             ws[0] = ws[37] = ws[9] = ws[14] = ws[19] =ws[24] = L' ';
00120             std::wistringstream wiss(ws);
00121             unsigned int a = 0;
00122             unsigned short b = 0;
00123             unsigned short c = 0;
00124             unsigned short d = 0;
00125             unsigned long long e = 0;
00126             static_assert(sizeof(d) == sizeof(char) * 2, "sizeof(d) == sizeof(char) * 2");
00127             static_assert(sizeof(e) == sizeof(char) * 8, "sizeof(e) == sizeof(char) * 8");
00128             wiss >> std::hex >> a >> b >> c >> d >> e;
00129             unsigned char *ad = (unsigned char*)(&d);
00130             unsigned char *ae = (unsigned char*)(&e);
00131             return Platform::Guid(a, b, c, ad[1], ad[0], ae[5], ae[4], ae[3], ae[2], ae[1], ae[0]);
00132         }
00133
00134         inline Platform::Object^ ConvertStringToObject(Windows::Foundation::PropertyType type, Platform::String^ str)
00135         {
00136             using namespace Platform;
00137             using namespace Windows::Foundation;
00138
00139             if (type == PropertyType::String)
00140             {
00141                 return PropertyValue::CreateString(str);
00142             }
00143
00144             switch (type)
00145             {
00146             case PropertyType::UInt8:
00147                 return PropertyValue::CreateUInt8((unsigned char)FromStringTo<unsigned short>(str));
00148             case PropertyType::UInt16:
00149                 return PropertyValue::CreateUInt16(FromStringTo<unsigned short>(str));
00150             case PropertyType::UInt32:
00151                 return PropertyValue::CreateUInt32(FromStringTo<unsigned int>(str));
00152             case PropertyType::UInt64:
00153                 return PropertyValue::CreateUInt64(FromStringTo<unsigned long long>(str));
00154             case PropertyType::Int16:
00155                 return PropertyValue::CreateInt16(FromStringTo<short>(str));
00156             case PropertyType::Int32:
00157                 return PropertyValue::CreateInt32(FromStringTo<int>(str));
00158             case PropertyType::Int64:
00159                 return PropertyValue::CreateInt64(FromStringTo<long long>(str));
00160             case PropertyType::Single:
00161                 return PropertyValue::CreateSingle(FromStringTo<float>(str));
00162             case PropertyType::Double:
00163                 return PropertyValue::CreateDouble(FromStringTo<double>(str));
00164             case PropertyType::Boolean:
00165                 return PropertyValue::CreateBoolean(FromStringTo<bool>(str));
00166             case PropertyType::Char16:
00167                 return PropertyValue::CreateChar16(str->Data()[0]);
00168             case PropertyType::Guid:
00169                 return PropertyValue::CreateGuid(FromStringTo<Guid>(str));
00170             default:
00171                 throw ref new Platform::InvalidCastException;
00172             }
00173         }
00174
00175         inline Platform::String^ ConvertPropertyValueToString(Windows::Foundation::IPropertyValue^ pv)
00176         {
00177             using namespace Platform;
00178             using namespace Windows::Foundation;
00179
00180             String^ valueString;
00181
00182             switch (pv->Type)
00183             {
00184             case PropertyType::String:
00185                 valueString = pv->GetString();
00186                 break;
00187
00188             case PropertyType::UInt8:
00189             case PropertyType::UInt16:
00190             case PropertyType::UInt32:
00191             case PropertyType::UInt64:
00192                 valueString = ToString(pv->GetUInt64());
00193                 break;
00194
00195             case PropertyType::Int16:
00196             case PropertyType::Int32:
00197             case PropertyType::Int64:
00198                 valueString = ToString(pv->GetInt64());
00199                 break;
00200
00201             case PropertyType::Single:
00202                 valueString = ToString(pv->GetSingle());
00203                 break;
00204
00205             case PropertyType::Double:
00206                 valueString = ToString(pv->GetDouble());
00207                 break;
00208
00209             case PropertyType::Boolean:
00210                 valueString = ToString(pv->GetBoolean());
00211                 break;
00212
00213             case PropertyType::Char16:
00214                 wchar_t buffer[2];
00215                 buffer[0] = pv->GetChar16();
00216                 buffer[1] = 0;
00217                 valueString = ref new String(buffer);
00218                 break;
00219
00220             case PropertyType::Guid:
00221                 valueString = pv->GetGuid().ToString();
00222                 break;
00223
00224             default:
00225                 throw ref new InvalidCastException;
00226             }
00227
00228             return valueString;
00229         }
00230
00231         inline Windows::Data::Xml::Dom::XmlElement^ CreateXmlElementFromObject(Windows::Data::Xml::Dom::XmlDocument^ doc, Platform::String^ name, Platform::Object^ value)
00232         {
00233             using namespace Platform;
00234             using namespace Windows::Foundation;
00235             using namespace Windows::Data::Xml::Dom;
00236
00237             XmlElement^ element = doc->CreateElement("item");
00238             element->SetAttribute("name", name);
00239
00240             IPropertyValue^ pv = (IPropertyValue^)value;
00241             element->SetAttribute("type", ToString((int)pv->Type));
00242             element->SetAttribute("value", ConvertPropertyValueToString(pv));
00243
00244             return element;
00245         }
00246
00247         inline concurrency::task<void> SerializeSessionState(Windows::Storage::IStorageFile^ file)
00248         {
00249             using namespace Windows::Data::Xml::Dom;
00250             using namespace Windows::Foundation;
00251             namespace WFC = Windows::Foundation::Collections;
00252             typedef Windows::Foundation::Collections::IKeyValuePair<Platform::String^, Platform::Object^> KVPair;
00253
00254             XmlDocument^ doc = ref new XmlDocument;
00255             doc->AppendChild(doc->CreateElement("items"));
00256             auto sessionState = SuspensionManager::SessionState();
00257
00258             std::for_each(WFC::begin(sessionState), WFC::end(sessionState), [doc](KVPair^ item)
00259             {
00260                 doc->DocumentElement->AppendChild(CreateXmlElementFromObject(doc, item->Key, item->Value));
00261             });
00262
00263             return concurrency::task<void>(doc->SaveToFileAsync(file));
00264         }
00265
00266         inline Windows::Foundation::PropertyType PropertyTypeFromString(Platform::String^ str)
00267         {
00268             int value = FromStringTo<int>(str);
00269             return (Windows::Foundation::PropertyType)value;
00270         }
00271
00272         inline concurrency::task<void> DeserializeSessionState(Windows::Storage::IStorageFile^ file)
00273         {
00274             using namespace Platform;
00275             using namespace Windows::Foundation;
00276             using namespace Windows::Data::Xml::Dom;
00277             namespace WFC = Windows::Foundation::Collections;
00278
00279             concurrency::task<XmlDocument^> loadFileTask(XmlDocument::LoadFromFileAsync(file));
00280             return loadFileTask.then([=](concurrency::task<XmlDocument^> docTask)
00281             {
00282                 try
00283                 {
00284                     auto doc = docTask.get();
00285                     auto items = doc->SelectNodes("/items/item");
00286                     auto sessionState = SuspensionManager::SessionState();
00287
00288                     std::for_each(WFC::begin(items), WFC::end(items), [sessionState](IXmlNode^ node)
00289                     {
00290                         auto element = (IXmlElement^)node;
00291                         String^ name = element->GetAttribute("name");
00292                         String^ value = element->GetAttribute("value");
00293                         PropertyType type = PropertyTypeFromString(element->GetAttribute("type"));
00294
00295                         Object^ valueObject = ConvertStringToObject(type, value);
00296                         sessionState->Insert(name, valueObject);
00297                     });
00298
00299                 }
00300                 catch (Platform::Exception^)
00301                 {
00302                     // Restoring is best effort
00303                 }
00304             });
00305         }
00306     } // namespace Details
00307 } // namespace CppSamplesUtils
Generated on Sat Nov 23 2024 16:07:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Raw notifications/C++/MainAppSample/ScenarioInput1.xaml.cpp Source File

  • Raw notifications
  • MainAppSample

ScenarioInput1.xaml.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 //
00009 // Scenario1Input.xaml.cpp
00010 // Implementation of the Scenario1Input class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioInput1.xaml.h"
00015
00016 using namespace RawNotificationsSampleCPP;
00017
00018 using namespace concurrency;
00019 using namespace Platform;
00020 using namespace Windows::ApplicationModel::Background;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Foundation::Collections;
00023 using namespace Windows::Graphics::Display;
00024 using namespace Windows::Networking::PushNotifications;
00025 using namespace Windows::Storage;
00026 using namespace Windows::UI::Core;
00027 using namespace Windows::UI::ViewManagement;
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 const wchar_t* SAMPLE_TASK_NAME = L"SampleBackgroundTask";
00037 const wchar_t* SAMPLE_TASK_ENTRY_POINT = L"BackgroundTasks.SampleBackgroundTask";
00038
00039 ScenarioInput1::ScenarioInput1()
00040 {
00041   InitializeComponent();
00042     _dispatcher = Window::Current->Dispatcher;
00043 }
00044
00045 ScenarioInput1::~ScenarioInput1()
00046 {
00047 }
00048
00049 void ScenarioInput1::OnNavigatedTo(NavigationEventArgs^ e)
00050 {
00051   // Get a pointer to our main page.
00052   rootPage = dynamic_cast<MainPage^>(e->Parameter);
00053   _frameLoadedToken = rootPage->OutputFrameLoaded += ref new EventHandler<Object^>(this, &ScenarioInput1::OutputFrameLoaded);
00054 }
00055
00056 void ScenarioInput1::OutputFrameLoaded(Object^ sender, Object^ e)
00057 {
00058   if (rootPage->Channel != nullptr)
00059   {
00060     OutputToTextBox(rootPage->Channel->Uri);
00061   }
00062 }
00063
00064 void ScenarioInput1::OnNavigatedFrom(NavigationEventArgs^ e)
00065 {
00066   rootPage->OutputFrameLoaded -= _frameLoadedToken;
00067 }
00068
00069 void ScenarioInput1::OutputToTextBox(String^ text)
00070 {
00071     // Find the output text box on the page
00072     auto outputFrame = dynamic_cast<Page^>(rootPage->OutputFrame->Content);
00073     auto textBox = dynamic_cast<TextBox^>(outputFrame->FindName("Scenario1ChannelOutput"));
00074
00075     // Write text
00076     textBox->Text = text;
00077 }
00078
00079 void ScenarioInput1::Scenario1Open_Click(Object^ sender, RoutedEventArgs^ e)
00080 {
00081     // Applications must have lock screen privileges in order to receive raw notifications
00082     create_task(BackgroundExecutionManager::RequestAccessAsync()).then([this] (BackgroundAccessStatus backgroundStatus)
00083   {
00084         // Make sure the user allowed privileges
00085         if (backgroundStatus != BackgroundAccessStatus::Denied && backgroundStatus != BackgroundAccessStatus::Unspecified)
00086         {
00087             OpenChannelAndRegisterTask();
00088         }
00089         else
00090         {
00091             // This event comes back in a background thread, so we need to move to the UI thread to access any UI elements
00092             rootPage->NotifyUser("Lock screen access is denied.", NotifyType::ErrorMessage);
00093         }
00094     });
00095 }
00096
00097 void ScenarioInput1::Scenario1Unregister_Click(Object^ sender, RoutedEventArgs^ e)
00098 {
00099   if (UnregisterBackgroundTask())
00100     {
00101         rootPage->NotifyUser("Task unregistered", NotifyType::StatusMessage);
00102     }
00103     else
00104     {
00105         rootPage->NotifyUser("No task is registered", NotifyType::ErrorMessage);
00106     }
00107 }
00108
00109 void ScenarioInput1::OpenChannelAndRegisterTask()
00110 {
00111   // Clear out the task just for the purpose of this sample
00112   UnregisterBackgroundTask();
00113
00114     // Open the channel. See the "Push and Polling Notifications" sample for more detail
00115
00116   if (rootPage->Channel == nullptr) {
00117     create_task(PushNotificationChannelManager::CreatePushNotificationChannelForApplicationAsync()).then([this] (task<PushNotificationChannel^> channelTask)
00118     {
00119       PushNotificationChannel^ newChannel;
00120       try
00121       {
00122         newChannel = channelTask.get();
00123       }
00124       catch (Exception^ ex)
00125       {
00126         rootPage->NotifyUser("Could not create a channel. Error: " + ex->Message, NotifyType::ErrorMessage);
00127       }
00128
00129       if (newChannel != nullptr)
00130       {
00131         // This event comes back in a background thread, so we need to move to the UI thread to access any UI elements
00132         OutputToTextBox(newChannel->Uri);
00133         rootPage->NotifyUser("Channel request succeeded!", NotifyType::StatusMessage);
00134
00135         rootPage->Channel = newChannel;
00136
00137         RegisterBackgroundTask();
00138         rootPage->NotifyUser("Task registered", NotifyType::StatusMessage);
00139       }
00140     });
00141   } else {
00142     RegisterBackgroundTask();
00143     rootPage->NotifyUser("Task registered", NotifyType::StatusMessage);
00144   }
00145 }
00146
00147 void ScenarioInput1::RegisterBackgroundTask()
00148 {
00149     auto taskBuilder = ref new BackgroundTaskBuilder();
00150     auto trigger = ref new PushNotificationTrigger();
00151     taskBuilder->SetTrigger(trigger);
00152
00153     // Background tasks must live in separate DLL, and be included in the package manifest
00154     // Also, make sure that your main application project includes a reference to this DLL
00155     taskBuilder->TaskEntryPoint = ref new String(SAMPLE_TASK_ENTRY_POINT);
00156     taskBuilder->Name = ref new String(SAMPLE_TASK_NAME);
00157
00158   BackgroundTaskRegistration^ task;
00159   try
00160   {
00161     task = taskBuilder->Register();
00162   }
00163   catch (Exception^ ex)
00164   {
00165     rootPage->NotifyUser("Registration error: " + ex->Message, NotifyType::ErrorMessage);
00166     UnregisterBackgroundTask();
00167   }
00168
00169   if (task != nullptr)
00170   {
00171     task->Completed += ref new BackgroundTaskCompletedEventHandler(this, &ScenarioInput1::BackgroundTaskCompleted);
00172   }
00173 }
00174
00175 bool ScenarioInput1::UnregisterBackgroundTask()
00176 {
00177   auto iter = BackgroundTaskRegistration::AllTasks->First();
00178   while (iter->HasCurrent)
00179   {
00180     auto task = iter->Current->Value;
00181     if (task->Name == ref new String(SAMPLE_TASK_NAME))
00182     {
00183       task->Unregister(true);
00184       return true;
00185     }
00186     iter->MoveNext();
00187   }
00188
00189   return false;
00190 }
00191
00192 void ScenarioInput1::BackgroundTaskCompleted(BackgroundTaskRegistration^ sender, BackgroundTaskCompletedEventArgs^ args)
00193 {
00194     try
00195     {
00196         // This sample assumes the payload is a string, but it can be of any type.
00197         auto payload = dynamic_cast<String^>(ApplicationData::Current->LocalSettings->Values->Lookup(ref new String(SAMPLE_TASK_NAME)));
00198         _dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, payload] () {
00199             rootPage->NotifyUser("Background work item triggered by raw notification with payload = " + payload + " has completed!", NotifyType::StatusMessage);
00200         }, CallbackContext::Any));
00201     }
00202     catch (Exception^ ex)
00203     {
00204         _dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this] () {
00205             rootPage->NotifyUser("Failed to retrieve background payload", NotifyType::ErrorMessage);
00206         }, CallbackContext::Any));
00207     }
00208 }
Generated on Sat Nov 23 2024 16:07:59 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Background task/C++/BackgroundTask/Constants.cpp Source File

  • Background task
  • BackgroundTask

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016 using namespace SDKSample::BackgroundTask;
00017
00018 String^ BackgroundTaskSample::SampleBackgroundTaskProgress = "";
00019 bool BackgroundTaskSample::SampleBackgroundTaskRegistered = false;
00020
00021 String^ BackgroundTaskSample::SampleBackgroundTaskWithConditionProgress = "";
00022 bool BackgroundTaskSample::SampleBackgroundTaskWithConditionRegistered = false;
00023
00024 String^ BackgroundTaskSample::ServicingCompleteTaskProgress = "";
00025 bool BackgroundTaskSample::ServicingCompleteTaskRegistered = false;
00026
00027 String^ BackgroundTaskSample::TimeTriggeredTaskProgress = "";
00028 bool BackgroundTaskSample::TimeTriggeredTaskRegistered = false;
00029
00030 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00031 {
00032     // The format here is the following:
00033     //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
00034     { "Sample background task in C++", "SDKSample.BackgroundTask.SampleBackgroundTask" },
00035     { "Sample background task in C++ with a condition", "SDKSample.BackgroundTask.SampleBackgroundTaskWithCondition" },
00036     { "Servicing complete background task in C++", "SDKSample.BackgroundTask.ServicingCompleteTask" },
00037     { "Sample background task with time trigger", "SDKSample.BackgroundTask.TimeTriggeredTask" }
00038 };
00039
00040 String^ BackgroundTaskSample::GetBackgroundTaskStatus(Platform::String^ name)
00041 {
00042     auto registered = false;
00043     if (name == SampleBackgroundTaskName)
00044     {
00045         registered = BackgroundTaskSample::SampleBackgroundTaskRegistered;
00046     }
00047     else if (name == SampleBackgroundTaskWithConditionName)
00048     {
00049         registered = BackgroundTaskSample::SampleBackgroundTaskWithConditionRegistered;
00050     }
00051     else if (name == ServicingCompleteTaskName)
00052     {
00053         registered = BackgroundTaskSample::ServicingCompleteTaskRegistered;
00054     }
00055     else if (name == TimeTriggeredTaskName)
00056     {
00057         registered = BackgroundTaskSample::TimeTriggeredTaskRegistered;
00058     }
00059
00060     String^ status = registered ? "Registered" : "Unregistered";
00061
00062     auto settings = ApplicationData::Current->LocalSettings->Values;
00063     if (settings->HasKey(name))
00064     {
00065         status += " - " + dynamic_cast<String^>(settings->Lookup(name));
00066     }
00067
00068     return status;
00069 }
00070
00071 //
00072 // Update the UI state for all registered background tasks.
00073 //
00074 void BackgroundTaskSample::InitializeBackgroundTaskStatus()
00075 {
00076     auto iter = BackgroundTaskRegistration::AllTasks->First();
00077     auto hascur = iter->HasCurrent;
00078     while (hascur)
00079     {
00080         auto cur = iter->Current->Value;
00081         UpdateBackgroundTaskStatus(cur->Name, true);
00082         hascur = iter->MoveNext();
00083     }
00084 }
00085
00086 BackgroundTaskRegistration^ BackgroundTaskSample::RegisterBackgroundTask(String^ taskEntryPoint, String^ name, IBackgroundTrigger^ trigger, IBackgroundCondition^ condition)
00087 {
00088     auto builder = ref new BackgroundTaskBuilder();
00089
00090     builder->Name = name;
00091     builder->TaskEntryPoint = taskEntryPoint;
00092     builder->SetTrigger(trigger);
00093
00094     if (condition != nullptr)
00095     {
00096         builder->AddCondition(condition);
00097     }
00098
00099     auto task = builder->Register();
00100
00101     UpdateBackgroundTaskStatus(name, true);
00102
00103     //
00104     // Remove previous completion status from local settings.
00105     //
00106     auto settings = ApplicationData::Current->LocalSettings->Values;
00107     settings->Remove(name);
00108
00109     return task;
00110 }
00111
00112 //
00113 // Registers a background task for the servicing-complete system event. This event occurs when the application is updated.
00114 //
00115 void BackgroundTaskSample::RegisterServicingCompleteBackgroundTask()
00116 {
00117     //
00118     // Check whether the servicing-complete background task is already registered.
00119     //
00120     auto iter = BackgroundTaskRegistration::AllTasks->First();
00121     auto hascur = iter->HasCurrent;
00122     while (hascur)
00123     {
00124         auto cur = iter->Current->Value;
00125
00126         if (cur->Name == ServicingCompleteTaskName)
00127         {
00128             //
00129             // The task is already registered.
00130             //
00131             return;
00132         }
00133
00134         hascur = iter->MoveNext();
00135     }
00136
00137     //
00138     // The servicing-complete background task is not already registered.
00139     //
00140     RegisterBackgroundTask(ServicingCompleteTaskEntryPoint,
00141                            ServicingCompleteTaskName,
00142                            ref new SystemTrigger(SystemTriggerType::ServicingComplete, false),
00143                            nullptr);
00144 }
00145
00146 //
00147 // Unregister background tasks with specified name.
00148 //
00149 void BackgroundTaskSample::UnregisterBackgroundTasks(String^ name)
00150 {
00151     //
00152     // Loop through all background tasks and unregister any that have a name that matches
00153     // the name passed into this function.
00154     //
00155     auto iter = BackgroundTaskRegistration::AllTasks->First();
00156     auto hascur = iter->HasCurrent;
00157     while (hascur)
00158     {
00159         auto cur = iter->Current->Value;
00160
00161         if(cur->Name == name)
00162         {
00163             cur->Unregister(true);
00164             UpdateBackgroundTaskStatus(name, false);
00165         }
00166
00167         hascur = iter->MoveNext();
00168     }
00169 }
00170
00171 void BackgroundTaskSample::UpdateBackgroundTaskStatus(Platform::String^ name, bool registered)
00172 {
00173     if (name == SampleBackgroundTaskName)
00174     {
00175         BackgroundTaskSample::SampleBackgroundTaskRegistered = registered;
00176     }
00177     else if (name == SampleBackgroundTaskWithConditionName)
00178     {
00179         BackgroundTaskSample::SampleBackgroundTaskWithConditionRegistered = registered;
00180     }
00181     else if (name == ServicingCompleteTaskName)
00182     {
00183         BackgroundTaskSample::ServicingCompleteTaskRegistered = registered;
00184     }
00185     else if (name == TimeTriggeredTaskName)
00186     {
00187         BackgroundTaskSample::TimeTriggeredTaskRegistered = registered;
00188     }
00189 }
00190
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX swap chain implementation/C++/SampleOverlay.cpp Source File

  • DirectX swap chain implementation

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 Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::UI::ViewManagement;
00015 using namespace Windows::Graphics::Display;
00016 using namespace D2D1;
00017
00018 SampleOverlay::SampleOverlay() :
00019     m_drawOverlay(true)
00020 {
00021 }
00022
00023 void SampleOverlay::Initialize(
00024     _In_ ID2D1Device*         d2dDevice,
00025     _In_ ID2D1DeviceContext*  d2dContext,
00026     _In_ IWICImagingFactory*  wicFactory,
00027     _In_ IDWriteFactory*      dwriteFactory,
00028     _In_ Platform::String^    caption
00029     )
00030 {
00031     m_wicFactory = wicFactory;
00032     m_dwriteFactory = dwriteFactory;
00033     m_sampleName = caption;
00034     m_d2dDevice = d2dDevice;
00035     m_d2dContext = d2dContext;
00036     m_padding = 3.0f;
00037     m_textVerticalOffset = 5.0f;
00038     m_logoSize = D2D1::SizeF(0.0f, 0.0f);
00039     m_overlayWidth = 0.0f;
00040
00041     ComPtr<ID2D1Factory> factory;
00042     d2dDevice->GetFactory(&factory);
00043
00044     DX::ThrowIfFailed(
00045         factory.As(&m_d2dFactory)
00046         );
00047
00048     ResetDirectXResources();
00049 }
00050
00051 void SampleOverlay::ResetDirectXResources()
00052 {
00053     DX::ThrowIfFailed(
00054         m_d2dContext->CreateSolidColorBrush(ColorF(ColorF::White), &m_whiteBrush)
00055         );
00056
00057     ComPtr<IWICBitmapDecoder> wicBitmapDecoder;
00058     DX::ThrowIfFailed(
00059         m_wicFactory->CreateDecoderFromFilename(
00060             L"windowsbig-sdk.png",
00061             nullptr,
00062             GENERIC_READ,
00063             WICDecodeMetadataCacheOnDemand,
00064             &wicBitmapDecoder
00065             )
00066         );
00067
00068     ComPtr<IWICBitmapFrameDecode> wicBitmapFrame;
00069     DX::ThrowIfFailed(
00070         wicBitmapDecoder->GetFrame(0, &wicBitmapFrame)
00071         );
00072
00073     ComPtr<IWICFormatConverter> wicFormatConverter;
00074     DX::ThrowIfFailed(
00075         m_wicFactory->CreateFormatConverter(&wicFormatConverter)
00076         );
00077
00078     DX::ThrowIfFailed(
00079         wicFormatConverter->Initialize(
00080             wicBitmapFrame.Get(),
00081             GUID_WICPixelFormat32bppPBGRA,
00082             WICBitmapDitherTypeNone,
00083             nullptr,
00084             0.0,
00085             WICBitmapPaletteTypeCustom  // the BGRA format has no palette so this value is ignored
00086             )
00087         );
00088
00089     double dpiX = 96.0f;
00090     double dpiY = 96.0f;
00091     DX::ThrowIfFailed(
00092         wicFormatConverter->GetResolution(&dpiX, &dpiY)
00093         );
00094
00095     DX::ThrowIfFailed(
00096         m_d2dContext->CreateBitmapFromWicBitmap(
00097             wicFormatConverter.Get(),
00098             BitmapProperties(
00099                 PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00100                 static_cast<float>(dpiX),
00101                 static_cast<float>(dpiY)
00102                 ),
00103             &m_logoBitmap
00104             )
00105         );
00106
00107     m_logoSize = m_logoBitmap->GetSize();
00108
00109     ComPtr<IDWriteTextFormat> nameTextFormat;
00110     DX::ThrowIfFailed(
00111         m_dwriteFactory->CreateTextFormat(
00112             L"Segoe UI",
00113             nullptr,
00114             DWRITE_FONT_WEIGHT_LIGHT,
00115             DWRITE_FONT_STYLE_NORMAL,
00116             DWRITE_FONT_STRETCH_NORMAL,
00117             36.0f,
00118             L"en-US",
00119             &nameTextFormat
00120             )
00121         );
00122
00123     DX::ThrowIfFailed(
00124         nameTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)
00125         );
00126
00127     DX::ThrowIfFailed(
00128         nameTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)
00129         );
00130
00131     DX::ThrowIfFailed(
00132         m_dwriteFactory->CreateTextLayout(
00133             m_sampleName->Data(),
00134             m_sampleName->Length(),
00135             nameTextFormat.Get(),
00136             4096.0f,
00137             4096.0f,
00138             &m_textLayout
00139             )
00140         );
00141
00142     DWRITE_TEXT_METRICS metrics = {0};
00143     DX::ThrowIfFailed(
00144         m_textLayout->GetMetrics(&metrics)
00145         );
00146
00147     m_overlayWidth = m_padding * 3.0f + m_logoSize.width + metrics.width;
00148
00149     DX::ThrowIfFailed(
00150         m_d2dFactory->CreateDrawingStateBlock(&m_stateBlock)
00151         );
00152
00153     UpdateForWindowSizeChange();
00154 }
00155
00156 void SampleOverlay::UpdateForWindowSizeChange()
00157 {
00158     if (CoreWindow::GetForCurrentThread()->Bounds.Width < m_overlayWidth)
00159     {
00160         m_drawOverlay = false;
00161     }
00162     else
00163     {
00164         m_drawOverlay = true;
00165     }
00166 }
00167
00168 void SampleOverlay::Render()
00169 {
00170     if (m_drawOverlay)
00171     {
00172         m_d2dContext->SaveDrawingState(m_stateBlock.Get());
00173
00174         m_d2dContext->BeginDraw();
00175         m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
00176         m_d2dContext->DrawBitmap(
00177             m_logoBitmap.Get(),
00178             D2D1::RectF(m_padding, 0.0f, m_logoSize.width + m_padding, m_logoSize.height)
00179             );
00180
00181         m_d2dContext->DrawTextLayout(
00182             Point2F(m_logoSize.width + 2.0f * m_padding, m_textVerticalOffset),
00183             m_textLayout.Get(),
00184             m_whiteBrush.Get()
00185             );
00186
00187         // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00188         // is lost. It will be handled during the next call to Present.
00189         HRESULT hr = m_d2dContext->EndDraw();
00190         if (hr != D2DERR_RECREATE_TARGET)
00191         {
00192             DX::ThrowIfFailed(hr);
00193         }
00194
00195         m_d2dContext->RestoreDrawingState(m_stateBlock.Get());
00196     }
00197 }
00198
00199 float SampleOverlay::GetTitleHeightInDips()
00200 {
00201     return m_logoSize.height;
00202 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Proximity/C++/MainPage.xaml.h Source File

  • Proximity

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace ProximityCPP
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051   [Windows::Foundation::Metadata::WebHostHidden]
00052     public ref class MainPage sealed
00053     {
00054     public:
00055         MainPage();
00056
00057         property bool AutoSizeInputSectionWhenSnapped
00058         {
00059             bool get()
00060             {
00061                 return autoSizeInputSectionWhenSnapped;
00062             }
00063
00064             void set(bool value)
00065             {
00066                 autoSizeInputSectionWhenSnapped = value;
00067             }
00068         }
00069
00070         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00071
00072         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00073         void LoadScenario(Platform::String^ scenarioName);
00074         void ClearLog(Windows::UI::Xaml::Controls::TextBlock^ textBlock);
00075         void LogInfo(Platform::String^ strMessage, Windows::UI::Xaml::Controls::TextBlock^ textBlock);
00076         bool IsLaunchedByTap();
00077         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00078         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00079
00080     private:
00081         ~MainPage();
00082         void SetFeatureName(Platform::String^ strFeature);
00083         void PopulateScenarios();
00084         void InvalidateSize();
00085         void InvalidateViewState();
00086
00087         Platform::Collections::Vector<Object^>^ ScenarioList;
00088         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00089         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00090         bool autoSizeInputSectionWhenSnapped;
00091
00092
00093     protected:
00094         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00095         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00096         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00097
00098     internal:
00099         static MainPage^ Current;
00100         bool   m_IsLaunchedByTap;
00101
00102     };
00103 }
Generated on Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Configure keys for media/C++/App.xaml.cpp Source File

  • Configure keys for media

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:26 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML user and custom controls/C++/App.xaml.h Source File

  • XAML user and custom controls

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Snap/C++/common/LayoutAwarePage.cpp Source File

  • Snap
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:33 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Accelerometer sensor/C++/Scenario1.xaml.cpp Source File

  • Accelerometer sensor

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::AccelerometerCPP;
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::Devices::Sensors;
00025 using namespace Windows::Foundation;
00026 using namespace Windows::UI::Core;
00027 using namespace Platform;
00028
00029 Scenario1::Scenario1() : rootPage(MainPage::Current), desiredReportInterval(0)
00030 {
00031     InitializeComponent();
00032
00033     accelerometer = Accelerometer::GetDefault();
00034     if (accelerometer != nullptr)
00035     {
00036         // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
00037         // This value will be used later to activate the sensor.
00038         uint32 minReportInterval = accelerometer->MinimumReportInterval;
00039         desiredReportInterval = minReportInterval > 16 ? minReportInterval : 16;
00040     }
00041     else
00042     {
00043         rootPage->NotifyUser("No accelerometer found", NotifyType::ErrorMessage);
00044     }
00045 }
00046
00047 /// <summary>
00048 /// Invoked when this page is about to be displayed in a Frame.
00049 /// </summary>
00050 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00051 /// property is typically used to configure the page.</param>
00052 void Scenario1::OnNavigatedTo(NavigationEventArgs^ e)
00053 {
00054     ScenarioEnableButton->IsEnabled = true;
00055     ScenarioDisableButton->IsEnabled = false;
00056 }
00057
00058 /// <summary>
00059 /// Invoked when this page is no longer displayed.
00060 /// </summary>
00061 /// <param name="e"></param>
00062 void Scenario1::OnNavigatedFrom(NavigationEventArgs^ e)
00063 {
00064     if (ScenarioDisableButton->IsEnabled)
00065     {
00066         Window::Current->VisibilityChanged::remove(visibilityToken);
00067         accelerometer->ReadingChanged::remove(readingToken);
00068
00069         // Restore the default report interval to release resources while the sensor is not in use
00070         accelerometer->ReportInterval = 0;
00071     }
00072 }
00073
00074 /// <summary>
00075 /// This is the event handler for VisibilityChanged events. You would register for these notifications
00076 /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00077 /// </summary>
00078 /// <param name="sender"></param>
00079 /// <param name="e">
00080 /// Event data that can be examined for the current visibility state.
00081 /// </param>
00082 void Scenario1::VisibilityChanged(Object^ sender, VisibilityChangedEventArgs^ e)
00083 {
00084     // The app should watch for VisibilityChanged events to disable and re-enable sensor input as appropriate
00085     if (ScenarioDisableButton->IsEnabled)
00086     {
00087         if (e->Visible)
00088         {
00089             // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00090             readingToken = accelerometer->ReadingChanged::add(ref new TypedEventHandler<Accelerometer^, AccelerometerReadingChangedEventArgs^>(this, &Scenario1::ReadingChanged));
00091         }
00092         else
00093         {
00094             // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00095             accelerometer->ReadingChanged::remove(readingToken);
00096         }
00097     }
00098 }
00099
00100 void Scenario1::ReadingChanged(Accelerometer^ sender, AccelerometerReadingChangedEventArgs^ e)
00101 {
00102     // We need to dispatch to the UI thread to display the output
00103     Dispatcher->RunAsync(
00104         CoreDispatcherPriority::Normal,
00105         ref new DispatchedHandler(
00106             [this, e]()
00107             {
00108                 AccelerometerReading^ reading = e->Reading;
00109
00110                 ScenarioOutput_X->Text = reading->AccelerationX.ToString();
00111                 ScenarioOutput_Y->Text = reading->AccelerationY.ToString();
00112                 ScenarioOutput_Z->Text = reading->AccelerationZ.ToString();
00113             },
00114             CallbackContext::Any
00115             )
00116         );
00117 }
00118
00119 void Scenario1::ScenarioEnable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00120 {
00121     if (accelerometer != nullptr)
00122     {
00123         // Establish the report interval
00124         accelerometer->ReportInterval = desiredReportInterval;
00125
00126         visibilityToken = Window::Current->VisibilityChanged::add(ref new WindowVisibilityChangedEventHandler(this, &Scenario1::VisibilityChanged));
00127         readingToken = accelerometer->ReadingChanged::add(ref new TypedEventHandler<Accelerometer^, AccelerometerReadingChangedEventArgs^>(this, &Scenario1::ReadingChanged));
00128
00129         ScenarioEnableButton->IsEnabled = false;
00130         ScenarioDisableButton->IsEnabled = true;
00131     }
00132     else
00133     {
00134         rootPage->NotifyUser("No accelerometer found", NotifyType::ErrorMessage);
00135     }
00136 }
00137
00138 void Scenario1::ScenarioDisable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00139 {
00140     Window::Current->VisibilityChanged::remove(visibilityToken);
00141     accelerometer->ReadingChanged::remove(readingToken);
00142
00143     // Restore the default report interval to release resources while the sensor is not in use
00144     accelerometer->ReportInterval = 0;
00145
00146     ScenarioEnableButton->IsEnabled = true;
00147     ScenarioDisableButton->IsEnabled = false;
00148 }
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D command list/C++/BasicTimer.cpp Source File

  • Direct2D command list

BasicTimer.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 "BasicTimer.h"
00010
00011 BasicTimer::BasicTimer()
00012 {
00013     if (!QueryPerformanceFrequency(&m_frequency))
00014     {
00015         throw ref new Platform::FailureException();
00016     }
00017     Reset();
00018 }
00019
00020 void BasicTimer::Reset()
00021 {
00022     Update();
00023     m_startTime = m_currentTime;
00024     m_total = 0.0f;
00025     m_delta = 1.0f / 60.0f;
00026 }
00027
00028 void BasicTimer::Update()
00029 {
00030     if (!QueryPerformanceCounter(&m_currentTime))
00031     {
00032         throw ref new Platform::FailureException();
00033     }
00034
00035     m_total = static_cast<float>(
00036         static_cast<double>(m_currentTime.QuadPart-m_startTime.QuadPart) /
00037         static_cast<double>(m_frequency.QuadPart)
00038         );
00039
00040     if (m_lastTime.QuadPart == m_startTime.QuadPart)
00041     {
00042         // If the timer was just reset, report a time delta equivalent to 60Hz frame time.
00043         m_delta = 1.0f / 60.0f;
00044     }
00045     else
00046     {
00047         m_delta = static_cast<float>(
00048             static_cast<double>(m_currentTime.QuadPart-m_lastTime.QuadPart) /
00049             static_cast<double>(m_frequency.QuadPart)
00050             );
00051     }
00052
00053     m_lastTime = m_currentTime;
00054 }
00055
00056 float BasicTimer::Total::get()
00057 {
00058     return m_total;
00059 }
00060
00061 float BasicTimer::Delta::get()
00062 {
00063     return m_delta;
00064 }
Generated on Sat Nov 23 2024 16:08:04 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File picker contracts/C++/Constants.h Source File

  • File picker contracts

Constants.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 namespace SDKSample
00015 {
00016     public enum class NotifyType
00017     {
00018         StatusMessage,
00019         ErrorMessage,
00020     };
00021
00022     public value struct Scenario
00023     {
00024         Platform::String^ Title;
00025         Platform::String^ ClassName;
00026     };
00027
00028     class Status
00029     {
00030     public:
00031         static Platform::String^ FileAdded;
00032         static Platform::String^ FileRemoved;
00033         static Platform::String^ FileAddFailed;
00034     };
00035
00036     public ref class PageSizeChangedEventArgs sealed
00037     {
00038     public:
00039         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00040         {
00041             Windows::UI::ViewManagement::ApplicationViewState get()
00042             {
00043                 return viewState;
00044             }
00045
00046             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00047             {
00048                 viewState = value;
00049             }
00050         }
00051
00052     private:
00053         Windows::UI::ViewManagement::ApplicationViewState viewState;
00054     };
00055 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Clipboard app/C++/common/LayoutAwarePage.cpp Source File

  • Clipboard app
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013
00014 using namespace Clipboard::Common;
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::UI::ViewManagement;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Interop;
00024
00025 LayoutAwarePage::LayoutAwarePage()
00026 {
00027     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00028     {
00029         return;
00030     }
00031
00032     // Create an empty default view model
00033     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00034
00035     // Map application view state to visual state for this page when it is part of the visual tree
00036     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::StartLayoutUpdates);
00037     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::StopLayoutUpdates);
00038 }
00039
00040 static TypeName _thisType = { LayoutAwarePage::typeid->FullName, TypeKind::Custom };
00041 static TypeName _observableMapType = { IObservableMap<Platform::String^, Object^>::typeid->FullName, TypeKind::Metadata };
00042 static Windows::UI::Xaml::DependencyProperty^ _defaultViewModelProperty = DependencyProperty::Register("DefaultViewModel", _observableMapType, _thisType, nullptr);
00043
00044 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00045 {
00046     return _defaultViewModelProperty;
00047 }
00048
00049 IObservableMap<Platform::String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00050 {
00051     return safe_cast<Windows::Foundation::Collections::IObservableMap<Platform::String^, Object^>^>(GetValue(DefaultViewModelProperty));
00052 }
00053
00054 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<Platform::String^, Object^>^ value)
00055 {
00056     SetValue(DefaultViewModelProperty, value);
00057 }
00058
00059 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00060 {
00061     // Use the navigation frame to return to the topmost page
00062     if (Frame != nullptr)
00063     {
00064         while (Frame->CanGoBack)
00065         {
00066             Frame->GoBack();
00067         }
00068     }
00069 }
00070
00071 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00072 {
00073     // Use the navigation frame to return to the previous page
00074     if ((Frame != nullptr) && (Frame->CanGoBack))
00075     {
00076         Frame->GoBack();
00077     }
00078 }
00079
00080 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00081 {
00082     auto control = safe_cast<Control^>(sender);
00083     if (_layoutAwareControls == nullptr)
00084     {
00085         // Start listening to view state changes when there are controls interested in updates
00086         _layoutAwareControls = ref new Vector<Control^>();
00087         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00088     }
00089
00090     _layoutAwareControls->Append(control);
00091
00092     // Set the initial visual state of the control
00093     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00094 }
00095
00096 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00097 {
00098     InvalidateVisualState();
00099 }
00100
00101 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00102 {
00103     auto control = safe_cast<Control^>(sender);
00104     unsigned int index;
00105     if ((_layoutAwareControls != nullptr) && (_layoutAwareControls->IndexOf(control, &index)))
00106     {
00107         _layoutAwareControls->RemoveAt(index);
00108         if (_layoutAwareControls->Size == 0)
00109         {
00110             // Stop listening to view state changes when no controls are interested in updates
00111             Window::Current->SizeChanged -= _windowSizeEventToken;
00112             _layoutAwareControls = nullptr;
00113         }
00114     }
00115 }
00116
00117 Platform::String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00118 {
00119     switch (viewState)
00120     {
00121     case ApplicationViewState::Filled:
00122         {
00123             return "Filled";
00124         }
00125
00126     case ApplicationViewState::Snapped:
00127         {
00128            return "Snapped";
00129         }
00130
00131     case ApplicationViewState::FullScreenPortrait:
00132         {
00133             return "FullScreenPortrait";
00134         }
00135
00136     case ApplicationViewState::FullScreenLandscape:
00137     default:
00138         {
00139             return "FullScreenLandscape";
00140         }
00141     }
00142 }
00143
00144 void LayoutAwarePage::InvalidateVisualState()
00145 {
00146     if (_layoutAwareControls != nullptr)
00147     {
00148         String^ visualState = DetermineVisualState(ApplicationView::Value);
00149         auto controlIterator = _layoutAwareControls->First();
00150         while (controlIterator->HasCurrent)
00151         {
00152             auto control = controlIterator->Current;
00153             VisualStateManager::GoToState(control, visualState, false);
00154             controlIterator->MoveNext();
00155         }
00156     }
00157 }
Generated on Sat Nov 23 2024 16:07:30 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Playback Manager Companion/C++/StreamTypeMedia.xaml.h Source File

  • Playback Manager Companion

StreamTypeMedia.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 // StreamTypeMedia.xaml.h
00013 // Declaration of the StreamTypeMedia class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "StreamTypeMedia.g.h"
00020 #include "MainPage.xaml.h"
00021 #include "Playback.h"
00022
00023 namespace SDKSample
00024 {
00025     namespace PlaybackManager2
00026     {
00027         /// <summary>
00028         /// An empty page that can be used on its own or navigated to within a Frame.
00029         /// </summary>
00030       public ref class StreamTypeMedia sealed
00031         {
00032         public:
00033             StreamTypeMedia();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039             void Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         Playback^ _playback;
00041       };
00042     }
00043 }
Generated on Sat Nov 23 2024 16:08:23 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

GameInfoOverlay Member List

This is the complete list of members for GameInfoOverlay, including all inherited members.
__pad0__ | GameInfoOverlay |
Bitmap() | GameInfoOverlay | [inline]
CreateDeviceIndependentResources(_In_ IDWriteFactory *dwriteFactory) | GameInfoOverlay |
CreateDeviceResources(_In_ ID2D1DeviceContext *d2dContext) | GameInfoOverlay |
CreateDpiDependentResources(float dpi) | GameInfoOverlay |
HideGameInfoOverlay() | GameInfoOverlay | [inline]
m_actionBrush | GameInfoOverlay | [private]
m_backgroundBrush | GameInfoOverlay | [private]
m_d2dContext | GameInfoOverlay | [private]
m_dpi | GameInfoOverlay | [private]
m_dwriteFactory | GameInfoOverlay | [private]
m_levelBitmap | GameInfoOverlay | [private]
m_textBrush | GameInfoOverlay | [private]
m_textFormatBody | GameInfoOverlay | [private]
m_textFormatTitle | GameInfoOverlay | [private]
m_visible | GameInfoOverlay | [private]
SetAction(GameInfoOverlayCommand action) | GameInfoOverlay |
SetGameLoading(uint32 dots) | GameInfoOverlay |
SetGameOver(bool win, int maxLevel, int hitCount, int shotCount, int highScore) | GameInfoOverlay |
SetGameStats(int maxLevel, int hitCount, int shotCount) | GameInfoOverlay |
SetLevelStart(int level, Platform::String^objective, float timeLimit, float bonusTime) | GameInfoOverlay |
SetPause() | GameInfoOverlay |
ShowGameInfoOverlay() | GameInfoOverlay | [inline]
Visible() | GameInfoOverlay | [inline]
Generated on Sat Nov 23 2024 16:09:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Animation metrics/C++/App.xaml.h Source File

  • Animation metrics

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Configure keys for media/C++/mediabuttons.xaml.h Source File

  • Configure keys for media

mediabuttons.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 // mediabuttons.xaml.h
00013 // Declaration of the mediabuttons class
00014 //
00015
00016 #pragma once
00017
00018
00019 #include "pch.h"
00020 #include "mediabuttons.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 using namespace Windows::Foundation;
00024 using namespace Windows::Storage;
00025 using namespace Platform;
00026 using namespace Concurrency;
00027
00028 namespace SDKSample
00029 {
00030     namespace MediaButtons
00031     {
00032       ref class Song sealed
00033       {
00034         public:
00035             Song(StorageFile^ file)
00036             {
00037                 fileInner = file;
00038             }
00039
00040
00041             property StorageFile^ File {
00042                 StorageFile^ get(){return fileInner;}
00043             }
00044
00045
00046             property String^ Artist {
00047                 String^ get(){return artistInner;}
00048           void set(String^ propArtist)
00049           {
00050             artistInner = propArtist;
00051           }
00052             }
00053
00054             property String^ Track {
00055                 String^ get(){return trackInner;}
00056           void set(String^ propTrack)
00057           {
00058             trackInner = propTrack;
00059           }
00060             }
00061
00062         private:
00063             StorageFile^ fileInner;
00064             String^ artistInner;
00065             String^ trackInner;
00066         };
00067
00068         /// <summary>
00069         /// An empty page that can be used on its own or navigated to within a Frame.
00070         /// </summary>
00071       [Windows::Foundation::Metadata::WebHostHidden]
00072         public ref class mediabuttons sealed
00073         {
00074         public:
00075             mediabuttons();
00076
00077         protected:
00078             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00079
00080       private:
00081             MainPage^ rootPage;
00082             void SelectFiles_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00083             void Play_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00084
00085         void SetMediaElementSourceAsync(Song^ song);
00086             void CreatePlaylist(Windows::Foundation::Collections::IVectorView<StorageFile^>^ files);
00087         void SetCurrentPlayingAsync(int playlistIndex);
00088             void DisplayStatus(Platform::String^ text);
00089             Platform::String^ GetTimeStampedMessage(Platform::String^ EventCalled);
00090
00091             void MediaElement_MediaEnded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00092             void MediaElement_MediaOpened(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00093             void MediaElement_CurrentStateChanged(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00094
00095             void PlayPause(Object^ sender, Object^ e);
00096             void Play(Object^ sender, Object^ e);
00097             void Stop(Object^ sender, Object^ e);
00098             void Pause(Object^ sender, Object^ e);
00099             void NextTrack(Object^ sender, Object^ e);
00100             void PrevTrack(Object^ sender, Object^ e);
00101             void FastForward(Object^ sender, Object^ e);
00102             void Rewind(Object^ sender, Object^ e);
00103             void ChannelUp(Object^ sender, Object^ e);
00104             void ChannelDown(Object^ sender, Object^ e);
00105             void Record(Object^ sender, Object^ e);
00106
00107         private:
00108             bool IsInitialized;
00109             Windows::UI::Core::CoreDispatcher^ _dispatcher;
00110
00111             bool _wasPlaying;
00112             int _currentSongIndex;
00113             int _playlistCount;
00114         EventRegistrationToken _nextTrackPressedEventToken;
00115         EventRegistrationToken _prevTrackPressedEventToken;
00116             Platform::Collections::Vector<Song^>^ _playlist;
00117
00118         };
00119     }
00120 }
Generated on Sat Nov 23 2024 16:07:59 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D magazine app/C++/Text.h Source File

  • Direct2D magazine app

Text.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 "Resource.h"
00011
00012 ref class Document;
00013
00014 //  <text> represents a block of formatted text, which can be used in multiple text frames.
00015 //  Text is a resource and as such it cannot draw. It allows child element to represent run
00016 //  of text such as the <bold> element.
00017 //
00018 //  Text accepts the following additional markup attributes:
00019 //      font-size = "<float>"
00020 //          Size of the font em height in design unit
00021 //      font-weight = "<100..999>"
00022 //          Weight of the font from 1 to 999. DirectWrite defines known weights for convenience in the
00023 //          DWRITE_FONT_WEIGHT enum.
00024 //      font-style = "<0|1|2>"
00025 //          Style of the font. DirectWrite defines known styles in DWRITE_FONT_STYLE enum.
00026 //      font-stretch = "<0..9>"
00027 //          Width of the font. DirectWrite defines known width in DWRITE_FONT_STRETCH enum.
00028 //      font-family = "<font family name>"
00029 //          Font family name as defined in the font's name table by the font author i.e. "Cambria" etc.
00030 //
00031 ref class Text : public Resource
00032 {
00033 internal:
00034     Text();
00035
00036     virtual bool Initialize(
00037         _In_ Document^ document,
00038         _In_ Windows::Data::Xml::Dom::XmlElement^ xmlElement
00039         ) override;
00040
00041     virtual bool AcceptChildNode(
00042         _In_ Document^ document,
00043         _In_ Windows::Data::Xml::Dom::IXmlNode^ childXmlNode
00044         ) override;
00045
00046     void GetTextLayout(_Outptr_ IDWriteTextLayout** textLayout);
00047
00048     inline size_t GetLength()
00049     {
00050         return m_textLength;
00051     }
00052
00053 private:
00054     Platform::String^ GetText(_In_ Windows::Data::Xml::Dom::IXmlNode^ xmlNode);
00055
00056     // DirectWrite text layout
00057     Microsoft::WRL::ComPtr<IDWriteTextLayout1> m_textLayout;
00058
00059     // Character offset to the current text run. Used during span addition
00060     size_t m_textPosition;
00061
00062     // Total character length of the text including all spans
00063     size_t m_textLength;
00064 };
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX postcard app/C++/PostcardRenderer.h Source File

  • DirectX postcard app

PostcardRenderer.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 "DirectXBase.h"
00012
00013 #include "ImageRenderer.h"
00014 #include "PaperRenderer.h"
00015 #include "ExtrudedTextRenderer.h"
00016 #include "InkRenderer.h"
00017
00018 // Enum that describes the current mode of the sample.
00019 enum class SampleMode
00020 {
00021     Ready,
00022     AddConstructionPaper,
00023     AddImage,
00024     AddEffect,
00025     AddText,
00026     AddSignature
00027 };
00028
00029 ref class PostcardRenderer : public DirectXBase
00030 {
00031 internal:
00032     PostcardRenderer();
00033
00034     virtual void CreateDeviceIndependentResources() override;
00035     virtual void CreateDeviceResources() override;
00036     virtual void CreateWindowSizeDependentResources() override;
00037     virtual void UpdateForWindowSizeChange() override;
00038     virtual void Render() override;
00039
00040     void OnPointerPressed(
00041         _In_ Platform::Object^ /* sender */,
00042         _In_ Windows::UI::Xaml::Input::PointerRoutedEventArgs^ args
00043         );
00044     void OnPointerReleased(
00045         _In_ Platform::Object^ /* sender */,
00046         _In_ Windows::UI::Xaml::Input::PointerRoutedEventArgs^ args
00047         );
00048     void OnPointerMoved(
00049         _In_ Platform::Object^ /* sender */,
00050         _In_ Windows::UI::Xaml::Input::PointerRoutedEventArgs^ args
00051         );
00052     void OnManipulationStarted(
00053         _In_ Platform::Object^ /* sender */,
00054         _In_ Windows::UI::Xaml::Input::ManipulationStartedRoutedEventArgs^ args
00055         );
00056     void OnManipulationCompleted(
00057         _In_ Platform::Object^ /* sender */,
00058         _In_ Windows::UI::Xaml::Input::ManipulationCompletedRoutedEventArgs^ args
00059         );
00060     void OnManipulationDelta(
00061         _In_ Platform::Object^ /* sender */,
00062         _In_ Windows::UI::Xaml::Input::ManipulationDeltaRoutedEventArgs^ args
00063         );
00064     void OnTapped(
00065         _In_ Platform::Object^ /* sender */,
00066         _In_ Windows::UI::Xaml::Input::TappedRoutedEventArgs^ args
00067         );
00068     void OnDataRequested(
00069         _In_ Windows::ApplicationModel::DataTransfer::DataTransferManager^ sender,
00070         _In_ Windows::ApplicationModel::DataTransfer::DataRequestedEventArgs^ args
00071         );
00072
00073     void UpdateForViewStateChanged(Windows::UI::ViewManagement::ApplicationViewState state);
00074     void SetSampleMode(SampleMode mode);
00075
00076     // Public image methods.
00077     void LoadImage(Windows::Storage::Streams::IRandomAccessStream^ randomAccessStream);
00078     void SetEffectIntensity(float value);
00079
00080     // Public paper methods.
00081     void AddPaper();
00082     void RemovePaper();
00083     void MovePaper();
00084     void StampPaper();
00085
00086     // Public text extrusion methods.
00087     void SetExtrudedText(Platform::String^ text);
00088
00089     // Public signature methods.
00090     void StartSignature();
00091     void ResetSignature();
00092
00093     // Public saving methods.
00094     void SavePostcard(Windows::Storage::Streams::IRandomAccessStream^ randomAccessStream, GUID wicFormat);
00095
00096     // Public reset methods.
00097     void ResetPostcard();
00098
00099 private:
00100     void SaveBitmapToStream(
00101         _In_ ID2D1Bitmap1* d2dBitmap,
00102         _In_ IWICImagingFactory2* wicFactory2,
00103         _In_ ID2D1DeviceContext* d2dContext,
00104         _In_ REFGUID wicFormat,
00105         _In_ IStream* stream
00106         );
00107
00108     SampleMode                                              m_sampleMode;
00109
00110     ImageRenderer^                                          m_imageRenderer;
00111     PaperRenderer^                                          m_paperRenderer;
00112     ExtrudedTextRenderer^                                   m_extrudedTextRenderer;
00113     InkRenderer^                                            m_inkRenderer;
00114
00115     Windows::UI::Xaml::Controls::SwapChainBackgroundPanel^  m_swapChainPanel;
00116     Windows::UI::ViewManagement::ApplicationViewState       m_windowState;
00117 };
Generated on Sat Nov 23 2024 16:08:15 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/CartoonEffect/AmpCartoon.h Source File

  • Hilo C++
  • CartoonEffect

AmpCartoon.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
00009 struct AmpPixel;
00010
00011 void ApplyCartoonEffectAmp(AmpPixel* sourcePixels,
00012                            AmpPixel* destinationPixels,
00013                            unsigned int width,
00014                            unsigned int height,
00015                            unsigned int neighborWindow,
00016                            unsigned int phases,
00017                            concurrency::cancellation_token token);
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: HomeGroup app/C++/common/LayoutAwarePage.cpp Source File

  • HomeGroup app
  • common

LayoutAwarePage.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 "LayoutAwarePage.h"
00013 #include "SuspensionManager.h"
00014
00015 using namespace SDKSample::Common;
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::System;
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 Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 /// <summary>
00030 /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
00031 /// </summary>
00032 LayoutAwarePage::LayoutAwarePage()
00033 {
00034     if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
00035     {
00036         return;
00037     }
00038
00039     // Create an empty default view model
00040     DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
00041
00042     // When this page is part of the visual tree make two changes:
00043     // 1) Map application view state to visual state for the page
00044     // 2) Handle keyboard and mouse navigation requests
00045     Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
00046
00047     // Undo the same changes when the page is no longer visible
00048     Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
00049 }
00050
00051 static DependencyProperty^ _defaultViewModelProperty =
00052     DependencyProperty::Register("DefaultViewModel",
00053     TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
00054
00055 /// <summary>
00056 /// Identifies the <see cref="DefaultViewModel"/> dependency property.
00057 /// </summary>
00058 DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
00059 {
00060     return _defaultViewModelProperty;
00061 }
00062
00063 /// <summary>
00064 /// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00065 /// used as a trivial view model.
00066 /// </summary>
00067 IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
00068 {
00069     return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
00070 }
00071
00072 /// <summary>
00073 /// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
00074 /// used as a trivial view model.
00075 /// </summary>
00076 void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
00077 {
00078     SetValue(DefaultViewModelProperty, value);
00079 }
00080
00081 /// <summary>
00082 /// Invoked when the page is part of the visual tree
00083 /// </summary>
00084 /// <param name="sender">Instance that triggered the event.</param>
00085 /// <param name="e">Event data describing the conditions that led to the event.</param>
00086 void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00087 {
00088   this->StartLayoutUpdates(sender, e);
00089
00090   // Keyboard and mouse navigation only apply when occupying the entire window
00091   if (this->ActualHeight == Window::Current->Bounds.Height &&
00092     this->ActualWidth == Window::Current->Bounds.Width)
00093   {
00094     // Listen to the window directly so focus isn't required
00095     _acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
00096       ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
00097       &LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
00098     _pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
00099       ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
00100       &LayoutAwarePage::CoreWindow_PointerPressed);
00101     _navigationShortcutsRegistered = true;
00102   }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when the page is removed from visual tree
00107 /// </summary>
00108 /// <param name="sender">Instance that triggered the event.</param>
00109 /// <param name="e">Event data describing the conditions that led to the event.</param>
00110 void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112   if (_navigationShortcutsRegistered)
00113   {
00114     Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
00115     Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
00116     _navigationShortcutsRegistered = false;
00117   }
00118   StopLayoutUpdates(sender, e);
00119 }
00120
00121 #pragma region Navigation support
00122
00123 /// <summary>
00124 /// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
00125 /// until it reaches the top of the navigation stack.
00126 /// </summary>
00127 /// <param name="sender">Instance that triggered the event.</param>
00128 /// <param name="e">Event data describing the conditions that led to the event.</param>
00129 void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     (void) sender;  // Unused parameter
00132     (void) e; // Unused parameter
00133
00134     // Use the navigation frame to return to the topmost page
00135     if (Frame != nullptr)
00136     {
00137         while (Frame->CanGoBack)
00138         {
00139             Frame->GoBack();
00140         }
00141     }
00142 }
00143
00144 /// <summary>
00145 /// Invoked as an event handler to navigate backward in the navigation stack
00146 /// associated with this page's <see cref="Frame"/>.
00147 /// </summary>
00148 /// <param name="sender">Instance that triggered the event.</param>
00149 /// <param name="e">Event data describing the conditions that led to the event.</param>
00150 void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
00151 {
00152     (void) sender;  // Unused parameter
00153     (void) e; // Unused parameter
00154
00155     // Use the navigation frame to return to the previous page
00156     if (Frame != nullptr && Frame->CanGoBack)
00157     {
00158         Frame->GoBack();
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Invoked as an event handler to navigate forward in the navigation stack
00164 /// associated with this page's <see cref="Frame"/>.
00165 /// </summary>
00166 /// <param name="sender">Instance that triggered the event.</param>
00167 /// <param name="e">Event data describing the conditions that led to the event.</param>
00168 void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
00169 {
00170     (void) sender;  // Unused parameter
00171     (void) e; // Unused parameter
00172
00173     // Use the navigation frame to advance to the next page
00174     if (Frame != nullptr && Frame->CanGoForward)
00175     {
00176         Frame->GoForward();
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Invoked on every keystroke, including system keys such as Alt key combinations, when
00182 /// this page is active and occupies the entire window.  Used to detect keyboard navigation
00183 /// between pages even when the page itself doesn't have focus.
00184 /// </summary>
00185 /// <param name="sender">Instance that triggered the event.</param>
00186 /// <param name="args">Event data describing the conditions that led to the event.</param>
00187 void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
00188 {
00189     auto virtualKey = args->VirtualKey;
00190
00191     // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00192     // are pressed
00193     if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
00194         args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
00195         (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
00196         (int)virtualKey == 166 || (int)virtualKey == 167))
00197     {
00198         auto coreWindow = Window::Current->CoreWindow;
00199         auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
00200         bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
00201         bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
00202         bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
00203         bool noModifiers = !menuKey && !controlKey && !shiftKey;
00204         bool onlyAlt = menuKey && !controlKey && !shiftKey;
00205
00206         if (((int)virtualKey == 166 && noModifiers) ||
00207             (virtualKey == VirtualKey::Left && onlyAlt))
00208         {
00209             // When the previous key or Alt+Left are pressed navigate back
00210             args->Handled = true;
00211             GoBack(this, ref new RoutedEventArgs());
00212         }
00213         else if (((int)virtualKey == 167 && noModifiers) ||
00214             (virtualKey == VirtualKey::Right && onlyAlt))
00215         {
00216             // When the next key or Alt+Right are pressed navigate forward
00217             args->Handled = true;
00218             GoForward(this, ref new RoutedEventArgs());
00219         }
00220     }
00221 }
00222
00223 /// <summary>
00224 /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
00225 /// page is active and occupies the entire window.  Used to detect browser-style next and
00226 /// previous mouse button clicks to navigate between pages.
00227 /// </summary>
00228 /// <param name="sender">Instance that triggered the event.</param>
00229 /// <param name="args">Event data describing the conditions that led to the event.</param>
00230 void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00231 {
00232     auto properties = args->CurrentPoint->Properties;
00233
00234     // Ignore button chords with the left, right, and middle buttons
00235     if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
00236         properties->IsMiddleButtonPressed) return;
00237
00238     // If back or foward are pressed (but not both) navigate appropriately
00239     bool backPressed = properties->IsXButton1Pressed;
00240     bool forwardPressed = properties->IsXButton2Pressed;
00241     if (backPressed ^ forwardPressed)
00242     {
00243         args->Handled = true;
00244         if (backPressed) GoBack(this, ref new RoutedEventArgs());
00245         if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
00246     }
00247 }
00248
00249 #pragma endregion
00250
00251 #pragma region Visual state switching
00252
00253 /// <summary>
00254 /// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
00255 /// <see cref="Control"/> within the page, to indicate that the sender should start receiving
00256 /// visual state management changes that correspond to application view state changes.
00257 /// </summary>
00258 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00259 /// corresponding to view states.</param>
00260 /// <param name="e">Event data that describes how the request was made.</param>
00261 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00262 /// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
00263 /// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
00264 /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
00265 /// events.</remarks>
00266 /// <seealso cref="DetermineVisualState"/>
00267 /// <seealso cref="InvalidateVisualState"/>
00268 void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00269 {
00270     (void) e; // Unused parameter
00271
00272     auto control = safe_cast<Control^>(sender);
00273     if (_layoutAwareControls == nullptr)
00274     {
00275         // Start listening to view state changes when there are controls interested in updates
00276         _layoutAwareControls = ref new Vector<Control^>();
00277         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
00278
00279         // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
00280         _this = this;
00281     }
00282     _layoutAwareControls->Append(control);
00283
00284     // Set the initial visual state of the control
00285     VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
00286 }
00287
00288 void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00289 {
00290     (void) sender;  // Unused parameter
00291     (void) e; // Unused parameter
00292
00293     InvalidateVisualState();
00294 }
00295
00296 /// <summary>
00297 /// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
00298 /// <see cref="Control"/>, to indicate that the sender should start receiving visual state
00299 /// management changes that correspond to application view state changes.
00300 /// </summary>
00301 /// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
00302 /// corresponding to view states.</param>
00303 /// <param name="e">Event data that describes how the request was made.</param>
00304 /// <remarks>The current view state will immediately be used to set the corresponding visual state
00305 /// when layout updates are requested.</remarks>
00306 /// <seealso cref="StartLayoutUpdates"/>
00307 void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
00308 {
00309     (void) e; // Unused parameter
00310
00311     auto control = safe_cast<Control^>(sender);
00312     unsigned int index;
00313     if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
00314     {
00315         _layoutAwareControls->RemoveAt(index);
00316         if (_layoutAwareControls->Size == 0)
00317         {
00318             // Stop listening to view state changes when no controls are interested in updates
00319             Window::Current->SizeChanged -= _windowSizeEventToken;
00320             _layoutAwareControls = nullptr;
00321             // Last control has received the Unload notification.
00322             _this = nullptr;
00323         }
00324     }
00325 }
00326
00327 /// <summary>
00328 /// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
00329 /// within the page.  The default implementation uses the names of enum values.  Subclasses may
00330 /// override this method to control the mapping scheme used.
00331 /// </summary>
00332 /// <param name="viewState">View state for which a visual state is desired.</param>
00333 /// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
00334 /// <seealso cref="InvalidateVisualState"/>
00335 String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
00336 {
00337     switch (viewState)
00338     {
00339     case ApplicationViewState::Filled:
00340         return "Filled";
00341     case ApplicationViewState::Snapped:
00342         return "Snapped";
00343     case ApplicationViewState::FullScreenPortrait:
00344         return "FullScreenPortrait";
00345     case ApplicationViewState::FullScreenLandscape:
00346     default:
00347         return "FullScreenLandscape";
00348     }
00349 }
00350
00351 /// <summary>
00352 /// Updates all controls that are listening for visual state changes with the correct visual
00353 /// state.
00354 /// </summary>
00355 /// <remarks>
00356 /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
00357 /// signal that a different value may be returned even though the view state has not changed.
00358 /// </remarks>
00359 void LayoutAwarePage::InvalidateVisualState()
00360 {
00361     if (_layoutAwareControls != nullptr)
00362     {
00363         String^ visualState = DetermineVisualState(ApplicationView::Value);
00364         auto controlIterator = _layoutAwareControls->First();
00365         while (controlIterator->HasCurrent)
00366         {
00367             auto control = controlIterator->Current;
00368             VisualStateManager::GoToState(control, visualState, false);
00369             controlIterator->MoveNext();
00370         }
00371     }
00372 }
00373
00374 #pragma endregion
00375
00376 #pragma region Process lifetime management
00377
00378 /// <summary>
00379 /// Invoked when this page is about to be displayed in a Frame.
00380 /// </summary>
00381 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00382 /// property provides the group to be displayed.</param>
00383 void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
00384 {
00385     // Returning to a cached page through navigation shouldn't trigger state loading
00386     if (_pageKey != nullptr) return;
00387
00388     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00389     _pageKey = "Page-" + Frame->BackStackDepth;
00390
00391     if (e->NavigationMode == NavigationMode::New)
00392     {
00393         // Clear existing state for forward navigation when adding a new page to the
00394         // navigation stack
00395         auto nextPageKey = _pageKey;
00396         int nextPageIndex = Frame->BackStackDepth;
00397         while (frameState->HasKey(nextPageKey))
00398         {
00399             frameState->Remove(nextPageKey);
00400             nextPageIndex++;
00401             nextPageKey = "Page-" + nextPageIndex;
00402         }
00403
00404         // Pass the navigation parameter to the new page
00405         LoadState(e->Parameter, nullptr);
00406     }
00407     else
00408     {
00409         // Pass the navigation parameter and preserved page state to the page, using
00410         // the same strategy for loading suspended state and recreating pages discarded
00411         // from cache
00412         LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
00413     }
00414 }
00415
00416 /// <summary>
00417 /// Invoked when this page will no longer be displayed in a Frame.
00418 /// </summary>
00419 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00420 /// property provides the group to be displayed.</param>
00421 void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
00422 {
00423     auto frameState = SuspensionManager::SessionStateForFrame(Frame);
00424     auto pageState = ref new Map<String^, Object^>();
00425     SaveState(pageState);
00426     frameState->Insert(_pageKey, pageState);
00427 }
00428
00429 /// <summary>
00430 /// Populates the page with content passed during navigation.  Any saved state is also
00431 /// provided when recreating a page from a prior session.
00432 /// </summary>
00433 /// <param name="navigationParameter">The parameter value passed to
00434 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
00435 /// </param>
00436 /// <param name="pageState">A map of state preserved by this page during an earlier
00437 /// session.  This will be null the first time a page is visited.</param>
00438 void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00439 {
00440 }
00441
00442 /// <summary>
00443 /// Preserves state associated with this page in case the application is suspended or the
00444 /// page is discarded from the navigation cache.  Values must conform to the serialization
00445 /// requirements of <see cref="SuspensionManager.SessionState"/>.
00446 /// </summary>
00447 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00448 void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
00449 {
00450 }
00451
00452 #pragma endregion
Generated on Sat Nov 23 2024 16:07:31 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Transcoding media/C++/Custom.xaml.cpp Source File

  • Transcoding media

Custom.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 // Custom.xaml.cpp
00013 // Implementation of the Custom class
00014 //
00015
00016
00017 #include "pch.h"
00018 #include "Custom.xaml.h"
00019
00020 using namespace SDKSample::Transcode;
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::Storage::Streams;
00026 using namespace concurrency;
00027
00028 Custom::Custom()
00029 {
00030     InitializeComponent();
00031
00032     // Hook up the UI
00033     PickFileButton->Click += ref new RoutedEventHandler(this, &Custom::PickFile);
00034     TargetFormat->SelectionChanged += ref new SelectionChangedEventHandler(this, &Custom::OnTargetFormatChanged);
00035     Transcode->Click += ref new RoutedEventHandler(this, &Custom::TranscodeCustom);
00036     Cancel->Click += ref new RoutedEventHandler(this, &Custom::TranscodeCancel);
00037
00038     // Media Controls
00039     InputPlayButton->Click += ref new RoutedEventHandler(this, &Custom::InputPlayButton_Click);
00040     InputPauseButton->Click += ref new RoutedEventHandler(this, &Custom::InputPauseButton_Click);
00041     InputStopButton->Click += ref new RoutedEventHandler(this, &Custom::InputStopButton_Click);
00042     OutputPlayButton->Click += ref new RoutedEventHandler(this, &Custom::OutputPlayButton_Click);
00043     OutputPauseButton->Click += ref new RoutedEventHandler(this, &Custom::OutputPauseButton_Click);
00044     OutputStopButton->Click += ref new RoutedEventHandler(this, &Custom::OutputStopButton_Click);
00045
00046     // File is not selected, disable all buttons but PickFileButton
00047     DisableButtons();
00048     SetPickFileButton(true);
00049     SetCancelButton(false);
00050
00051     // Initialize Objects
00052     _Transcoder = ref new MediaTranscoder();
00053     _Profile = nullptr;
00054     _InputFile = nullptr;
00055     _OutputFile = nullptr;
00056     _OutputFileName = "TranscodeSampleOutput.mp4";
00057     _CTS = cancellation_token_source();
00058
00059     // Initialize UI with default settings
00060     MediaEncodingProfile^ defaultProfile = MediaEncodingProfile::CreateMp4(VideoEncodingQuality::Wvga);
00061     VideoW->Text = defaultProfile->Video->Width.ToString();
00062     VideoH->Text = defaultProfile->Video->Height.ToString();
00063     VideoBR->Text = defaultProfile->Video->Bitrate.ToString();
00064     VideoFR->Text = defaultProfile->Video->FrameRate->Numerator.ToString();
00065     AudioBPS->Text = defaultProfile->Audio->BitsPerSample.ToString();
00066     AudioCC->Text = defaultProfile->Audio->ChannelCount.ToString();
00067     AudioBR->Text = defaultProfile->Audio->Bitrate.ToString();
00068     AudioSR->Text = defaultProfile->Audio->SampleRate.ToString();
00069
00070     _UseMp4 = true;
00071 }
00072
00073 /// <summary>
00074 /// Invoked when this page is about to be displayed in a Frame.
00075 /// </summary>
00076 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00077 /// property is typically used to configure the page.</param>
00078 void Custom::OnNavigatedTo(NavigationEventArgs^ e)
00079 {
00080     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00081     // as NotifyUser()
00082     rootPage = MainPage::Current;
00083 }
00084
00085 void Custom::GetCustomProfile()
00086 {
00087     if(_UseMp4)
00088     {
00089         _Profile = MediaEncodingProfile::CreateMp4(VideoEncodingQuality::Wvga);
00090     }
00091     else
00092     {
00093         _Profile = MediaEncodingProfile::CreateWmv(VideoEncodingQuality::Wvga);
00094     }
00095
00096     // TryParse() is not available. Using _wtoi() with #include <stdlib.h>
00097     try
00098     {
00099         _Profile->Video->Width                    = _wtoi(VideoW->Text->Data());
00100         _Profile->Video->Height                   = _wtoi(VideoH->Text->Data());
00101         _Profile->Video->Bitrate                  = _wtoi(VideoBR->Text->Data());
00102         _Profile->Video->FrameRate->Numerator     = _wtoi(VideoFR->Text->Data());
00103         _Profile->Video->FrameRate->Denominator   = 1;
00104         _Profile->Audio->BitsPerSample            = _wtoi(AudioBPS->Text->Data());
00105         _Profile->Audio->ChannelCount             = _wtoi(AudioCC->Text->Data());
00106         _Profile->Audio->Bitrate                  = _wtoi(AudioBR->Text->Data());
00107         _Profile->Audio->SampleRate               = _wtoi(AudioSR->Text->Data());
00108     }
00109     catch (Exception^ exception)
00110     {
00111         TranscodeError(exception->Message);
00112     }
00113 }
00114
00115 void Custom::TranscodeCustom(Object^ sender, RoutedEventArgs^ e)
00116 {
00117     StopPlayers();
00118     DisableButtons();
00119     GetCustomProfile();
00120
00121     // Clear messages
00122     StatusMessage->Text = "";
00123
00124     try
00125     {
00126         if (_InputFile != nullptr)
00127         {
00128             auto videoLibrary = KnownFolders::VideosLibrary;
00129             create_task(videoLibrary->CreateFileAsync(_OutputFileName, CreationCollisionOption::GenerateUniqueName), _CTS.get_token()).then(
00130                 [this](StorageFile^ destinationFile)
00131             {
00132                 try
00133                 {
00134                     _OutputFile = destinationFile;
00135                     return _Transcoder->PrepareFileTranscodeAsync(_InputFile, _OutputFile, _Profile);
00136                 }
00137                 catch (Platform::Exception^ exception)
00138                 {
00139                     TranscodeError(exception->Message);
00140                 }
00141
00142                 cancel_current_task();
00143             }).then(
00144                 [this](PrepareTranscodeResult^ transcode)
00145             {
00146                 try
00147                 {
00148                     if(transcode->CanTranscode)
00149                     {
00150                         OutputMsg->Text = "";
00151                         SetCancelButton(true);
00152                         Windows::Foundation::IAsyncActionWithProgress<double>^ transcodeOp = transcode->TranscodeAsync();
00153
00154                         // Set Progress Callback
00155                         transcodeOp->Progress = ref new AsyncActionProgressHandler<double>(
00156                         [this](IAsyncActionWithProgress<double>^ asyncInfo, double percent){
00157                             TranscodeProgress(asyncInfo, percent);
00158                         }, Platform::CallbackContext::Same);
00159
00160                         return transcodeOp;
00161                     }
00162                     else
00163                     {
00164                         TranscodeFailure(transcode->FailureReason);
00165                     }
00166                 }
00167                 catch (Platform::Exception^ exception)
00168                 {
00169                     TranscodeError(exception->Message);
00170                 }
00171
00172                 cancel_current_task();
00173             }).then(
00174                 [this](task<void> transcodeTask)
00175             {
00176                 try
00177                 {
00178                     transcodeTask.get();
00179                     OutputMsg->Text = "Transcode Completed.";
00180                     OutputPath->Text = "Output (" + _OutputFile->Path + ")";
00181                     PlayFile(_OutputFile);
00182                 }
00183                 catch (task_canceled&)
00184                 {
00185                     OutputMsg->Foreground = ref new Windows::UI::Xaml::Media::SolidColorBrush(Windows::UI::Colors::Red);
00186                     OutputMsg->Text = "Transcode Cancelled.";
00187                 }
00188                 catch(Exception^ exception)
00189                 {
00190                     TranscodeError(exception->Message);
00191                 }
00192
00193                 EnableButtons();
00194                 SetCancelButton(false);
00195             });
00196         }
00197     }
00198     catch (Platform::Exception^ exception)
00199     {
00200         TranscodeError(exception->Message);
00201     }
00202 }
00203
00204 void Custom::TranscodeCancel(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00205 {
00206     try
00207     {
00208         _CTS.cancel();
00209         _CTS = cancellation_token_source();
00210
00211         if(_OutputFile != nullptr)
00212         {
00213             create_task(_OutputFile->DeleteAsync()).then(
00214                 [this](task<void> deleteTask)
00215             {
00216                 try
00217                 {
00218                     deleteTask.get();
00219                 }
00220                 catch (Platform::Exception^ exception)
00221                 {
00222                     TranscodeError(exception->Message);
00223                 }
00224             });
00225         }
00226     }
00227     catch (Platform::Exception^ exception)
00228     {
00229         TranscodeError(exception->Message);
00230     }
00231 }
00232
00233 void Custom::TranscodeProgress(IAsyncActionWithProgress<double>^ asyncInfo, double percent)
00234 {
00235     OutputMsg->Foreground = ref new Windows::UI::Xaml::Media::SolidColorBrush(Windows::UI::Colors::Green);
00236     OutputMsg->Text = "Progress:  " + ((int)percent).ToString() + "%";
00237 }
00238
00239 void Custom::TranscodeError(Platform::String^ error)
00240 {
00241     StatusMessage->Foreground = ref new Windows::UI::Xaml::Media::SolidColorBrush(Windows::UI::Colors::Red);
00242     StatusMessage->Text = error;
00243     EnableButtons();
00244     SetCancelButton(false);
00245 }
00246
00247 void Custom::TranscodeFailure(TranscodeFailureReason reason)
00248 {
00249     try
00250     {
00251         if(_OutputFile != nullptr)
00252         {
00253             create_task(_OutputFile->DeleteAsync()).then(
00254                 [this](task<void> deleteTask)
00255             {
00256                 try
00257                 {
00258                     deleteTask.get();
00259                 }
00260                 catch (Platform::Exception^ exception)
00261                 {
00262                     TranscodeError(exception->Message);
00263                 }
00264             });
00265         }
00266     }
00267     catch(Platform::Exception^ exception)
00268     {
00269         TranscodeError(exception->Message);
00270     }
00271
00272     switch (reason)
00273     {
00274     case TranscodeFailureReason::CodecNotFound:
00275         TranscodeError("Codec not found.");
00276         break;
00277     case TranscodeFailureReason::InvalidProfile:
00278         TranscodeError("Invalid profile.");
00279         break;
00280     default:
00281         TranscodeError("Unknown failure.");
00282     }
00283 }
00284
00285 void Custom::SetCancelButton(bool isEnabled)
00286 {
00287     Cancel->IsEnabled = isEnabled;
00288 }
00289
00290 void Custom::EnableButtons()
00291 {
00292     PickFileButton->IsEnabled = true;
00293     TargetFormat->IsEnabled = true;
00294     Transcode->IsEnabled = true;
00295 }
00296
00297 void Custom::DisableButtons()
00298 {
00299     PickFileButton->IsEnabled = false;
00300     TargetFormat->IsEnabled = false;
00301     Transcode->IsEnabled = false;
00302 }
00303
00304 void Custom::PickFile(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00305 {
00306     try
00307     {
00308     Windows::UI::ViewManagement::ApplicationViewState currentState = Windows::UI::ViewManagement::ApplicationView::Value;
00309     if(currentState == Windows::UI::ViewManagement::ApplicationViewState::Snapped && !Windows::UI::ViewManagement::ApplicationView::TryUnsnap())
00310     {
00311       TranscodeError("Cannot pick files while application is in snapped view");
00312     }
00313     else
00314     {
00315       FileOpenPicker^ picker = ref new FileOpenPicker();
00316       picker->SuggestedStartLocation = PickerLocationId::VideosLibrary;
00317       picker->FileTypeFilter->Append(".wmv");
00318       picker->FileTypeFilter->Append(".mp4");
00319
00320       create_task(picker->PickSingleFileAsync()).then(
00321         [this](StorageFile^ inputFile)
00322       {
00323         try
00324         {
00325           _InputFile = inputFile;
00326
00327           if(_InputFile != nullptr)
00328           {
00329             return inputFile->OpenAsync(FileAccessMode::Read);
00330           }
00331         }
00332         catch (Platform::Exception^ exception)
00333         {
00334           TranscodeError(exception->Message);
00335         }
00336
00337         cancel_current_task();
00338       }).then(
00339         [this](IRandomAccessStream^ inputStream)
00340       {
00341         try
00342         {
00343           InputVideo->SetSource(inputStream, _InputFile->ContentType);;
00344           InputVideo->Play();
00345
00346           //Enable buttons
00347           EnableButtons();
00348         }
00349         catch (Platform::Exception^ exception)
00350         {
00351           TranscodeError(exception->Message);
00352         }
00353       });
00354     }
00355     }
00356     catch(Exception^ exception)
00357     {
00358         TranscodeError(exception->Message);
00359     }
00360 }
00361
00362 void Custom::OnTargetFormatChanged(Object^ sender, SelectionChangedEventArgs^ e)
00363 {
00364     if (TargetFormat->SelectedIndex > 0)
00365     {
00366         _OutputFileName = "TranscodeSampleOutput.wmv";
00367         _UseMp4 = false;
00368     }
00369     else
00370     {
00371         _OutputFileName = "TranscodeSampleOutput.mp4";
00372         _UseMp4 = true;
00373     }
00374 }
00375
00376 void Custom::InputPlayButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00377 {
00378     if (InputVideo->DefaultPlaybackRate == 0)
00379     {
00380         InputVideo->DefaultPlaybackRate = 1.0;
00381         InputVideo->PlaybackRate = 1.0;
00382     }
00383
00384     InputVideo->Play();
00385 }
00386
00387 void Custom::InputStopButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00388 {
00389     InputVideo->Stop();
00390 }
00391
00392 void Custom::InputPauseButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00393 {
00394     InputVideo->Pause();
00395 }
00396
00397 void Custom::OutputPlayButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00398 {
00399     if (OutputVideo->DefaultPlaybackRate == 0)
00400     {
00401         OutputVideo->DefaultPlaybackRate = 1.0;
00402         OutputVideo->PlaybackRate = 1.0;
00403     }
00404
00405     OutputVideo->Play();
00406 }
00407
00408 void Custom::OutputStopButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00409 {
00410     OutputVideo->Stop();
00411 }
00412
00413 void Custom::OutputPauseButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00414 {
00415     OutputVideo->Pause();
00416 }
00417
00418 void Custom::SetPickFileButton(bool isEnabled)
00419 {
00420     PickFileButton->IsEnabled = isEnabled;
00421 }
00422
00423
00424 void Custom::StopPlayers()
00425 {
00426     if(InputVideo->CurrentState != Media::MediaElementState::Paused)
00427     {
00428         InputVideo->Pause();
00429     }
00430     if(OutputVideo->CurrentState != Media::MediaElementState::Paused)
00431     {
00432         OutputVideo->Pause();
00433     }
00434 }
00435
00436 void Custom::PlayFile(Windows::Storage::StorageFile^ MediaFile)
00437 {
00438     try
00439     {
00440         create_task(MediaFile->OpenAsync(FileAccessMode::Read)).then(
00441             [&, this, MediaFile](IRandomAccessStream^ outputStream)
00442         {
00443             try
00444             {
00445                 OutputVideo->SetSource(outputStream, MediaFile->ContentType);
00446                 OutputVideo->Play();
00447             }
00448             catch (Platform::Exception^ exception)
00449             {
00450                 TranscodeError(exception->Message);
00451             }
00452         });
00453     }
00454     catch (Exception^ exception)
00455     {
00456         TranscodeError(exception->Message);
00457     }
00458 }
Generated on Sat Nov 23 2024 16:08:25 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D-Direct2D interop/C++/pch.h Source File

  • Direct3D-Direct2D interop

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 <d3d11_1.h>
00012 #include <d2d1_1.h>
00013 #include <d2d1effects.h>
00014 #include <dwrite_1.h>
00015 #include <wincodec.h>
00016 #include <agile.h>
00017 #include "BasicMath.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Raw notifications/C++/SampleBackgroundTask/pch.cpp Source File

  • Raw notifications
  • SampleBackgroundTask

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Scheduled notifications/C#,C++/ScenarioOutput2.xaml.h Source File

  • Scheduled notifications
  • C#,C++

ScenarioOutput2.xaml.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 //
00009 // Scenario2Output.xaml.h
00010 // Declaration of the Scenario2Output class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioOutput2.g.h"
00017 #include "MainPage.g.h"
00018
00019 namespace ScheduledNotificationsSampleCPP
00020 {
00021   [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class ScenarioOutput2 sealed
00023     {
00024     public:
00025         ScenarioOutput2();
00026   private:
00027     ~ScenarioOutput2();
00028     };
00029 }
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Removable storage/C++/MainPage.xaml.h Source File

  • Removable storage

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: File and folder thumbnail/C++/Scenario5.xaml.h Source File

  • File and folder thumbnail

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 SDKSample
00023 {
00024     namespace FileThumbnails
00025     {
00026         [Windows::Foundation::Metadata::WebHostHidden]
00027         public ref class Scenario5 sealed
00028         {
00029         public:
00030             Scenario5();
00031
00032         protected:
00033             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00034
00035         private:
00036             MainPage^ rootPage;
00037
00038             void GetThumbnailButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039         };
00040     }
00041 }
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Web authentication broker/C++/common/LayoutAwarePage.h Source File

  • Web authentication broker
  • common

LayoutAwarePage.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 namespace SDKSample
00016 {
00017     namespace Common
00018     {
00019         /// <summary>
00020         /// Typical implementation of Page that provides several important conveniences:
00021         /// <list type="bullet">
00022         /// <item>
00023         /// <description>Application view state to visual state mapping</description>
00024         /// </item>
00025         /// <item>
00026         /// <description>GoBack, GoForward, and GoHome event handlers</description>
00027         /// </item>
00028         /// <item>
00029         /// <description>Mouse and keyboard shortcuts for navigation</description>
00030         /// </item>
00031         /// <item>
00032         /// <description>State management for navigation and process lifetime management</description>
00033         /// </item>
00034         /// <item>
00035         /// <description>A default view model</description>
00036         /// </item>
00037         /// </list>
00038         /// </summary>
00039         [Windows::Foundation::Metadata::WebHostHidden]
00040         public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
00041         {
00042         internal:
00043             LayoutAwarePage();
00044
00045         public:
00046             void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047             void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048             void InvalidateVisualState();
00049             static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
00050             {
00051                 Windows::UI::Xaml::DependencyProperty^ get();
00052             };
00053             property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
00054             {
00055                 Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
00056                 void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
00057             }
00058
00059         protected:
00060             virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061             virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062             virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063             virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
00064             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00065             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00066             virtual void LoadState(Platform::Object^ navigationParameter,
00067                 Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00068             virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
00069
00070         private:
00071             Platform::String^ _pageKey;
00072             bool _navigationShortcutsRegistered;
00073             Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
00074             Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
00075                 _acceleratorKeyEventToken, _pointerPressedEventToken;
00076             Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
00077             void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00078             void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079             void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080
00081             void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
00082                 Windows::UI::Core::AcceleratorKeyEventArgs^ args);
00083             void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
00084                 Windows::UI::Core::PointerEventArgs^ args);
00085             LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
00086         };
00087     }
00088 }
Generated on Sat Nov 23 2024 16:07:35 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

PaperRenderer Member List

This is the complete list of members for PaperRenderer, including all inherited members.
__pad0__ | PaperRenderer |
AddPaper() | PaperRenderer |
CreateDeviceIndependentResources(Microsoft::WRL::ComPtr< ID2D1Factory1 > d2dFactory) | PaperRenderer |
CreateDeviceResources(Microsoft::WRL::ComPtr< ID2D1DeviceContext > d2dContext) | PaperRenderer |
CreateWindowSizeDependentResources(float dpi) | PaperRenderer |
DrawPaper() | PaperRenderer |
HitTestFragmentsWithPosition(D2D1_POINT_2F position) | PaperRenderer | [private]
m_blackBrush | PaperRenderer | [private]
m_d2dContext | PaperRenderer | [private]
m_d2dFactory | PaperRenderer | [private]
m_dpi | PaperRenderer | [private]
m_paperFragmentList | PaperRenderer | [private]
m_paperMode | PaperRenderer | [private]
m_selectedFragment | PaperRenderer | [private]
m_starStampGeometry | PaperRenderer | [private]
MovePaper() | PaperRenderer |
OnManipulationCompleted(Windows::UI::Xaml::Input::ManipulationCompletedRoutedEventArgs^args) | PaperRenderer |
OnManipulationDelta(Windows::UI::Xaml::Input::ManipulationDeltaRoutedEventArgs^args) | PaperRenderer |
OnManipulationStarted(Windows::UI::Xaml::Input::ManipulationStartedRoutedEventArgs^args) | PaperRenderer |
OnTapped(Windows::Foundation::Point position) | PaperRenderer |
RandomFloat() | PaperRenderer | [private]
RemovePaper() | PaperRenderer |
Reset() | PaperRenderer |
StampPaper() | PaperRenderer |
Generated on Sat Nov 23 2024 16:09:19 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

DeviceAppForWebcam::Common::LayoutAwarePage Member List

This is the complete list of members for DeviceAppForWebcam::Common::LayoutAwarePage, including all inherited members.
__pad0__ | DeviceAppForWebcam::Common::LayoutAwarePage |
_defaultViewModel | DeviceAppForWebcam::Common::LayoutAwarePage | [private]
_layoutAwareControls | DeviceAppForWebcam::Common::LayoutAwarePage | [private]
_windowSizeEventToken | DeviceAppForWebcam::Common::LayoutAwarePage | [private]
DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState) | DeviceAppForWebcam::Common::LayoutAwarePage | [virtual]
GoBack(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | DeviceAppForWebcam::Common::LayoutAwarePage | [virtual]
InvalidateVisualState() | DeviceAppForWebcam::Common::LayoutAwarePage |
StartLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | DeviceAppForWebcam::Common::LayoutAwarePage |
StopLayoutUpdates(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | DeviceAppForWebcam::Common::LayoutAwarePage |
WindowSizeChanged(Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | DeviceAppForWebcam::Common::LayoutAwarePage | [private]
Generated on Sat Nov 23 2024 16:09:37 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Windows Store device app for camera/C++/pch.cpp Source File

  • Windows Store device app for camera

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

CAutoDXGILock Member List

This is the complete list of members for CAutoDXGILock, including all inherited members.
CAutoDXDevLockBase(_In_ Microsoft::WRL::ComPtr< IMFDXGIDeviceManager > spDevManager) | CAutoDXDevLockBase< IMFDXGIDeviceManager, ID3D11Device > | [inline]
CAutoDXGILock(_In_ Microsoft::WRL::ComPtr< IMFDXGIDeviceManager > spDevManager) | CAutoDXGILock | [inline]
LockDevice(_Out_ Microsoft::WRL::ComPtr< ID3D11Device > &spDev) | CAutoDXGILock | [inline, virtual]
m_hDev | CAutoDXDevLockBase< IMFDXGIDeviceManager, ID3D11Device > | [protected]
m_locked | CAutoDXDevLockBase< IMFDXGIDeviceManager, ID3D11Device > | [protected]
m_spDevManager | CAutoDXDevLockBase< IMFDXGIDeviceManager, ID3D11Device > | [protected]
~CAutoDXDevLockBase() | CAutoDXDevLockBase< IMFDXGIDeviceManager, ID3D11Device > | [inline]
Generated on Sat Nov 23 2024 16:09:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Application data/C++/MainPage.xaml.h Source File

  • Application data

MainPage.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 // MainPage.xaml.h
00013 // Declaration of the MainPage.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "MainPage.g.h"
00020 #include "Common\LayoutAwarePage.h" // Required by generated header
00021 #include "Constants.h"
00022
00023 namespace SDKSample
00024 {
00025     public enum class NotifyType
00026     {
00027         StatusMessage,
00028         ErrorMessage
00029     };
00030
00031     public ref class MainPageSizeChangedEventArgs sealed
00032     {
00033     public:
00034         property Windows::UI::ViewManagement::ApplicationViewState ViewState
00035         {
00036             Windows::UI::ViewManagement::ApplicationViewState get()
00037             {
00038                 return viewState;
00039             }
00040
00041             void set(Windows::UI::ViewManagement::ApplicationViewState value)
00042             {
00043                 viewState = value;
00044             }
00045         }
00046
00047     private:
00048         Windows::UI::ViewManagement::ApplicationViewState viewState;
00049     };
00050
00051     public ref class MainPage sealed
00052     {
00053     public:
00054         MainPage();
00055
00056     protected:
00057         virtual void LoadState(Platform::Object^ navigationParameter,
00058             Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00059         virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
00060
00061     internal:
00062         property bool AutoSizeInputSectionWhenSnapped
00063         {
00064             bool get()
00065             {
00066                 return autoSizeInputSectionWhenSnapped;
00067             }
00068
00069             void set(bool value)
00070             {
00071                 autoSizeInputSectionWhenSnapped = value;
00072             }
00073         }
00074
00075         property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
00076        {
00077             Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
00078             {
00079                 return safe_cast<App^>(App::Current)->LaunchArgs;
00080             }
00081         }
00082
00083         void NotifyUser(Platform::String^ strMessage, NotifyType type);
00084         void LoadScenario(Platform::String^ scenarioName);
00085         event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
00086         event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
00087
00088     private:
00089         void PopulateScenarios();
00090         void InvalidateSize();
00091         void InvalidateViewState();
00092
00093         Platform::Collections::Vector<Object^>^ ScenarioList;
00094         Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
00095         void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         bool autoSizeInputSectionWhenSnapped;
00097
00098         void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00099         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00100
00101     internal:
00102         static MainPage^ Current;
00103
00104     };
00105 }
Generated on Sat Nov 23 2024 16:07:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D printing images and effects/C++/D2DPageRenderer.h Source File

  • Direct2D printing images and effects

D2DPageRenderer.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 <DirectXBase.h>
00010 #include <printpreview.h>
00011 #include "SampleOverlay.h"
00012
00013 ref class PageRendererContext;
00014
00015 // This class is shared between the display, print, and print-preview threads.
00016 // To ensure thread-safety, it should contain only immutable resources,
00017 // factories, and devices.
00018 //
00019 // For performance, we also cache the display PageRendererContext on the
00020 // PageRenderer.
00021 ref class PageRenderer : public DirectXBase
00022 {
00023 internal:
00024     PageRenderer();
00025
00026     virtual void CreateDeviceIndependentResources() override;
00027     virtual void CreateDeviceResources() override;
00028     virtual void Render() override;
00029     virtual void UpdateForWindowSizeChange() override;
00030
00031     void SetSnappedMode(_In_ bool isSnapped);
00032
00033     // Print out one page.
00034     void PrintPage(
00035         _In_ uint32                 pageNumber,
00036         _In_ D2D1_RECT_F            imageableArea,
00037         _In_ D2D1_SIZE_F            pageSize,
00038         _In_opt_ IStream*           pagePrintTicketStream
00039         );
00040
00041     // Create DXGI surface for preview.
00042     void DrawPreviewSurface(
00043         _In_  float                             width,
00044         _In_  float                             height,
00045         _In_  float                             scale,
00046         _In_  D2D1_RECT_F                       contentBox,
00047         _In_  uint32                            desiredJobPage,
00048         _In_  IPrintPreviewDxgiPackageTarget*   previewTarget
00049         );
00050
00051     // Create Direct2D print control for caller, who only needs to
00052     // specify IPrintDocumentPackageTarget and print control property.
00053     void CreatePrintControl(
00054         _In_  IPrintDocumentPackageTarget*      docPackageTarget,
00055         _In_  D2D1_PRINT_CONTROL_PROPERTIES*    printControlProperties
00056         );
00057
00058     // Close print control with protection.
00059     HRESULT ClosePrintControl();
00060
00061     IWICColorContext* GetWicColorContextNoRef();
00062     IWICBitmapSource* GetOriginalWicBitmapSourceNoRef();
00063     IWICBitmapSource* GetWicBitmapSourceWithEmbeddedColorContextNoRef();
00064     IDWriteTextFormat* GetTextFormatNoRef();
00065     IDWriteTextFormat* GetMessageFormatNoRef();
00066
00067 private:
00068     Microsoft::WRL::ComPtr<ID2D1PrintControl>       m_d2dPrintControl;
00069
00070     // Overlay for sample title.
00071     SampleOverlay^                                  m_sampleOverlay;
00072
00073     // Whether the app is in the snapped mode.
00074     bool                                            m_isSnapped;
00075
00076     // Page renderer context for use for display. Note that this object is mutable
00077     // and hence should *only* be used by the display thread.
00078     PageRendererContext^                            m_displayPageRendererContext;
00079
00080     // Immutable resources
00081     Microsoft::WRL::ComPtr<IWICFormatConverter>     m_wicConvertedSource;
00082     Microsoft::WRL::ComPtr<IWICColorContext>        m_wicColorContext;
00083     Microsoft::WRL::ComPtr<IWICBitmapFrameDecode>   m_profiledWicBitmap;
00084     Microsoft::WRL::ComPtr<IDWriteTextFormat>       m_textFormat;
00085     Microsoft::WRL::ComPtr<IDWriteTextFormat>       m_messageFormat;
00086 };
Generated on Sat Nov 23 2024 16:08:06 for Win8-Examples by doxygen 1.7.1


Win8-Examples: App tiles and badges/C#,C++/EnableNotificationQueue.xaml.cpp Source File

  • App tiles and badges
  • C#,C++

EnableNotificationQueue.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 // EnableNotificationQueue.xaml.cpp
00013 // Implementation of the EnableNotificationQueue class
00014 //
00015
00016 #include "pch.h"
00017 #include "EnableNotificationQueue.xaml.h"
00018
00019 using namespace SDKSample::Tiles;
00020
00021 using namespace Platform;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Navigation;
00025 using namespace Windows::UI::Notifications;
00026 using namespace NotificationsExtensions::TileContent;
00027
00028 EnableNotificationQueue::EnableNotificationQueue()
00029 {
00030     InitializeComponent();
00031 }
00032
00033 void EnableNotificationQueue::OnNavigatedTo(NavigationEventArgs^ e)
00034 {
00035     rootPage = MainPage::Current;
00036 }
00037
00038 void EnableNotificationQueue::EnableNotificationQueue_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00039 {
00040   TileUpdateManager::CreateTileUpdaterForApplication()->EnableNotificationQueue(true);
00041   OutputTextBlock->Text = "Notification queue enabled";
00042 }
00043
00044 void EnableNotificationQueue::DisableNotificationQueue_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00045 {
00046   TileUpdateManager::CreateTileUpdaterForApplication()->EnableNotificationQueue(false);
00047   OutputTextBlock->Text = "Notification queue disabled";
00048 }
00049
00050 void EnableNotificationQueue::UpdateTile_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00051 {
00052   String^ text = "TestTag01";
00053   if( TextContent->Text->IsEmpty())
00054   {
00055     text = TextContent->Text;
00056   }
00057
00058   auto tileContent = TileContentFactory::CreateTileWideText03();
00059   tileContent->TextHeadingWrap->Text = text;
00060   auto squareContent = TileContentFactory::CreateTileSquareText04();
00061   squareContent->TextBodyWrap->Text = text;
00062   tileContent->SquareContent = squareContent;
00063
00064   auto tile = tileContent->CreateNotification();
00065
00066   String^ tag = "TestTag01";
00067   if ( !IdBox->Text->IsEmpty())
00068   {
00069     tag = IdBox->Text;
00070   }
00071
00072   // set the tag on the notification
00073   tile->Tag = tag;
00074   TileUpdateManager::CreateTileUpdaterForApplication()->Update(tile);
00075
00076   OutputTextBlock->Text = "Tile notification sent. It is tagged with " + tag;
00077 }
00078
00079 void EnableNotificationQueue::ClearTile_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00080 {
00081   TileUpdateManager::CreateTileUpdaterForApplication()->Clear();
00082   OutputTextBlock->Text = "Tile cleared";
00083 }
Generated on Sat Nov 23 2024 16:07:54 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DXGI swap chain rotation/C++/DxgiRotation.h Source File

  • DXGI swap chain rotation

DxgiRotation.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 "DirectXBase.h"
00011 #include "SampleOverlay.h"
00012 #include "BasicMath.h"
00013 #include "BasicCamera.h"
00014
00015 // describes the constant buffer that will be used to draw the cube
00016 struct ConstantBuffer
00017 {
00018     float4x4 model;
00019     float4x4 view;
00020     float4x4 projection;
00021 };
00022
00023 ref class DxgiRotation : public DirectXBase
00024 {
00025 internal:
00026     virtual void CreateDeviceIndependentResources() override;
00027     virtual void CreateDeviceResources() override;
00028     virtual void CreateWindowSizeDependentResources() override;
00029     virtual void Render() override;
00030
00031     void Update(float TimeTotal, float TimeDelta);
00032
00033 private:
00034     SampleOverlay^  m_sampleOverlay;
00035
00036     Microsoft::WRL::ComPtr<ID3D11InputLayout>           m_inputLayout;                // cube vertex input layout
00037     Microsoft::WRL::ComPtr<ID3D11Buffer>                m_vertexBuffer;               // cube vertex buffer
00038     Microsoft::WRL::ComPtr<ID3D11Buffer>                m_indexBuffer;                // cube index buffer
00039     Microsoft::WRL::ComPtr<ID3D11VertexShader>          m_vertexShader;               // cube vertex shader
00040     Microsoft::WRL::ComPtr<ID3D11PixelShader>           m_pixelShader;                // cube pixel shader
00041     Microsoft::WRL::ComPtr<ID3D11Texture2D>             m_texture;                    // cube texture
00042     Microsoft::WRL::ComPtr<ID3D11ShaderResourceView>    m_textureSRV;                 // cube texture view
00043     Microsoft::WRL::ComPtr<ID3D11SamplerState>          m_sampler;                    // cube texture sampler
00044     Microsoft::WRL::ComPtr<ID3D11Buffer>                m_constantBuffer;             // constant buffer resource
00045     Microsoft::WRL::ComPtr<IWICFormatConverter>         m_referenceBitmapSource;      // oriented reference image source
00046     Microsoft::WRL::ComPtr<ID2D1Bitmap>                 m_referenceBitmap;            // oriented reference image
00047     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>        m_textBrush;                  // reference text brush
00048     Microsoft::WRL::ComPtr<IDWriteTextFormat>           m_textFormat;                 // reference text format
00049     Microsoft::WRL::ComPtr<IDWriteTextLayout>           m_textLayout;                 // reference text layout
00050
00051     unsigned int    m_indexCount;                  // cube index count
00052     ConstantBuffer  m_constantBufferData;          // constant buffer resource data
00053     BasicCamera^    m_Camera;                      // scene camera
00054 };
Generated on Sat Nov 23 2024 16:08:15 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Raw notifications/C++/MainAppSample/MainPage.xaml.h Source File

  • Raw notifications
  • MainAppSample

MainPage.xaml.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 //
00009 // MainPage.xaml.h
00010 // Declaration of the MainPage.xaml class.
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "MainPage.g.h"
00017
00018 using namespace Windows::UI::Xaml;
00019 using namespace Windows::UI::Xaml::Controls;
00020 using namespace Windows::Graphics::Display;
00021 using namespace Windows::UI::ViewManagement;
00022 using namespace Windows::UI::Xaml::Navigation;
00023 using namespace Windows::Foundation;
00024 using namespace Windows::System;
00025 using namespace Platform;
00026 using namespace Windows::UI::Xaml::Interop;
00027
00028 namespace RawNotificationsSampleCPP
00029 {
00030   public enum class NotifyType
00031   {
00032     StatusMessage,
00033     ErrorMessage
00034   };
00035
00036   [Windows::Foundation::Metadata::WebHostHidden]
00037   public ref class MainPage sealed
00038   {
00039   public:
00040     MainPage();
00041
00042     property Windows::UI::Xaml::Controls::Frame^ ScenariosFrame
00043     {
00044       Windows::UI::Xaml::Controls::Frame^ get() { return _scenariosFrame; }
00045     }
00046     property Windows::UI::Xaml::Controls::Frame^ InputFrame
00047     {
00048       Windows::UI::Xaml::Controls::Frame^ get() { return _inputFrame; }
00049     }
00050     property Windows::UI::Xaml::Controls::Frame^ OutputFrame
00051     {
00052       Windows::UI::Xaml::Controls::Frame^ get() { return _outputFrame; }
00053     }
00054
00055     event Windows::Foundation::EventHandler<Platform::Object^>^ InputFrameLoaded;
00056     event Windows::Foundation::EventHandler<Platform::Object^>^ OutputFrameLoaded;
00057
00058     void NotifyUser(String^ strMessage, NotifyType type);
00059     void DoNavigation(TypeName pageType, Windows::UI::Xaml::Controls::Frame^ frame);
00060     String^ ConvertViewState(ApplicationViewState state);
00061     String^ ConvertResolution(ResolutionScale scale);
00062
00063     property Windows::Networking::PushNotifications::PushNotificationChannel^ Channel
00064     {
00065       Windows::Networking::PushNotifications::PushNotificationChannel^ get() { return _channel; }
00066       void set (Windows::Networking::PushNotifications::PushNotificationChannel^ newChannel) { _channel = newChannel; }
00067     }
00068
00069   private:
00070     ~MainPage();
00071     Windows::UI::Xaml::Controls::Frame^ _scenariosFrame;
00072     Windows::UI::Xaml::Controls::Frame^ _inputFrame;
00073     Windows::UI::Xaml::Controls::Frame^ _outputFrame;
00074     void Footer_Click(Object^ sender, RoutedEventArgs^ e);
00075     Windows::Foundation::EventRegistrationToken _displayHandlerToken;
00076     Windows::Foundation::EventRegistrationToken _layoutHandlerToken;
00077     Windows::Foundation::EventRegistrationToken _pageLoadedHandlerToken;
00078     Windows::Foundation::EventRegistrationToken _logicalDpiChangedToken;
00079     Windows::Foundation::EventRegistrationToken _inputFrameLoadedToken;
00080     Windows::Foundation::EventRegistrationToken _outputFrameLoadedToken;
00081     void Page_SizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00082     void DisplayProperties_LogicalDpiChanged(Object^ sender);
00083     void Page_Loaded(Object^ sender, RoutedEventArgs^ e);
00084     void CheckResolutionAndViewState();
00085     void SetFeatureName(Platform::String^ strFeature);
00086     void inputFrameNavigated(Object^ sender, NavigationEventArgs^ e);
00087     void outputFrameNavigated(Object^ sender, NavigationEventArgs^ e);
00088
00089     Windows::Networking::PushNotifications::PushNotificationChannel^ _channel;
00090   };
00091 }
Generated on Sat Nov 23 2024 16:07:47 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Custom driver access/C#,C++/DLL/fx2device.h Source File

  • Custom driver access
  • C#,C++
  • DLL

fx2device.h

Go to the documentation of this file.
00001 ﻿#pragma once
00002
00003 #include <specstrings.h>
00004 #include <deviceaccess.h>
00005 #include <winioctl.h>
00006 #include <strsafe.h>
00007
00008 #include <wrl\client.h>
00009
00010 // #include "ppltasks_mod2.h"
00011 #include <ppltasks.h>
00012
00013 #include <functional>
00014
00015 #include "public.h"
00016 #include "support.h"
00017 #include "repeater.h"
00018
00019 using namespace Windows::Foundation;
00020 using namespace Platform;
00021 using namespace Microsoft::WRL;
00022 using namespace concurrency;
00023
00024 const BYTE c_NumBarsInGraph = 8;
00025 const BYTE c_NumSwitches = 8;
00026 const BYTE c_SegmentMask[] = {
00027     0xD7, // 0
00028     0x06, // 1
00029     0xB3, // 2
00030     0xA7, // 3
00031     0x66, // 4
00032     0xE5, // 5
00033     0xF4, // 6
00034     0x07, // 7
00035     0xF7, // 8
00036     0x67, // 9
00037 };
00038 const unsigned int c_SegmentMaskCe = _countof(c_SegmentMask);
00039
00040 inline void THROW_HR(HRESULT hr)
00041 {
00042     if (hr != 0) {
00043         throw Platform::Exception::ReCreateException(hr);
00044     }
00045 }
00046
00047 namespace Samples {
00048     namespace Devices {
00049         namespace Fx2 {
00050
00051             ref class Fx2Device;
00052             ref class SwitchStateChangedEventArgs;
00053             ref class BarGraphDisplayResult;
00054
00055             public delegate void SwitchStateChangedHandler(Fx2Device^ Sender, SwitchStateChangedEventArgs^ EventArgs);
00056
00057             /// <summary>
00058             /// The device projection for an OSR Fx2 device
00059             /// </summary>
00060             public ref class Fx2Device sealed
00061             {
00062
00063             private:
00064                 String^ m_Id;
00065
00066                 ComPtr<IDeviceIoControl> m_DeviceIoControl;
00067
00068                 //
00069                 // Fields to track the switch state of the fx2 board.
00070                 //
00071                 struct {
00072                     LONG ListenerCount;
00073                     Repeater Repeater;
00074
00075                     SWITCH_STATE Buffer;
00076                     ULONG_PTR CancelContext;
00077                     ULONG FailureCount;
00078                 } m_SwitchState;
00079                 event SwitchStateChangedHandler^ m_SwitchStateChangedEvent;
00080
00081                 Fx2Device(__in IDeviceIoControl* DeviceControl, __in String^ Id);
00082                 ~Fx2Device ();
00083
00084                 void StartEventLoop();
00085                 void StopEventLoop();
00086
00087             public:
00088
00089                 /// <summary>Returns the device selector that an app should use to locate Fx2 devices</summary>
00090                 /// <returns>The selector string for the Fx2 device interface</returns>
00091                 static String^ GetDeviceSelector();
00092
00093                 static Fx2Device^ FromId(__in String^ InterfacePath);
00094
00095                 property String^ Id {String^ get();}
00096                 property BYTE SevenSegmentDisplay {BYTE get(); void set(__in BYTE value);}
00097
00098                 void SetBarGraphDisplay(__in const Array<bool>^ Values);
00099                 IAsyncOperation<BarGraphDisplayResult^>^ GetBarGraphDisplayAsync(void);
00100
00101                 property Array<bool>^ SwitchState {Array<bool>^ get();}
00102
00103                 event SwitchStateChangedHandler^ SwitchStateChanged {
00104                     EventRegistrationToken add(__in SwitchStateChangedHandler^ h);
00105                     void remove(__in EventRegistrationToken cookie);
00106                     void raise(__in Fx2Device^ Sender, __in SwitchStateChangedEventArgs^ args) {m_SwitchStateChangedEvent::raise(Sender, args);}
00107                 };
00108             };
00109
00110             public ref class SwitchStateChangedEventArgs sealed {
00111                 friend ref class Fx2Device;
00112
00113             private:
00114                 HRESULT m_Hr;
00115                 Array<bool>^ m_Switches;
00116                 SWITCH_STATE m_State;
00117
00118                 SwitchStateChangedEventArgs(__in HRESULT Hr) {
00119                     m_Hr = Hr;
00120                     m_Switches = nullptr;
00121                     ZeroMemory(&m_State, sizeof(m_State));
00122                 }
00123
00124                 SwitchStateChangedEventArgs(__in SWITCH_STATE State) {
00125                     m_Hr = S_OK;
00126                     m_Switches = ref new Array<bool>(c_NumSwitches);
00127                     m_State = State;
00128                     for(int i = 0; i < c_NumSwitches; i += 1) {
00129                         m_Switches[i] = ((State.SwitchesAsUChar & (1 << i)) != 0);
00130                     }
00131                 }
00132
00133                 void CheckResult(void) {
00134                     if (m_Hr != S_OK) {
00135                         throw Platform::Exception::CreateException(m_Hr, "Error requesting switch state");
00136                     }
00137                 }
00138
00139             public:
00140
00141                 property BYTE AsByte {BYTE get() {CheckResult(); return m_State.SwitchesAsUChar;}};
00142                 property Array<bool>^ SwitchState {Array<bool>^ get() {CheckResult(); return m_Switches;}};
00143             };
00144
00145             public ref class BarGraphDisplayResult sealed {
00146                 friend ref class Fx2Device;
00147
00148             private:
00149                 Array<bool>^ m_Bars;
00150                 BAR_GRAPH_STATE m_State;
00151                 ULONG_PTR m_CancelToken;
00152
00153                 void UpdateBars() {
00154                     for(int i = 0; i < c_NumBarsInGraph; i += 1) {
00155                         m_Bars[i] = ((m_State.BarsAsUChar & (1 << i)) != 0);
00156                     }
00157                 }
00158
00159             public:
00160                 BarGraphDisplayResult() : m_CancelToken(0) {
00161                     m_Bars = ref new Array<bool>(c_NumBarsInGraph);
00162                     ZeroMemory(&m_State, sizeof(m_State));
00163                 }
00164
00165                 property BYTE AsByte {BYTE get() {return m_State.BarsAsUChar;}};
00166                 property Array<bool>^ BarGraphDisplay {Array<bool>^ get() {return m_Bars;}}
00167
00168             internal:
00169                 ULONG_PTR* GetCancelToken(void) {return &m_CancelToken;}
00170             };
00171         }
00172     }
00173 }
00174 using namespace Samples::Devices;
00175 using namespace Samples::Devices::Fx2;
Generated on Sat Nov 23 2024 16:08:01 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DXGI offer and reclaim resources/C++/BasicLoader.h Source File

  • DXGI offer and reclaim resources

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 Sat Nov 23 2024 16:08:08 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D tutorial/C++/Lesson5.Components/BasicShapes.h Source File

  • Direct3D tutorial
  • Lesson5.Components

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 Sat Nov 23 2024 16:08:10 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Search contract/C++/Scenario1.xaml.h Source File

  • Search contract

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 SDKSample
00023 {
00024     namespace SearchContract
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 Scenario1 sealed
00031         {
00032         public:
00033             Scenario1();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         };
00038     }
00039 }
Generated on Sat Nov 23 2024 16:07:50 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Language font mapping/C++/ScenarioList.xaml.h Source File

  • Language font mapping

ScenarioList.xaml.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 //
00009 // ScenarioList.xaml.h
00010 // Declaration of the ScenarioList class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioList.g.h"
00017 #include "MainPage.g.h"
00018
00019 namespace LanguageFontCPP
00020 {
00021     [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class ScenarioList sealed
00023     {
00024     public:
00025         ScenarioList();
00026
00027     protected:
00028         void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00029         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030
00031     private:
00032         ~ScenarioList();
00033         MainPage^ rootPage;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:57 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Edge gesture invocation/C++/ScenarioOutput1.xaml.h Source File

  • Edge gesture invocation

ScenarioOutput1.xaml.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 //
00009 // ScenarioOutput1.xaml.h
00010 // Declaration of the ScenarioOutput1 class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioOutput1.g.h"
00017 #include "MainPage.xaml.h"
00018
00019 namespace EdgeGestureSample
00020 {
00021   [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class ScenarioOutput1 sealed
00023     {
00024     public:
00025         ScenarioOutput1();
00026
00027     protected:
00028         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030
00031     private:
00032     void rootPage_InputFrameLoaded(Object^ sender, Object^ e);
00033     ~ScenarioOutput1();
00034
00035         MainPage^ rootPage;
00036         Windows::Foundation::EventRegistrationToken _frameLoadedToken;
00037     };
00038 }
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media extensions/C++/MediaExtensions/Grayscale/dllmain.cpp Source File

  • Media extensions
  • MediaExtensions
  • Grayscale

dllmain.cpp

Go to the documentation of this file.
00001 //////////////////////////////////////////////////////////////////////////
00002 //
00003 // dllmain.cpp
00004 //
00005 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00007 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00008 // PARTICULAR PURPOSE.
00009 //
00010 // Copyright (c) Microsoft Corporation. All rights reserved.
00011 //
00012 //////////////////////////////////////////////////////////////////////////
00013
00014 #include <initguid.h>
00015 #include "Grayscale.h"
00016
00017 using namespace Microsoft::WRL;
00018
00019 namespace Microsoft { namespace Samples {
00020     ActivatableClass(CGrayscale);
00021 }}
00022
00023 BOOL WINAPI DllMain( _In_ HINSTANCE hInstance, _In_ DWORD dwReason, _In_opt_ LPVOID lpReserved )
00024 {
00025     if( DLL_PROCESS_ATTACH == dwReason )
00026     {
00027         //
00028         //  Don't need per-thread callbacks
00029         //
00030         DisableThreadLibraryCalls( hInstance );
00031
00032         Module<InProc>::GetModule().Create();
00033     }
00034     else if( DLL_PROCESS_DETACH == dwReason )
00035     {
00036         Module<InProc>::GetModule().Terminate();
00037     }
00038
00039     return TRUE;
00040 }
00041
00042 HRESULT WINAPI DllGetActivationFactory( _In_ HSTRING activatibleClassId, _Outptr_ IActivationFactory** factory )
00043 {
00044     auto &module = Microsoft::WRL::Module< Microsoft::WRL::InProc >::GetModule();
00045     return module.GetActivationFactory( activatibleClassId, factory );
00046 }
00047
00048 HRESULT WINAPI DllCanUnloadNow()
00049 {
00050     auto &module = Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule();
00051     return (module.Terminate()) ? S_OK : S_FALSE;
00052 }
00053
00054 STDAPI DllGetClassObject( _In_ REFCLSID rclsid, _In_ REFIID riid, _Outptr_ LPVOID FAR* ppv )
00055 {
00056     auto &module = Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule();
00057     return module.GetClassObject( rclsid, riid, ppv );
00058 }
Generated on Sat Nov 23 2024 16:08:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML Direct2D lighting effects/C++/pch.h Source File

  • XAML Direct2D lighting effects

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 <d3d11_1.h>
00012 #include <d2d1_1.h>
00013 #include <d2d1effects.h>
00014 #include <dwrite_1.h>
00015 #include <wincodec.h>
00016 #include <agile.h>
00017
00018 #include "windows.ui.xaml.media.dxinterop.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D 3D transform effect/C++/App.xaml.h Source File

  • Direct2D 3D transform effect

App.xaml.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 "MainPage.xaml.h"
00011 #include "App.g.h"
00012
00013 namespace D2D3DTransforms
00014 {
00015     [Windows::Foundation::Metadata::WebHostHidden]
00016     public ref class App sealed
00017     {
00018     public:
00019         App();
00020
00021         virtual void OnLaunched(
00022             _In_ Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ args
00023             ) override;
00024
00025     private:
00026         void OnLogicalDpiChanged(
00027             _In_ Platform::Object^ sender
00028             );
00029
00030         void OnSuspending(
00031             _In_ Platform::Object^ sender,
00032             _In_ Windows::ApplicationModel::SuspendingEventArgs^ args
00033             );
00034
00035         void OnWindowSizeChanged(
00036             _In_ Windows::UI::Core::CoreWindow^ sender,
00037             _In_ Windows::UI::Core::WindowSizeChangedEventArgs^ args
00038             );
00039
00040         MainPage^ m_mainPage;
00041     };
00042 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML images/C++/App.xaml.h Source File

  • XAML images

App.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 // App.xaml.h
00013 // Declaration of the App.xaml class.
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "App.g.h"
00020 #include "MainPage.g.h"
00021
00022 namespace SDKSample
00023 {
00024     ref class App
00025     {
00026     internal:
00027         App();
00028         virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
00029         Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
00030     protected:
00031         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
00032     private:
00033         Windows::UI::Xaml::Controls::Frame^ rootFrame;
00034     };
00035 }
Generated on Sat Nov 23 2024 16:07:29 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML two-dimensional transforms/C++/pch.h Source File

  • XAML two-dimensional transforms

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 //
00012 // pch.h
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "Common\LayoutAwarePage.h"
00021 #include "Common\SuspensionManager.h"
00022 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

SDKSample::DisplayOrientation::sealed Member List

This is the complete list of members for SDKSample::DisplayOrientation::sealed, including all inherited members.
accelerometer | SDKSample::DisplayOrientation::sealed | [private]
CalculateDeviceRotation(Windows::Devices::Sensors::Accelerometer^sender, Windows::Devices::Sensors::AccelerometerReadingChangedEventArgs^args) | SDKSample::DisplayOrientation::sealed | [private]
CalculateDeviceRotation(Windows::Devices::Sensors::Accelerometer^sender, Windows::Devices::Sensors::AccelerometerReadingChangedEventArgs^args) | SDKSample::DisplayOrientation::sealed | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::DisplayOrientation::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::DisplayOrientation::sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::DisplayOrientation::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::DisplayOrientation::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::DisplayOrientation::sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | SDKSample::DisplayOrientation::sealed | [protected, virtual]
OnOrientationChanged(Platform::Object^sender) | SDKSample::DisplayOrientation::sealed | [private]
orientationChangedEventToken | SDKSample::DisplayOrientation::sealed | [private]
readingChangedEventToken | SDKSample::DisplayOrientation::sealed | [private]
rotationAngle | SDKSample::DisplayOrientation::sealed | [private]
Scenario1() | SDKSample::DisplayOrientation::sealed |
Scenario2() | SDKSample::DisplayOrientation::sealed |
Scenario2Button_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | SDKSample::DisplayOrientation::sealed | [private]
Scenario3() | SDKSample::DisplayOrientation::sealed |
UpdateArrowForRotation() | SDKSample::DisplayOrientation::sealed | [private]
UpdateArrowForRotation() | SDKSample::DisplayOrientation::sealed | [private]
Generated on Sat Nov 23 2024 16:09:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/BasicReaderWriter.h Source File

  • XAML DirectX 3D shooting game

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     Platform::String^ m_locationPath;
00019
00020 internal:
00021     BasicReaderWriter();
00022     BasicReaderWriter(
00023         _In_ Windows::Storage::StorageFolder^ folder
00024         );
00025
00026     Platform::Array<byte>^ ReadData(
00027         _In_ Platform::String^ filename
00028         );
00029
00030     concurrency::task<Platform::Array<byte>^> ReadDataAsync(
00031         _In_ Platform::String^ filename
00032         );
00033
00034     uint32 WriteData(
00035         _In_ Platform::String^ filename,
00036         _In_ const Platform::Array<byte>^ fileData
00037         );
00038
00039     concurrency::task<void> WriteDataAsync(
00040         _In_ Platform::String^ filename,
00041         _In_ const Platform::Array<byte>^ fileData
00042         );
00043 };
Generated on Sat Nov 23 2024 16:08:09 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Calendar details and math/C++/Constants.cpp Source File

  • Calendar details and math

Constants.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 "Constants.h"
00014
00015 using namespace SDKSample;
00016
00017 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00018 {
00019     // The format here is the following:
00020     //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
00021     { "Display a calendar", "SDKSample.CalendarSample.DisplayCalendarData" },
00022     { "Retrieve calendar statistics", "SDKSample.CalendarSample.DisplayCalendarStatistics" },
00023     { "Calendar enumeration and math", "SDKSample.CalendarSample.CalendarEnumerationAndMath" }
00024 };
Generated on Sat Nov 23 2024 16:07:39 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML user and custom controls/C++/MainPage.xaml.cpp Source File

  • XAML user and custom controls

MainPage.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 // MainPage.xaml.cpp
00013 // Implementation of the MainPage.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "App.xaml.h"
00019
00020 #include <collection.h>
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Platform;
00027 using namespace SDKSample;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030 using namespace Windows::Graphics::Display;
00031 using namespace Windows::UI::ViewManagement;
00032
00033 MainPage^ MainPage::Current = nullptr;
00034
00035 MainPage::MainPage()
00036 {
00037     InitializeComponent();
00038
00039     // This frame is hidden, meaning it is never shown.  It is simply used to load
00040     // each scenario page and then pluck out the input and output sections and
00041     // place them into the UserControls on the main page.
00042     HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
00043     HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044     ContentRoot->Children->Append(HiddenFrame);
00045
00046     FeatureName->Text = FEATURE_NAME;
00047
00048     this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
00049     Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
00050
00051     MainPage::Current = this;
00052     autoSizeInputSectionWhenSnapped = true;
00053 }
00054
00055 /// <summary>
00056 /// We need to handle SizeChanged so that we can make the sample layout property
00057 /// in the various layouts.
00058 /// </summary>
00059 /// <param name="sender"></param>
00060 /// <param name="e"></param>
00061 void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00062 {
00063     InvalidateSize();
00064     MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
00065     args->ViewState = ApplicationView::Value;
00066     MainPageResized(this, args);
00067
00068 }
00069
00070 void MainPage::InvalidateSize()
00071 {
00072     // Get the window width
00073     double windowWidth = this->ActualWidth;
00074
00075     if (windowWidth != 0.0)
00076     {
00077         // Get the width of the ListBox.
00078         double listBoxWidth = Scenarios->ActualWidth;
00079
00080         // Is the ListBox using any margins that we need to consider?
00081         double listBoxMarginLeft = Scenarios->Margin.Left;
00082         double listBoxMarginRight = Scenarios->Margin.Right;
00083
00084         // Figure out how much room is left after considering the list box width
00085         double availableWidth = windowWidth - listBoxWidth;
00086
00087         // Is the top most child using margins?
00088         double layoutRootMarginLeft = ContentRoot->Margin.Left;
00089         double layoutRootMarginRight = ContentRoot->Margin.Right;
00090
00091         // We have different widths to use depending on the view state
00092         if (ApplicationView::Value != ApplicationViewState::Snapped)
00093         {
00094             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00095             // and the LayoutRoot's margins
00096             InputSection->Width = ((availableWidth) -
00097                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00098         }
00099         else
00100         {
00101             // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00102             if (autoSizeInputSectionWhenSnapped)
00103             {
00104                 InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00105             }
00106         }
00107     }
00108     InvalidateViewState();
00109 }
00110
00111 void MainPage::InvalidateViewState()
00112 {
00113     // Are we going to snapped mode?
00114     if (ApplicationView::Value == ApplicationViewState::Snapped)
00115     {
00116         Grid::SetRow(DescriptionText, 3);
00117         Grid::SetColumn(DescriptionText, 0);
00118
00119         Grid::SetRow(InputSection, 4);
00120         Grid::SetColumn(InputSection, 0);
00121
00122         Grid::SetRow(FooterPanel, 2);
00123         Grid::SetColumn(FooterPanel, 0);
00124     }
00125     else
00126     {
00127         Grid::SetRow(DescriptionText, 1);
00128         Grid::SetColumn(DescriptionText, 1);
00129
00130         Grid::SetRow(InputSection, 2);
00131         Grid::SetColumn(InputSection, 1);
00132
00133         Grid::SetRow(FooterPanel, 1);
00134         Grid::SetColumn(FooterPanel, 1);
00135     }
00136
00137     //  Since we don't load the scenario page in the traditional manner (we just pluck out the
00138     // input and output sections from the page) we need to ensure that any VSM code used
00139     // by the scenario's input and output sections is fired.
00140     VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00141     VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
00142 }
00143
00144 void MainPage::PopulateScenarios()
00145 {
00146     ScenarioList = ref new Platform::Collections::Vector<Object^>();
00147
00148     // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
00149     for (unsigned int i = 0; i < scenarios->Length; ++i)
00150     {
00151         Scenario s = scenarios[i];
00152         ListBoxItem^ item = ref new ListBoxItem();
00153         item->Name = s.ClassName;
00154         item->Content = (i + 1).ToString() + ") " + s.Title;
00155         ScenarioList->Append(item);
00156     }
00157
00158     // Bind the ListBox to the scenario list.
00159     Scenarios->ItemsSource = ScenarioList;
00160     Scenarios->ScrollIntoView(Scenarios->SelectedItem);
00161 }
00162
00163 /// <summary>
00164 /// This method is responsible for loading the individual input and output sections for each scenario.  This
00165 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00166 /// and output sections into the respective UserControl on the main page.
00167 /// </summary>
00168 /// <param name="scenarioName"></param>
00169 void MainPage::LoadScenario(String^ scenarioName)
00170 {
00171     autoSizeInputSectionWhenSnapped = true;
00172
00173     // Load the ScenarioX.xaml file into the Frame.
00174     TypeName scenarioType = {scenarioName, TypeKind::Custom};
00175     HiddenFrame->Navigate(scenarioType, this);
00176
00177     // Get the top element, the Page, so we can look up the elements
00178     // that represent the input and output sections of the ScenarioX file.
00179     Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
00180
00181     // Get each element.
00182     UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
00183     UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
00184
00185     if (input == nullptr)
00186     {
00187         // Malformed input section.
00188         NotifyUser("Cannot load scenario input section for " + scenarioName +
00189             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
00190         return;
00191     }
00192
00193     if (output == nullptr)
00194     {
00195         // Malformed output section.
00196         NotifyUser("Cannot load scenario output section for " + scenarioName +
00197             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
00198         return;
00199     }
00200
00201     // Find the LayoutRoot which parents the input and output sections in the main page.
00202     Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
00203
00204     if (panel != nullptr)
00205     {
00206         unsigned int index = 0;
00207         UIElementCollection^ collection = panel->Children;
00208
00209         // Get rid of the content that is currently in the intput and output sections.
00210         collection->IndexOf(input, &index);
00211         collection->RemoveAt(index);
00212
00213         collection->IndexOf(output, &index);
00214         collection->RemoveAt(index);
00215
00216         // Populate the input and output sections with the newly loaded content.
00217         InputSection->Content = input;
00218         OutputSection->Content = output;
00219
00220         ScenarioLoaded(this, nullptr);
00221     }
00222     else
00223     {
00224         // Malformed Scenario file.
00225         NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
00226             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
00227     }
00228 }
00229
00230 void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00231 {
00232     if (Scenarios->SelectedItem != nullptr)
00233     {
00234         NotifyUser("", NotifyType::StatusMessage);
00235
00236         LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
00237         InvalidateSize();
00238     }
00239 }
00240
00241 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00242 {
00243     switch (type)
00244     {
00245     case NotifyType::StatusMessage:
00246         // Use the status message style.
00247         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
00248         break;
00249     case NotifyType::ErrorMessage:
00250         // Use the error message style.
00251         StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
00252         break;
00253     default:
00254         break;
00255     }
00256     StatusBlock->Text = strMessage;
00257
00258     // Collapsed the StatusBlock if it has no text to conserve real estate.
00259     if (StatusBlock->Text != "")
00260     {
00261         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00262     }
00263     else
00264     {
00265         StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00266     }
00267 }
00268
00269 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00270 {
00271     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00272     Windows::System::Launcher::LaunchUriAsync(uri);
00273 }
00274
00275
00276 /// <summary>
00277 /// Populates the page with content passed during navigation.  Any saved state is also
00278 /// provided when recreating a page from a prior session.
00279 /// </summary>
00280 /// <param name="navigationParameter">The parameter value passed to
00281 /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
00282 /// </param>
00283 /// <param name="pageState">A map of state preserved by this page during an earlier
00284 /// session.  This will be null the first time a page is visited.</param>
00285 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
00286 {
00287     (void) navigationParameter; // Unused parameter
00288
00289     PopulateScenarios();
00290
00291     // Starting scenario is the first or based upon a previous state.
00292     ListBoxItem^ startingScenario = nullptr;
00293     int startingScenarioIndex = -1;
00294
00295     if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
00296     {
00297         startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
00298     }
00299
00300     Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
00301
00302     InvalidateViewState();
00303 }
00304
00305 /// <summary>
00306 /// Preserves state associated with this page in case the application is suspended or the
00307 /// page is discarded from the navigation cache.  Values must conform to the serialization
00308 /// requirements of <see cref="SuspensionManager::SessionState"/>.
00309 /// </summary>
00310 /// <param name="pageState">An empty map to be populated with serializable state.</param>
00311 void MainPage::SaveState(IMap<String^, Object^>^ pageState)
00312 {
00313     int selectedListBoxItemIndex = Scenarios->SelectedIndex;
00314     pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
00315 }
Generated on Sat Nov 23 2024 16:07:45 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D effects on primitives/C++/pch.cpp Source File

  • Direct2D effects on primitives

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 Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Edge gesture invocation/C++/ScenarioInput2.xaml.cpp Source File

  • Edge gesture invocation

ScenarioInput2.xaml.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 //
00009 // ScenarioInput2.xaml.cpp
00010 // Implementation of the ScenarioInput2 class
00011 //
00012
00013 #include "pch.h"
00014 #include "ScenarioInput2.xaml.h"
00015
00016 using namespace EdgeGestureSample;
00017
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::UI::ViewManagement;
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
00031 ScenarioInput2::ScenarioInput2()
00032 {
00033     InitializeComponent();
00034 }
00035
00036 ScenarioInput2::~ScenarioInput2()
00037 {
00038 }
00039
00040 #pragma region Template-Related Code - Do not remove
00041 void ScenarioInput2::OnNavigatedTo(NavigationEventArgs^ e)
00042 {
00043     // Get a pointer to our main page.
00044     rootPage = dynamic_cast<MainPage^>(e->Parameter);
00045
00046     // We want to be notified when the OutputFrame is loaded so we can get to the content.
00047     _frameLoadedToken = rootPage->OutputFrameLoaded += ref new Windows::Foundation::EventHandler<Platform::Object^>(this, &ScenarioInput2::rootPage_OutputFrameLoaded);
00048 }
00049
00050 void ScenarioInput2::OnNavigatedFrom(NavigationEventArgs^ e)
00051 {
00052     RightClickRegion->RightTapped -= RightClickRegionEventToken;
00053     rootPage->RightTapped -= RightClickEventToken;
00054     EdgeGesture^ edgeGesture = Windows::UI::Input::EdgeGesture::GetForCurrentView();
00055     edgeGesture->Starting -= EdgeGestureStartingEventToken;
00056     edgeGesture->Completed -= EdgeGestureCompletedEventToken;
00057     edgeGesture->Canceled -= EdgeGestureCanceledEventToken;
00058
00059     rootPage->OutputFrameLoaded -= _frameLoadedToken;
00060 }
00061
00062 #pragma endregion
00063
00064 #pragma region Use this code if you need access to elements in the output frame - otherwise delete
00065 void ScenarioInput2::rootPage_OutputFrameLoaded(Object^ sender, Object^ e)
00066 {
00067     // Get a pointer to the content within the OutputFrame.
00068     Page^ outputFrame = dynamic_cast<Page^>(rootPage->OutputFrame->Content);
00069
00070     outputText = dynamic_cast<TextBlock^>(outputFrame->FindName("OutputText"));
00071     RightClickRegion = dynamic_cast<ListBox^>(outputFrame->FindName("RightClickRegion"));
00072
00073     InitializeEdgeGestureHandlers();
00074 }
00075
00076 #pragma endregion
00077
00078 #pragma region Event handlers
00079
00080 void ScenarioInput2::OnStarting(EdgeGesture^ sender, EdgeGestureEventArgs^ e)
00081 {
00082     outputText->Text = "Invoking with touch.";
00083 }
00084
00085 void ScenarioInput2::OnCompleted(EdgeGesture^ sender, EdgeGestureEventArgs^ e)
00086 {
00087     // Determine whether it was touch or keyboard invocation
00088     if (e->Kind == Windows::UI::Input::EdgeGestureKind::Touch)
00089     {
00090         outputText->Text = "Invoked with touch.";
00091     }
00092     else if (e->Kind == Windows::UI::Input::EdgeGestureKind::Keyboard)
00093     {
00094         outputText->Text = "Invoked with keyboard.";
00095     }
00096     else if (e->Kind == Windows::UI::Input::EdgeGestureKind::Mouse)
00097     {
00098         outputText->Text = "Invoked with right-click.";
00099     }
00100 }
00101
00102 void ScenarioInput2::OnCanceled(EdgeGesture^ sender, EdgeGestureEventArgs^ e)
00103 {
00104     outputText->Text = "Canceled with touch.";
00105 }
00106
00107 void ScenarioInput2::OnContextMenu(Object^ sender, RightTappedRoutedEventArgs^ e)
00108 {
00109     outputText->Text = "Invoked with right-click.";
00110 }
00111
00112 void ScenarioInput2::RightClickOverride(Object^ sender, RightTappedRoutedEventArgs^ e)
00113 {
00114     outputText->Text = "The ContextMenu event was handled.  The EdgeGesture event will not fire.";
00115     e->Handled = true;
00116 }
00117
00118 void ScenarioInput2::InitializeEdgeGestureHandlers()
00119 {
00120     EdgeGesture^ edgeGesture = Windows::UI::Input::EdgeGesture::GetForCurrentView();
00121
00122     EdgeGestureStartingEventToken = edgeGesture->Starting += ref new TypedEventHandler<EdgeGesture^, EdgeGestureEventArgs^>(this, &ScenarioInput2::OnStarting);
00123     EdgeGestureCompletedEventToken = edgeGesture->Completed += ref new TypedEventHandler<EdgeGesture^, EdgeGestureEventArgs^>(this, &ScenarioInput2::OnCompleted);
00124     EdgeGestureCanceledEventToken = edgeGesture->Canceled += ref new TypedEventHandler<EdgeGesture^, EdgeGestureEventArgs^>(this, &ScenarioInput2::OnCanceled);
00125
00126     RightClickEventToken = rootPage->RightTapped += ref new RightTappedEventHandler(this, &ScenarioInput2::OnContextMenu);
00127     RightClickRegionEventToken = RightClickRegion->RightTapped += ref new RightTappedEventHandler(this, &ScenarioInput2::RightClickOverride);
00128
00129     outputText->Text = "Sample initialized and events registered.";
00130 }
00131
00132 #pragma endregion
Generated on Sat Nov 23 2024 16:08:00 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Manipulations and gestures (C++)/C++/DrawingObject.cpp Source File

  • Input Manipulations and gestures (C++)
  • C++

DrawingObject.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 "DrawingObject.h"
00010
00011 ///////////////////////////////////////////////////////////////////////////////
00012 // Object constructor, destructor and initialization.
00013 //
00014
00015 DrawingObject::DrawingObject(_In_opt_ ManipulatableObject^ parent, _In_ IRenderer^ renderer)
00016 :   ManipulatableObject(parent),
00017     _renderer(renderer),
00018     _color(Color::MaxCount),
00019     _initColor(Color::MaxCount),
00020     _initX(0),
00021     _initY(0),
00022     _initDX(0),
00023     _initDY(0)
00024 {
00025     _descText[0] = L'\0';
00026     _descPosition.X = 0;
00027     _descPosition.Y = 0;
00028 }
00029
00030 DrawingObject::~DrawingObject()
00031 {
00032 }
00033
00034 void DrawingObject::Initialize(_In_ Color color, _In_ float x, _In_ float y, _In_ float dx, _In_ float dy)
00035 {
00036     _color = color;
00037     _initColor = color;
00038     // Normalize rectangle
00039     if (dx < 0)
00040     {
00041         x += dx;
00042         dx = -dx;
00043     }
00044     if (dy < 0)
00045     {
00046         y += dy;
00047         dy = -dy;
00048     }
00049     _initX = x;
00050     _initY = y;
00051     _initDX = dx;
00052     _initDY = dy;
00053     _descText[0] = L'\0';
00054     _descPosition.X = 0;
00055     _descPosition.Y = 0;
00056
00057     SetInitialPosition(D2D1::Point2F(_initX + _initDX/2, _initY + _initDX/2));
00058     SetManipulationTransform(D2D1::Matrix3x2F::Identity());
00059 }
00060
00061 ///////////////////////////////////////////////////////////////////////////////
00062 // Object drawing methods.
00063 //
00064
00065 void DrawingObject::Draw(
00066     _In_ ID2D1DeviceContext* deviceContext,
00067     _In_ ID2D1SolidColorBrush* brush)
00068 {
00069     // Cumulative transformation matrix.
00070     D2D1::Matrix3x2F mxTransform = Transform();
00071     deviceContext->SetTransform(&mxTransform);
00072
00073     // Draw the object.
00074     D2D1_RECT_F rect = D2D1::RectF(-_initDX/2, -_initDY/2, _initDX/2, _initDY/2);
00075     deviceContext->FillRectangle(rect, brush);
00076     deviceContext->DrawRectangle(rect, brush);
00077
00078     // Restore our transform to nothing.
00079     deviceContext->SetTransform(D2D1::Matrix3x2F::Identity());
00080 }
00081
00082 void DrawingObject::DrawOverlay(
00083     _In_ ID2D1DeviceContext* deviceContext,
00084     _In_ IDWriteTextFormat* textFormat,
00085     _In_ ID2D1SolidColorBrush* brush)
00086 {
00087     D2D_POINT_2F position = D2D1::Point2F(_descPosition.X, _descPosition.Y);
00088     position = ParentTransform().TransformPoint(position);
00089
00090     brush->SetOpacity(1.0f);
00091
00092     textFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
00093     textFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
00094     textFormat->SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);
00095
00096     size_t descLen = 0;
00097     (void)StringCchLength(_descText , ARRAYSIZE(_descText), &descLen);
00098     if (descLen != 0)
00099     {
00100         D2D1_RECT_F descRect = D2D1::RectF(
00101             position.x - _initDX/2,
00102             position.y - _initDY/2,
00103             position.x + _initDX/2,
00104             position.y + _initDY/2);
00105         deviceContext->DrawText(_descText, (UINT)descLen, textFormat,
00106             descRect, brush);
00107     }
00108 }
00109
00110 ///////////////////////////////////////////////////////////////////////////////
00111 // Object hit-testing.
00112 //
00113
00114 bool DrawingObject::HitTest(_In_ Windows::Foundation::Point position)
00115 {
00116     D2D1::Matrix3x2F mxLocalInv = LocalTransform();
00117     if (D2D1InvertMatrix(&mxLocalInv))
00118     {
00119         // "Untransform" (x, y) from parent coordinate system to object's initial principal axes coordinate system.
00120         D2D1_POINT_2F pt = mxLocalInv.TransformPoint(D2D1::Point2F(position.X, position.Y));
00121
00122         // Hit test against object rectangle
00123         D2D1_RECT_F rcInit = D2D1::RectF(-_initDX/2, -_initDY/2, _initDX/2, _initDY/2);   // object initial rectangle
00124         return (pt.x >= rcInit.left) && (pt.x <= rcInit.right) &&
00125                (pt.y >= rcInit.top) && (pt.y <= rcInit.bottom);
00126     }
00127
00128     return false;
00129 }
00130
00131 ///////////////////////////////////////////////////////////////////////////////
00132 // Attach/detach GestureRecognizer to/from the object.
00133 //
00134
00135 void DrawingObject::Attach(_In_ Windows::UI::Input::GestureRecognizer^ gestureRecognizer)
00136 {
00137     // Configure gesture recognizer
00138     gestureRecognizer->GestureSettings =
00139         Windows::UI::Input::GestureSettings::Tap                            |
00140         Windows::UI::Input::GestureSettings::Hold                           |
00141         Windows::UI::Input::GestureSettings::HoldWithMouse                  |
00142         Windows::UI::Input::GestureSettings::RightTap                       |
00143         Windows::UI::Input::GestureSettings::ManipulationTranslateX         |
00144         Windows::UI::Input::GestureSettings::ManipulationTranslateY         |
00145         Windows::UI::Input::GestureSettings::ManipulationRotate             |
00146         Windows::UI::Input::GestureSettings::ManipulationScale              |
00147         Windows::UI::Input::GestureSettings::ManipulationTranslateInertia   |
00148         Windows::UI::Input::GestureSettings::ManipulationRotateInertia      |
00149         Windows::UI::Input::GestureSettings::ManipulationScaleInertia;
00150
00151     // Register all the gesture event handlers
00152     _tokenTapped = gestureRecognizer->Tapped::add(
00153         ref new Windows::Foundation::TypedEventHandler<
00154             Windows::UI::Input::GestureRecognizer^, Windows::UI::Input::TappedEventArgs^>(
00155                 this, &DrawingObject::OnTapped));
00156
00157     _tokenRightTapped = gestureRecognizer->RightTapped::add(
00158         ref new Windows::Foundation::TypedEventHandler<
00159             Windows::UI::Input::GestureRecognizer^, Windows::UI::Input::RightTappedEventArgs^>(
00160                 this, &DrawingObject::OnRightTapped));
00161
00162     _tokenHolding = gestureRecognizer->Holding::add(
00163         ref new Windows::Foundation::TypedEventHandler<
00164             Windows::UI::Input::GestureRecognizer^, Windows::UI::Input::HoldingEventArgs^>(
00165                 this, &DrawingObject::OnHolding));
00166
00167     _tokenManipulationStarted = gestureRecognizer->ManipulationStarted::add(
00168         ref new Windows::Foundation::TypedEventHandler<
00169             Windows::UI::Input::GestureRecognizer^, Windows::UI::Input::ManipulationStartedEventArgs^>(
00170                 this, &DrawingObject::OnManipulationStarted));
00171
00172     _tokenManipulationUpdated = gestureRecognizer->ManipulationUpdated::add(
00173         ref new Windows::Foundation::TypedEventHandler<
00174             Windows::UI::Input::GestureRecognizer^, Windows::UI::Input::ManipulationUpdatedEventArgs^>(
00175                 this, &DrawingObject::OnManipulationUpdated));
00176
00177     _tokenManipulationInertiaStarting = gestureRecognizer->ManipulationInertiaStarting::add(
00178         ref new Windows::Foundation::TypedEventHandler<
00179             Windows::UI::Input::GestureRecognizer^, Windows::UI::Input::ManipulationInertiaStartingEventArgs^>(
00180                 this, &DrawingObject::OnManipulationInertiaStarting));
00181
00182     _tokenManipulationCompleted = gestureRecognizer->ManipulationCompleted::add(
00183         ref new Windows::Foundation::TypedEventHandler<Windows::UI::Input::GestureRecognizer^,
00184         Windows::UI::Input::ManipulationCompletedEventArgs^>(this, &DrawingObject::OnManipulationCompleted));
00185 }
00186
00187 void DrawingObject::Detach(_In_ Windows::UI::Input::GestureRecognizer^ gestureRecognizer)
00188 {
00189     // Remove all the event handlers
00190     gestureRecognizer->Tapped::remove(_tokenTapped);
00191     gestureRecognizer->RightTapped::remove(_tokenRightTapped);
00192     gestureRecognizer->Holding::remove(_tokenHolding);
00193     gestureRecognizer->ManipulationStarted::remove(_tokenManipulationStarted);
00194     gestureRecognizer->ManipulationUpdated::remove(_tokenManipulationUpdated);
00195     gestureRecognizer->ManipulationInertiaStarting::remove(_tokenManipulationInertiaStarting);
00196     gestureRecognizer->ManipulationCompleted::remove(_tokenManipulationCompleted);
00197 }
00198
00199 ///////////////////////////////////////////////////////////////////////////////
00200 // GestureRecognizer event handlers.
00201 //
00202
00203 void DrawingObject::OnTapped(
00204     _In_ Windows::UI::Input::GestureRecognizer^,
00205     _In_ Windows::UI::Input::TappedEventArgs^)
00206 {
00207     ++_color;
00208     if (_color >= Color::MaxCount)
00209     {
00210         _color = Color::First;
00211     }
00212     _renderer->RequestRedraw();
00213 }
00214
00215 void DrawingObject::OnRightTapped(
00216     _In_ Windows::UI::Input::GestureRecognizer^,
00217     _In_ Windows::UI::Input::RightTappedEventArgs^)
00218 {
00219     Initialize(_initColor, _initX, _initY, _initDX, _initDY);
00220     _renderer->RequestRedraw();
00221 }
00222
00223 void DrawingObject::OnHolding(
00224     _In_ Windows::UI::Input::GestureRecognizer^,
00225     _In_ Windows::UI::Input::HoldingEventArgs^ args)
00226 {
00227     if (args->HoldingState == Windows::UI::Input::HoldingState::Started)
00228     {
00229         GetObjectDescription();
00230         _descPosition = args->Position;
00231     }
00232     else
00233     {
00234         _descText[0] = L'\0';
00235     }
00236     _renderer->RequestRedraw();
00237 }
00238
00239 void DrawingObject::OnManipulationStarted(
00240     _In_ Windows::UI::Input::GestureRecognizer^,
00241     _In_ Windows::UI::Input::ManipulationStartedEventArgs^)
00242 {
00243 }
00244
00245 void DrawingObject::OnManipulationUpdated(
00246     _In_ Windows::UI::Input::GestureRecognizer^ sender,
00247     _In_ Windows::UI::Input::ManipulationUpdatedEventArgs^ args)
00248 {
00249     Windows::UI::Input::ManipulationDelta delta = args->Delta;
00250     Windows::Foundation::Point position = args->Position;
00251
00252     delta = LimitManipulationScale(delta, 0.25f, 20.0f);
00253     position = SingleFingerRotation(sender, position, sqrt(_initDX*_initDX + _initDY*_initDY) / (2*3));
00254
00255     UpdateManipulationTransform(delta, position);
00256
00257     _renderer->RequestRedraw();
00258 }
00259
00260 void DrawingObject::OnManipulationInertiaStarting(
00261     _In_ Windows::UI::Input::GestureRecognizer^,
00262     _In_ Windows::UI::Input::ManipulationInertiaStartingEventArgs^)
00263 {
00264 }
00265
00266 void DrawingObject::OnManipulationCompleted(
00267     _In_ Windows::UI::Input::GestureRecognizer^,
00268     _In_ Windows::UI::Input::ManipulationCompletedEventArgs^)
00269 {
00270 }
00271
00272 ///////////////////////////////////////////////////////////////////////////////
00273 // Display object information.
00274 //
00275
00276 inline double sgn_sqrt(double x)
00277 {
00278     return ((x >= 0) ? 1 : -1) * sqrt(fabs(x));
00279 }
00280
00281 void DrawingObject::GetObjectDescription()
00282 {
00283     D2D1::Matrix3x2F mxManip = ManipulationTransform();
00284     float scale = sqrt(fabs(mxManip.Determinant()));
00285     float rotation = (float) (atan2(sgn_sqrt(-mxManip._12 * mxManip._21), sgn_sqrt(mxManip._11 * mxManip._22)) * 180 / M_PI);
00286     StringCchPrintfW(_descText, ARRAYSIZE(_descText), L"T=(%g,%g)\nS=%g\nR=%g",
00287         mxManip._31, mxManip._32, scale, rotation);
00288 }
00289
00290 ///////////////////////////////////////////////////////////////////////////////
00291 // Serialization/deserialization methods.
00292 //
00293
00294 void DrawingObject::Serialize(_In_ Windows::Foundation::Collections::IPropertySet^ properties)
00295 {
00296     __super::Serialize(properties);
00297     properties->Insert("Color", Windows::Foundation::PropertyValue::CreateUInt32((unsigned int)_color));
00298 }
00299
00300 void DrawingObject::Deserialize(_In_ Windows::Foundation::Collections::IPropertySet^ properties)
00301 {
00302     __super::Deserialize(properties);
00303     if (properties->HasKey("Color"))
00304     {
00305         _color            = (Color) safe_cast<Windows::Foundation::IPropertyValue^>(properties->Lookup("Color"))->GetUInt32();
00306     }
00307 }
Generated on Sat Nov 23 2024 16:08:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CryptoWinRT/C++/Scenario3.xaml.cpp Source File

  • CryptoWinRT

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 SDKSample::CryptoWinRT;
00020
00021 using namespace Platform;
00022 using namespace Windows::Security::Cryptography;
00023 using namespace Windows::Security::Cryptography::Core;
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 Scenario3::Scenario3()
00030 {
00031     InitializeComponent();
00032     AlgorithmNames->SelectedIndex = 0;
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 void Scenario3::OnNavigatedTo(NavigationEventArgs^ e)
00041 {
00042     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00043     // as NotifyUser()
00044     rootPage = MainPage::Current;
00045 }
00046
00047
00048 void SDKSample::CryptoWinRT::Scenario3::RunSample_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00049 {
00050     Scenario3Text->Text = "";
00051
00052     // Create a sample message.
00053     String^ Message = "Some message to authenticate";
00054     String^ algName = AlgorithmNames->SelectionBoxItem->ToString();
00055
00056     // Created a MacAlgorithmProvider object for the algorithm specified on input.
00057     MacAlgorithmProvider^ Algorithm = MacAlgorithmProvider::OpenAlgorithm(algName);
00058
00059     Scenario3Text->Text += "*** Sample Hmac Algorithm: " + Algorithm->AlgorithmName + "\n";
00060     Scenario3Text->Text += "\tOriginal Message" + Message + "\n";
00061
00062     // Create a key.
00063     IBuffer^ keymaterial = CryptographicBuffer::GenerateRandom(Algorithm->MacLength);
00064     CryptographicKey^ hmacKey = Algorithm->CreateKey(keymaterial);
00065
00066     // Sign the message by using the key.
00067     IBuffer^ signature = CryptographicEngine::Sign(hmacKey,
00068                                                    CryptographicBuffer::ConvertStringToBinary(Message, BinaryStringEncoding::Utf8));
00069
00070     Scenario3Text->Text += "\tSignature:  " + CryptographicBuffer::EncodeToHexString(signature) + "\n";
00071
00072     // Verify the signature.
00073     hmacKey = Algorithm->CreateKey(keymaterial);
00074
00075     bool IsAuthenticated = CryptographicEngine::VerifySignature(
00076                                     hmacKey,
00077                                     CryptographicBuffer::ConvertStringToBinary(Message, BinaryStringEncoding::Utf8),
00078                                     signature
00079                                     );
00080
00081     if (IsAuthenticated)
00082     {
00083         Scenario3Text->Text += "Verified HMAC\n";
00084     }
00085     else
00086     {
00087         Scenario3Text->Text += "Failed to verify HMAC\n";
00088     }
00089 }
Generated on Sat Nov 23 2024 16:07:51 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct2D custom image effects/C++/ComputeShader/pch.h Source File

  • Direct2D custom image effects
  • ComputeShader

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 <d3d11_1.h>
00012 #include <d2d1_1.h>
00013 #include <d2d1effects.h>
00014 #include <dwrite_1.h>
00015 #include <wincodec.h>
00016 #include <math.h>
00017 #include <agile.h>
00018 #include <d2d1effectauthor.h>
00019 #include <d2d1effecthelpers.h>
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML text editing/C++/Scenario7.xaml.cpp Source File

  • XAML text editing

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 SDKSample::TextEditing;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 Scenario7::Scenario7()
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 Scenario7::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 SDKSample::TextEditing::Scenario7::Default_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00043 {
00044     Button^ b = safe_cast<Button^>(sender);
00045     if (b != nullptr)
00046     {
00047         rootPage->NotifyUser("You clicked the " + b->Name + " button", NotifyType::StatusMessage);
00048     }
00049 }
00050
00051 void SDKSample::TextEditing::Scenario7::Other_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00052 {
00053     Button^ b = safe_cast<Button^>(sender);
00054     if (b != nullptr)
00055     {
00056         rootPage->NotifyUser("You clicked the " + b->Name + " button", NotifyType::StatusMessage);
00057     }
00058 }
Generated on Sat Nov 23 2024 16:07:56 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Print/C++/ScenarioInput4.xaml.h Source File

  • Print

ScenarioInput4.xaml.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 //
00009 // ScenarioInput4.xaml.h
00010 // Declaration of the ScenarioInput4 class
00011 //
00012
00013 #pragma once
00014
00015 #include "pch.h"
00016 #include "ScenarioInput4.g.h"
00017 #include "MainPage.xaml.h"
00018 #include "DisplayContent.h"
00019
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Printing;
00022
00023 namespace PrintSample
00024 {
00025     /// <summary>
00026     /// Scenario that demos how to add custom options (specific for the application)
00027     /// </summary>
00028     [Windows::Foundation::Metadata::WebHostHidden]
00029     public ref class ScenarioInput4 sealed
00030     {
00031     public:
00032         ScenarioInput4();
00033
00034     protected:
00035         virtual void PreparetPrintContent() override;
00036
00037         /// <summary>
00038         /// This is the event handler for PrintManager.PrintTaskRequested.
00039         /// 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.
00040         /// Therefore, we use this handler to only create the print task.
00041         /// The print settings customization can be done when the print document source is requested.
00042         /// </summary>
00043         /// <param name="sender">PrintManager</param>
00044         /// <param name="e">PrintTaskRequestedEventArgs</param>
00045         virtual void PrintTaskRequested(Windows::Graphics::Printing::PrintManager^ sender, Windows::Graphics::Printing::PrintTaskRequestedEventArgs^ e) override;
00046
00047         /// <summary>
00048         /// This is the event handler for PrintDocument.Paginate. It creates print preview pages for the app.
00049         /// </summary>
00050         /// <param name="sender"></param>
00051         /// <param name="e">Paginate Event Arguments</param>
00052         virtual void CreatePrintPreviewPages(Object^ sender, PaginateEventArgs^ e) override;
00053
00054         /// <summary>
00055         /// This function creates and adds one print preview page to the internal cache of print preview
00056         /// pages stored in m_printPreviewPages.
00057         /// </summary>
00058         /// <param name="lastRTBOAdded">Last RichTextBlockOverflow element added in the current content</param>
00059         /// <param name="printPageDescription">Printer's page description</param>
00060         virtual RichTextBlockOverflow^ AddOnePrintPreviewPage(RichTextBlockOverflow^ lastRTBOAdded, Windows::Graphics::Printing::PrintPageDescription printPageDescription) override;
00061
00062     private:
00063         /// <summary>
00064         /// A flag that determines if text & images are to be shown
00065         /// </summary>
00066         DisplayContent                                      m_imageText;
00067
00068         /// <summary>
00069         /// Helper getter for image showing
00070         /// </summary>
00071         property bool ShowImage
00072         {
00073             bool get()
00074             {
00075                 return (m_imageText & DisplayContent::Images) == DisplayContent::Images;
00076             }
00077         }
00078
00079         /// <summary>
00080         /// Helper getter for text showing
00081         /// </summary>
00082         property bool ShowText
00083         {
00084             bool get()
00085             {
00086                 return (m_imageText & DisplayContent::Text) == DisplayContent::Text;
00087             }
00088         }
00089
00090         /// <summary>
00091         /// Option change event handler
00092         /// </summary>
00093         /// <param name="sender">PrintTaskOptionsDetails object</param>
00094         /// <param name="args">the event arguments containing the changed option id</param>
00095         void printDetailedOptions_OptionChanged(Windows::Graphics::Printing::OptionDetails::PrintTaskOptionDetails^ sender,
00096                                                 Windows::Graphics::Printing::OptionDetails::PrintTaskOptionChangedEventArgs^ args);
00097
00098         /// <summary>
00099         /// Helper function used to triger a preview refresh
00100         /// </summary>
00101         void RefreshPreview();
00102
00103     public:
00104         virtual void OnNavigatedTo(NavigationEventArgs^ e) override;
00105         virtual void OnNavigatedFrom(NavigationEventArgs^ e) override;
00106     };
00107 }
Generated on Sat Nov 23 2024 16:08:22 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML DirectX 3D shooting game/C++/SoundEffect.h Source File

  • XAML DirectX 3D shooting game

SoundEffect.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 // SoundEffect:
00011 // This class plays a sound using XAudio2.  It uses a mastering voice provided
00012 // from the Audio class.  The sound data can be read from disk using the MediaReader
00013 // class.
00014
00015 ref class SoundEffect
00016 {
00017 internal:
00018     SoundEffect();
00019
00020     void Initialize(
00021         _In_ IXAudio2*              masteringEngine,
00022         _In_ WAVEFORMATEX*          sourceFormat,
00023         _In_ Platform::Array<byte>^ soundData
00024         );
00025
00026     void PlaySound(_In_ float volume);
00027
00028 protected private:
00029     bool                    m_audioAvailable;
00030     IXAudio2SourceVoice*    m_sourceVoice;
00031     Platform::Array<byte>^  m_soundData;
00032 };
Generated on Sat Nov 23 2024 16:08:14 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Lock screen personalization/C++/Constants.h Source File

  • Lock screen personalization

Constants.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 namespace SDKSample
00016 {
00017     public value struct Scenario
00018     {
00019         Platform::String^ Title;
00020         Platform::String^ ClassName;
00021     };
00022
00023     partial ref class MainPage
00024     {
00025     public:
00026         static property Platform::String^ FEATURE_NAME
00027         {
00028             Platform::String^ get()
00029             {
00030                 return ref new Platform::String(L"Personalization C++");
00031             }
00032         }
00033
00034         static property Platform::Array<Scenario>^ scenarios
00035         {
00036             Platform::Array<Scenario>^ get()
00037             {
00038                 return scenariosInner;
00039             }
00040         }
00041
00042     internal:
00043         bool EnsureUnsnapped();
00044
00045     private:
00046         static Platform::Array<Scenario>^ scenariosInner;
00047     };
00048 }
Generated on Sat Nov 23 2024 16:07:40 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Member List

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

PageRendererContext Member List

This is the complete list of members for PageRendererContext, including all inherited members.
__pad0__ | PageRendererContext |
d2dContext | PageRendererContext |
Draw(_In_ float scale) | PageRendererContext |
DrawMessage(_In_ Platform::String^string) | PageRendererContext |
m_blackBrush | PageRendererContext | [private]
m_d2dContext | PageRendererContext | [private]
m_margin | PageRendererContext | [private]
m_messageFormat | PageRendererContext | [private]
m_targetBox | PageRendererContext | [private]
m_textFormat | PageRendererContext | [private]
m_type | PageRendererContext | [private]
pageRenderer | PageRendererContext |
type | PageRendererContext |
UpdateTargetBox(_In_ D2D1_RECT_F &targetBox) | PageRendererContext |
Generated on Sat Nov 23 2024 16:09:18 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Input Touch keyboard/C++/App.xaml.cpp Source File

  • Input Touch keyboard

App.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 // App.xaml.cpp
00013 // Implementation of the App.xaml class.
00014 //
00015
00016 #include "pch.h"
00017 #include "MainPage.xaml.h"
00018 #include "Common\SuspensionManager.h"
00019
00020 using namespace SDKSample;
00021 using namespace SDKSample::Common;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel;
00026 using namespace Windows::ApplicationModel::Activation;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
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::Interop;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038
00039 /// <summary>
00040 /// Initializes the singleton application object.  This is the first line of authored code
00041 /// executed, and as such is the logical equivalent of main() or WinMain().
00042 /// </summary>
00043 App::App()
00044 {
00045     InitializeComponent();
00046     this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points will
00051 /// be used when the application is launched to open a specific file, to display search results,
00052 /// and so forth.
00053 /// </summary>
00054 /// <param name="pArgs">Details about the launch request and process.</param>
00055 void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
00056 {
00057     this->LaunchArgs = pArgs;
00058
00059     // Do not repeat app initialization when already running, just ensure that
00060     // the window is active
00061     if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
00062     {
00063         Window::Current->Activate();
00064         return;
00065     }
00066
00067     // Create a Frame to act as the navigation context and associate it with
00068     // a SuspensionManager key
00069     auto rootFrame = ref new Frame();
00070     SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
00071
00072     auto prerequisite = task<void>([](){});
00073     if (pArgs->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         prerequisite = SuspensionManager::RestoreAsync();
00078     }
00079     prerequisite.then([=]()
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         if (rootFrame->Content == nullptr)
00085         {
00086             if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
00087             {
00088                 throw ref new FailureException("Failed to create initial page");
00089             }
00090         }
00091
00092         // Place the frame in the current Window and ensure that it is active
00093         Window::Current->Content = rootFrame;
00094         Window::Current->Activate();
00095     }, task_continuation_context::use_current());
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 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00106 {
00107     (void) sender;  // Unused parameter
00108
00109     auto deferral = e->SuspendingOperation->GetDeferral();
00110     SuspensionManager::SaveAsync().then([=]()
00111     {
00112         deferral->Complete();
00113     });
00114 }
Generated on Sat Nov 23 2024 16:07:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DXGI offer and reclaim resources/C++/BasicShapes.h Source File

  • DXGI offer and reclaim resources

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 Sat Nov 23 2024 16:08:10 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/FaceMesh.cpp Source File

  • DirectX 3D shooting game

FaceMesh.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 "FaceMesh.h"
00010 #include "DirectXSample.h"
00011 #include "ConstantBuffers.h"
00012
00013 using namespace Microsoft::WRL;
00014 using namespace DirectX;
00015
00016 FaceMesh::FaceMesh(_In_ ID3D11Device *device)
00017 {
00018     D3D11_BUFFER_DESC bd = {0};
00019     D3D11_SUBRESOURCE_DATA initData = {0};
00020
00021     PNTVertex target_vertices[] =
00022     {
00023         {XMFLOAT3(0.0f, 0.0f, 0.0f), XMFLOAT3(0.0f, 0.0f, 1.0f), XMFLOAT2(1.0f, 1.0f)},
00024         {XMFLOAT3(1.0f, 0.0f, 0.0f), XMFLOAT3(0.0f, 0.0f, 1.0f), XMFLOAT2(0.0f, 1.0f)},
00025         {XMFLOAT3(1.0f, 1.0f, 0.0f), XMFLOAT3(0.0f, 0.0f, 1.0f), XMFLOAT2(0.0f, 0.0f)},
00026         {XMFLOAT3(0.0f, 1.0f, 0.0f), XMFLOAT3(0.0f, 0.0f, 1.0f), XMFLOAT2(1.0f, 0.0f)}
00027     };
00028     WORD target_indices[] =
00029     {
00030         0, 1, 2,
00031         0, 2, 3,
00032         0, 2, 1,
00033         0, 3, 2
00034     };
00035
00036     m_vertexCount = 4;
00037     m_indexCount = 12;
00038
00039     bd.Usage = D3D11_USAGE_DEFAULT;
00040     bd.ByteWidth = sizeof(PNTVertex) * m_vertexCount;
00041     bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
00042     bd.CPUAccessFlags = 0;
00043     initData.pSysMem = target_vertices;
00044     DX::ThrowIfFailed(
00045         device->CreateBuffer(&bd, &initData, &m_vertexBuffer)
00046         );
00047
00048     bd.Usage = D3D11_USAGE_DEFAULT;
00049     bd.ByteWidth = sizeof(WORD) * m_indexCount;
00050     bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
00051     bd.CPUAccessFlags = 0;
00052     initData.pSysMem = target_indices;
00053     DX::ThrowIfFailed(
00054         device->CreateBuffer(&bd, &initData, &m_indexBuffer)
00055         );
00056 }
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/CartoonEffect/Utils.h Source File

  • Hilo C++
  • CartoonEffect

Utils.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
00009 class Utils
00010 {
00011 public:
00012     static const float64 Wr;
00013     static const float64 Wb;
00014     static const float64 Wg;
00015
00016     static inline void RGBToYUV(COLORREF color, float64& y, float64& u, float64& v)
00017     {
00018         float64 r = GetRValue(color) / 255.0;
00019         float64 g = GetGValue(color) / 255.0;
00020         float64 b = GetBValue(color) / 255.0;
00021
00022         y = Wr * r + Wb * b + Wg * g;
00023         u = 0.436 * (b - y) / (1 - Wb);
00024         v = 0.615 * (r - y) / (1 - Wr);
00025     }
00026
00027     static inline float64 GetDistance(COLORREF color1, COLORREF color2)
00028     {
00029         float64 y1, u1, v1, y2, u2, v2;
00030         RGBToYUV(color1, y1, u1, v1);
00031         RGBToYUV(color2, y2, u2, v2);
00032
00033         return sqrt(pow(u1 - u2, 2) + pow(v1 - v2, 2));
00034     }
00035
00036     static inline float SmoothStep(float a, float b, float x)
00037     {
00038         if (x < a) return 0.0f;
00039         else if (x >= b) return 1.0f;
00040
00041         x = (x - a) / (b - a);
00042         return (x * x * (3.0f - 2.0f * x));
00043     }
00044 };
Generated on Sat Nov 23 2024 16:08:16 for Win8-Examples by doxygen 1.7.1


Win8-Examples: DirectX 3D shooting game/C++/Animate.h Source File

  • DirectX 3D shooting game

Animate.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 // Animate:
00011 // This is an abstract class for animations.  It defines a set of
00012 // capabilities for animating XMFLOAT3 variables.  An animation has the following
00013 // characteristics:
00014 //     Start - the time for the animation to start.
00015 //     Duration - the length of time the animation is to run.
00016 //     Continuous - whether the animation loops after duration is reached or just
00017 //         stops.
00018 // There are two query functions:
00019 //     IsActive - determines if the animation is active at time t.
00020 //     IsFinished - determines if the animation is done at time t.
00021 // It is expected that each derived class will provide an Evaluate method for the
00022 // specific kind of animation.
00023
00024 ref class Animate abstract
00025 {
00026 internal:
00027     Animate();
00028
00029     virtual DirectX::XMFLOAT3 Evaluate (_In_ float t) = 0;
00030
00031     bool  IsActive(_In_ float t) { return ((t >= m_startTime) && (m_continuous || (t < (m_startTime + m_duration)))); };
00032     bool  IsFinished(_In_ float t) { return (!m_continuous && (t >= (m_startTime + m_duration))); }
00033     float Start();
00034     void  Start(_In_ float start);
00035     float Duration();
00036     void  Duration(_In_ float duration);
00037     bool  Continuous();
00038     void  Continuous(_In_ bool continuous);
00039
00040 protected private:
00041     bool  m_continuous;      // if true means at end cycle back to beginning
00042     float m_startTime;       // time at which animation begins
00043     float m_duration;        // for continuous this is the duration of 1 cycle through path
00044 };
00045
00046 //----------------------------------------------------------------------
00047
00048 // AnimateLinePosition:
00049 // This class is a specialization of Animate that defines an animation of a position vector
00050 // along a straight line defined in world coordinates from startPosition to endPosition.
00051
00052 ref class AnimateLinePosition: public Animate
00053 {
00054 internal:
00055     AnimateLinePosition(
00056         _In_ DirectX::XMFLOAT3 startPosition,
00057         _In_ DirectX::XMFLOAT3 endPosition,
00058         _In_ float duration,
00059         _In_ bool continuous
00060         );
00061     virtual DirectX::XMFLOAT3 Evaluate(_In_ float t) override;
00062
00063 private:
00064     DirectX::XMFLOAT3 m_startPosition;
00065     DirectX::XMFLOAT3 m_endPosition;
00066     float             m_length;
00067 };
00068
00069 //----------------------------------------------------------------------
00070
00071 struct LineSegment
00072 {
00073     DirectX::XMFLOAT3 position;
00074     float             length;
00075     float             uStart;
00076     float             uLength;
00077 };
00078
00079 // AnimateLineListPosition:
00080 // This class is a specialization of Animate that defines an animation of a position vector
00081 // along a set of line segments defined by a set of points.  The animation along the path is
00082 // such that the evaluation of the position along the path will be uniform independent of
00083 // the length of each of the line segments.  A continuous loop can be achieved by having the
00084 // first and last points of the list be the same.
00085
00086 ref class AnimateLineListPosition: public Animate
00087 {
00088 internal:
00089     AnimateLineListPosition(
00090         _In_ unsigned int count,
00091         _In_reads_(count) DirectX::XMFLOAT3 position[],
00092         _In_ float duration,
00093         _In_ bool continuous
00094         );
00095     virtual DirectX::XMFLOAT3 Evaluate(_In_ float t) override;
00096
00097 private:
00098     unsigned int             m_count;
00099     float                    m_totalLength;
00100     std::vector<LineSegment> m_segment;
00101 };
00102
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 ref class AnimateCirclePosition: public Animate
00114 {
00115 internal:
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 };
00134
00135 //----------------------------------------------------------------------
Generated on Sat Nov 23 2024 16:08:13 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Hilo C++/C++/Hilo/pch.h Source File

  • Hilo C++
  • Hilo

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 // pch.h
00009 // Header for standard system include files.
00010 //
00011
00012 #pragma once
00013
00014 #include <assert.h>
00015 #include <collection.h>
00016 #include <ppltasks.h>
00017 #include <sstream>
00018
00019 #include "TaskExtensions.h"
00020 #include "TaskExceptionsExtensions.h"
00021 #include "App.xaml.h"
Generated on Sat Nov 23 2024 16:07:48 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Media engine native C++ video playback/C++/videoview.h Source File

  • Media engine native C++ video playback

videoview.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include "MEPlayer.h"
00004
00005 ref class VideoView
00006 {
00007 internal:
00008     VideoView();
00009
00010     void Initialize(
00011         _In_ Platform::Agile<Windows::UI::Core::CoreWindow> window,
00012         _In_ Platform::Agile<Windows::ApplicationModel::Core::CoreApplicationView> applicationView
00013         );
00014
00015     // Declare Event Handlers
00016     void OnWindowSizeChanged(
00017         _In_ Windows::UI::Core::CoreWindow^ sender,
00018         _In_ Windows::UI::Core::WindowSizeChangedEventArgs^ args
00019         );
00020
00021     void OnPointerPressed(
00022         _In_ Windows::UI::Core::CoreWindow^ sender,
00023         _In_ Windows::UI::Core::PointerEventArgs^ args
00024         );
00025
00026     void OnKeyPressed(
00027         _In_ Windows::UI::Core::CoreWindow^ sender,
00028         _In_ Windows::UI::Core::KeyEventArgs^ args
00029         );
00030
00031   void OnResuming(
00032         _In_ Platform::Object^ sender,
00033         _In_ Platform::Object^ args);
00034
00035     void OnSuspending(
00036         _In_ Platform::Object^ sender,
00037         _In_ Windows::ApplicationModel::SuspendingEventArgs^ args);
00038
00039     void Run();
00040
00041 private:
00042
00043     // Basics
00044     Platform::Agile<Windows::UI::Core::CoreWindow> m_window;
00045     Platform::Agile<Windows::ApplicationModel::Core::CoreApplicationView> m_applicationView;
00046
00047     // MediaEngine Player
00048     MEPlayer^ m_player;
00049 };
Generated on Sat Nov 23 2024 16:08:20 for Win8-Examples by doxygen 1.7.1


Win8-Examples: Direct3D HLSL fractal generator/C++/DirectXBase.cpp Source File

  • Direct3D HLSL fractal generator

DirectXBase.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 "DirectXBase.h"
00010
00011 using namespace Windows::UI::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::Graphics::Display;
00015 using namespace D2D1;
00016
00017 // Constructor.
00018 DirectXBase::DirectXBase() :
00019     m_windowSizeChangeInProgress(false),
00020     m_dpi(-1.0f)
00021 {
00022 }
00023
00024 // Initialize the DirectX resources required to run.
00025 void DirectXBase::Initialize(CoreWindow^ window, float dpi)
00026 {
00027     m_window = window;
00028
00029     CreateDeviceIndependentResources();
00030     CreateDeviceResources();
00031     SetDpi(dpi);
00032 }
00033
00034 // Recreate all device resources and set them back to the current state.
00035 void DirectXBase::HandleDeviceLost()
00036 {
00037     // Reset these member variables to ensure that SetDpi recreates all resources.
00038     float dpi = m_dpi;
00039     m_dpi = -1.0f;
00040     m_windowBounds.Width = 0;
00041     m_windowBounds.Height = 0;
00042     m_swapChain = nullptr;
00043
00044     CreateDeviceResources();
00045     SetDpi(dpi);
00046 }
00047
00048 // These are the resources required independent of the device.
00049 void DirectXBase::CreateDeviceIndependentResources()
00050 {
00051     D2D1_FACTORY_OPTIONS options;
00052     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00053
00054 #if defined(_DEBUG)
00055     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00056     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00057 #endif
00058
00059     DX::ThrowIfFailed(
00060         D2D1CreateFactory(
00061             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00062             __uuidof(ID2D1Factory1),
00063             &options,
00064             &m_d2dFactory
00065             )
00066         );
00067
00068     DX::ThrowIfFailed(
00069         DWriteCreateFactory(
00070             DWRITE_FACTORY_TYPE_SHARED,
00071             __uuidof(IDWriteFactory),
00072             &m_dwriteFactory
00073             )
00074         );
00075
00076     DX::ThrowIfFailed(
00077         CoCreateInstance(
00078             CLSID_WICImagingFactory,
00079             nullptr,
00080             CLSCTX_INPROC_SERVER,
00081             IID_PPV_ARGS(&m_wicFactory)
00082             )
00083         );
00084 }
00085
00086 // These are the resources that depend on the device.
00087 void DirectXBase::CreateDeviceResources()
00088 {
00089     // This flag adds support for surfaces with a different color channel ordering
00090     // than the API default. It is required for compatibility with Direct2D.
00091     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00092     ComPtr<IDXGIDevice> dxgiDevice;
00093
00094 #if defined(_DEBUG)
00095     // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00096     creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00097 #endif
00098
00099     // This array defines the set of DirectX hardware feature levels this app will support.
00100     // Note the ordering should be preserved.
00101     // Don't forget to declare your application's minimum required feature level in its
00102     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00103     D3D_FEATURE_LEVEL featureLevels[] =
00104     {
00105         D3D_FEATURE_LEVEL_11_1,
00106         D3D_FEATURE_LEVEL_11_0,
00107         D3D_FEATURE_LEVEL_10_1,
00108         D3D_FEATURE_LEVEL_10_0,
00109         D3D_FEATURE_LEVEL_9_3,
00110         D3D_FEATURE_LEVEL_9_2,
00111         D3D_FEATURE_LEVEL_9_1
00112     };
00113
00114     // Create the Direct3D 11 API device object and a corresponding context.
00115     ComPtr<ID3D11Device> device;
00116     ComPtr<ID3D11DeviceContext> context;
00117     DX::ThrowIfFailed(
00118         D3D11CreateDevice(
00119             nullptr,                    // Specify nullptr to use the default adapter.
00120             D3D_DRIVER_TYPE_HARDWARE,
00121             0,
00122             creationFlags,              // Set debug and Direct2D compatibility flags.
00123             featureLevels,              // List of feature levels this app can support.
00124             ARRAYSIZE(featureLevels),
00125             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Metro style apps.
00126             &device,                    // Returns the Direct3D device created.
00127             &m_featureLevel,            // Returns feature level of device created.
00128             &context                    // Returns the device immediate context.
00129             )
00130         );
00131
00132     // Get the Direct3D 11.1 API device and context interfaces.
00133     DX::ThrowIfFailed(
00134         device.As(&m_d3dDevice)
00135         );
00136
00137     DX::ThrowIfFailed(
00138         context.As(&m_d3dContext)
00139         );
00140
00141     // Get the underlying DXGI device of the Direct3D device.
00142     DX::ThrowIfFailed(
00143         m_d3dDevice.As(&dxgiDevice)
00144         );
00145
00146     // Create the Direct2D device object and a corresponding context.
00147     DX::ThrowIfFailed(
00148         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00149         );
00150
00151     DX::ThrowIfFailed(
00152         m_d2dDevice->CreateDeviceContext(
00153             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00154             &m_d2dContext
00155             )
00156         );
00157 }
00158
00159 // Helps track the DPI in the helper class.
00160 // This is called in the dpiChanged event handler in the view class.
00161 void DirectXBase::SetDpi(float dpi)
00162 {
00163     if (dpi != m_dpi)
00164     {
00165         // Save the DPI of this display in our class.
00166         m_dpi = dpi;
00167
00168         // Update Direct2D's stored DPI.
00169         m_d2dContext->SetDpi(m_dpi, m_dpi);
00170
00171         // Often a DPI change implies a window size change. In some cases Windows will issue
00172         // both a size changed event and a DPI changed event. In this case, the resulting bounds
00173         // will not change, and the window resize code will only be executed once.
00174         UpdateForWindowSizeChange();
00175     }
00176 }
00177
00178 // This routine is called in the event handler for the view SizeChanged event.
00179 void DirectXBase::UpdateForWindowSizeChange()
00180 {
00181     // Only handle window size changed if there is no pending DPI change.
00182     if (m_dpi != DisplayProperties::LogicalDpi)
00183     {
00184         return;
00185     }
00186
00187     if (m_window->Bounds.Width  != m_windowBounds.Width ||
00188         m_window->Bounds.Height != m_windowBounds.Height)
00189     {
00190         m_d2dContext->SetTarget(nullptr);
00191         m_d2dTargetBitmap = nullptr;
00192         m_d3dRenderTargetView = nullptr;
00193         m_d3dDepthStencilView = nullptr;
00194         m_windowSizeChangeInProgress = true;
00195         CreateWindowSizeDependentResources();
00196     }
00197 }
00198
00199 // Allocate all memory resources that change on a window SizeChanged event.
00200 void DirectXBase::CreateWindowSizeDependentResources()
00201 {
00202     // Store the window bounds so the next time we get a SizeChanged event we can
00203     // avoid rebuilding everything if the size is identical.
00204     m_windowBounds = m_window->Bounds;
00205
00206     if (m_swapChain != nullptr)
00207     {
00208         // If the swap chain already exists, resize it.
00209         HRESULT hr = m_swapChain->ResizeBuffers(2, 0, 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0);
00210
00211         if (hr == DXGI_ERROR_DEVICE_REMOVED)
00212         {
00213             // If the device was removed for any reason, a new device and swapchain will need to be created.
00214             HandleDeviceLost();
00215
00216             // Everything is set up now. Do not continue execution of this method.
00217             return;
00218         }
00219         else
00220         {
00221             DX::ThrowIfFailed(hr);
00222         }
00223     }
00224     else
00225     {
00226         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00227         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00228         swapChainDesc.Width = 0;                                     // Use automatic sizing.
00229         swapChainDesc.Height = 0;
00230         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;           // This is the most common swap chain format.
00231         swapChainDesc.Stereo = false;
00232         swapChainDesc.SampleDesc.Count = 1;                          // Don't use multi-sampling.
00233         swapChainDesc.SampleDesc.Quality = 0;
00234         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00235         swapChainDesc.BufferCount = 2;                               // Use double-buffering to minimize latency.
00236         swapChainDesc.Scaling = DXGI_SCALING_NONE;
00237         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Metro style apps must use this SwapEffect.
00238         swapChainDesc.Flags = 0;
00239
00240         ComPtr<IDXGIDevice1> dxgiDevice;
00241         DX::ThrowIfFailed(
00242             m_d3dDevice.As(&dxgiDevice)
00243             );
00244
00245         ComPtr<IDXGIAdapter> dxgiAdapter;
00246         DX::ThrowIfFailed(
00247             dxgiDevice->GetAdapter(&dxgiAdapter)
00248             );
00249
00250         ComPtr<IDXGIFactory2> dxgiFactory;
00251         DX::ThrowIfFailed(
00252             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00253             );
00254
00255         CoreWindow^ window = m_window.Get();
00256         DX::ThrowIfFailed(
00257             dxgiFactory->CreateSwapChainForCoreWindow(
00258                 m_d3dDevice.Get(),
00259                 reinterpret_cast<IUnknown*>(window),
00260                 &swapChainDesc,
00261                 nullptr,
00262                 &m_swapChain
00263                 )
00264             );
00265
00266         // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
00267         // ensures that the application will only render after each VSync, minimizing power consumption.
00268         DX::ThrowIfFailed(
00269             dxgiDevice->SetMaximumFrameLatency(1)
00270             );
00271     }
00272
00273     // Create a Direct3D render target view of the swap chain back buffer.
00274     ComPtr<ID3D11Texture2D> backBuffer;
00275     DX::ThrowIfFailed(
00276         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00277         );
00278
00279     DX::ThrowIfFailed(
00280         m_d3dDevice->CreateRenderTargetView(
00281             backBuffer.Get(),
00282             nullptr,
00283             &m_d3dRenderTargetView
00284             )
00285         );
00286
00287     // Cache the rendertarget dimensions in our helper class for convenient use.
00288     D3D11_TEXTURE2D_DESC backBufferDesc = {0};
00289     backBuffer->GetDesc(&backBufferDesc);
00290     m_renderTargetSize.Width  = static_cast<float>(backBufferDesc.Width);
00291     m_renderTargetSize.Height = static_cast<float>(backBufferDesc.Height);
00292
00293     // Create a depth stencil view for use with 3D rendering if needed.
00294     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00295         DXGI_FORMAT_D24_UNORM_S8_UINT,
00296         backBufferDesc.Width,
00297         backBufferDesc.Height,
00298         1,
00299         1,
00300         D3D11_BIND_DEPTH_STENCIL
00301         );
00302
00303     ComPtr<ID3D11Texture2D> depthStencil;
00304     DX::ThrowIfFailed(
00305         m_d3dDevice->CreateTexture2D(
00306             &depthStencilDesc,
00307             nullptr,
00308             &depthStencil
00309             )
00310         );
00311
00312     auto viewDesc = CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D);
00313     DX::ThrowIfFailed(
00314         m_d3dDevice->CreateDepthStencilView(
00315             depthStencil.Get(),
00316             &viewDesc,
00317             &m_d3dDepthStencilView
00318             )
00319         );
00320
00321     // Set the 3D rendering viewport to target the entire window.
00322     CD3D11_VIEWPORT viewport(
00323         0.0f,
00324         0.0f,
00325         static_cast<float>(backBufferDesc.Width),
00326         static_cast<float>(backBufferDesc.Height)
00327         );
00328
00329     m_d3dContext->RSSetViewports(1, &viewport);
00330
00331     // Create a Direct2D target bitmap associated with the
00332     // swap chain back buffer and set it as the current target.
00333     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00334         BitmapProperties1(
00335             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00336             PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00337             m_dpi,
00338             m_dpi
00339             );
00340
00341     ComPtr<IDXGISurface> dxgiBackBuffer;
00342     DX::ThrowIfFailed(
00343         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00344         );
00345
00346     DX::ThrowIfFailed(
00347         m_d2dContext->CreateBitmapFromDxgiSurface(
00348             dxgiBackBuffer.Get(),
00349             &bitmapProperties,
00350             &m_d2dTargetBitmap
00351             )
00352         );
00353
00354     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00355
00356     // Grayscale text anti-aliasing is recommended for all Metro style apps.
00357     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00358 }
00359
00360 // Method to deliver the final image to the display.
00361 void DirectXBase::Present()
00362 {
00363     // The application may optionally specify "dirty" or "scroll" rects to improve efficiency
00364     // in certain scenarios.  In this sample, however, we do not utilize those features.
00365     DXGI_PRESENT_PARAMETERS parameters = {0};
00366     parameters.DirtyRectsCount = 0;
00367     parameters.pDirtyRects = nullptr;
00368     parameters.pScrollRect = nullptr;
00369     parameters.pScrollOffset = nullptr;
00370
00371     // The first argument instructs DXGI to block until VSync, putting the application
00372     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00373     // frames that will never be displayed to the screen.
00374     HRESULT hr = m_swapChain->Present1(1, 0, &parameters);
00375
00376     // Discard the contents of the render target.
00377     // This is a valid operation only when the existing contents will be entirely
00378     // overwritten. If dirty or scroll rects are used, this call should be removed.
00379     m_d3dContext->DiscardView(m_d3dRenderTargetView.Get());
00380
00381     // Discard the contents of the depth stencil.
00382     m_d3dContext->DiscardView(m_d3dDepthStencilView.Get());
00383
00384     // If the device was removed either by a disconnect or a driver upgrade, we
00385     // must recreate all device resources.
00386     if (hr == DXGI_ERROR_DEVICE_REMOVED)
00387     {
00388         HandleDeviceLost();
00389     }
00390     else
00391     {
00392         DX::ThrowIfFailed(hr);
00393     }
00394
00395     if (m_windowSizeChangeInProgress)
00396     {
00397         // A window size change has been initiated and the app has just completed presenting
00398         // the first frame with the new size. Notify the resize manager so we can short
00399         // circuit any resize animation and prevent unnecessary delays.
00400         CoreWindowResizeManager::GetForCurrentView()->NotifyLayoutCompleted();
00401         m_windowSizeChangeInProgress = false;
00402     }
00403 }
00404
00405 void DirectXBase::ValidateDevice()
00406 {
00407     // The D3D Device is no longer valid if the default adapter changes or if
00408     // the device has been removed.
00409
00410     // First, get the information for the adapter related to the current device.
00411
00412     ComPtr<IDXGIDevice1> dxgiDevice;
00413     ComPtr<IDXGIAdapter> deviceAdapter;
00414     DXGI_ADAPTER_DESC deviceDesc;
00415     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00416     DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter));
00417     DX::ThrowIfFailed(deviceAdapter->GetDesc(&deviceDesc));
00418
00419     // Next, get the information for the default adapter.
00420
00421     ComPtr<IDXGIFactory2> dxgiFactory;
00422     ComPtr<IDXGIAdapter1> currentAdapter;
00423     DXGI_ADAPTER_DESC currentDesc;
00424     DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)));
00425     DX::ThrowIfFailed(dxgiFactory->EnumAdapters1(0, &currentAdapter));
00426     DX::ThrowIfFailed(currentAdapter->GetDesc(&currentDesc));
00427
00428     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00429     // a new D3D device must be created.
00430
00431     if ((deviceDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart) ||
00432         (deviceDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart) ||
00433         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00434     {
00435         // Release references to resources related to the old device.
00436         dxgiDevice = nullptr;
00437         deviceAdapter = nullptr;
00438
00439         // Create a new device and swap chain.
00440         HandleDeviceLost();
00441     }
00442 }
Generated on Sat Nov 23 2024 16:08:02 for Win8-Examples by doxygen 1.7.1


Win8-Examples: XAML ListView and GridView essentials/C++/SampleDataSource.cpp Source File

  • XAML ListView and GridView essentials

SampleDataSource.cpp

Go to the documentation of this file.
00001
00002
00003 //*********************************************************
00004 //
00005 // Copyright (c) Microsoft. All rights reserved.
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 #pragma once
00014
00015 #include "pch.h"
00016 #include "SampleDataSource.h"
00017
00018 using namespace Windows::UI::Xaml::Media;
00019 using namespace SDKSample::ListViewSampleDataSource;
00020
00021 //Methods of class Item
00022 Item::Item():_Title(""),_Subtitle(""),_Link(""),_Category(""),_Description(""),_Content(""),_Image(nullptr)
00023 {
00024 }
00025
00026
00027
Generated on Sat Nov 23 2024 16:08:27 for Win8-Examples by doxygen 1.7.1


Win8-Examples: CameraCaptureUI/C++/CapturePhoto.xaml.cpp Source File

  • CameraCaptureUI

CapturePhoto.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 // CapturePhoto.xaml.cpp
00013 // Implementation of the CapturePhoto class
00014 //
00015
00016 #include "pch.h"
00017 #include "CapturePhoto.xaml.h"
00018
00019 using namespace SDKSample::CameraCapture;
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::UI::Xaml::Media::Imaging;
00025 using namespace Windows::Media::Capture;
00026 using namespace Windows::Storage;
00027 using namespace Windows::Foundation;
00028
00029 CapturePhoto::CapturePhoto()
00030 {
00031     InitializeComponent();
00032     appSettings = ApplicationData::Current->LocalSettings->Values;
00033     ResetButton->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
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 CapturePhoto::OnNavigatedTo(NavigationEventArgs^ e)
00042 {
00043     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00044     // as NotifyUser()
00045     rootPage = MainPage::Current;
00046
00047     // Set the initial photo
00048
00049     // Check for any previously stored photo in application data
00050     if (appSettings->HasKey("capturedPhoto"))
00051     {
00052         CapturePhotoButton->IsEnabled = false;
00053
00054         // Load the image from specified path
00055         Platform::String^ filePath = safe_cast<IPropertyValue^>(appSettings->Lookup("capturedPhoto"))->GetString();
00056         LoadPhoto(filePath);
00057     }
00058     else
00059     {
00060         // Load the placeholder image
00061         rootPage->NotifyUser("The photo will be shown here.", NotifyType::StatusMessage);
00062         CapturedPhoto->Source = ref new BitmapImage(ref new Windows::Foundation::Uri(BaseUri->AbsoluteUri, "Assets/placeholder-sdk.png"));
00063     }
00064 }
00065
00066 /// <summary>
00067 /// Invoked when CapturePhoto button is clicked.
00068 /// Shows the camera capture UI in photo mode.
00069 /// When the user takes a photo, shows the image in output section.
00070 /// </summary>
00071 void CapturePhoto::CapturePhoto_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00072 {
00073     try
00074     {
00075         CameraCaptureUI^ dialog = ref new CameraCaptureUI();
00076
00077         dialog->PhotoSettings->CroppedAspectRatio = Size(16, 9);
00078
00079         concurrency::task<StorageFile^> (dialog->CaptureFileAsync(CameraCaptureUIMode::Photo)).then([this] (StorageFile^ file)
00080         {
00081             if (nullptr != file)
00082             {
00083                 concurrency::task<Streams::IRandomAccessStream^> (file->OpenAsync(FileAccessMode::Read)).then([this] (Streams::IRandomAccessStream^ stream)
00084                 {
00085                     BitmapImage^ bitmapImage = ref new BitmapImage();
00086                     bitmapImage->SetSource(stream);
00087                     CapturedPhoto->Source = bitmapImage;
00088                     ResetButton->Visibility = Windows::UI::Xaml::Visibility::Visible;
00089                     rootPage->NotifyUser("", NotifyType::StatusMessage);
00090                 });
00091
00092                 // Store the path in Application Data
00093                 appSettings->Insert("capturedPhoto", PropertyValue::CreateString(file->Path));
00094             }
00095             else
00096             {
00097                 rootPage->NotifyUser("No photo captured", NotifyType::ErrorMessage);
00098             }
00099         });
00100
00101     }
00102     catch (Platform::Exception^ ex)
00103     {
00104         rootPage->NotifyUser(ex->Message, NotifyType::ErrorMessage);
00105     }
00106 }
00107
00108 /// <summary>
00109 /// Invoked when Reset button is clicked.
00110 /// Resets the scenario.
00111 /// </summary>
00112 void CapturePhoto::Reset_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00113 {
00114     rootPage->NotifyUser("The photo will be shown here.", NotifyType::StatusMessage);
00115     ResetButton->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00116     CapturedPhoto->Source = ref new BitmapImage(ref new Windows::Foundation::Uri(BaseUri->AbsoluteUri, "Assets/placeholder-sdk.png"));
00117
00118     // Remove file from Application Data
00119     appSettings->Remove("capturedPhoto");
00120 }
00121
00122 /// <summary>
00123 /// Loads the image from the specified file.
00124 /// </summary>
00125 void CapturePhoto::LoadPhoto(Platform::String^ filePath)
00126 {
00127     concurrency::task<StorageFile^>(StorageFile::GetFileFromPathAsync(filePath)).then([this] (StorageFile^ file)
00128     {
00129         return file->OpenAsync(FileAccessMode::Read);
00130     })
00131         .then([this](concurrency::task<Streams::IRandomAccessStream^> openTask)
00132     {
00133         try
00134         {
00135             auto stream = openTask.get();
00136             BitmapImage^ bitmapImage = ref new BitmapImage();
00137             bitmapImage->SetSource(stream);
00138             CapturedPhoto->Source = bitmapImage;
00139             ResetButton->Visibility = Windows::UI::Xaml::Visibility::Visible;
00140             CapturePhotoButton->IsEnabled = true;
00141             rootPage->NotifyUser("", NotifyType::StatusMessage);
00142         }
00143         catch (Platform::Exception^ ex)
00144         {
00145             CapturePhotoButton->IsEnabled = true;
00146             appSettings->Remove("capturedPhoto");
00147             rootPage->NotifyUser(ex->Message, NotifyType::ErrorMessage);
00148         }
00149     });
00150 }
Generated on Sat Nov 23 2024 16:07:58 for Win8-Examples by doxygen 1.7.1